echarts.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  7. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  8. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  9. // declaration is behind of the using position (for example in `Model.extent`,
  10. // And tools like rollup can not analysis the dependency if not import).
  11. var dev;
  12. // In browser
  13. if (typeof window !== 'undefined') {
  14. dev = window.__DEV__;
  15. }
  16. // In node
  17. else if (typeof global !== 'undefined') {
  18. dev = global.__DEV__;
  19. }
  20. if (typeof dev === 'undefined') {
  21. dev = true;
  22. }
  23. var __DEV__ = dev;
  24. /**
  25. * zrender: 生成唯一id
  26. *
  27. * @author errorrik (errorrik@gmail.com)
  28. */
  29. var idStart = 0x0907;
  30. var guid = function () {
  31. return idStart++;
  32. };
  33. /**
  34. * echarts设备环境识别
  35. *
  36. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  37. * @author firede[firede@firede.us]
  38. * @desc thanks zepto.
  39. */
  40. var env = {};
  41. if (typeof navigator === 'undefined') {
  42. // In node
  43. env = {
  44. browser: {},
  45. os: {},
  46. node: true,
  47. // Assume canvas is supported
  48. canvasSupported: true,
  49. svgSupported: true
  50. };
  51. }
  52. else {
  53. env = detect(navigator.userAgent);
  54. }
  55. var env$1 = env;
  56. // Zepto.js
  57. // (c) 2010-2013 Thomas Fuchs
  58. // Zepto.js may be freely distributed under the MIT license.
  59. function detect(ua) {
  60. var os = {};
  61. var browser = {};
  62. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  63. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  64. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  65. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  66. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  67. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  68. // var touchpad = webos && ua.match(/TouchPad/);
  69. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  70. // var silk = ua.match(/Silk\/([\d._]+)/);
  71. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  72. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  73. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  74. // var playbook = ua.match(/PlayBook/);
  75. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  76. var firefox = ua.match(/Firefox\/([\d.]+)/);
  77. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  78. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  79. var ie = ua.match(/MSIE\s([\d.]+)/)
  80. // IE 11 Trident/7.0; rv:11.0
  81. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  82. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  83. var weChat = (/micromessenger/i).test(ua);
  84. // Todo: clean this up with a better OS/browser seperation:
  85. // - discern (more) between multiple browsers on android
  86. // - decide if kindle fire in silk mode is android or not
  87. // - Firefox on Android doesn't specify the Android version
  88. // - possibly devide in os, device and browser hashes
  89. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  90. // if (android) os.android = true, os.version = android[2];
  91. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  92. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  93. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  94. // if (webos) os.webos = true, os.version = webos[2];
  95. // if (touchpad) os.touchpad = true;
  96. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  97. // if (bb10) os.bb10 = true, os.version = bb10[2];
  98. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  99. // if (playbook) browser.playbook = true;
  100. // if (kindle) os.kindle = true, os.version = kindle[1];
  101. // if (silk) browser.silk = true, browser.version = silk[1];
  102. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  103. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  104. if (firefox) {
  105. browser.firefox = true;
  106. browser.version = firefox[1];
  107. }
  108. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  109. // if (webview) browser.webview = true;
  110. if (ie) {
  111. browser.ie = true;
  112. browser.version = ie[1];
  113. }
  114. if (edge) {
  115. browser.edge = true;
  116. browser.version = edge[1];
  117. }
  118. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  119. // not be set on win phone. So we do not consider Win Phone.
  120. if (weChat) {
  121. browser.weChat = true;
  122. }
  123. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  124. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  125. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  126. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  127. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  128. return {
  129. browser: browser,
  130. os: os,
  131. node: false,
  132. // 原生canvas支持,改极端点了
  133. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  134. canvasSupported: !!document.createElement('canvas').getContext,
  135. svgSupported: typeof SVGRect !== 'undefined',
  136. // @see <http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript>
  137. // works on most browsers
  138. // IE10/11 does not support touch event, and MS Edge supports them but not by
  139. // default, so we dont check navigator.maxTouchPoints for them here.
  140. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  141. // <http://caniuse.com/#search=pointer%20event>.
  142. pointerEventsSupported: 'onpointerdown' in window
  143. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  144. // events currently. So we dont use that on other browsers unless tested sufficiently.
  145. // Although IE 10 supports pointer event, it use old style and is different from the
  146. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  147. && (browser.edge || (browser.ie && browser.version >= 11))
  148. };
  149. }
  150. /**
  151. * @module zrender/core/util
  152. */
  153. // 用于处理merge时无法遍历Date等对象的问题
  154. var BUILTIN_OBJECT = {
  155. '[object Function]': 1,
  156. '[object RegExp]': 1,
  157. '[object Date]': 1,
  158. '[object Error]': 1,
  159. '[object CanvasGradient]': 1,
  160. '[object CanvasPattern]': 1,
  161. // For node-canvas
  162. '[object Image]': 1,
  163. '[object Canvas]': 1
  164. };
  165. var TYPED_ARRAY = {
  166. '[object Int8Array]': 1,
  167. '[object Uint8Array]': 1,
  168. '[object Uint8ClampedArray]': 1,
  169. '[object Int16Array]': 1,
  170. '[object Uint16Array]': 1,
  171. '[object Int32Array]': 1,
  172. '[object Uint32Array]': 1,
  173. '[object Float32Array]': 1,
  174. '[object Float64Array]': 1
  175. };
  176. var objToString = Object.prototype.toString;
  177. var arrayProto = Array.prototype;
  178. var nativeForEach = arrayProto.forEach;
  179. var nativeFilter = arrayProto.filter;
  180. var nativeSlice = arrayProto.slice;
  181. var nativeMap = arrayProto.map;
  182. var nativeReduce = arrayProto.reduce;
  183. // Avoid assign to an exported variable, for transforming to cjs.
  184. var methods = {};
  185. function $override(name, fn) {
  186. methods[name] = fn;
  187. }
  188. /**
  189. * Those data types can be cloned:
  190. * Plain object, Array, TypedArray, number, string, null, undefined.
  191. * Those data types will be assgined using the orginal data:
  192. * BUILTIN_OBJECT
  193. * Instance of user defined class will be cloned to a plain object, without
  194. * properties in prototype.
  195. * Other data types is not supported (not sure what will happen).
  196. *
  197. * Caution: do not support clone Date, for performance consideration.
  198. * (There might be a large number of date in `series.data`).
  199. * So date should not be modified in and out of echarts.
  200. *
  201. * @param {*} source
  202. * @return {*} new
  203. */
  204. function clone(source) {
  205. if (source == null || typeof source != 'object') {
  206. return source;
  207. }
  208. var result = source;
  209. var typeStr = objToString.call(source);
  210. if (typeStr === '[object Array]') {
  211. result = [];
  212. for (var i = 0, len = source.length; i < len; i++) {
  213. result[i] = clone(source[i]);
  214. }
  215. }
  216. else if (TYPED_ARRAY[typeStr]) {
  217. var Ctor = source.constructor;
  218. if (source.constructor.from) {
  219. result = Ctor.from(source);
  220. }
  221. else {
  222. result = new Ctor(source.length);
  223. for (var i = 0, len = source.length; i < len; i++) {
  224. result[i] = clone(source[i]);
  225. }
  226. }
  227. }
  228. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  229. result = {};
  230. for (var key in source) {
  231. if (source.hasOwnProperty(key)) {
  232. result[key] = clone(source[key]);
  233. }
  234. }
  235. }
  236. return result;
  237. }
  238. /**
  239. * @memberOf module:zrender/core/util
  240. * @param {*} target
  241. * @param {*} source
  242. * @param {boolean} [overwrite=false]
  243. */
  244. function merge(target, source, overwrite) {
  245. // We should escapse that source is string
  246. // and enter for ... in ...
  247. if (!isObject(source) || !isObject(target)) {
  248. return overwrite ? clone(source) : target;
  249. }
  250. for (var key in source) {
  251. if (source.hasOwnProperty(key)) {
  252. var targetProp = target[key];
  253. var sourceProp = source[key];
  254. if (isObject(sourceProp)
  255. && isObject(targetProp)
  256. && !isArray(sourceProp)
  257. && !isArray(targetProp)
  258. && !isDom(sourceProp)
  259. && !isDom(targetProp)
  260. && !isBuiltInObject(sourceProp)
  261. && !isBuiltInObject(targetProp)
  262. && !isPrimitive(sourceProp)
  263. && !isPrimitive(targetProp)
  264. ) {
  265. // 如果需要递归覆盖,就递归调用merge
  266. merge(targetProp, sourceProp, overwrite);
  267. }
  268. else if (overwrite || !(key in target)) {
  269. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  270. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  271. target[key] = clone(source[key], true);
  272. }
  273. }
  274. }
  275. return target;
  276. }
  277. /**
  278. * @param {Array} targetAndSources The first item is target, and the rests are source.
  279. * @param {boolean} [overwrite=false]
  280. * @return {*} target
  281. */
  282. function mergeAll(targetAndSources, overwrite) {
  283. var result = targetAndSources[0];
  284. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  285. result = merge(result, targetAndSources[i], overwrite);
  286. }
  287. return result;
  288. }
  289. /**
  290. * @param {*} target
  291. * @param {*} source
  292. * @memberOf module:zrender/core/util
  293. */
  294. function extend(target, source) {
  295. for (var key in source) {
  296. if (source.hasOwnProperty(key)) {
  297. target[key] = source[key];
  298. }
  299. }
  300. return target;
  301. }
  302. /**
  303. * @param {*} target
  304. * @param {*} source
  305. * @param {boolean} [overlay=false]
  306. * @memberOf module:zrender/core/util
  307. */
  308. function defaults(target, source, overlay) {
  309. for (var key in source) {
  310. if (source.hasOwnProperty(key)
  311. && (overlay ? source[key] != null : target[key] == null)
  312. ) {
  313. target[key] = source[key];
  314. }
  315. }
  316. return target;
  317. }
  318. var createCanvas = function () {
  319. return methods.createCanvas();
  320. };
  321. methods.createCanvas = function () {
  322. return document.createElement('canvas');
  323. };
  324. // FIXME
  325. var _ctx;
  326. function getContext() {
  327. if (!_ctx) {
  328. // Use util.createCanvas instead of createCanvas
  329. // because createCanvas may be overwritten in different environment
  330. _ctx = createCanvas().getContext('2d');
  331. }
  332. return _ctx;
  333. }
  334. /**
  335. * 查询数组中元素的index
  336. * @memberOf module:zrender/core/util
  337. */
  338. function indexOf(array, value) {
  339. if (array) {
  340. if (array.indexOf) {
  341. return array.indexOf(value);
  342. }
  343. for (var i = 0, len = array.length; i < len; i++) {
  344. if (array[i] === value) {
  345. return i;
  346. }
  347. }
  348. }
  349. return -1;
  350. }
  351. /**
  352. * 构造类继承关系
  353. *
  354. * @memberOf module:zrender/core/util
  355. * @param {Function} clazz 源类
  356. * @param {Function} baseClazz 基类
  357. */
  358. function inherits(clazz, baseClazz) {
  359. var clazzPrototype = clazz.prototype;
  360. function F() {}
  361. F.prototype = baseClazz.prototype;
  362. clazz.prototype = new F();
  363. for (var prop in clazzPrototype) {
  364. clazz.prototype[prop] = clazzPrototype[prop];
  365. }
  366. clazz.prototype.constructor = clazz;
  367. clazz.superClass = baseClazz;
  368. }
  369. /**
  370. * @memberOf module:zrender/core/util
  371. * @param {Object|Function} target
  372. * @param {Object|Function} sorce
  373. * @param {boolean} overlay
  374. */
  375. function mixin(target, source, overlay) {
  376. target = 'prototype' in target ? target.prototype : target;
  377. source = 'prototype' in source ? source.prototype : source;
  378. defaults(target, source, overlay);
  379. }
  380. /**
  381. * Consider typed array.
  382. * @param {Array|TypedArray} data
  383. */
  384. function isArrayLike(data) {
  385. if (! data) {
  386. return;
  387. }
  388. if (typeof data == 'string') {
  389. return false;
  390. }
  391. return typeof data.length == 'number';
  392. }
  393. /**
  394. * 数组或对象遍历
  395. * @memberOf module:zrender/core/util
  396. * @param {Object|Array} obj
  397. * @param {Function} cb
  398. * @param {*} [context]
  399. */
  400. function each$1(obj, cb, context) {
  401. if (!(obj && cb)) {
  402. return;
  403. }
  404. if (obj.forEach && obj.forEach === nativeForEach) {
  405. obj.forEach(cb, context);
  406. }
  407. else if (obj.length === +obj.length) {
  408. for (var i = 0, len = obj.length; i < len; i++) {
  409. cb.call(context, obj[i], i, obj);
  410. }
  411. }
  412. else {
  413. for (var key in obj) {
  414. if (obj.hasOwnProperty(key)) {
  415. cb.call(context, obj[key], key, obj);
  416. }
  417. }
  418. }
  419. }
  420. /**
  421. * 数组映射
  422. * @memberOf module:zrender/core/util
  423. * @param {Array} obj
  424. * @param {Function} cb
  425. * @param {*} [context]
  426. * @return {Array}
  427. */
  428. function map(obj, cb, context) {
  429. if (!(obj && cb)) {
  430. return;
  431. }
  432. if (obj.map && obj.map === nativeMap) {
  433. return obj.map(cb, context);
  434. }
  435. else {
  436. var result = [];
  437. for (var i = 0, len = obj.length; i < len; i++) {
  438. result.push(cb.call(context, obj[i], i, obj));
  439. }
  440. return result;
  441. }
  442. }
  443. /**
  444. * @memberOf module:zrender/core/util
  445. * @param {Array} obj
  446. * @param {Function} cb
  447. * @param {Object} [memo]
  448. * @param {*} [context]
  449. * @return {Array}
  450. */
  451. function reduce(obj, cb, memo, context) {
  452. if (!(obj && cb)) {
  453. return;
  454. }
  455. if (obj.reduce && obj.reduce === nativeReduce) {
  456. return obj.reduce(cb, memo, context);
  457. }
  458. else {
  459. for (var i = 0, len = obj.length; i < len; i++) {
  460. memo = cb.call(context, memo, obj[i], i, obj);
  461. }
  462. return memo;
  463. }
  464. }
  465. /**
  466. * 数组过滤
  467. * @memberOf module:zrender/core/util
  468. * @param {Array} obj
  469. * @param {Function} cb
  470. * @param {*} [context]
  471. * @return {Array}
  472. */
  473. function filter(obj, cb, context) {
  474. if (!(obj && cb)) {
  475. return;
  476. }
  477. if (obj.filter && obj.filter === nativeFilter) {
  478. return obj.filter(cb, context);
  479. }
  480. else {
  481. var result = [];
  482. for (var i = 0, len = obj.length; i < len; i++) {
  483. if (cb.call(context, obj[i], i, obj)) {
  484. result.push(obj[i]);
  485. }
  486. }
  487. return result;
  488. }
  489. }
  490. /**
  491. * 数组项查找
  492. * @memberOf module:zrender/core/util
  493. * @param {Array} obj
  494. * @param {Function} cb
  495. * @param {*} [context]
  496. * @return {*}
  497. */
  498. function find(obj, cb, context) {
  499. if (!(obj && cb)) {
  500. return;
  501. }
  502. for (var i = 0, len = obj.length; i < len; i++) {
  503. if (cb.call(context, obj[i], i, obj)) {
  504. return obj[i];
  505. }
  506. }
  507. }
  508. /**
  509. * @memberOf module:zrender/core/util
  510. * @param {Function} func
  511. * @param {*} context
  512. * @return {Function}
  513. */
  514. function bind(func, context) {
  515. var args = nativeSlice.call(arguments, 2);
  516. return function () {
  517. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  518. };
  519. }
  520. /**
  521. * @memberOf module:zrender/core/util
  522. * @param {Function} func
  523. * @return {Function}
  524. */
  525. function curry(func) {
  526. var args = nativeSlice.call(arguments, 1);
  527. return function () {
  528. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  529. };
  530. }
  531. /**
  532. * @memberOf module:zrender/core/util
  533. * @param {*} value
  534. * @return {boolean}
  535. */
  536. function isArray(value) {
  537. return objToString.call(value) === '[object Array]';
  538. }
  539. /**
  540. * @memberOf module:zrender/core/util
  541. * @param {*} value
  542. * @return {boolean}
  543. */
  544. function isFunction(value) {
  545. return typeof value === 'function';
  546. }
  547. /**
  548. * @memberOf module:zrender/core/util
  549. * @param {*} value
  550. * @return {boolean}
  551. */
  552. function isString(value) {
  553. return objToString.call(value) === '[object String]';
  554. }
  555. /**
  556. * @memberOf module:zrender/core/util
  557. * @param {*} value
  558. * @return {boolean}
  559. */
  560. function isObject(value) {
  561. // Avoid a V8 JIT bug in Chrome 19-20.
  562. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  563. var type = typeof value;
  564. return type === 'function' || (!!value && type == 'object');
  565. }
  566. /**
  567. * @memberOf module:zrender/core/util
  568. * @param {*} value
  569. * @return {boolean}
  570. */
  571. function isBuiltInObject(value) {
  572. return !!BUILTIN_OBJECT[objToString.call(value)];
  573. }
  574. /**
  575. * @memberOf module:zrender/core/util
  576. * @param {*} value
  577. * @return {boolean}
  578. */
  579. function isDom(value) {
  580. return typeof value === 'object'
  581. && typeof value.nodeType === 'number'
  582. && typeof value.ownerDocument === 'object';
  583. }
  584. /**
  585. * Whether is exactly NaN. Notice isNaN('a') returns true.
  586. * @param {*} value
  587. * @return {boolean}
  588. */
  589. function eqNaN(value) {
  590. return value !== value;
  591. }
  592. /**
  593. * If value1 is not null, then return value1, otherwise judget rest of values.
  594. * Low performance.
  595. * @memberOf module:zrender/core/util
  596. * @return {*} Final value
  597. */
  598. function retrieve(values) {
  599. for (var i = 0, len = arguments.length; i < len; i++) {
  600. if (arguments[i] != null) {
  601. return arguments[i];
  602. }
  603. }
  604. }
  605. function retrieve2(value0, value1) {
  606. return value0 != null
  607. ? value0
  608. : value1;
  609. }
  610. function retrieve3(value0, value1, value2) {
  611. return value0 != null
  612. ? value0
  613. : value1 != null
  614. ? value1
  615. : value2;
  616. }
  617. /**
  618. * @memberOf module:zrender/core/util
  619. * @param {Array} arr
  620. * @param {number} startIndex
  621. * @param {number} endIndex
  622. * @return {Array}
  623. */
  624. function slice() {
  625. return Function.call.apply(nativeSlice, arguments);
  626. }
  627. /**
  628. * Normalize css liked array configuration
  629. * e.g.
  630. * 3 => [3, 3, 3, 3]
  631. * [4, 2] => [4, 2, 4, 2]
  632. * [4, 3, 2] => [4, 3, 2, 3]
  633. * @param {number|Array.<number>} val
  634. * @return {Array.<number>}
  635. */
  636. function normalizeCssArray(val) {
  637. if (typeof (val) === 'number') {
  638. return [val, val, val, val];
  639. }
  640. var len = val.length;
  641. if (len === 2) {
  642. // vertical | horizontal
  643. return [val[0], val[1], val[0], val[1]];
  644. }
  645. else if (len === 3) {
  646. // top | horizontal | bottom
  647. return [val[0], val[1], val[2], val[1]];
  648. }
  649. return val;
  650. }
  651. /**
  652. * @memberOf module:zrender/core/util
  653. * @param {boolean} condition
  654. * @param {string} message
  655. */
  656. function assert(condition, message) {
  657. if (!condition) {
  658. throw new Error(message);
  659. }
  660. }
  661. var primitiveKey = '__ec_primitive__';
  662. /**
  663. * Set an object as primitive to be ignored traversing children in clone or merge
  664. */
  665. function setAsPrimitive(obj) {
  666. obj[primitiveKey] = true;
  667. }
  668. function isPrimitive(obj) {
  669. return obj[primitiveKey];
  670. }
  671. /**
  672. * @constructor
  673. * @param {Object} obj Only apply `ownProperty`.
  674. */
  675. function HashMap(obj) {
  676. obj && each$1(obj, function (value, key) {
  677. this.set(key, value);
  678. }, this);
  679. }
  680. // Add prefix to avoid conflict with Object.prototype.
  681. var HASH_MAP_PREFIX = '_ec_';
  682. var HASH_MAP_PREFIX_LENGTH = 4;
  683. HashMap.prototype = {
  684. constructor: HashMap,
  685. // Do not provide `has` method to avoid defining what is `has`.
  686. // (We usually treat `null` and `undefined` as the same, different
  687. // from ES6 Map).
  688. get: function (key) {
  689. return this[HASH_MAP_PREFIX + key];
  690. },
  691. set: function (key, value) {
  692. this[HASH_MAP_PREFIX + key] = value;
  693. // Comparing with invocation chaining, `return value` is more commonly
  694. // used in this case: `var someVal = map.set('a', genVal());`
  695. return value;
  696. },
  697. // Although util.each can be performed on this hashMap directly, user
  698. // should not use the exposed keys, who are prefixed.
  699. each: function (cb, context) {
  700. context !== void 0 && (cb = bind(cb, context));
  701. for (var prefixedKey in this) {
  702. this.hasOwnProperty(prefixedKey)
  703. && cb(this[prefixedKey], prefixedKey.slice(HASH_MAP_PREFIX_LENGTH));
  704. }
  705. },
  706. // Do not use this method if performance sensitive.
  707. removeKey: function (key) {
  708. delete this[HASH_MAP_PREFIX + key];
  709. }
  710. };
  711. function createHashMap(obj) {
  712. return new HashMap(obj);
  713. }
  714. function noop() {}
  715. var zrUtil = (Object.freeze || Object)({
  716. $override: $override,
  717. clone: clone,
  718. merge: merge,
  719. mergeAll: mergeAll,
  720. extend: extend,
  721. defaults: defaults,
  722. createCanvas: createCanvas,
  723. getContext: getContext,
  724. indexOf: indexOf,
  725. inherits: inherits,
  726. mixin: mixin,
  727. isArrayLike: isArrayLike,
  728. each: each$1,
  729. map: map,
  730. reduce: reduce,
  731. filter: filter,
  732. find: find,
  733. bind: bind,
  734. curry: curry,
  735. isArray: isArray,
  736. isFunction: isFunction,
  737. isString: isString,
  738. isObject: isObject,
  739. isBuiltInObject: isBuiltInObject,
  740. isDom: isDom,
  741. eqNaN: eqNaN,
  742. retrieve: retrieve,
  743. retrieve2: retrieve2,
  744. retrieve3: retrieve3,
  745. slice: slice,
  746. normalizeCssArray: normalizeCssArray,
  747. assert: assert,
  748. setAsPrimitive: setAsPrimitive,
  749. isPrimitive: isPrimitive,
  750. createHashMap: createHashMap,
  751. noop: noop
  752. });
  753. var ArrayCtor = typeof Float32Array === 'undefined'
  754. ? Array
  755. : Float32Array;
  756. /**
  757. * 创建一个向量
  758. * @param {number} [x=0]
  759. * @param {number} [y=0]
  760. * @return {Vector2}
  761. */
  762. function create(x, y) {
  763. var out = new ArrayCtor(2);
  764. if (x == null) {
  765. x = 0;
  766. }
  767. if (y == null) {
  768. y = 0;
  769. }
  770. out[0] = x;
  771. out[1] = y;
  772. return out;
  773. }
  774. /**
  775. * 复制向量数据
  776. * @param {Vector2} out
  777. * @param {Vector2} v
  778. * @return {Vector2}
  779. */
  780. function copy(out, v) {
  781. out[0] = v[0];
  782. out[1] = v[1];
  783. return out;
  784. }
  785. /**
  786. * 克隆一个向量
  787. * @param {Vector2} v
  788. * @return {Vector2}
  789. */
  790. function clone$1(v) {
  791. var out = new ArrayCtor(2);
  792. out[0] = v[0];
  793. out[1] = v[1];
  794. return out;
  795. }
  796. /**
  797. * 设置向量的两个项
  798. * @param {Vector2} out
  799. * @param {number} a
  800. * @param {number} b
  801. * @return {Vector2} 结果
  802. */
  803. function set(out, a, b) {
  804. out[0] = a;
  805. out[1] = b;
  806. return out;
  807. }
  808. /**
  809. * 向量相加
  810. * @param {Vector2} out
  811. * @param {Vector2} v1
  812. * @param {Vector2} v2
  813. */
  814. function add(out, v1, v2) {
  815. out[0] = v1[0] + v2[0];
  816. out[1] = v1[1] + v2[1];
  817. return out;
  818. }
  819. /**
  820. * 向量缩放后相加
  821. * @param {Vector2} out
  822. * @param {Vector2} v1
  823. * @param {Vector2} v2
  824. * @param {number} a
  825. */
  826. function scaleAndAdd(out, v1, v2, a) {
  827. out[0] = v1[0] + v2[0] * a;
  828. out[1] = v1[1] + v2[1] * a;
  829. return out;
  830. }
  831. /**
  832. * 向量相减
  833. * @param {Vector2} out
  834. * @param {Vector2} v1
  835. * @param {Vector2} v2
  836. */
  837. function sub(out, v1, v2) {
  838. out[0] = v1[0] - v2[0];
  839. out[1] = v1[1] - v2[1];
  840. return out;
  841. }
  842. /**
  843. * 向量长度
  844. * @param {Vector2} v
  845. * @return {number}
  846. */
  847. function len(v) {
  848. return Math.sqrt(lenSquare(v));
  849. }
  850. var length = len; // jshint ignore:line
  851. /**
  852. * 向量长度平方
  853. * @param {Vector2} v
  854. * @return {number}
  855. */
  856. function lenSquare(v) {
  857. return v[0] * v[0] + v[1] * v[1];
  858. }
  859. var lengthSquare = lenSquare;
  860. /**
  861. * 向量乘法
  862. * @param {Vector2} out
  863. * @param {Vector2} v1
  864. * @param {Vector2} v2
  865. */
  866. function mul(out, v1, v2) {
  867. out[0] = v1[0] * v2[0];
  868. out[1] = v1[1] * v2[1];
  869. return out;
  870. }
  871. /**
  872. * 向量除法
  873. * @param {Vector2} out
  874. * @param {Vector2} v1
  875. * @param {Vector2} v2
  876. */
  877. function div(out, v1, v2) {
  878. out[0] = v1[0] / v2[0];
  879. out[1] = v1[1] / v2[1];
  880. return out;
  881. }
  882. /**
  883. * 向量点乘
  884. * @param {Vector2} v1
  885. * @param {Vector2} v2
  886. * @return {number}
  887. */
  888. function dot(v1, v2) {
  889. return v1[0] * v2[0] + v1[1] * v2[1];
  890. }
  891. /**
  892. * 向量缩放
  893. * @param {Vector2} out
  894. * @param {Vector2} v
  895. * @param {number} s
  896. */
  897. function scale(out, v, s) {
  898. out[0] = v[0] * s;
  899. out[1] = v[1] * s;
  900. return out;
  901. }
  902. /**
  903. * 向量归一化
  904. * @param {Vector2} out
  905. * @param {Vector2} v
  906. */
  907. function normalize(out, v) {
  908. var d = len(v);
  909. if (d === 0) {
  910. out[0] = 0;
  911. out[1] = 0;
  912. }
  913. else {
  914. out[0] = v[0] / d;
  915. out[1] = v[1] / d;
  916. }
  917. return out;
  918. }
  919. /**
  920. * 计算向量间距离
  921. * @param {Vector2} v1
  922. * @param {Vector2} v2
  923. * @return {number}
  924. */
  925. function distance(v1, v2) {
  926. return Math.sqrt(
  927. (v1[0] - v2[0]) * (v1[0] - v2[0])
  928. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  929. );
  930. }
  931. var dist = distance;
  932. /**
  933. * 向量距离平方
  934. * @param {Vector2} v1
  935. * @param {Vector2} v2
  936. * @return {number}
  937. */
  938. function distanceSquare(v1, v2) {
  939. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  940. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  941. }
  942. var distSquare = distanceSquare;
  943. /**
  944. * 求负向量
  945. * @param {Vector2} out
  946. * @param {Vector2} v
  947. */
  948. function negate(out, v) {
  949. out[0] = -v[0];
  950. out[1] = -v[1];
  951. return out;
  952. }
  953. /**
  954. * 插值两个点
  955. * @param {Vector2} out
  956. * @param {Vector2} v1
  957. * @param {Vector2} v2
  958. * @param {number} t
  959. */
  960. function lerp(out, v1, v2, t) {
  961. out[0] = v1[0] + t * (v2[0] - v1[0]);
  962. out[1] = v1[1] + t * (v2[1] - v1[1]);
  963. return out;
  964. }
  965. /**
  966. * 矩阵左乘向量
  967. * @param {Vector2} out
  968. * @param {Vector2} v
  969. * @param {Vector2} m
  970. */
  971. function applyTransform(out, v, m) {
  972. var x = v[0];
  973. var y = v[1];
  974. out[0] = m[0] * x + m[2] * y + m[4];
  975. out[1] = m[1] * x + m[3] * y + m[5];
  976. return out;
  977. }
  978. /**
  979. * 求两个向量最小值
  980. * @param {Vector2} out
  981. * @param {Vector2} v1
  982. * @param {Vector2} v2
  983. */
  984. function min(out, v1, v2) {
  985. out[0] = Math.min(v1[0], v2[0]);
  986. out[1] = Math.min(v1[1], v2[1]);
  987. return out;
  988. }
  989. /**
  990. * 求两个向量最大值
  991. * @param {Vector2} out
  992. * @param {Vector2} v1
  993. * @param {Vector2} v2
  994. */
  995. function max(out, v1, v2) {
  996. out[0] = Math.max(v1[0], v2[0]);
  997. out[1] = Math.max(v1[1], v2[1]);
  998. return out;
  999. }
  1000. var vector = (Object.freeze || Object)({
  1001. create: create,
  1002. copy: copy,
  1003. clone: clone$1,
  1004. set: set,
  1005. add: add,
  1006. scaleAndAdd: scaleAndAdd,
  1007. sub: sub,
  1008. len: len,
  1009. length: length,
  1010. lenSquare: lenSquare,
  1011. lengthSquare: lengthSquare,
  1012. mul: mul,
  1013. div: div,
  1014. dot: dot,
  1015. scale: scale,
  1016. normalize: normalize,
  1017. distance: distance,
  1018. dist: dist,
  1019. distanceSquare: distanceSquare,
  1020. distSquare: distSquare,
  1021. negate: negate,
  1022. lerp: lerp,
  1023. applyTransform: applyTransform,
  1024. min: min,
  1025. max: max
  1026. });
  1027. // TODO Draggable for group
  1028. // FIXME Draggable on element which has parent rotation or scale
  1029. function Draggable() {
  1030. this.on('mousedown', this._dragStart, this);
  1031. this.on('mousemove', this._drag, this);
  1032. this.on('mouseup', this._dragEnd, this);
  1033. this.on('globalout', this._dragEnd, this);
  1034. // this._dropTarget = null;
  1035. // this._draggingTarget = null;
  1036. // this._x = 0;
  1037. // this._y = 0;
  1038. }
  1039. Draggable.prototype = {
  1040. constructor: Draggable,
  1041. _dragStart: function (e) {
  1042. var draggingTarget = e.target;
  1043. if (draggingTarget && draggingTarget.draggable) {
  1044. this._draggingTarget = draggingTarget;
  1045. draggingTarget.dragging = true;
  1046. this._x = e.offsetX;
  1047. this._y = e.offsetY;
  1048. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1049. }
  1050. },
  1051. _drag: function (e) {
  1052. var draggingTarget = this._draggingTarget;
  1053. if (draggingTarget) {
  1054. var x = e.offsetX;
  1055. var y = e.offsetY;
  1056. var dx = x - this._x;
  1057. var dy = y - this._y;
  1058. this._x = x;
  1059. this._y = y;
  1060. draggingTarget.drift(dx, dy, e);
  1061. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1062. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1063. var lastDropTarget = this._dropTarget;
  1064. this._dropTarget = dropTarget;
  1065. if (draggingTarget !== dropTarget) {
  1066. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1067. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1068. }
  1069. if (dropTarget && dropTarget !== lastDropTarget) {
  1070. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1071. }
  1072. }
  1073. }
  1074. },
  1075. _dragEnd: function (e) {
  1076. var draggingTarget = this._draggingTarget;
  1077. if (draggingTarget) {
  1078. draggingTarget.dragging = false;
  1079. }
  1080. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1081. if (this._dropTarget) {
  1082. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1083. }
  1084. this._draggingTarget = null;
  1085. this._dropTarget = null;
  1086. }
  1087. };
  1088. function param(target, e) {
  1089. return {target: target, topTarget: e && e.topTarget};
  1090. }
  1091. /**
  1092. * 事件扩展
  1093. * @module zrender/mixin/Eventful
  1094. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1095. * pissang (https://www.github.com/pissang)
  1096. */
  1097. var arrySlice = Array.prototype.slice;
  1098. /**
  1099. * 事件分发器
  1100. * @alias module:zrender/mixin/Eventful
  1101. * @constructor
  1102. */
  1103. var Eventful = function () {
  1104. this._$handlers = {};
  1105. };
  1106. Eventful.prototype = {
  1107. constructor: Eventful,
  1108. /**
  1109. * 单次触发绑定,trigger后销毁
  1110. *
  1111. * @param {string} event 事件名
  1112. * @param {Function} handler 响应函数
  1113. * @param {Object} context
  1114. */
  1115. one: function (event, handler, context) {
  1116. var _h = this._$handlers;
  1117. if (!handler || !event) {
  1118. return this;
  1119. }
  1120. if (!_h[event]) {
  1121. _h[event] = [];
  1122. }
  1123. for (var i = 0; i < _h[event].length; i++) {
  1124. if (_h[event][i].h === handler) {
  1125. return this;
  1126. }
  1127. }
  1128. _h[event].push({
  1129. h: handler,
  1130. one: true,
  1131. ctx: context || this
  1132. });
  1133. return this;
  1134. },
  1135. /**
  1136. * 绑定事件
  1137. * @param {string} event 事件名
  1138. * @param {Function} handler 事件处理函数
  1139. * @param {Object} [context]
  1140. */
  1141. on: function (event, handler, context) {
  1142. var _h = this._$handlers;
  1143. if (!handler || !event) {
  1144. return this;
  1145. }
  1146. if (!_h[event]) {
  1147. _h[event] = [];
  1148. }
  1149. for (var i = 0; i < _h[event].length; i++) {
  1150. if (_h[event][i].h === handler) {
  1151. return this;
  1152. }
  1153. }
  1154. _h[event].push({
  1155. h: handler,
  1156. one: false,
  1157. ctx: context || this
  1158. });
  1159. return this;
  1160. },
  1161. /**
  1162. * 是否绑定了事件
  1163. * @param {string} event
  1164. * @return {boolean}
  1165. */
  1166. isSilent: function (event) {
  1167. var _h = this._$handlers;
  1168. return _h[event] && _h[event].length;
  1169. },
  1170. /**
  1171. * 解绑事件
  1172. * @param {string} event 事件名
  1173. * @param {Function} [handler] 事件处理函数
  1174. */
  1175. off: function (event, handler) {
  1176. var _h = this._$handlers;
  1177. if (!event) {
  1178. this._$handlers = {};
  1179. return this;
  1180. }
  1181. if (handler) {
  1182. if (_h[event]) {
  1183. var newList = [];
  1184. for (var i = 0, l = _h[event].length; i < l; i++) {
  1185. if (_h[event][i]['h'] != handler) {
  1186. newList.push(_h[event][i]);
  1187. }
  1188. }
  1189. _h[event] = newList;
  1190. }
  1191. if (_h[event] && _h[event].length === 0) {
  1192. delete _h[event];
  1193. }
  1194. }
  1195. else {
  1196. delete _h[event];
  1197. }
  1198. return this;
  1199. },
  1200. /**
  1201. * 事件分发
  1202. *
  1203. * @param {string} type 事件类型
  1204. */
  1205. trigger: function (type) {
  1206. if (this._$handlers[type]) {
  1207. var args = arguments;
  1208. var argLen = args.length;
  1209. if (argLen > 3) {
  1210. args = arrySlice.call(args, 1);
  1211. }
  1212. var _h = this._$handlers[type];
  1213. var len = _h.length;
  1214. for (var i = 0; i < len;) {
  1215. // Optimize advise from backbone
  1216. switch (argLen) {
  1217. case 1:
  1218. _h[i]['h'].call(_h[i]['ctx']);
  1219. break;
  1220. case 2:
  1221. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1222. break;
  1223. case 3:
  1224. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1225. break;
  1226. default:
  1227. // have more than 2 given arguments
  1228. _h[i]['h'].apply(_h[i]['ctx'], args);
  1229. break;
  1230. }
  1231. if (_h[i]['one']) {
  1232. _h.splice(i, 1);
  1233. len--;
  1234. }
  1235. else {
  1236. i++;
  1237. }
  1238. }
  1239. }
  1240. return this;
  1241. },
  1242. /**
  1243. * 带有context的事件分发, 最后一个参数是事件回调的context
  1244. * @param {string} type 事件类型
  1245. */
  1246. triggerWithContext: function (type) {
  1247. if (this._$handlers[type]) {
  1248. var args = arguments;
  1249. var argLen = args.length;
  1250. if (argLen > 4) {
  1251. args = arrySlice.call(args, 1, args.length - 1);
  1252. }
  1253. var ctx = args[args.length - 1];
  1254. var _h = this._$handlers[type];
  1255. var len = _h.length;
  1256. for (var i = 0; i < len;) {
  1257. // Optimize advise from backbone
  1258. switch (argLen) {
  1259. case 1:
  1260. _h[i]['h'].call(ctx);
  1261. break;
  1262. case 2:
  1263. _h[i]['h'].call(ctx, args[1]);
  1264. break;
  1265. case 3:
  1266. _h[i]['h'].call(ctx, args[1], args[2]);
  1267. break;
  1268. default:
  1269. // have more than 2 given arguments
  1270. _h[i]['h'].apply(ctx, args);
  1271. break;
  1272. }
  1273. if (_h[i]['one']) {
  1274. _h.splice(i, 1);
  1275. len--;
  1276. }
  1277. else {
  1278. i++;
  1279. }
  1280. }
  1281. }
  1282. return this;
  1283. }
  1284. };
  1285. /**
  1286. * Handler
  1287. * @module zrender/Handler
  1288. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1289. * errorrik (errorrik@gmail.com)
  1290. * pissang (shenyi.914@gmail.com)
  1291. */
  1292. var SILENT = 'silent';
  1293. function makeEventPacket(eveType, targetInfo, event) {
  1294. return {
  1295. type: eveType,
  1296. event: event,
  1297. // target can only be an element that is not silent.
  1298. target: targetInfo.target,
  1299. // topTarget can be a silent element.
  1300. topTarget: targetInfo.topTarget,
  1301. cancelBubble: false,
  1302. offsetX: event.zrX,
  1303. offsetY: event.zrY,
  1304. gestureEvent: event.gestureEvent,
  1305. pinchX: event.pinchX,
  1306. pinchY: event.pinchY,
  1307. pinchScale: event.pinchScale,
  1308. wheelDelta: event.zrDelta,
  1309. zrByTouch: event.zrByTouch,
  1310. which: event.which
  1311. };
  1312. }
  1313. function EmptyProxy () {}
  1314. EmptyProxy.prototype.dispose = function () {};
  1315. var handlerNames = [
  1316. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1317. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1318. ];
  1319. /**
  1320. * @alias module:zrender/Handler
  1321. * @constructor
  1322. * @extends module:zrender/mixin/Eventful
  1323. * @param {module:zrender/Storage} storage Storage instance.
  1324. * @param {module:zrender/Painter} painter Painter instance.
  1325. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1326. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1327. */
  1328. var Handler = function(storage, painter, proxy, painterRoot) {
  1329. Eventful.call(this);
  1330. this.storage = storage;
  1331. this.painter = painter;
  1332. this.painterRoot = painterRoot;
  1333. proxy = proxy || new EmptyProxy();
  1334. /**
  1335. * Proxy of event. can be Dom, WebGLSurface, etc.
  1336. */
  1337. this.proxy = proxy;
  1338. // Attach handler
  1339. proxy.handler = this;
  1340. /**
  1341. * {target, topTarget, x, y}
  1342. * @private
  1343. * @type {Object}
  1344. */
  1345. this._hovered = {};
  1346. /**
  1347. * @private
  1348. * @type {Date}
  1349. */
  1350. this._lastTouchMoment;
  1351. /**
  1352. * @private
  1353. * @type {number}
  1354. */
  1355. this._lastX;
  1356. /**
  1357. * @private
  1358. * @type {number}
  1359. */
  1360. this._lastY;
  1361. Draggable.call(this);
  1362. each$1(handlerNames, function (name) {
  1363. proxy.on && proxy.on(name, this[name], this);
  1364. }, this);
  1365. };
  1366. Handler.prototype = {
  1367. constructor: Handler,
  1368. mousemove: function (event) {
  1369. var x = event.zrX;
  1370. var y = event.zrY;
  1371. var lastHovered = this._hovered;
  1372. var lastHoveredTarget = lastHovered.target;
  1373. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1374. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1375. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1376. // See #6198.
  1377. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1378. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1379. lastHoveredTarget = lastHovered.target;
  1380. }
  1381. var hovered = this._hovered = this.findHover(x, y);
  1382. var hoveredTarget = hovered.target;
  1383. var proxy = this.proxy;
  1384. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1385. // Mouse out on previous hovered element
  1386. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1387. this.dispatchToElement(lastHovered, 'mouseout', event);
  1388. }
  1389. // Mouse moving on one element
  1390. this.dispatchToElement(hovered, 'mousemove', event);
  1391. // Mouse over on a new element
  1392. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1393. this.dispatchToElement(hovered, 'mouseover', event);
  1394. }
  1395. },
  1396. mouseout: function (event) {
  1397. this.dispatchToElement(this._hovered, 'mouseout', event);
  1398. // There might be some doms created by upper layer application
  1399. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1400. // dom created by echarts), where 'globalout' event should not
  1401. // be triggered when mouse enters these doms. (But 'mouseout'
  1402. // should be triggered at the original hovered element as usual).
  1403. var element = event.toElement || event.relatedTarget;
  1404. var innerDom;
  1405. do {
  1406. element = element && element.parentNode;
  1407. }
  1408. while (element && element.nodeType != 9 && !(
  1409. innerDom = element === this.painterRoot
  1410. ));
  1411. !innerDom && this.trigger('globalout', {event: event});
  1412. },
  1413. /**
  1414. * Resize
  1415. */
  1416. resize: function (event) {
  1417. this._hovered = {};
  1418. },
  1419. /**
  1420. * Dispatch event
  1421. * @param {string} eventName
  1422. * @param {event=} eventArgs
  1423. */
  1424. dispatch: function (eventName, eventArgs) {
  1425. var handler = this[eventName];
  1426. handler && handler.call(this, eventArgs);
  1427. },
  1428. /**
  1429. * Dispose
  1430. */
  1431. dispose: function () {
  1432. this.proxy.dispose();
  1433. this.storage =
  1434. this.proxy =
  1435. this.painter = null;
  1436. },
  1437. /**
  1438. * 设置默认的cursor style
  1439. * @param {string} [cursorStyle='default'] 例如 crosshair
  1440. */
  1441. setCursorStyle: function (cursorStyle) {
  1442. var proxy = this.proxy;
  1443. proxy.setCursor && proxy.setCursor(cursorStyle);
  1444. },
  1445. /**
  1446. * 事件分发代理
  1447. *
  1448. * @private
  1449. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1450. * @param {string} eventName 事件名称
  1451. * @param {Object} event 事件对象
  1452. */
  1453. dispatchToElement: function (targetInfo, eventName, event) {
  1454. targetInfo = targetInfo || {};
  1455. var el = targetInfo.target;
  1456. if (el && el.silent) {
  1457. return;
  1458. }
  1459. var eventHandler = 'on' + eventName;
  1460. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1461. while (el) {
  1462. el[eventHandler]
  1463. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1464. el.trigger(eventName, eventPacket);
  1465. el = el.parent;
  1466. if (eventPacket.cancelBubble) {
  1467. break;
  1468. }
  1469. }
  1470. if (!eventPacket.cancelBubble) {
  1471. // 冒泡到顶级 zrender 对象
  1472. this.trigger(eventName, eventPacket);
  1473. // 分发事件到用户自定义层
  1474. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1475. this.painter && this.painter.eachOtherLayer(function (layer) {
  1476. if (typeof(layer[eventHandler]) == 'function') {
  1477. layer[eventHandler].call(layer, eventPacket);
  1478. }
  1479. if (layer.trigger) {
  1480. layer.trigger(eventName, eventPacket);
  1481. }
  1482. });
  1483. }
  1484. },
  1485. /**
  1486. * @private
  1487. * @param {number} x
  1488. * @param {number} y
  1489. * @param {module:zrender/graphic/Displayable} exclude
  1490. * @return {model:zrender/Element}
  1491. * @method
  1492. */
  1493. findHover: function(x, y, exclude) {
  1494. var list = this.storage.getDisplayList();
  1495. var out = {x: x, y: y};
  1496. for (var i = list.length - 1; i >= 0 ; i--) {
  1497. var hoverCheckResult;
  1498. if (list[i] !== exclude
  1499. // getDisplayList may include ignored item in VML mode
  1500. && !list[i].ignore
  1501. && (hoverCheckResult = isHover(list[i], x, y))
  1502. ) {
  1503. !out.topTarget && (out.topTarget = list[i]);
  1504. if (hoverCheckResult !== SILENT) {
  1505. out.target = list[i];
  1506. break;
  1507. }
  1508. }
  1509. }
  1510. return out;
  1511. }
  1512. };
  1513. // Common handlers
  1514. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1515. Handler.prototype[name] = function (event) {
  1516. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1517. var hovered = this.findHover(event.zrX, event.zrY);
  1518. var hoveredTarget = hovered.target;
  1519. if (name === 'mousedown') {
  1520. this._downEl = hoveredTarget;
  1521. this._downPoint = [event.zrX, event.zrY];
  1522. // In case click triggered before mouseup
  1523. this._upEl = hoveredTarget;
  1524. }
  1525. else if (name === 'mosueup') {
  1526. this._upEl = hoveredTarget;
  1527. }
  1528. else if (name === 'click') {
  1529. if (this._downEl !== this._upEl
  1530. // Original click event is triggered on the whole canvas element,
  1531. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1532. // which should be filtered, otherwise it will bring trouble to
  1533. // pan and zoom.
  1534. || !this._downPoint
  1535. // Arbitrary value
  1536. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1537. ) {
  1538. return;
  1539. }
  1540. this._downPoint = null;
  1541. }
  1542. this.dispatchToElement(hovered, name, event);
  1543. };
  1544. });
  1545. function isHover(displayable, x, y) {
  1546. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1547. var el = displayable;
  1548. var isSilent;
  1549. while (el) {
  1550. // If clipped by ancestor.
  1551. // FIXME: If clipPath has neither stroke nor fill,
  1552. // el.clipPath.contain(x, y) will always return false.
  1553. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1554. return false;
  1555. }
  1556. if (el.silent) {
  1557. isSilent = true;
  1558. }
  1559. el = el.parent;
  1560. }
  1561. return isSilent ? SILENT : true;
  1562. }
  1563. return false;
  1564. }
  1565. mixin(Handler, Eventful);
  1566. mixin(Handler, Draggable);
  1567. /**
  1568. * 3x2矩阵操作类
  1569. * @exports zrender/tool/matrix
  1570. */
  1571. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1572. ? Array
  1573. : Float32Array;
  1574. /**
  1575. * 创建一个单位矩阵
  1576. * @return {Float32Array|Array.<number>}
  1577. */
  1578. function create$1() {
  1579. var out = new ArrayCtor$1(6);
  1580. identity(out);
  1581. return out;
  1582. }
  1583. /**
  1584. * 设置矩阵为单位矩阵
  1585. * @param {Float32Array|Array.<number>} out
  1586. */
  1587. function identity(out) {
  1588. out[0] = 1;
  1589. out[1] = 0;
  1590. out[2] = 0;
  1591. out[3] = 1;
  1592. out[4] = 0;
  1593. out[5] = 0;
  1594. return out;
  1595. }
  1596. /**
  1597. * 复制矩阵
  1598. * @param {Float32Array|Array.<number>} out
  1599. * @param {Float32Array|Array.<number>} m
  1600. */
  1601. function copy$1(out, m) {
  1602. out[0] = m[0];
  1603. out[1] = m[1];
  1604. out[2] = m[2];
  1605. out[3] = m[3];
  1606. out[4] = m[4];
  1607. out[5] = m[5];
  1608. return out;
  1609. }
  1610. /**
  1611. * 矩阵相乘
  1612. * @param {Float32Array|Array.<number>} out
  1613. * @param {Float32Array|Array.<number>} m1
  1614. * @param {Float32Array|Array.<number>} m2
  1615. */
  1616. function mul$1(out, m1, m2) {
  1617. // Consider matrix.mul(m, m2, m);
  1618. // where out is the same as m2.
  1619. // So use temp variable to escape error.
  1620. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1621. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1622. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1623. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1624. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1625. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1626. out[0] = out0;
  1627. out[1] = out1;
  1628. out[2] = out2;
  1629. out[3] = out3;
  1630. out[4] = out4;
  1631. out[5] = out5;
  1632. return out;
  1633. }
  1634. /**
  1635. * 平移变换
  1636. * @param {Float32Array|Array.<number>} out
  1637. * @param {Float32Array|Array.<number>} a
  1638. * @param {Float32Array|Array.<number>} v
  1639. */
  1640. function translate(out, a, v) {
  1641. out[0] = a[0];
  1642. out[1] = a[1];
  1643. out[2] = a[2];
  1644. out[3] = a[3];
  1645. out[4] = a[4] + v[0];
  1646. out[5] = a[5] + v[1];
  1647. return out;
  1648. }
  1649. /**
  1650. * 旋转变换
  1651. * @param {Float32Array|Array.<number>} out
  1652. * @param {Float32Array|Array.<number>} a
  1653. * @param {number} rad
  1654. */
  1655. function rotate(out, a, rad) {
  1656. var aa = a[0];
  1657. var ac = a[2];
  1658. var atx = a[4];
  1659. var ab = a[1];
  1660. var ad = a[3];
  1661. var aty = a[5];
  1662. var st = Math.sin(rad);
  1663. var ct = Math.cos(rad);
  1664. out[0] = aa * ct + ab * st;
  1665. out[1] = -aa * st + ab * ct;
  1666. out[2] = ac * ct + ad * st;
  1667. out[3] = -ac * st + ct * ad;
  1668. out[4] = ct * atx + st * aty;
  1669. out[5] = ct * aty - st * atx;
  1670. return out;
  1671. }
  1672. /**
  1673. * 缩放变换
  1674. * @param {Float32Array|Array.<number>} out
  1675. * @param {Float32Array|Array.<number>} a
  1676. * @param {Float32Array|Array.<number>} v
  1677. */
  1678. function scale$1(out, a, v) {
  1679. var vx = v[0];
  1680. var vy = v[1];
  1681. out[0] = a[0] * vx;
  1682. out[1] = a[1] * vy;
  1683. out[2] = a[2] * vx;
  1684. out[3] = a[3] * vy;
  1685. out[4] = a[4] * vx;
  1686. out[5] = a[5] * vy;
  1687. return out;
  1688. }
  1689. /**
  1690. * 求逆矩阵
  1691. * @param {Float32Array|Array.<number>} out
  1692. * @param {Float32Array|Array.<number>} a
  1693. */
  1694. function invert(out, a) {
  1695. var aa = a[0];
  1696. var ac = a[2];
  1697. var atx = a[4];
  1698. var ab = a[1];
  1699. var ad = a[3];
  1700. var aty = a[5];
  1701. var det = aa * ad - ab * ac;
  1702. if (!det) {
  1703. return null;
  1704. }
  1705. det = 1.0 / det;
  1706. out[0] = ad * det;
  1707. out[1] = -ab * det;
  1708. out[2] = -ac * det;
  1709. out[3] = aa * det;
  1710. out[4] = (ac * aty - ad * atx) * det;
  1711. out[5] = (ab * atx - aa * aty) * det;
  1712. return out;
  1713. }
  1714. var matrix = (Object.freeze || Object)({
  1715. create: create$1,
  1716. identity: identity,
  1717. copy: copy$1,
  1718. mul: mul$1,
  1719. translate: translate,
  1720. rotate: rotate,
  1721. scale: scale$1,
  1722. invert: invert
  1723. });
  1724. /**
  1725. * 提供变换扩展
  1726. * @module zrender/mixin/Transformable
  1727. * @author pissang (https://www.github.com/pissang)
  1728. */
  1729. var mIdentity = identity;
  1730. var EPSILON = 5e-5;
  1731. function isNotAroundZero(val) {
  1732. return val > EPSILON || val < -EPSILON;
  1733. }
  1734. /**
  1735. * @alias module:zrender/mixin/Transformable
  1736. * @constructor
  1737. */
  1738. var Transformable = function (opts) {
  1739. opts = opts || {};
  1740. // If there are no given position, rotation, scale
  1741. if (!opts.position) {
  1742. /**
  1743. * 平移
  1744. * @type {Array.<number>}
  1745. * @default [0, 0]
  1746. */
  1747. this.position = [0, 0];
  1748. }
  1749. if (opts.rotation == null) {
  1750. /**
  1751. * 旋转
  1752. * @type {Array.<number>}
  1753. * @default 0
  1754. */
  1755. this.rotation = 0;
  1756. }
  1757. if (!opts.scale) {
  1758. /**
  1759. * 缩放
  1760. * @type {Array.<number>}
  1761. * @default [1, 1]
  1762. */
  1763. this.scale = [1, 1];
  1764. }
  1765. /**
  1766. * 旋转和缩放的原点
  1767. * @type {Array.<number>}
  1768. * @default null
  1769. */
  1770. this.origin = this.origin || null;
  1771. };
  1772. var transformableProto = Transformable.prototype;
  1773. transformableProto.transform = null;
  1774. /**
  1775. * 判断是否需要有坐标变换
  1776. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1777. */
  1778. transformableProto.needLocalTransform = function () {
  1779. return isNotAroundZero(this.rotation)
  1780. || isNotAroundZero(this.position[0])
  1781. || isNotAroundZero(this.position[1])
  1782. || isNotAroundZero(this.scale[0] - 1)
  1783. || isNotAroundZero(this.scale[1] - 1);
  1784. };
  1785. transformableProto.updateTransform = function () {
  1786. var parent = this.parent;
  1787. var parentHasTransform = parent && parent.transform;
  1788. var needLocalTransform = this.needLocalTransform();
  1789. var m = this.transform;
  1790. if (!(needLocalTransform || parentHasTransform)) {
  1791. m && mIdentity(m);
  1792. return;
  1793. }
  1794. m = m || create$1();
  1795. if (needLocalTransform) {
  1796. this.getLocalTransform(m);
  1797. }
  1798. else {
  1799. mIdentity(m);
  1800. }
  1801. // 应用父节点变换
  1802. if (parentHasTransform) {
  1803. if (needLocalTransform) {
  1804. mul$1(m, parent.transform, m);
  1805. }
  1806. else {
  1807. copy$1(m, parent.transform);
  1808. }
  1809. }
  1810. // 保存这个变换矩阵
  1811. this.transform = m;
  1812. this.invTransform = this.invTransform || create$1();
  1813. invert(this.invTransform, m);
  1814. };
  1815. transformableProto.getLocalTransform = function (m) {
  1816. return Transformable.getLocalTransform(this, m);
  1817. };
  1818. /**
  1819. * 将自己的transform应用到context上
  1820. * @param {CanvasRenderingContext2D} ctx
  1821. */
  1822. transformableProto.setTransform = function (ctx) {
  1823. var m = this.transform;
  1824. var dpr = ctx.dpr || 1;
  1825. if (m) {
  1826. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1827. }
  1828. else {
  1829. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1830. }
  1831. };
  1832. transformableProto.restoreTransform = function (ctx) {
  1833. var dpr = ctx.dpr || 1;
  1834. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1835. };
  1836. var tmpTransform = [];
  1837. /**
  1838. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1839. */
  1840. transformableProto.decomposeTransform = function () {
  1841. if (!this.transform) {
  1842. return;
  1843. }
  1844. var parent = this.parent;
  1845. var m = this.transform;
  1846. if (parent && parent.transform) {
  1847. // Get local transform and decompose them to position, scale, rotation
  1848. mul$1(tmpTransform, parent.invTransform, m);
  1849. m = tmpTransform;
  1850. }
  1851. var sx = m[0] * m[0] + m[1] * m[1];
  1852. var sy = m[2] * m[2] + m[3] * m[3];
  1853. var position = this.position;
  1854. var scale$$1 = this.scale;
  1855. if (isNotAroundZero(sx - 1)) {
  1856. sx = Math.sqrt(sx);
  1857. }
  1858. if (isNotAroundZero(sy - 1)) {
  1859. sy = Math.sqrt(sy);
  1860. }
  1861. if (m[0] < 0) {
  1862. sx = -sx;
  1863. }
  1864. if (m[3] < 0) {
  1865. sy = -sy;
  1866. }
  1867. position[0] = m[4];
  1868. position[1] = m[5];
  1869. scale$$1[0] = sx;
  1870. scale$$1[1] = sy;
  1871. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1872. };
  1873. /**
  1874. * Get global scale
  1875. * @return {Array.<number>}
  1876. */
  1877. transformableProto.getGlobalScale = function () {
  1878. var m = this.transform;
  1879. if (!m) {
  1880. return [1, 1];
  1881. }
  1882. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1883. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1884. if (m[0] < 0) {
  1885. sx = -sx;
  1886. }
  1887. if (m[3] < 0) {
  1888. sy = -sy;
  1889. }
  1890. return [sx, sy];
  1891. };
  1892. /**
  1893. * 变换坐标位置到 shape 的局部坐标空间
  1894. * @method
  1895. * @param {number} x
  1896. * @param {number} y
  1897. * @return {Array.<number>}
  1898. */
  1899. transformableProto.transformCoordToLocal = function (x, y) {
  1900. var v2 = [x, y];
  1901. var invTransform = this.invTransform;
  1902. if (invTransform) {
  1903. applyTransform(v2, v2, invTransform);
  1904. }
  1905. return v2;
  1906. };
  1907. /**
  1908. * 变换局部坐标位置到全局坐标空间
  1909. * @method
  1910. * @param {number} x
  1911. * @param {number} y
  1912. * @return {Array.<number>}
  1913. */
  1914. transformableProto.transformCoordToGlobal = function (x, y) {
  1915. var v2 = [x, y];
  1916. var transform = this.transform;
  1917. if (transform) {
  1918. applyTransform(v2, v2, transform);
  1919. }
  1920. return v2;
  1921. };
  1922. /**
  1923. * @static
  1924. * @param {Object} target
  1925. * @param {Array.<number>} target.origin
  1926. * @param {number} target.rotation
  1927. * @param {Array.<number>} target.position
  1928. * @param {Array.<number>} [m]
  1929. */
  1930. Transformable.getLocalTransform = function (target, m) {
  1931. m = m || [];
  1932. mIdentity(m);
  1933. var origin = target.origin;
  1934. var scale$$1 = target.scale || [1, 1];
  1935. var rotation = target.rotation || 0;
  1936. var position = target.position || [0, 0];
  1937. if (origin) {
  1938. // Translate to origin
  1939. m[4] -= origin[0];
  1940. m[5] -= origin[1];
  1941. }
  1942. scale$1(m, m, scale$$1);
  1943. if (rotation) {
  1944. rotate(m, m, rotation);
  1945. }
  1946. if (origin) {
  1947. // Translate back from origin
  1948. m[4] += origin[0];
  1949. m[5] += origin[1];
  1950. }
  1951. m[4] += position[0];
  1952. m[5] += position[1];
  1953. return m;
  1954. };
  1955. /**
  1956. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  1957. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  1958. * @exports zrender/animation/easing
  1959. */
  1960. var easing = {
  1961. /**
  1962. * @param {number} k
  1963. * @return {number}
  1964. */
  1965. linear: function (k) {
  1966. return k;
  1967. },
  1968. /**
  1969. * @param {number} k
  1970. * @return {number}
  1971. */
  1972. quadraticIn: function (k) {
  1973. return k * k;
  1974. },
  1975. /**
  1976. * @param {number} k
  1977. * @return {number}
  1978. */
  1979. quadraticOut: function (k) {
  1980. return k * (2 - k);
  1981. },
  1982. /**
  1983. * @param {number} k
  1984. * @return {number}
  1985. */
  1986. quadraticInOut: function (k) {
  1987. if ((k *= 2) < 1) {
  1988. return 0.5 * k * k;
  1989. }
  1990. return -0.5 * (--k * (k - 2) - 1);
  1991. },
  1992. // 三次方的缓动(t^3)
  1993. /**
  1994. * @param {number} k
  1995. * @return {number}
  1996. */
  1997. cubicIn: function (k) {
  1998. return k * k * k;
  1999. },
  2000. /**
  2001. * @param {number} k
  2002. * @return {number}
  2003. */
  2004. cubicOut: function (k) {
  2005. return --k * k * k + 1;
  2006. },
  2007. /**
  2008. * @param {number} k
  2009. * @return {number}
  2010. */
  2011. cubicInOut: function (k) {
  2012. if ((k *= 2) < 1) {
  2013. return 0.5 * k * k * k;
  2014. }
  2015. return 0.5 * ((k -= 2) * k * k + 2);
  2016. },
  2017. // 四次方的缓动(t^4)
  2018. /**
  2019. * @param {number} k
  2020. * @return {number}
  2021. */
  2022. quarticIn: function (k) {
  2023. return k * k * k * k;
  2024. },
  2025. /**
  2026. * @param {number} k
  2027. * @return {number}
  2028. */
  2029. quarticOut: function (k) {
  2030. return 1 - (--k * k * k * k);
  2031. },
  2032. /**
  2033. * @param {number} k
  2034. * @return {number}
  2035. */
  2036. quarticInOut: function (k) {
  2037. if ((k *= 2) < 1) {
  2038. return 0.5 * k * k * k * k;
  2039. }
  2040. return -0.5 * ((k -= 2) * k * k * k - 2);
  2041. },
  2042. // 五次方的缓动(t^5)
  2043. /**
  2044. * @param {number} k
  2045. * @return {number}
  2046. */
  2047. quinticIn: function (k) {
  2048. return k * k * k * k * k;
  2049. },
  2050. /**
  2051. * @param {number} k
  2052. * @return {number}
  2053. */
  2054. quinticOut: function (k) {
  2055. return --k * k * k * k * k + 1;
  2056. },
  2057. /**
  2058. * @param {number} k
  2059. * @return {number}
  2060. */
  2061. quinticInOut: function (k) {
  2062. if ((k *= 2) < 1) {
  2063. return 0.5 * k * k * k * k * k;
  2064. }
  2065. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2066. },
  2067. // 正弦曲线的缓动(sin(t))
  2068. /**
  2069. * @param {number} k
  2070. * @return {number}
  2071. */
  2072. sinusoidalIn: function (k) {
  2073. return 1 - Math.cos(k * Math.PI / 2);
  2074. },
  2075. /**
  2076. * @param {number} k
  2077. * @return {number}
  2078. */
  2079. sinusoidalOut: function (k) {
  2080. return Math.sin(k * Math.PI / 2);
  2081. },
  2082. /**
  2083. * @param {number} k
  2084. * @return {number}
  2085. */
  2086. sinusoidalInOut: function (k) {
  2087. return 0.5 * (1 - Math.cos(Math.PI * k));
  2088. },
  2089. // 指数曲线的缓动(2^t)
  2090. /**
  2091. * @param {number} k
  2092. * @return {number}
  2093. */
  2094. exponentialIn: function (k) {
  2095. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2096. },
  2097. /**
  2098. * @param {number} k
  2099. * @return {number}
  2100. */
  2101. exponentialOut: function (k) {
  2102. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2103. },
  2104. /**
  2105. * @param {number} k
  2106. * @return {number}
  2107. */
  2108. exponentialInOut: function (k) {
  2109. if (k === 0) {
  2110. return 0;
  2111. }
  2112. if (k === 1) {
  2113. return 1;
  2114. }
  2115. if ((k *= 2) < 1) {
  2116. return 0.5 * Math.pow(1024, k - 1);
  2117. }
  2118. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2119. },
  2120. // 圆形曲线的缓动(sqrt(1-t^2))
  2121. /**
  2122. * @param {number} k
  2123. * @return {number}
  2124. */
  2125. circularIn: function (k) {
  2126. return 1 - Math.sqrt(1 - k * k);
  2127. },
  2128. /**
  2129. * @param {number} k
  2130. * @return {number}
  2131. */
  2132. circularOut: function (k) {
  2133. return Math.sqrt(1 - (--k * k));
  2134. },
  2135. /**
  2136. * @param {number} k
  2137. * @return {number}
  2138. */
  2139. circularInOut: function (k) {
  2140. if ((k *= 2) < 1) {
  2141. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2142. }
  2143. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2144. },
  2145. // 创建类似于弹簧在停止前来回振荡的动画
  2146. /**
  2147. * @param {number} k
  2148. * @return {number}
  2149. */
  2150. elasticIn: function (k) {
  2151. var s;
  2152. var a = 0.1;
  2153. var p = 0.4;
  2154. if (k === 0) {
  2155. return 0;
  2156. }
  2157. if (k === 1) {
  2158. return 1;
  2159. }
  2160. if (!a || a < 1) {
  2161. a = 1; s = p / 4;
  2162. }
  2163. else {
  2164. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2165. }
  2166. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2167. Math.sin((k - s) * (2 * Math.PI) / p));
  2168. },
  2169. /**
  2170. * @param {number} k
  2171. * @return {number}
  2172. */
  2173. elasticOut: function (k) {
  2174. var s;
  2175. var a = 0.1;
  2176. var p = 0.4;
  2177. if (k === 0) {
  2178. return 0;
  2179. }
  2180. if (k === 1) {
  2181. return 1;
  2182. }
  2183. if (!a || a < 1) {
  2184. a = 1; s = p / 4;
  2185. }
  2186. else {
  2187. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2188. }
  2189. return (a * Math.pow(2, -10 * k) *
  2190. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2191. },
  2192. /**
  2193. * @param {number} k
  2194. * @return {number}
  2195. */
  2196. elasticInOut: function (k) {
  2197. var s;
  2198. var a = 0.1;
  2199. var p = 0.4;
  2200. if (k === 0) {
  2201. return 0;
  2202. }
  2203. if (k === 1) {
  2204. return 1;
  2205. }
  2206. if (!a || a < 1) {
  2207. a = 1; s = p / 4;
  2208. }
  2209. else {
  2210. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2211. }
  2212. if ((k *= 2) < 1) {
  2213. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2214. * Math.sin((k - s) * (2 * Math.PI) / p));
  2215. }
  2216. return a * Math.pow(2, -10 * (k -= 1))
  2217. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2218. },
  2219. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2220. /**
  2221. * @param {number} k
  2222. * @return {number}
  2223. */
  2224. backIn: function (k) {
  2225. var s = 1.70158;
  2226. return k * k * ((s + 1) * k - s);
  2227. },
  2228. /**
  2229. * @param {number} k
  2230. * @return {number}
  2231. */
  2232. backOut: function (k) {
  2233. var s = 1.70158;
  2234. return --k * k * ((s + 1) * k + s) + 1;
  2235. },
  2236. /**
  2237. * @param {number} k
  2238. * @return {number}
  2239. */
  2240. backInOut: function (k) {
  2241. var s = 1.70158 * 1.525;
  2242. if ((k *= 2) < 1) {
  2243. return 0.5 * (k * k * ((s + 1) * k - s));
  2244. }
  2245. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2246. },
  2247. // 创建弹跳效果
  2248. /**
  2249. * @param {number} k
  2250. * @return {number}
  2251. */
  2252. bounceIn: function (k) {
  2253. return 1 - easing.bounceOut(1 - k);
  2254. },
  2255. /**
  2256. * @param {number} k
  2257. * @return {number}
  2258. */
  2259. bounceOut: function (k) {
  2260. if (k < (1 / 2.75)) {
  2261. return 7.5625 * k * k;
  2262. }
  2263. else if (k < (2 / 2.75)) {
  2264. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2265. }
  2266. else if (k < (2.5 / 2.75)) {
  2267. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2268. }
  2269. else {
  2270. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2271. }
  2272. },
  2273. /**
  2274. * @param {number} k
  2275. * @return {number}
  2276. */
  2277. bounceInOut: function (k) {
  2278. if (k < 0.5) {
  2279. return easing.bounceIn(k * 2) * 0.5;
  2280. }
  2281. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2282. }
  2283. };
  2284. /**
  2285. * 动画主控制器
  2286. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2287. * @config life(1000) 动画时长
  2288. * @config delay(0) 动画延迟时间
  2289. * @config loop(true)
  2290. * @config gap(0) 循环的间隔时间
  2291. * @config onframe
  2292. * @config easing(optional)
  2293. * @config ondestroy(optional)
  2294. * @config onrestart(optional)
  2295. *
  2296. * TODO pause
  2297. */
  2298. function Clip(options) {
  2299. this._target = options.target;
  2300. // 生命周期
  2301. this._life = options.life || 1000;
  2302. // 延时
  2303. this._delay = options.delay || 0;
  2304. // 开始时间
  2305. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2306. this._initialized = false;
  2307. // 是否循环
  2308. this.loop = options.loop == null ? false : options.loop;
  2309. this.gap = options.gap || 0;
  2310. this.easing = options.easing || 'Linear';
  2311. this.onframe = options.onframe;
  2312. this.ondestroy = options.ondestroy;
  2313. this.onrestart = options.onrestart;
  2314. this._pausedTime = 0;
  2315. this._paused = false;
  2316. }
  2317. Clip.prototype = {
  2318. constructor: Clip,
  2319. step: function (globalTime, deltaTime) {
  2320. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2321. // PENDING
  2322. if (!this._initialized) {
  2323. this._startTime = globalTime + this._delay;
  2324. this._initialized = true;
  2325. }
  2326. if (this._paused) {
  2327. this._pausedTime += deltaTime;
  2328. return;
  2329. }
  2330. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2331. // 还没开始
  2332. if (percent < 0) {
  2333. return;
  2334. }
  2335. percent = Math.min(percent, 1);
  2336. var easing$$1 = this.easing;
  2337. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2338. var schedule = typeof easingFunc === 'function'
  2339. ? easingFunc(percent)
  2340. : percent;
  2341. this.fire('frame', schedule);
  2342. // 结束
  2343. if (percent == 1) {
  2344. if (this.loop) {
  2345. this.restart (globalTime);
  2346. // 重新开始周期
  2347. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2348. return 'restart';
  2349. }
  2350. // 动画完成将这个控制器标识为待删除
  2351. // 在Animation.update中进行批量删除
  2352. this._needsRemove = true;
  2353. return 'destroy';
  2354. }
  2355. return null;
  2356. },
  2357. restart: function (globalTime) {
  2358. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2359. this._startTime = globalTime - remainder + this.gap;
  2360. this._pausedTime = 0;
  2361. this._needsRemove = false;
  2362. },
  2363. fire: function (eventType, arg) {
  2364. eventType = 'on' + eventType;
  2365. if (this[eventType]) {
  2366. this[eventType](this._target, arg);
  2367. }
  2368. },
  2369. pause: function () {
  2370. this._paused = true;
  2371. },
  2372. resume: function () {
  2373. this._paused = false;
  2374. }
  2375. };
  2376. // Simple LRU cache use doubly linked list
  2377. // @module zrender/core/LRU
  2378. /**
  2379. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2380. * @constructor
  2381. */
  2382. var LinkedList = function () {
  2383. /**
  2384. * @type {module:zrender/core/LRU~Entry}
  2385. */
  2386. this.head = null;
  2387. /**
  2388. * @type {module:zrender/core/LRU~Entry}
  2389. */
  2390. this.tail = null;
  2391. this._len = 0;
  2392. };
  2393. var linkedListProto = LinkedList.prototype;
  2394. /**
  2395. * Insert a new value at the tail
  2396. * @param {} val
  2397. * @return {module:zrender/core/LRU~Entry}
  2398. */
  2399. linkedListProto.insert = function (val) {
  2400. var entry = new Entry(val);
  2401. this.insertEntry(entry);
  2402. return entry;
  2403. };
  2404. /**
  2405. * Insert an entry at the tail
  2406. * @param {module:zrender/core/LRU~Entry} entry
  2407. */
  2408. linkedListProto.insertEntry = function (entry) {
  2409. if (!this.head) {
  2410. this.head = this.tail = entry;
  2411. }
  2412. else {
  2413. this.tail.next = entry;
  2414. entry.prev = this.tail;
  2415. entry.next = null;
  2416. this.tail = entry;
  2417. }
  2418. this._len++;
  2419. };
  2420. /**
  2421. * Remove entry.
  2422. * @param {module:zrender/core/LRU~Entry} entry
  2423. */
  2424. linkedListProto.remove = function (entry) {
  2425. var prev = entry.prev;
  2426. var next = entry.next;
  2427. if (prev) {
  2428. prev.next = next;
  2429. }
  2430. else {
  2431. // Is head
  2432. this.head = next;
  2433. }
  2434. if (next) {
  2435. next.prev = prev;
  2436. }
  2437. else {
  2438. // Is tail
  2439. this.tail = prev;
  2440. }
  2441. entry.next = entry.prev = null;
  2442. this._len--;
  2443. };
  2444. /**
  2445. * @return {number}
  2446. */
  2447. linkedListProto.len = function () {
  2448. return this._len;
  2449. };
  2450. /**
  2451. * Clear list
  2452. */
  2453. linkedListProto.clear = function () {
  2454. this.head = this.tail = null;
  2455. this._len = 0;
  2456. };
  2457. /**
  2458. * @constructor
  2459. * @param {} val
  2460. */
  2461. var Entry = function (val) {
  2462. /**
  2463. * @type {}
  2464. */
  2465. this.value = val;
  2466. /**
  2467. * @type {module:zrender/core/LRU~Entry}
  2468. */
  2469. this.next;
  2470. /**
  2471. * @type {module:zrender/core/LRU~Entry}
  2472. */
  2473. this.prev;
  2474. };
  2475. /**
  2476. * LRU Cache
  2477. * @constructor
  2478. * @alias module:zrender/core/LRU
  2479. */
  2480. var LRU = function (maxSize) {
  2481. this._list = new LinkedList();
  2482. this._map = {};
  2483. this._maxSize = maxSize || 10;
  2484. this._lastRemovedEntry = null;
  2485. };
  2486. var LRUProto = LRU.prototype;
  2487. /**
  2488. * @param {string} key
  2489. * @param {} value
  2490. * @return {} Removed value
  2491. */
  2492. LRUProto.put = function (key, value) {
  2493. var list = this._list;
  2494. var map = this._map;
  2495. var removed = null;
  2496. if (map[key] == null) {
  2497. var len = list.len();
  2498. // Reuse last removed entry
  2499. var entry = this._lastRemovedEntry;
  2500. if (len >= this._maxSize && len > 0) {
  2501. // Remove the least recently used
  2502. var leastUsedEntry = list.head;
  2503. list.remove(leastUsedEntry);
  2504. delete map[leastUsedEntry.key];
  2505. removed = leastUsedEntry.value;
  2506. this._lastRemovedEntry = leastUsedEntry;
  2507. }
  2508. if (entry) {
  2509. entry.value = value;
  2510. }
  2511. else {
  2512. entry = new Entry(value);
  2513. }
  2514. entry.key = key;
  2515. list.insertEntry(entry);
  2516. map[key] = entry;
  2517. }
  2518. return removed;
  2519. };
  2520. /**
  2521. * @param {string} key
  2522. * @return {}
  2523. */
  2524. LRUProto.get = function (key) {
  2525. var entry = this._map[key];
  2526. var list = this._list;
  2527. if (entry != null) {
  2528. // Put the latest used entry in the tail
  2529. if (entry !== list.tail) {
  2530. list.remove(entry);
  2531. list.insertEntry(entry);
  2532. }
  2533. return entry.value;
  2534. }
  2535. };
  2536. /**
  2537. * Clear the cache
  2538. */
  2539. LRUProto.clear = function () {
  2540. this._list.clear();
  2541. this._map = {};
  2542. };
  2543. var kCSSColorTable = {
  2544. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2545. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2546. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2547. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2548. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2549. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2550. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2551. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2552. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2553. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2554. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2555. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2556. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2557. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2558. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2559. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2560. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2561. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2562. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2563. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2564. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2565. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2566. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2567. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2568. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2569. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2570. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2571. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2572. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2573. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2574. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2575. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2576. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2577. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2578. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2579. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2580. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2581. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2582. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2583. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2584. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2585. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2586. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2587. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2588. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2589. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2590. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2591. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2592. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2593. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2594. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2595. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2596. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2597. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2598. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2599. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2600. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2601. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2602. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2603. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2604. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2605. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2606. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2607. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2608. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2609. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2610. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2611. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2612. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2613. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2614. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2615. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2616. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2617. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2618. };
  2619. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2620. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2621. return i < 0 ? 0 : i > 255 ? 255 : i;
  2622. }
  2623. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2624. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2625. return i < 0 ? 0 : i > 360 ? 360 : i;
  2626. }
  2627. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2628. return f < 0 ? 0 : f > 1 ? 1 : f;
  2629. }
  2630. function parseCssInt(str) { // int or percentage.
  2631. if (str.length && str.charAt(str.length - 1) === '%') {
  2632. return clampCssByte(parseFloat(str) / 100 * 255);
  2633. }
  2634. return clampCssByte(parseInt(str, 10));
  2635. }
  2636. function parseCssFloat(str) { // float or percentage.
  2637. if (str.length && str.charAt(str.length - 1) === '%') {
  2638. return clampCssFloat(parseFloat(str) / 100);
  2639. }
  2640. return clampCssFloat(parseFloat(str));
  2641. }
  2642. function cssHueToRgb(m1, m2, h) {
  2643. if (h < 0) {
  2644. h += 1;
  2645. }
  2646. else if (h > 1) {
  2647. h -= 1;
  2648. }
  2649. if (h * 6 < 1) {
  2650. return m1 + (m2 - m1) * h * 6;
  2651. }
  2652. if (h * 2 < 1) {
  2653. return m2;
  2654. }
  2655. if (h * 3 < 2) {
  2656. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2657. }
  2658. return m1;
  2659. }
  2660. function lerpNumber(a, b, p) {
  2661. return a + (b - a) * p;
  2662. }
  2663. function setRgba(out, r, g, b, a) {
  2664. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2665. return out;
  2666. }
  2667. function copyRgba(out, a) {
  2668. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2669. return out;
  2670. }
  2671. var colorCache = new LRU(20);
  2672. var lastRemovedArr = null;
  2673. function putToCache(colorStr, rgbaArr) {
  2674. // Reuse removed array
  2675. if (lastRemovedArr) {
  2676. copyRgba(lastRemovedArr, rgbaArr);
  2677. }
  2678. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2679. }
  2680. /**
  2681. * @param {string} colorStr
  2682. * @param {Array.<number>} out
  2683. * @return {Array.<number>}
  2684. * @memberOf module:zrender/util/color
  2685. */
  2686. function parse(colorStr, rgbaArr) {
  2687. if (!colorStr) {
  2688. return;
  2689. }
  2690. rgbaArr = rgbaArr || [];
  2691. var cached = colorCache.get(colorStr);
  2692. if (cached) {
  2693. return copyRgba(rgbaArr, cached);
  2694. }
  2695. // colorStr may be not string
  2696. colorStr = colorStr + '';
  2697. // Remove all whitespace, not compliant, but should just be more accepting.
  2698. var str = colorStr.replace(/ /g, '').toLowerCase();
  2699. // Color keywords (and transparent) lookup.
  2700. if (str in kCSSColorTable) {
  2701. copyRgba(rgbaArr, kCSSColorTable[str]);
  2702. putToCache(colorStr, rgbaArr);
  2703. return rgbaArr;
  2704. }
  2705. // #abc and #abc123 syntax.
  2706. if (str.charAt(0) === '#') {
  2707. if (str.length === 4) {
  2708. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2709. if (!(iv >= 0 && iv <= 0xfff)) {
  2710. setRgba(rgbaArr, 0, 0, 0, 1);
  2711. return; // Covers NaN.
  2712. }
  2713. setRgba(rgbaArr,
  2714. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2715. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2716. (iv & 0xf) | ((iv & 0xf) << 4),
  2717. 1
  2718. );
  2719. putToCache(colorStr, rgbaArr);
  2720. return rgbaArr;
  2721. }
  2722. else if (str.length === 7) {
  2723. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2724. if (!(iv >= 0 && iv <= 0xffffff)) {
  2725. setRgba(rgbaArr, 0, 0, 0, 1);
  2726. return; // Covers NaN.
  2727. }
  2728. setRgba(rgbaArr,
  2729. (iv & 0xff0000) >> 16,
  2730. (iv & 0xff00) >> 8,
  2731. iv & 0xff,
  2732. 1
  2733. );
  2734. putToCache(colorStr, rgbaArr);
  2735. return rgbaArr;
  2736. }
  2737. return;
  2738. }
  2739. var op = str.indexOf('('), ep = str.indexOf(')');
  2740. if (op !== -1 && ep + 1 === str.length) {
  2741. var fname = str.substr(0, op);
  2742. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2743. var alpha = 1; // To allow case fallthrough.
  2744. switch (fname) {
  2745. case 'rgba':
  2746. if (params.length !== 4) {
  2747. setRgba(rgbaArr, 0, 0, 0, 1);
  2748. return;
  2749. }
  2750. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2751. // Fall through.
  2752. case 'rgb':
  2753. if (params.length !== 3) {
  2754. setRgba(rgbaArr, 0, 0, 0, 1);
  2755. return;
  2756. }
  2757. setRgba(rgbaArr,
  2758. parseCssInt(params[0]),
  2759. parseCssInt(params[1]),
  2760. parseCssInt(params[2]),
  2761. alpha
  2762. );
  2763. putToCache(colorStr, rgbaArr);
  2764. return rgbaArr;
  2765. case 'hsla':
  2766. if (params.length !== 4) {
  2767. setRgba(rgbaArr, 0, 0, 0, 1);
  2768. return;
  2769. }
  2770. params[3] = parseCssFloat(params[3]);
  2771. hsla2rgba(params, rgbaArr);
  2772. putToCache(colorStr, rgbaArr);
  2773. return rgbaArr;
  2774. case 'hsl':
  2775. if (params.length !== 3) {
  2776. setRgba(rgbaArr, 0, 0, 0, 1);
  2777. return;
  2778. }
  2779. hsla2rgba(params, rgbaArr);
  2780. putToCache(colorStr, rgbaArr);
  2781. return rgbaArr;
  2782. default:
  2783. return;
  2784. }
  2785. }
  2786. setRgba(rgbaArr, 0, 0, 0, 1);
  2787. return;
  2788. }
  2789. /**
  2790. * @param {Array.<number>} hsla
  2791. * @param {Array.<number>} rgba
  2792. * @return {Array.<number>} rgba
  2793. */
  2794. function hsla2rgba(hsla, rgba) {
  2795. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2796. // NOTE(deanm): According to the CSS spec s/l should only be
  2797. // percentages, but we don't bother and let float or percentage.
  2798. var s = parseCssFloat(hsla[1]);
  2799. var l = parseCssFloat(hsla[2]);
  2800. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2801. var m1 = l * 2 - m2;
  2802. rgba = rgba || [];
  2803. setRgba(rgba,
  2804. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2805. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2806. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2807. 1
  2808. );
  2809. if (hsla.length === 4) {
  2810. rgba[3] = hsla[3];
  2811. }
  2812. return rgba;
  2813. }
  2814. /**
  2815. * @param {Array.<number>} rgba
  2816. * @return {Array.<number>} hsla
  2817. */
  2818. function rgba2hsla(rgba) {
  2819. if (!rgba) {
  2820. return;
  2821. }
  2822. // RGB from 0 to 255
  2823. var R = rgba[0] / 255;
  2824. var G = rgba[1] / 255;
  2825. var B = rgba[2] / 255;
  2826. var vMin = Math.min(R, G, B); // Min. value of RGB
  2827. var vMax = Math.max(R, G, B); // Max. value of RGB
  2828. var delta = vMax - vMin; // Delta RGB value
  2829. var L = (vMax + vMin) / 2;
  2830. var H;
  2831. var S;
  2832. // HSL results from 0 to 1
  2833. if (delta === 0) {
  2834. H = 0;
  2835. S = 0;
  2836. }
  2837. else {
  2838. if (L < 0.5) {
  2839. S = delta / (vMax + vMin);
  2840. }
  2841. else {
  2842. S = delta / (2 - vMax - vMin);
  2843. }
  2844. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2845. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2846. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2847. if (R === vMax) {
  2848. H = deltaB - deltaG;
  2849. }
  2850. else if (G === vMax) {
  2851. H = (1 / 3) + deltaR - deltaB;
  2852. }
  2853. else if (B === vMax) {
  2854. H = (2 / 3) + deltaG - deltaR;
  2855. }
  2856. if (H < 0) {
  2857. H += 1;
  2858. }
  2859. if (H > 1) {
  2860. H -= 1;
  2861. }
  2862. }
  2863. var hsla = [H * 360, S, L];
  2864. if (rgba[3] != null) {
  2865. hsla.push(rgba[3]);
  2866. }
  2867. return hsla;
  2868. }
  2869. /**
  2870. * @param {string} color
  2871. * @param {number} level
  2872. * @return {string}
  2873. * @memberOf module:zrender/util/color
  2874. */
  2875. function lift(color, level) {
  2876. var colorArr = parse(color);
  2877. if (colorArr) {
  2878. for (var i = 0; i < 3; i++) {
  2879. if (level < 0) {
  2880. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2881. }
  2882. else {
  2883. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2884. }
  2885. }
  2886. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2887. }
  2888. }
  2889. /**
  2890. * @param {string} color
  2891. * @return {string}
  2892. * @memberOf module:zrender/util/color
  2893. */
  2894. function toHex(color) {
  2895. var colorArr = parse(color);
  2896. if (colorArr) {
  2897. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2898. }
  2899. }
  2900. /**
  2901. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  2902. * @param {number} normalizedValue A float between 0 and 1.
  2903. * @param {Array.<Array.<number>>} colors List of rgba color array
  2904. * @param {Array.<number>} [out] Mapped gba color array
  2905. * @return {Array.<number>} will be null/undefined if input illegal.
  2906. */
  2907. function fastLerp(normalizedValue, colors, out) {
  2908. if (!(colors && colors.length)
  2909. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2910. ) {
  2911. return;
  2912. }
  2913. out = out || [];
  2914. var value = normalizedValue * (colors.length - 1);
  2915. var leftIndex = Math.floor(value);
  2916. var rightIndex = Math.ceil(value);
  2917. var leftColor = colors[leftIndex];
  2918. var rightColor = colors[rightIndex];
  2919. var dv = value - leftIndex;
  2920. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  2921. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  2922. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  2923. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  2924. return out;
  2925. }
  2926. /**
  2927. * @deprecated
  2928. */
  2929. var fastMapToColor = fastLerp;
  2930. /**
  2931. * @param {number} normalizedValue A float between 0 and 1.
  2932. * @param {Array.<string>} colors Color list.
  2933. * @param {boolean=} fullOutput Default false.
  2934. * @return {(string|Object)} Result color. If fullOutput,
  2935. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  2936. * @memberOf module:zrender/util/color
  2937. */
  2938. function lerp$1(normalizedValue, colors, fullOutput) {
  2939. if (!(colors && colors.length)
  2940. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2941. ) {
  2942. return;
  2943. }
  2944. var value = normalizedValue * (colors.length - 1);
  2945. var leftIndex = Math.floor(value);
  2946. var rightIndex = Math.ceil(value);
  2947. var leftColor = parse(colors[leftIndex]);
  2948. var rightColor = parse(colors[rightIndex]);
  2949. var dv = value - leftIndex;
  2950. var color = stringify(
  2951. [
  2952. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  2953. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  2954. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  2955. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  2956. ],
  2957. 'rgba'
  2958. );
  2959. return fullOutput
  2960. ? {
  2961. color: color,
  2962. leftIndex: leftIndex,
  2963. rightIndex: rightIndex,
  2964. value: value
  2965. }
  2966. : color;
  2967. }
  2968. /**
  2969. * @deprecated
  2970. */
  2971. var mapToColor = lerp$1;
  2972. /**
  2973. * @param {string} color
  2974. * @param {number=} h 0 ~ 360, ignore when null.
  2975. * @param {number=} s 0 ~ 1, ignore when null.
  2976. * @param {number=} l 0 ~ 1, ignore when null.
  2977. * @return {string} Color string in rgba format.
  2978. * @memberOf module:zrender/util/color
  2979. */
  2980. function modifyHSL(color, h, s, l) {
  2981. color = parse(color);
  2982. if (color) {
  2983. color = rgba2hsla(color);
  2984. h != null && (color[0] = clampCssAngle(h));
  2985. s != null && (color[1] = parseCssFloat(s));
  2986. l != null && (color[2] = parseCssFloat(l));
  2987. return stringify(hsla2rgba(color), 'rgba');
  2988. }
  2989. }
  2990. /**
  2991. * @param {string} color
  2992. * @param {number=} alpha 0 ~ 1
  2993. * @return {string} Color string in rgba format.
  2994. * @memberOf module:zrender/util/color
  2995. */
  2996. function modifyAlpha(color, alpha) {
  2997. color = parse(color);
  2998. if (color && alpha != null) {
  2999. color[3] = clampCssFloat(alpha);
  3000. return stringify(color, 'rgba');
  3001. }
  3002. }
  3003. /**
  3004. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3005. * @param {string} type 'rgba', 'hsva', ...
  3006. * @return {string} Result color. (If input illegal, return undefined).
  3007. */
  3008. function stringify(arrColor, type) {
  3009. if (!arrColor || !arrColor.length) {
  3010. return;
  3011. }
  3012. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3013. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3014. colorStr += ',' + arrColor[3];
  3015. }
  3016. return type + '(' + colorStr + ')';
  3017. }
  3018. var color = (Object.freeze || Object)({
  3019. parse: parse,
  3020. lift: lift,
  3021. toHex: toHex,
  3022. fastLerp: fastLerp,
  3023. fastMapToColor: fastMapToColor,
  3024. lerp: lerp$1,
  3025. mapToColor: mapToColor,
  3026. modifyHSL: modifyHSL,
  3027. modifyAlpha: modifyAlpha,
  3028. stringify: stringify
  3029. });
  3030. /**
  3031. * @module echarts/animation/Animator
  3032. */
  3033. var arraySlice = Array.prototype.slice;
  3034. function defaultGetter(target, key) {
  3035. return target[key];
  3036. }
  3037. function defaultSetter(target, key, value) {
  3038. target[key] = value;
  3039. }
  3040. /**
  3041. * @param {number} p0
  3042. * @param {number} p1
  3043. * @param {number} percent
  3044. * @return {number}
  3045. */
  3046. function interpolateNumber(p0, p1, percent) {
  3047. return (p1 - p0) * percent + p0;
  3048. }
  3049. /**
  3050. * @param {string} p0
  3051. * @param {string} p1
  3052. * @param {number} percent
  3053. * @return {string}
  3054. */
  3055. function interpolateString(p0, p1, percent) {
  3056. return percent > 0.5 ? p1 : p0;
  3057. }
  3058. /**
  3059. * @param {Array} p0
  3060. * @param {Array} p1
  3061. * @param {number} percent
  3062. * @param {Array} out
  3063. * @param {number} arrDim
  3064. */
  3065. function interpolateArray(p0, p1, percent, out, arrDim) {
  3066. var len = p0.length;
  3067. if (arrDim == 1) {
  3068. for (var i = 0; i < len; i++) {
  3069. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3070. }
  3071. }
  3072. else {
  3073. var len2 = len && p0[0].length;
  3074. for (var i = 0; i < len; i++) {
  3075. for (var j = 0; j < len2; j++) {
  3076. out[i][j] = interpolateNumber(
  3077. p0[i][j], p1[i][j], percent
  3078. );
  3079. }
  3080. }
  3081. }
  3082. }
  3083. // arr0 is source array, arr1 is target array.
  3084. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3085. function fillArr(arr0, arr1, arrDim) {
  3086. var arr0Len = arr0.length;
  3087. var arr1Len = arr1.length;
  3088. if (arr0Len !== arr1Len) {
  3089. // FIXME Not work for TypedArray
  3090. var isPreviousLarger = arr0Len > arr1Len;
  3091. if (isPreviousLarger) {
  3092. // Cut the previous
  3093. arr0.length = arr1Len;
  3094. }
  3095. else {
  3096. // Fill the previous
  3097. for (var i = arr0Len; i < arr1Len; i++) {
  3098. arr0.push(
  3099. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3100. );
  3101. }
  3102. }
  3103. }
  3104. // Handling NaN value
  3105. var len2 = arr0[0] && arr0[0].length;
  3106. for (var i = 0; i < arr0.length; i++) {
  3107. if (arrDim === 1) {
  3108. if (isNaN(arr0[i])) {
  3109. arr0[i] = arr1[i];
  3110. }
  3111. }
  3112. else {
  3113. for (var j = 0; j < len2; j++) {
  3114. if (isNaN(arr0[i][j])) {
  3115. arr0[i][j] = arr1[i][j];
  3116. }
  3117. }
  3118. }
  3119. }
  3120. }
  3121. /**
  3122. * @param {Array} arr0
  3123. * @param {Array} arr1
  3124. * @param {number} arrDim
  3125. * @return {boolean}
  3126. */
  3127. function isArraySame(arr0, arr1, arrDim) {
  3128. if (arr0 === arr1) {
  3129. return true;
  3130. }
  3131. var len = arr0.length;
  3132. if (len !== arr1.length) {
  3133. return false;
  3134. }
  3135. if (arrDim === 1) {
  3136. for (var i = 0; i < len; i++) {
  3137. if (arr0[i] !== arr1[i]) {
  3138. return false;
  3139. }
  3140. }
  3141. }
  3142. else {
  3143. var len2 = arr0[0].length;
  3144. for (var i = 0; i < len; i++) {
  3145. for (var j = 0; j < len2; j++) {
  3146. if (arr0[i][j] !== arr1[i][j]) {
  3147. return false;
  3148. }
  3149. }
  3150. }
  3151. }
  3152. return true;
  3153. }
  3154. /**
  3155. * Catmull Rom interpolate array
  3156. * @param {Array} p0
  3157. * @param {Array} p1
  3158. * @param {Array} p2
  3159. * @param {Array} p3
  3160. * @param {number} t
  3161. * @param {number} t2
  3162. * @param {number} t3
  3163. * @param {Array} out
  3164. * @param {number} arrDim
  3165. */
  3166. function catmullRomInterpolateArray(
  3167. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3168. ) {
  3169. var len = p0.length;
  3170. if (arrDim == 1) {
  3171. for (var i = 0; i < len; i++) {
  3172. out[i] = catmullRomInterpolate(
  3173. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3174. );
  3175. }
  3176. }
  3177. else {
  3178. var len2 = p0[0].length;
  3179. for (var i = 0; i < len; i++) {
  3180. for (var j = 0; j < len2; j++) {
  3181. out[i][j] = catmullRomInterpolate(
  3182. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3183. t, t2, t3
  3184. );
  3185. }
  3186. }
  3187. }
  3188. }
  3189. /**
  3190. * Catmull Rom interpolate number
  3191. * @param {number} p0
  3192. * @param {number} p1
  3193. * @param {number} p2
  3194. * @param {number} p3
  3195. * @param {number} t
  3196. * @param {number} t2
  3197. * @param {number} t3
  3198. * @return {number}
  3199. */
  3200. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3201. var v0 = (p2 - p0) * 0.5;
  3202. var v1 = (p3 - p1) * 0.5;
  3203. return (2 * (p1 - p2) + v0 + v1) * t3
  3204. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3205. + v0 * t + p1;
  3206. }
  3207. function cloneValue(value) {
  3208. if (isArrayLike(value)) {
  3209. var len = value.length;
  3210. if (isArrayLike(value[0])) {
  3211. var ret = [];
  3212. for (var i = 0; i < len; i++) {
  3213. ret.push(arraySlice.call(value[i]));
  3214. }
  3215. return ret;
  3216. }
  3217. return arraySlice.call(value);
  3218. }
  3219. return value;
  3220. }
  3221. function rgba2String(rgba) {
  3222. rgba[0] = Math.floor(rgba[0]);
  3223. rgba[1] = Math.floor(rgba[1]);
  3224. rgba[2] = Math.floor(rgba[2]);
  3225. return 'rgba(' + rgba.join(',') + ')';
  3226. }
  3227. function getArrayDim(keyframes) {
  3228. var lastValue = keyframes[keyframes.length - 1].value;
  3229. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3230. }
  3231. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3232. var getter = animator._getter;
  3233. var setter = animator._setter;
  3234. var useSpline = easing === 'spline';
  3235. var trackLen = keyframes.length;
  3236. if (!trackLen) {
  3237. return;
  3238. }
  3239. // Guess data type
  3240. var firstVal = keyframes[0].value;
  3241. var isValueArray = isArrayLike(firstVal);
  3242. var isValueColor = false;
  3243. var isValueString = false;
  3244. // For vertices morphing
  3245. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3246. var trackMaxTime;
  3247. // Sort keyframe as ascending
  3248. keyframes.sort(function(a, b) {
  3249. return a.time - b.time;
  3250. });
  3251. trackMaxTime = keyframes[trackLen - 1].time;
  3252. // Percents of each keyframe
  3253. var kfPercents = [];
  3254. // Value of each keyframe
  3255. var kfValues = [];
  3256. var prevValue = keyframes[0].value;
  3257. var isAllValueEqual = true;
  3258. for (var i = 0; i < trackLen; i++) {
  3259. kfPercents.push(keyframes[i].time / trackMaxTime);
  3260. // Assume value is a color when it is a string
  3261. var value = keyframes[i].value;
  3262. // Check if value is equal, deep check if value is array
  3263. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3264. || (!isValueArray && value === prevValue))) {
  3265. isAllValueEqual = false;
  3266. }
  3267. prevValue = value;
  3268. // Try converting a string to a color array
  3269. if (typeof value == 'string') {
  3270. var colorArray = parse(value);
  3271. if (colorArray) {
  3272. value = colorArray;
  3273. isValueColor = true;
  3274. }
  3275. else {
  3276. isValueString = true;
  3277. }
  3278. }
  3279. kfValues.push(value);
  3280. }
  3281. if (!forceAnimate && isAllValueEqual) {
  3282. return;
  3283. }
  3284. var lastValue = kfValues[trackLen - 1];
  3285. // Polyfill array and NaN value
  3286. for (var i = 0; i < trackLen - 1; i++) {
  3287. if (isValueArray) {
  3288. fillArr(kfValues[i], lastValue, arrDim);
  3289. }
  3290. else {
  3291. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3292. kfValues[i] = lastValue;
  3293. }
  3294. }
  3295. }
  3296. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3297. // Cache the key of last frame to speed up when
  3298. // animation playback is sequency
  3299. var lastFrame = 0;
  3300. var lastFramePercent = 0;
  3301. var start;
  3302. var w;
  3303. var p0;
  3304. var p1;
  3305. var p2;
  3306. var p3;
  3307. if (isValueColor) {
  3308. var rgba = [0, 0, 0, 0];
  3309. }
  3310. var onframe = function (target, percent) {
  3311. // Find the range keyframes
  3312. // kf1-----kf2---------current--------kf3
  3313. // find kf2 and kf3 and do interpolation
  3314. var frame;
  3315. // In the easing function like elasticOut, percent may less than 0
  3316. if (percent < 0) {
  3317. frame = 0;
  3318. }
  3319. else if (percent < lastFramePercent) {
  3320. // Start from next key
  3321. // PENDING start from lastFrame ?
  3322. start = Math.min(lastFrame + 1, trackLen - 1);
  3323. for (frame = start; frame >= 0; frame--) {
  3324. if (kfPercents[frame] <= percent) {
  3325. break;
  3326. }
  3327. }
  3328. // PENDING really need to do this ?
  3329. frame = Math.min(frame, trackLen - 2);
  3330. }
  3331. else {
  3332. for (frame = lastFrame; frame < trackLen; frame++) {
  3333. if (kfPercents[frame] > percent) {
  3334. break;
  3335. }
  3336. }
  3337. frame = Math.min(frame - 1, trackLen - 2);
  3338. }
  3339. lastFrame = frame;
  3340. lastFramePercent = percent;
  3341. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3342. if (range === 0) {
  3343. return;
  3344. }
  3345. else {
  3346. w = (percent - kfPercents[frame]) / range;
  3347. }
  3348. if (useSpline) {
  3349. p1 = kfValues[frame];
  3350. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3351. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3352. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3353. if (isValueArray) {
  3354. catmullRomInterpolateArray(
  3355. p0, p1, p2, p3, w, w * w, w * w * w,
  3356. getter(target, propName),
  3357. arrDim
  3358. );
  3359. }
  3360. else {
  3361. var value;
  3362. if (isValueColor) {
  3363. value = catmullRomInterpolateArray(
  3364. p0, p1, p2, p3, w, w * w, w * w * w,
  3365. rgba, 1
  3366. );
  3367. value = rgba2String(rgba);
  3368. }
  3369. else if (isValueString) {
  3370. // String is step(0.5)
  3371. return interpolateString(p1, p2, w);
  3372. }
  3373. else {
  3374. value = catmullRomInterpolate(
  3375. p0, p1, p2, p3, w, w * w, w * w * w
  3376. );
  3377. }
  3378. setter(
  3379. target,
  3380. propName,
  3381. value
  3382. );
  3383. }
  3384. }
  3385. else {
  3386. if (isValueArray) {
  3387. interpolateArray(
  3388. kfValues[frame], kfValues[frame + 1], w,
  3389. getter(target, propName),
  3390. arrDim
  3391. );
  3392. }
  3393. else {
  3394. var value;
  3395. if (isValueColor) {
  3396. interpolateArray(
  3397. kfValues[frame], kfValues[frame + 1], w,
  3398. rgba, 1
  3399. );
  3400. value = rgba2String(rgba);
  3401. }
  3402. else if (isValueString) {
  3403. // String is step(0.5)
  3404. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3405. }
  3406. else {
  3407. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3408. }
  3409. setter(
  3410. target,
  3411. propName,
  3412. value
  3413. );
  3414. }
  3415. }
  3416. };
  3417. var clip = new Clip({
  3418. target: animator._target,
  3419. life: trackMaxTime,
  3420. loop: animator._loop,
  3421. delay: animator._delay,
  3422. onframe: onframe,
  3423. ondestroy: oneTrackDone
  3424. });
  3425. if (easing && easing !== 'spline') {
  3426. clip.easing = easing;
  3427. }
  3428. return clip;
  3429. }
  3430. /**
  3431. * @alias module:zrender/animation/Animator
  3432. * @constructor
  3433. * @param {Object} target
  3434. * @param {boolean} loop
  3435. * @param {Function} getter
  3436. * @param {Function} setter
  3437. */
  3438. var Animator = function(target, loop, getter, setter) {
  3439. this._tracks = {};
  3440. this._target = target;
  3441. this._loop = loop || false;
  3442. this._getter = getter || defaultGetter;
  3443. this._setter = setter || defaultSetter;
  3444. this._clipCount = 0;
  3445. this._delay = 0;
  3446. this._doneList = [];
  3447. this._onframeList = [];
  3448. this._clipList = [];
  3449. };
  3450. Animator.prototype = {
  3451. /**
  3452. * 设置动画关键帧
  3453. * @param {number} time 关键帧时间,单位是ms
  3454. * @param {Object} props 关键帧的属性值,key-value表示
  3455. * @return {module:zrender/animation/Animator}
  3456. */
  3457. when: function(time /* ms */, props) {
  3458. var tracks = this._tracks;
  3459. for (var propName in props) {
  3460. if (!props.hasOwnProperty(propName)) {
  3461. continue;
  3462. }
  3463. if (!tracks[propName]) {
  3464. tracks[propName] = [];
  3465. // Invalid value
  3466. var value = this._getter(this._target, propName);
  3467. if (value == null) {
  3468. // zrLog('Invalid property ' + propName);
  3469. continue;
  3470. }
  3471. // If time is 0
  3472. // Then props is given initialize value
  3473. // Else
  3474. // Initialize value from current prop value
  3475. if (time !== 0) {
  3476. tracks[propName].push({
  3477. time: 0,
  3478. value: cloneValue(value)
  3479. });
  3480. }
  3481. }
  3482. tracks[propName].push({
  3483. time: time,
  3484. value: props[propName]
  3485. });
  3486. }
  3487. return this;
  3488. },
  3489. /**
  3490. * 添加动画每一帧的回调函数
  3491. * @param {Function} callback
  3492. * @return {module:zrender/animation/Animator}
  3493. */
  3494. during: function (callback) {
  3495. this._onframeList.push(callback);
  3496. return this;
  3497. },
  3498. pause: function () {
  3499. for (var i = 0; i < this._clipList.length; i++) {
  3500. this._clipList[i].pause();
  3501. }
  3502. this._paused = true;
  3503. },
  3504. resume: function () {
  3505. for (var i = 0; i < this._clipList.length; i++) {
  3506. this._clipList[i].resume();
  3507. }
  3508. this._paused = false;
  3509. },
  3510. isPaused: function () {
  3511. return !!this._paused;
  3512. },
  3513. _doneCallback: function () {
  3514. // Clear all tracks
  3515. this._tracks = {};
  3516. // Clear all clips
  3517. this._clipList.length = 0;
  3518. var doneList = this._doneList;
  3519. var len = doneList.length;
  3520. for (var i = 0; i < len; i++) {
  3521. doneList[i].call(this);
  3522. }
  3523. },
  3524. /**
  3525. * 开始执行动画
  3526. * @param {string|Function} [easing]
  3527. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3528. * @param {boolean} forceAnimate
  3529. * @return {module:zrender/animation/Animator}
  3530. */
  3531. start: function (easing, forceAnimate) {
  3532. var self = this;
  3533. var clipCount = 0;
  3534. var oneTrackDone = function() {
  3535. clipCount--;
  3536. if (!clipCount) {
  3537. self._doneCallback();
  3538. }
  3539. };
  3540. var lastClip;
  3541. for (var propName in this._tracks) {
  3542. if (!this._tracks.hasOwnProperty(propName)) {
  3543. continue;
  3544. }
  3545. var clip = createTrackClip(
  3546. this, easing, oneTrackDone,
  3547. this._tracks[propName], propName, forceAnimate
  3548. );
  3549. if (clip) {
  3550. this._clipList.push(clip);
  3551. clipCount++;
  3552. // If start after added to animation
  3553. if (this.animation) {
  3554. this.animation.addClip(clip);
  3555. }
  3556. lastClip = clip;
  3557. }
  3558. }
  3559. // Add during callback on the last clip
  3560. if (lastClip) {
  3561. var oldOnFrame = lastClip.onframe;
  3562. lastClip.onframe = function (target, percent) {
  3563. oldOnFrame(target, percent);
  3564. for (var i = 0; i < self._onframeList.length; i++) {
  3565. self._onframeList[i](target, percent);
  3566. }
  3567. };
  3568. }
  3569. // This optimization will help the case that in the upper application
  3570. // the view may be refreshed frequently, where animation will be
  3571. // called repeatly but nothing changed.
  3572. if (!clipCount) {
  3573. this._doneCallback();
  3574. }
  3575. return this;
  3576. },
  3577. /**
  3578. * 停止动画
  3579. * @param {boolean} forwardToLast If move to last frame before stop
  3580. */
  3581. stop: function (forwardToLast) {
  3582. var clipList = this._clipList;
  3583. var animation = this.animation;
  3584. for (var i = 0; i < clipList.length; i++) {
  3585. var clip = clipList[i];
  3586. if (forwardToLast) {
  3587. // Move to last frame before stop
  3588. clip.onframe(this._target, 1);
  3589. }
  3590. animation && animation.removeClip(clip);
  3591. }
  3592. clipList.length = 0;
  3593. },
  3594. /**
  3595. * 设置动画延迟开始的时间
  3596. * @param {number} time 单位ms
  3597. * @return {module:zrender/animation/Animator}
  3598. */
  3599. delay: function (time) {
  3600. this._delay = time;
  3601. return this;
  3602. },
  3603. /**
  3604. * 添加动画结束的回调
  3605. * @param {Function} cb
  3606. * @return {module:zrender/animation/Animator}
  3607. */
  3608. done: function(cb) {
  3609. if (cb) {
  3610. this._doneList.push(cb);
  3611. }
  3612. return this;
  3613. },
  3614. /**
  3615. * @return {Array.<module:zrender/animation/Clip>}
  3616. */
  3617. getClips: function () {
  3618. return this._clipList;
  3619. }
  3620. };
  3621. var dpr = 1;
  3622. // If in browser environment
  3623. if (typeof window !== 'undefined') {
  3624. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3625. }
  3626. /**
  3627. * config默认配置项
  3628. * @exports zrender/config
  3629. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3630. */
  3631. /**
  3632. * debug日志选项:catchBrushException为true下有效
  3633. * 0 : 不生成debug数据,发布用
  3634. * 1 : 异常抛出,调试用
  3635. * 2 : 控制台输出,调试用
  3636. */
  3637. var debugMode = 0;
  3638. // retina 屏幕优化
  3639. var devicePixelRatio = dpr;
  3640. var log = function () {
  3641. };
  3642. if (debugMode === 1) {
  3643. log = function () {
  3644. for (var k in arguments) {
  3645. throw new Error(arguments[k]);
  3646. }
  3647. };
  3648. }
  3649. else if (debugMode > 1) {
  3650. log = function () {
  3651. for (var k in arguments) {
  3652. console.log(arguments[k]);
  3653. }
  3654. };
  3655. }
  3656. var zrLog = log;
  3657. /**
  3658. * @alias modue:zrender/mixin/Animatable
  3659. * @constructor
  3660. */
  3661. var Animatable = function () {
  3662. /**
  3663. * @type {Array.<module:zrender/animation/Animator>}
  3664. * @readOnly
  3665. */
  3666. this.animators = [];
  3667. };
  3668. Animatable.prototype = {
  3669. constructor: Animatable,
  3670. /**
  3671. * 动画
  3672. *
  3673. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3674. * @param {boolean} [loop] Whether to loop animation.
  3675. * @return {module:zrender/animation/Animator}
  3676. * @example:
  3677. * el.animate('style', false)
  3678. * .when(1000, {x: 10} )
  3679. * .done(function(){ // Animation done })
  3680. * .start()
  3681. */
  3682. animate: function (path, loop) {
  3683. var target;
  3684. var animatingShape = false;
  3685. var el = this;
  3686. var zr = this.__zr;
  3687. if (path) {
  3688. var pathSplitted = path.split('.');
  3689. var prop = el;
  3690. // If animating shape
  3691. animatingShape = pathSplitted[0] === 'shape';
  3692. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3693. if (!prop) {
  3694. continue;
  3695. }
  3696. prop = prop[pathSplitted[i]];
  3697. }
  3698. if (prop) {
  3699. target = prop;
  3700. }
  3701. }
  3702. else {
  3703. target = el;
  3704. }
  3705. if (!target) {
  3706. zrLog(
  3707. 'Property "'
  3708. + path
  3709. + '" is not existed in element '
  3710. + el.id
  3711. );
  3712. return;
  3713. }
  3714. var animators = el.animators;
  3715. var animator = new Animator(target, loop);
  3716. animator.during(function (target) {
  3717. el.dirty(animatingShape);
  3718. })
  3719. .done(function () {
  3720. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3721. animators.splice(indexOf(animators, animator), 1);
  3722. });
  3723. animators.push(animator);
  3724. // If animate after added to the zrender
  3725. if (zr) {
  3726. zr.animation.addAnimator(animator);
  3727. }
  3728. return animator;
  3729. },
  3730. /**
  3731. * 停止动画
  3732. * @param {boolean} forwardToLast If move to last frame before stop
  3733. */
  3734. stopAnimation: function (forwardToLast) {
  3735. var animators = this.animators;
  3736. var len = animators.length;
  3737. for (var i = 0; i < len; i++) {
  3738. animators[i].stop(forwardToLast);
  3739. }
  3740. animators.length = 0;
  3741. return this;
  3742. },
  3743. /**
  3744. * Caution: this method will stop previous animation.
  3745. * So do not use this method to one element twice before
  3746. * animation starts, unless you know what you are doing.
  3747. * @param {Object} target
  3748. * @param {number} [time=500] Time in ms
  3749. * @param {string} [easing='linear']
  3750. * @param {number} [delay=0]
  3751. * @param {Function} [callback]
  3752. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3753. * immediently when target values are the same as current values.
  3754. *
  3755. * @example
  3756. * // Animate position
  3757. * el.animateTo({
  3758. * position: [10, 10]
  3759. * }, function () { // done })
  3760. *
  3761. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3762. * el.animateTo({
  3763. * shape: {
  3764. * width: 500
  3765. * },
  3766. * style: {
  3767. * fill: 'red'
  3768. * }
  3769. * position: [10, 10]
  3770. * }, 100, 100, 'cubicOut', function () { // done })
  3771. */
  3772. // TODO Return animation key
  3773. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3774. // animateTo(target, time, easing, callback);
  3775. if (isString(delay)) {
  3776. callback = easing;
  3777. easing = delay;
  3778. delay = 0;
  3779. }
  3780. // animateTo(target, time, delay, callback);
  3781. else if (isFunction(easing)) {
  3782. callback = easing;
  3783. easing = 'linear';
  3784. delay = 0;
  3785. }
  3786. // animateTo(target, time, callback);
  3787. else if (isFunction(delay)) {
  3788. callback = delay;
  3789. delay = 0;
  3790. }
  3791. // animateTo(target, callback)
  3792. else if (isFunction(time)) {
  3793. callback = time;
  3794. time = 500;
  3795. }
  3796. // animateTo(target)
  3797. else if (!time) {
  3798. time = 500;
  3799. }
  3800. // Stop all previous animations
  3801. this.stopAnimation();
  3802. this._animateToShallow('', this, target, time, delay);
  3803. // Animators may be removed immediately after start
  3804. // if there is nothing to animate
  3805. var animators = this.animators.slice();
  3806. var count = animators.length;
  3807. function done() {
  3808. count--;
  3809. if (!count) {
  3810. callback && callback();
  3811. }
  3812. }
  3813. // No animators. This should be checked before animators[i].start(),
  3814. // because 'done' may be executed immediately if no need to animate.
  3815. if (!count) {
  3816. callback && callback();
  3817. }
  3818. // Start after all animators created
  3819. // Incase any animator is done immediately when all animation properties are not changed
  3820. for (var i = 0; i < animators.length; i++) {
  3821. animators[i]
  3822. .done(done)
  3823. .start(easing, forceAnimate);
  3824. }
  3825. },
  3826. /**
  3827. * @private
  3828. * @param {string} path=''
  3829. * @param {Object} source=this
  3830. * @param {Object} target
  3831. * @param {number} [time=500]
  3832. * @param {number} [delay=0]
  3833. *
  3834. * @example
  3835. * // Animate position
  3836. * el._animateToShallow({
  3837. * position: [10, 10]
  3838. * })
  3839. *
  3840. * // Animate shape, style and position in 100ms, delayed 100ms
  3841. * el._animateToShallow({
  3842. * shape: {
  3843. * width: 500
  3844. * },
  3845. * style: {
  3846. * fill: 'red'
  3847. * }
  3848. * position: [10, 10]
  3849. * }, 100, 100)
  3850. */
  3851. _animateToShallow: function (path, source, target, time, delay) {
  3852. var objShallow = {};
  3853. var propertyCount = 0;
  3854. for (var name in target) {
  3855. if (!target.hasOwnProperty(name)) {
  3856. continue;
  3857. }
  3858. if (source[name] != null) {
  3859. if (isObject(target[name]) && !isArrayLike(target[name])) {
  3860. this._animateToShallow(
  3861. path ? path + '.' + name : name,
  3862. source[name],
  3863. target[name],
  3864. time,
  3865. delay
  3866. );
  3867. }
  3868. else {
  3869. objShallow[name] = target[name];
  3870. propertyCount++;
  3871. }
  3872. }
  3873. else if (target[name] != null) {
  3874. // Attr directly if not has property
  3875. // FIXME, if some property not needed for element ?
  3876. if (!path) {
  3877. this.attr(name, target[name]);
  3878. }
  3879. else { // Shape or style
  3880. var props = {};
  3881. props[path] = {};
  3882. props[path][name] = target[name];
  3883. this.attr(props);
  3884. }
  3885. }
  3886. }
  3887. if (propertyCount > 0) {
  3888. this.animate(path, false)
  3889. .when(time == null ? 500 : time, objShallow)
  3890. .delay(delay || 0);
  3891. }
  3892. return this;
  3893. }
  3894. };
  3895. /**
  3896. * @alias module:zrender/Element
  3897. * @constructor
  3898. * @extends {module:zrender/mixin/Animatable}
  3899. * @extends {module:zrender/mixin/Transformable}
  3900. * @extends {module:zrender/mixin/Eventful}
  3901. */
  3902. var Element = function (opts) { // jshint ignore:line
  3903. Transformable.call(this, opts);
  3904. Eventful.call(this, opts);
  3905. Animatable.call(this, opts);
  3906. /**
  3907. * 画布元素ID
  3908. * @type {string}
  3909. */
  3910. this.id = opts.id || guid();
  3911. };
  3912. Element.prototype = {
  3913. /**
  3914. * 元素类型
  3915. * Element type
  3916. * @type {string}
  3917. */
  3918. type: 'element',
  3919. /**
  3920. * 元素名字
  3921. * Element name
  3922. * @type {string}
  3923. */
  3924. name: '',
  3925. /**
  3926. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  3927. * ZRender instance will be assigned when element is associated with zrender
  3928. * @name module:/zrender/Element#__zr
  3929. * @type {module:zrender/ZRender}
  3930. */
  3931. __zr: null,
  3932. /**
  3933. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  3934. * If ignore drawing and events of the element object
  3935. * @name module:/zrender/Element#ignore
  3936. * @type {boolean}
  3937. * @default false
  3938. */
  3939. ignore: false,
  3940. /**
  3941. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  3942. * 该路径会继承被裁减对象的变换
  3943. * @type {module:zrender/graphic/Path}
  3944. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  3945. * @readOnly
  3946. */
  3947. clipPath: null,
  3948. /**
  3949. * Drift element
  3950. * @param {number} dx dx on the global space
  3951. * @param {number} dy dy on the global space
  3952. */
  3953. drift: function (dx, dy) {
  3954. switch (this.draggable) {
  3955. case 'horizontal':
  3956. dy = 0;
  3957. break;
  3958. case 'vertical':
  3959. dx = 0;
  3960. break;
  3961. }
  3962. var m = this.transform;
  3963. if (!m) {
  3964. m = this.transform = [1, 0, 0, 1, 0, 0];
  3965. }
  3966. m[4] += dx;
  3967. m[5] += dy;
  3968. this.decomposeTransform();
  3969. this.dirty(false);
  3970. },
  3971. /**
  3972. * Hook before update
  3973. */
  3974. beforeUpdate: function () {},
  3975. /**
  3976. * Hook after update
  3977. */
  3978. afterUpdate: function () {},
  3979. /**
  3980. * Update each frame
  3981. */
  3982. update: function () {
  3983. this.updateTransform();
  3984. },
  3985. /**
  3986. * @param {Function} cb
  3987. * @param {} context
  3988. */
  3989. traverse: function (cb, context) {},
  3990. /**
  3991. * @protected
  3992. */
  3993. attrKV: function (key, value) {
  3994. if (key === 'position' || key === 'scale' || key === 'origin') {
  3995. // Copy the array
  3996. if (value) {
  3997. var target = this[key];
  3998. if (!target) {
  3999. target = this[key] = [];
  4000. }
  4001. target[0] = value[0];
  4002. target[1] = value[1];
  4003. }
  4004. }
  4005. else {
  4006. this[key] = value;
  4007. }
  4008. },
  4009. /**
  4010. * Hide the element
  4011. */
  4012. hide: function () {
  4013. this.ignore = true;
  4014. this.__zr && this.__zr.refresh();
  4015. },
  4016. /**
  4017. * Show the element
  4018. */
  4019. show: function () {
  4020. this.ignore = false;
  4021. this.__zr && this.__zr.refresh();
  4022. },
  4023. /**
  4024. * @param {string|Object} key
  4025. * @param {*} value
  4026. */
  4027. attr: function (key, value) {
  4028. if (typeof key === 'string') {
  4029. this.attrKV(key, value);
  4030. }
  4031. else if (isObject(key)) {
  4032. for (var name in key) {
  4033. if (key.hasOwnProperty(name)) {
  4034. this.attrKV(name, key[name]);
  4035. }
  4036. }
  4037. }
  4038. this.dirty(false);
  4039. return this;
  4040. },
  4041. /**
  4042. * @param {module:zrender/graphic/Path} clipPath
  4043. */
  4044. setClipPath: function (clipPath) {
  4045. var zr = this.__zr;
  4046. if (zr) {
  4047. clipPath.addSelfToZr(zr);
  4048. }
  4049. // Remove previous clip path
  4050. if (this.clipPath && this.clipPath !== clipPath) {
  4051. this.removeClipPath();
  4052. }
  4053. this.clipPath = clipPath;
  4054. clipPath.__zr = zr;
  4055. clipPath.__clipTarget = this;
  4056. this.dirty(false);
  4057. },
  4058. /**
  4059. */
  4060. removeClipPath: function () {
  4061. var clipPath = this.clipPath;
  4062. if (clipPath) {
  4063. if (clipPath.__zr) {
  4064. clipPath.removeSelfFromZr(clipPath.__zr);
  4065. }
  4066. clipPath.__zr = null;
  4067. clipPath.__clipTarget = null;
  4068. this.clipPath = null;
  4069. this.dirty(false);
  4070. }
  4071. },
  4072. /**
  4073. * Add self from zrender instance.
  4074. * Not recursively because it will be invoked when element added to storage.
  4075. * @param {module:zrender/ZRender} zr
  4076. */
  4077. addSelfToZr: function (zr) {
  4078. this.__zr = zr;
  4079. // 添加动画
  4080. var animators = this.animators;
  4081. if (animators) {
  4082. for (var i = 0; i < animators.length; i++) {
  4083. zr.animation.addAnimator(animators[i]);
  4084. }
  4085. }
  4086. if (this.clipPath) {
  4087. this.clipPath.addSelfToZr(zr);
  4088. }
  4089. },
  4090. /**
  4091. * Remove self from zrender instance.
  4092. * Not recursively because it will be invoked when element added to storage.
  4093. * @param {module:zrender/ZRender} zr
  4094. */
  4095. removeSelfFromZr: function (zr) {
  4096. this.__zr = null;
  4097. // 移除动画
  4098. var animators = this.animators;
  4099. if (animators) {
  4100. for (var i = 0; i < animators.length; i++) {
  4101. zr.animation.removeAnimator(animators[i]);
  4102. }
  4103. }
  4104. if (this.clipPath) {
  4105. this.clipPath.removeSelfFromZr(zr);
  4106. }
  4107. }
  4108. };
  4109. mixin(Element, Animatable);
  4110. mixin(Element, Transformable);
  4111. mixin(Element, Eventful);
  4112. /**
  4113. * @module echarts/core/BoundingRect
  4114. */
  4115. var v2ApplyTransform = applyTransform;
  4116. var mathMin = Math.min;
  4117. var mathMax = Math.max;
  4118. /**
  4119. * @alias module:echarts/core/BoundingRect
  4120. */
  4121. function BoundingRect(x, y, width, height) {
  4122. if (width < 0) {
  4123. x = x + width;
  4124. width = -width;
  4125. }
  4126. if (height < 0) {
  4127. y = y + height;
  4128. height = -height;
  4129. }
  4130. /**
  4131. * @type {number}
  4132. */
  4133. this.x = x;
  4134. /**
  4135. * @type {number}
  4136. */
  4137. this.y = y;
  4138. /**
  4139. * @type {number}
  4140. */
  4141. this.width = width;
  4142. /**
  4143. * @type {number}
  4144. */
  4145. this.height = height;
  4146. }
  4147. BoundingRect.prototype = {
  4148. constructor: BoundingRect,
  4149. /**
  4150. * @param {module:echarts/core/BoundingRect} other
  4151. */
  4152. union: function (other) {
  4153. var x = mathMin(other.x, this.x);
  4154. var y = mathMin(other.y, this.y);
  4155. this.width = mathMax(
  4156. other.x + other.width,
  4157. this.x + this.width
  4158. ) - x;
  4159. this.height = mathMax(
  4160. other.y + other.height,
  4161. this.y + this.height
  4162. ) - y;
  4163. this.x = x;
  4164. this.y = y;
  4165. },
  4166. /**
  4167. * @param {Array.<number>} m
  4168. * @methods
  4169. */
  4170. applyTransform: (function () {
  4171. var lt = [];
  4172. var rb = [];
  4173. var lb = [];
  4174. var rt = [];
  4175. return function (m) {
  4176. // In case usage like this
  4177. // el.getBoundingRect().applyTransform(el.transform)
  4178. // And element has no transform
  4179. if (!m) {
  4180. return;
  4181. }
  4182. lt[0] = lb[0] = this.x;
  4183. lt[1] = rt[1] = this.y;
  4184. rb[0] = rt[0] = this.x + this.width;
  4185. rb[1] = lb[1] = this.y + this.height;
  4186. v2ApplyTransform(lt, lt, m);
  4187. v2ApplyTransform(rb, rb, m);
  4188. v2ApplyTransform(lb, lb, m);
  4189. v2ApplyTransform(rt, rt, m);
  4190. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4191. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4192. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4193. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4194. this.width = maxX - this.x;
  4195. this.height = maxY - this.y;
  4196. };
  4197. })(),
  4198. /**
  4199. * Calculate matrix of transforming from self to target rect
  4200. * @param {module:zrender/core/BoundingRect} b
  4201. * @return {Array.<number>}
  4202. */
  4203. calculateTransform: function (b) {
  4204. var a = this;
  4205. var sx = b.width / a.width;
  4206. var sy = b.height / a.height;
  4207. var m = create$1();
  4208. // 矩阵右乘
  4209. translate(m, m, [-a.x, -a.y]);
  4210. scale$1(m, m, [sx, sy]);
  4211. translate(m, m, [b.x, b.y]);
  4212. return m;
  4213. },
  4214. /**
  4215. * @param {(module:echarts/core/BoundingRect|Object)} b
  4216. * @return {boolean}
  4217. */
  4218. intersect: function (b) {
  4219. if (!b) {
  4220. return false;
  4221. }
  4222. if (!(b instanceof BoundingRect)) {
  4223. // Normalize negative width/height.
  4224. b = BoundingRect.create(b);
  4225. }
  4226. var a = this;
  4227. var ax0 = a.x;
  4228. var ax1 = a.x + a.width;
  4229. var ay0 = a.y;
  4230. var ay1 = a.y + a.height;
  4231. var bx0 = b.x;
  4232. var bx1 = b.x + b.width;
  4233. var by0 = b.y;
  4234. var by1 = b.y + b.height;
  4235. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4236. },
  4237. contain: function (x, y) {
  4238. var rect = this;
  4239. return x >= rect.x
  4240. && x <= (rect.x + rect.width)
  4241. && y >= rect.y
  4242. && y <= (rect.y + rect.height);
  4243. },
  4244. /**
  4245. * @return {module:echarts/core/BoundingRect}
  4246. */
  4247. clone: function () {
  4248. return new BoundingRect(this.x, this.y, this.width, this.height);
  4249. },
  4250. /**
  4251. * Copy from another rect
  4252. */
  4253. copy: function (other) {
  4254. this.x = other.x;
  4255. this.y = other.y;
  4256. this.width = other.width;
  4257. this.height = other.height;
  4258. },
  4259. plain: function () {
  4260. return {
  4261. x: this.x,
  4262. y: this.y,
  4263. width: this.width,
  4264. height: this.height
  4265. };
  4266. }
  4267. };
  4268. /**
  4269. * @param {Object|module:zrender/core/BoundingRect} rect
  4270. * @param {number} rect.x
  4271. * @param {number} rect.y
  4272. * @param {number} rect.width
  4273. * @param {number} rect.height
  4274. * @return {module:zrender/core/BoundingRect}
  4275. */
  4276. BoundingRect.create = function (rect) {
  4277. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4278. };
  4279. /**
  4280. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4281. * @module zrender/graphic/Group
  4282. * @example
  4283. * var Group = require('zrender/container/Group');
  4284. * var Circle = require('zrender/graphic/shape/Circle');
  4285. * var g = new Group();
  4286. * g.position[0] = 100;
  4287. * g.position[1] = 100;
  4288. * g.add(new Circle({
  4289. * style: {
  4290. * x: 100,
  4291. * y: 100,
  4292. * r: 20,
  4293. * }
  4294. * }));
  4295. * zr.add(g);
  4296. */
  4297. /**
  4298. * @alias module:zrender/graphic/Group
  4299. * @constructor
  4300. * @extends module:zrender/mixin/Transformable
  4301. * @extends module:zrender/mixin/Eventful
  4302. */
  4303. var Group = function (opts) {
  4304. opts = opts || {};
  4305. Element.call(this, opts);
  4306. for (var key in opts) {
  4307. if (opts.hasOwnProperty(key)) {
  4308. this[key] = opts[key];
  4309. }
  4310. }
  4311. this._children = [];
  4312. this.__storage = null;
  4313. this.__dirty = true;
  4314. };
  4315. Group.prototype = {
  4316. constructor: Group,
  4317. isGroup: true,
  4318. /**
  4319. * @type {string}
  4320. */
  4321. type: 'group',
  4322. /**
  4323. * 所有子孙元素是否响应鼠标事件
  4324. * @name module:/zrender/container/Group#silent
  4325. * @type {boolean}
  4326. * @default false
  4327. */
  4328. silent: false,
  4329. /**
  4330. * @return {Array.<module:zrender/Element>}
  4331. */
  4332. children: function () {
  4333. return this._children.slice();
  4334. },
  4335. /**
  4336. * 获取指定 index 的儿子节点
  4337. * @param {number} idx
  4338. * @return {module:zrender/Element}
  4339. */
  4340. childAt: function (idx) {
  4341. return this._children[idx];
  4342. },
  4343. /**
  4344. * 获取指定名字的儿子节点
  4345. * @param {string} name
  4346. * @return {module:zrender/Element}
  4347. */
  4348. childOfName: function (name) {
  4349. var children = this._children;
  4350. for (var i = 0; i < children.length; i++) {
  4351. if (children[i].name === name) {
  4352. return children[i];
  4353. }
  4354. }
  4355. },
  4356. /**
  4357. * @return {number}
  4358. */
  4359. childCount: function () {
  4360. return this._children.length;
  4361. },
  4362. /**
  4363. * 添加子节点到最后
  4364. * @param {module:zrender/Element} child
  4365. */
  4366. add: function (child) {
  4367. if (child && child !== this && child.parent !== this) {
  4368. this._children.push(child);
  4369. this._doAdd(child);
  4370. }
  4371. return this;
  4372. },
  4373. /**
  4374. * 添加子节点在 nextSibling 之前
  4375. * @param {module:zrender/Element} child
  4376. * @param {module:zrender/Element} nextSibling
  4377. */
  4378. addBefore: function (child, nextSibling) {
  4379. if (child && child !== this && child.parent !== this
  4380. && nextSibling && nextSibling.parent === this) {
  4381. var children = this._children;
  4382. var idx = children.indexOf(nextSibling);
  4383. if (idx >= 0) {
  4384. children.splice(idx, 0, child);
  4385. this._doAdd(child);
  4386. }
  4387. }
  4388. return this;
  4389. },
  4390. _doAdd: function (child) {
  4391. if (child.parent) {
  4392. child.parent.remove(child);
  4393. }
  4394. child.parent = this;
  4395. var storage = this.__storage;
  4396. var zr = this.__zr;
  4397. if (storage && storage !== child.__storage) {
  4398. storage.addToStorage(child);
  4399. if (child instanceof Group) {
  4400. child.addChildrenToStorage(storage);
  4401. }
  4402. }
  4403. zr && zr.refresh();
  4404. },
  4405. /**
  4406. * 移除子节点
  4407. * @param {module:zrender/Element} child
  4408. */
  4409. remove: function (child) {
  4410. var zr = this.__zr;
  4411. var storage = this.__storage;
  4412. var children = this._children;
  4413. var idx = indexOf(children, child);
  4414. if (idx < 0) {
  4415. return this;
  4416. }
  4417. children.splice(idx, 1);
  4418. child.parent = null;
  4419. if (storage) {
  4420. storage.delFromStorage(child);
  4421. if (child instanceof Group) {
  4422. child.delChildrenFromStorage(storage);
  4423. }
  4424. }
  4425. zr && zr.refresh();
  4426. return this;
  4427. },
  4428. /**
  4429. * 移除所有子节点
  4430. */
  4431. removeAll: function () {
  4432. var children = this._children;
  4433. var storage = this.__storage;
  4434. var child;
  4435. var i;
  4436. for (i = 0; i < children.length; i++) {
  4437. child = children[i];
  4438. if (storage) {
  4439. storage.delFromStorage(child);
  4440. if (child instanceof Group) {
  4441. child.delChildrenFromStorage(storage);
  4442. }
  4443. }
  4444. child.parent = null;
  4445. }
  4446. children.length = 0;
  4447. return this;
  4448. },
  4449. /**
  4450. * 遍历所有子节点
  4451. * @param {Function} cb
  4452. * @param {} context
  4453. */
  4454. eachChild: function (cb, context) {
  4455. var children = this._children;
  4456. for (var i = 0; i < children.length; i++) {
  4457. var child = children[i];
  4458. cb.call(context, child, i);
  4459. }
  4460. return this;
  4461. },
  4462. /**
  4463. * 深度优先遍历所有子孙节点
  4464. * @param {Function} cb
  4465. * @param {} context
  4466. */
  4467. traverse: function (cb, context) {
  4468. for (var i = 0; i < this._children.length; i++) {
  4469. var child = this._children[i];
  4470. cb.call(context, child);
  4471. if (child.type === 'group') {
  4472. child.traverse(cb, context);
  4473. }
  4474. }
  4475. return this;
  4476. },
  4477. addChildrenToStorage: function (storage) {
  4478. for (var i = 0; i < this._children.length; i++) {
  4479. var child = this._children[i];
  4480. storage.addToStorage(child);
  4481. if (child instanceof Group) {
  4482. child.addChildrenToStorage(storage);
  4483. }
  4484. }
  4485. },
  4486. delChildrenFromStorage: function (storage) {
  4487. for (var i = 0; i < this._children.length; i++) {
  4488. var child = this._children[i];
  4489. storage.delFromStorage(child);
  4490. if (child instanceof Group) {
  4491. child.delChildrenFromStorage(storage);
  4492. }
  4493. }
  4494. },
  4495. dirty: function () {
  4496. this.__dirty = true;
  4497. this.__zr && this.__zr.refresh();
  4498. return this;
  4499. },
  4500. /**
  4501. * @return {module:zrender/core/BoundingRect}
  4502. */
  4503. getBoundingRect: function (includeChildren) {
  4504. // TODO Caching
  4505. var rect = null;
  4506. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4507. var children = includeChildren || this._children;
  4508. var tmpMat = [];
  4509. for (var i = 0; i < children.length; i++) {
  4510. var child = children[i];
  4511. if (child.ignore || child.invisible) {
  4512. continue;
  4513. }
  4514. var childRect = child.getBoundingRect();
  4515. var transform = child.getLocalTransform(tmpMat);
  4516. // TODO
  4517. // The boundingRect cacluated by transforming original
  4518. // rect may be bigger than the actual bundingRect when rotation
  4519. // is used. (Consider a circle rotated aginst its center, where
  4520. // the actual boundingRect should be the same as that not be
  4521. // rotated.) But we can not find better approach to calculate
  4522. // actual boundingRect yet, considering performance.
  4523. if (transform) {
  4524. tmpRect.copy(childRect);
  4525. tmpRect.applyTransform(transform);
  4526. rect = rect || tmpRect.clone();
  4527. rect.union(tmpRect);
  4528. }
  4529. else {
  4530. rect = rect || childRect.clone();
  4531. rect.union(childRect);
  4532. }
  4533. }
  4534. return rect || tmpRect;
  4535. }
  4536. };
  4537. inherits(Group, Element);
  4538. // https://github.com/mziccard/node-timsort
  4539. var DEFAULT_MIN_MERGE = 32;
  4540. var DEFAULT_MIN_GALLOPING = 7;
  4541. function minRunLength(n) {
  4542. var r = 0;
  4543. while (n >= DEFAULT_MIN_MERGE) {
  4544. r |= n & 1;
  4545. n >>= 1;
  4546. }
  4547. return n + r;
  4548. }
  4549. function makeAscendingRun(array, lo, hi, compare) {
  4550. var runHi = lo + 1;
  4551. if (runHi === hi) {
  4552. return 1;
  4553. }
  4554. if (compare(array[runHi++], array[lo]) < 0) {
  4555. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4556. runHi++;
  4557. }
  4558. reverseRun(array, lo, runHi);
  4559. }
  4560. else {
  4561. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4562. runHi++;
  4563. }
  4564. }
  4565. return runHi - lo;
  4566. }
  4567. function reverseRun(array, lo, hi) {
  4568. hi--;
  4569. while (lo < hi) {
  4570. var t = array[lo];
  4571. array[lo++] = array[hi];
  4572. array[hi--] = t;
  4573. }
  4574. }
  4575. function binaryInsertionSort(array, lo, hi, start, compare) {
  4576. if (start === lo) {
  4577. start++;
  4578. }
  4579. for (; start < hi; start++) {
  4580. var pivot = array[start];
  4581. var left = lo;
  4582. var right = start;
  4583. var mid;
  4584. while (left < right) {
  4585. mid = left + right >>> 1;
  4586. if (compare(pivot, array[mid]) < 0) {
  4587. right = mid;
  4588. }
  4589. else {
  4590. left = mid + 1;
  4591. }
  4592. }
  4593. var n = start - left;
  4594. switch (n) {
  4595. case 3:
  4596. array[left + 3] = array[left + 2];
  4597. case 2:
  4598. array[left + 2] = array[left + 1];
  4599. case 1:
  4600. array[left + 1] = array[left];
  4601. break;
  4602. default:
  4603. while (n > 0) {
  4604. array[left + n] = array[left + n - 1];
  4605. n--;
  4606. }
  4607. }
  4608. array[left] = pivot;
  4609. }
  4610. }
  4611. function gallopLeft(value, array, start, length, hint, compare) {
  4612. var lastOffset = 0;
  4613. var maxOffset = 0;
  4614. var offset = 1;
  4615. if (compare(value, array[start + hint]) > 0) {
  4616. maxOffset = length - hint;
  4617. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4618. lastOffset = offset;
  4619. offset = (offset << 1) + 1;
  4620. if (offset <= 0) {
  4621. offset = maxOffset;
  4622. }
  4623. }
  4624. if (offset > maxOffset) {
  4625. offset = maxOffset;
  4626. }
  4627. lastOffset += hint;
  4628. offset += hint;
  4629. }
  4630. else {
  4631. maxOffset = hint + 1;
  4632. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4633. lastOffset = offset;
  4634. offset = (offset << 1) + 1;
  4635. if (offset <= 0) {
  4636. offset = maxOffset;
  4637. }
  4638. }
  4639. if (offset > maxOffset) {
  4640. offset = maxOffset;
  4641. }
  4642. var tmp = lastOffset;
  4643. lastOffset = hint - offset;
  4644. offset = hint - tmp;
  4645. }
  4646. lastOffset++;
  4647. while (lastOffset < offset) {
  4648. var m = lastOffset + (offset - lastOffset >>> 1);
  4649. if (compare(value, array[start + m]) > 0) {
  4650. lastOffset = m + 1;
  4651. }
  4652. else {
  4653. offset = m;
  4654. }
  4655. }
  4656. return offset;
  4657. }
  4658. function gallopRight(value, array, start, length, hint, compare) {
  4659. var lastOffset = 0;
  4660. var maxOffset = 0;
  4661. var offset = 1;
  4662. if (compare(value, array[start + hint]) < 0) {
  4663. maxOffset = hint + 1;
  4664. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4665. lastOffset = offset;
  4666. offset = (offset << 1) + 1;
  4667. if (offset <= 0) {
  4668. offset = maxOffset;
  4669. }
  4670. }
  4671. if (offset > maxOffset) {
  4672. offset = maxOffset;
  4673. }
  4674. var tmp = lastOffset;
  4675. lastOffset = hint - offset;
  4676. offset = hint - tmp;
  4677. }
  4678. else {
  4679. maxOffset = length - hint;
  4680. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4681. lastOffset = offset;
  4682. offset = (offset << 1) + 1;
  4683. if (offset <= 0) {
  4684. offset = maxOffset;
  4685. }
  4686. }
  4687. if (offset > maxOffset) {
  4688. offset = maxOffset;
  4689. }
  4690. lastOffset += hint;
  4691. offset += hint;
  4692. }
  4693. lastOffset++;
  4694. while (lastOffset < offset) {
  4695. var m = lastOffset + (offset - lastOffset >>> 1);
  4696. if (compare(value, array[start + m]) < 0) {
  4697. offset = m;
  4698. }
  4699. else {
  4700. lastOffset = m + 1;
  4701. }
  4702. }
  4703. return offset;
  4704. }
  4705. function TimSort(array, compare) {
  4706. var minGallop = DEFAULT_MIN_GALLOPING;
  4707. var runStart;
  4708. var runLength;
  4709. var stackSize = 0;
  4710. var tmp = [];
  4711. runStart = [];
  4712. runLength = [];
  4713. function pushRun(_runStart, _runLength) {
  4714. runStart[stackSize] = _runStart;
  4715. runLength[stackSize] = _runLength;
  4716. stackSize += 1;
  4717. }
  4718. function mergeRuns() {
  4719. while (stackSize > 1) {
  4720. var n = stackSize - 2;
  4721. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4722. if (runLength[n - 1] < runLength[n + 1]) {
  4723. n--;
  4724. }
  4725. }
  4726. else if (runLength[n] > runLength[n + 1]) {
  4727. break;
  4728. }
  4729. mergeAt(n);
  4730. }
  4731. }
  4732. function forceMergeRuns() {
  4733. while (stackSize > 1) {
  4734. var n = stackSize - 2;
  4735. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4736. n--;
  4737. }
  4738. mergeAt(n);
  4739. }
  4740. }
  4741. function mergeAt(i) {
  4742. var start1 = runStart[i];
  4743. var length1 = runLength[i];
  4744. var start2 = runStart[i + 1];
  4745. var length2 = runLength[i + 1];
  4746. runLength[i] = length1 + length2;
  4747. if (i === stackSize - 3) {
  4748. runStart[i + 1] = runStart[i + 2];
  4749. runLength[i + 1] = runLength[i + 2];
  4750. }
  4751. stackSize--;
  4752. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4753. start1 += k;
  4754. length1 -= k;
  4755. if (length1 === 0) {
  4756. return;
  4757. }
  4758. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4759. if (length2 === 0) {
  4760. return;
  4761. }
  4762. if (length1 <= length2) {
  4763. mergeLow(start1, length1, start2, length2);
  4764. }
  4765. else {
  4766. mergeHigh(start1, length1, start2, length2);
  4767. }
  4768. }
  4769. function mergeLow(start1, length1, start2, length2) {
  4770. var i = 0;
  4771. for (i = 0; i < length1; i++) {
  4772. tmp[i] = array[start1 + i];
  4773. }
  4774. var cursor1 = 0;
  4775. var cursor2 = start2;
  4776. var dest = start1;
  4777. array[dest++] = array[cursor2++];
  4778. if (--length2 === 0) {
  4779. for (i = 0; i < length1; i++) {
  4780. array[dest + i] = tmp[cursor1 + i];
  4781. }
  4782. return;
  4783. }
  4784. if (length1 === 1) {
  4785. for (i = 0; i < length2; i++) {
  4786. array[dest + i] = array[cursor2 + i];
  4787. }
  4788. array[dest + length2] = tmp[cursor1];
  4789. return;
  4790. }
  4791. var _minGallop = minGallop;
  4792. var count1, count2, exit;
  4793. while (1) {
  4794. count1 = 0;
  4795. count2 = 0;
  4796. exit = false;
  4797. do {
  4798. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4799. array[dest++] = array[cursor2++];
  4800. count2++;
  4801. count1 = 0;
  4802. if (--length2 === 0) {
  4803. exit = true;
  4804. break;
  4805. }
  4806. }
  4807. else {
  4808. array[dest++] = tmp[cursor1++];
  4809. count1++;
  4810. count2 = 0;
  4811. if (--length1 === 1) {
  4812. exit = true;
  4813. break;
  4814. }
  4815. }
  4816. } while ((count1 | count2) < _minGallop);
  4817. if (exit) {
  4818. break;
  4819. }
  4820. do {
  4821. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4822. if (count1 !== 0) {
  4823. for (i = 0; i < count1; i++) {
  4824. array[dest + i] = tmp[cursor1 + i];
  4825. }
  4826. dest += count1;
  4827. cursor1 += count1;
  4828. length1 -= count1;
  4829. if (length1 <= 1) {
  4830. exit = true;
  4831. break;
  4832. }
  4833. }
  4834. array[dest++] = array[cursor2++];
  4835. if (--length2 === 0) {
  4836. exit = true;
  4837. break;
  4838. }
  4839. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4840. if (count2 !== 0) {
  4841. for (i = 0; i < count2; i++) {
  4842. array[dest + i] = array[cursor2 + i];
  4843. }
  4844. dest += count2;
  4845. cursor2 += count2;
  4846. length2 -= count2;
  4847. if (length2 === 0) {
  4848. exit = true;
  4849. break;
  4850. }
  4851. }
  4852. array[dest++] = tmp[cursor1++];
  4853. if (--length1 === 1) {
  4854. exit = true;
  4855. break;
  4856. }
  4857. _minGallop--;
  4858. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4859. if (exit) {
  4860. break;
  4861. }
  4862. if (_minGallop < 0) {
  4863. _minGallop = 0;
  4864. }
  4865. _minGallop += 2;
  4866. }
  4867. minGallop = _minGallop;
  4868. minGallop < 1 && (minGallop = 1);
  4869. if (length1 === 1) {
  4870. for (i = 0; i < length2; i++) {
  4871. array[dest + i] = array[cursor2 + i];
  4872. }
  4873. array[dest + length2] = tmp[cursor1];
  4874. }
  4875. else if (length1 === 0) {
  4876. throw new Error();
  4877. // throw new Error('mergeLow preconditions were not respected');
  4878. }
  4879. else {
  4880. for (i = 0; i < length1; i++) {
  4881. array[dest + i] = tmp[cursor1 + i];
  4882. }
  4883. }
  4884. }
  4885. function mergeHigh (start1, length1, start2, length2) {
  4886. var i = 0;
  4887. for (i = 0; i < length2; i++) {
  4888. tmp[i] = array[start2 + i];
  4889. }
  4890. var cursor1 = start1 + length1 - 1;
  4891. var cursor2 = length2 - 1;
  4892. var dest = start2 + length2 - 1;
  4893. var customCursor = 0;
  4894. var customDest = 0;
  4895. array[dest--] = array[cursor1--];
  4896. if (--length1 === 0) {
  4897. customCursor = dest - (length2 - 1);
  4898. for (i = 0; i < length2; i++) {
  4899. array[customCursor + i] = tmp[i];
  4900. }
  4901. return;
  4902. }
  4903. if (length2 === 1) {
  4904. dest -= length1;
  4905. cursor1 -= length1;
  4906. customDest = dest + 1;
  4907. customCursor = cursor1 + 1;
  4908. for (i = length1 - 1; i >= 0; i--) {
  4909. array[customDest + i] = array[customCursor + i];
  4910. }
  4911. array[dest] = tmp[cursor2];
  4912. return;
  4913. }
  4914. var _minGallop = minGallop;
  4915. while (true) {
  4916. var count1 = 0;
  4917. var count2 = 0;
  4918. var exit = false;
  4919. do {
  4920. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  4921. array[dest--] = array[cursor1--];
  4922. count1++;
  4923. count2 = 0;
  4924. if (--length1 === 0) {
  4925. exit = true;
  4926. break;
  4927. }
  4928. }
  4929. else {
  4930. array[dest--] = tmp[cursor2--];
  4931. count2++;
  4932. count1 = 0;
  4933. if (--length2 === 1) {
  4934. exit = true;
  4935. break;
  4936. }
  4937. }
  4938. } while ((count1 | count2) < _minGallop);
  4939. if (exit) {
  4940. break;
  4941. }
  4942. do {
  4943. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  4944. if (count1 !== 0) {
  4945. dest -= count1;
  4946. cursor1 -= count1;
  4947. length1 -= count1;
  4948. customDest = dest + 1;
  4949. customCursor = cursor1 + 1;
  4950. for (i = count1 - 1; i >= 0; i--) {
  4951. array[customDest + i] = array[customCursor + i];
  4952. }
  4953. if (length1 === 0) {
  4954. exit = true;
  4955. break;
  4956. }
  4957. }
  4958. array[dest--] = tmp[cursor2--];
  4959. if (--length2 === 1) {
  4960. exit = true;
  4961. break;
  4962. }
  4963. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  4964. if (count2 !== 0) {
  4965. dest -= count2;
  4966. cursor2 -= count2;
  4967. length2 -= count2;
  4968. customDest = dest + 1;
  4969. customCursor = cursor2 + 1;
  4970. for (i = 0; i < count2; i++) {
  4971. array[customDest + i] = tmp[customCursor + i];
  4972. }
  4973. if (length2 <= 1) {
  4974. exit = true;
  4975. break;
  4976. }
  4977. }
  4978. array[dest--] = array[cursor1--];
  4979. if (--length1 === 0) {
  4980. exit = true;
  4981. break;
  4982. }
  4983. _minGallop--;
  4984. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4985. if (exit) {
  4986. break;
  4987. }
  4988. if (_minGallop < 0) {
  4989. _minGallop = 0;
  4990. }
  4991. _minGallop += 2;
  4992. }
  4993. minGallop = _minGallop;
  4994. if (minGallop < 1) {
  4995. minGallop = 1;
  4996. }
  4997. if (length2 === 1) {
  4998. dest -= length1;
  4999. cursor1 -= length1;
  5000. customDest = dest + 1;
  5001. customCursor = cursor1 + 1;
  5002. for (i = length1 - 1; i >= 0; i--) {
  5003. array[customDest + i] = array[customCursor + i];
  5004. }
  5005. array[dest] = tmp[cursor2];
  5006. }
  5007. else if (length2 === 0) {
  5008. throw new Error();
  5009. // throw new Error('mergeHigh preconditions were not respected');
  5010. }
  5011. else {
  5012. customCursor = dest - (length2 - 1);
  5013. for (i = 0; i < length2; i++) {
  5014. array[customCursor + i] = tmp[i];
  5015. }
  5016. }
  5017. }
  5018. this.mergeRuns = mergeRuns;
  5019. this.forceMergeRuns = forceMergeRuns;
  5020. this.pushRun = pushRun;
  5021. }
  5022. function sort(array, compare, lo, hi) {
  5023. if (!lo) {
  5024. lo = 0;
  5025. }
  5026. if (!hi) {
  5027. hi = array.length;
  5028. }
  5029. var remaining = hi - lo;
  5030. if (remaining < 2) {
  5031. return;
  5032. }
  5033. var runLength = 0;
  5034. if (remaining < DEFAULT_MIN_MERGE) {
  5035. runLength = makeAscendingRun(array, lo, hi, compare);
  5036. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5037. return;
  5038. }
  5039. var ts = new TimSort(array, compare);
  5040. var minRun = minRunLength(remaining);
  5041. do {
  5042. runLength = makeAscendingRun(array, lo, hi, compare);
  5043. if (runLength < minRun) {
  5044. var force = remaining;
  5045. if (force > minRun) {
  5046. force = minRun;
  5047. }
  5048. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5049. runLength = force;
  5050. }
  5051. ts.pushRun(lo, runLength);
  5052. ts.mergeRuns();
  5053. remaining -= runLength;
  5054. lo += runLength;
  5055. } while (remaining !== 0);
  5056. ts.forceMergeRuns();
  5057. }
  5058. /**
  5059. * Storage内容仓库模块
  5060. * @module zrender/Storage
  5061. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  5062. * @author errorrik (errorrik@gmail.com)
  5063. * @author pissang (https://github.com/pissang/)
  5064. */
  5065. // Use timsort because in most case elements are partially sorted
  5066. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5067. function shapeCompareFunc(a, b) {
  5068. if (a.zlevel === b.zlevel) {
  5069. if (a.z === b.z) {
  5070. // if (a.z2 === b.z2) {
  5071. // // FIXME Slow has renderidx compare
  5072. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5073. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5074. // return a.__renderidx - b.__renderidx;
  5075. // }
  5076. return a.z2 - b.z2;
  5077. }
  5078. return a.z - b.z;
  5079. }
  5080. return a.zlevel - b.zlevel;
  5081. }
  5082. /**
  5083. * 内容仓库 (M)
  5084. * @alias module:zrender/Storage
  5085. * @constructor
  5086. */
  5087. var Storage = function () { // jshint ignore:line
  5088. this._roots = [];
  5089. this._displayList = [];
  5090. this._displayListLen = 0;
  5091. };
  5092. Storage.prototype = {
  5093. constructor: Storage,
  5094. /**
  5095. * @param {Function} cb
  5096. *
  5097. */
  5098. traverse: function (cb, context) {
  5099. for (var i = 0; i < this._roots.length; i++) {
  5100. this._roots[i].traverse(cb, context);
  5101. }
  5102. },
  5103. /**
  5104. * 返回所有图形的绘制队列
  5105. * @param {boolean} [update=false] 是否在返回前更新该数组
  5106. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5107. *
  5108. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5109. * @return {Array.<module:zrender/graphic/Displayable>}
  5110. */
  5111. getDisplayList: function (update, includeIgnore) {
  5112. includeIgnore = includeIgnore || false;
  5113. if (update) {
  5114. this.updateDisplayList(includeIgnore);
  5115. }
  5116. return this._displayList;
  5117. },
  5118. /**
  5119. * 更新图形的绘制队列。
  5120. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5121. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5122. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5123. */
  5124. updateDisplayList: function (includeIgnore) {
  5125. this._displayListLen = 0;
  5126. var roots = this._roots;
  5127. var displayList = this._displayList;
  5128. for (var i = 0, len = roots.length; i < len; i++) {
  5129. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5130. }
  5131. displayList.length = this._displayListLen;
  5132. // for (var i = 0, len = displayList.length; i < len; i++) {
  5133. // displayList[i].__renderidx = i;
  5134. // }
  5135. // displayList.sort(shapeCompareFunc);
  5136. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5137. },
  5138. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5139. if (el.ignore && !includeIgnore) {
  5140. return;
  5141. }
  5142. el.beforeUpdate();
  5143. if (el.__dirty) {
  5144. el.update();
  5145. }
  5146. el.afterUpdate();
  5147. var userSetClipPath = el.clipPath;
  5148. if (userSetClipPath) {
  5149. // FIXME 效率影响
  5150. if (clipPaths) {
  5151. clipPaths = clipPaths.slice();
  5152. }
  5153. else {
  5154. clipPaths = [];
  5155. }
  5156. var currentClipPath = userSetClipPath;
  5157. var parentClipPath = el;
  5158. // Recursively add clip path
  5159. while (currentClipPath) {
  5160. // clipPath 的变换是基于使用这个 clipPath 的元素
  5161. currentClipPath.parent = parentClipPath;
  5162. currentClipPath.updateTransform();
  5163. clipPaths.push(currentClipPath);
  5164. parentClipPath = currentClipPath;
  5165. currentClipPath = currentClipPath.clipPath;
  5166. }
  5167. }
  5168. if (el.isGroup) {
  5169. var children = el._children;
  5170. for (var i = 0; i < children.length; i++) {
  5171. var child = children[i];
  5172. // Force to mark as dirty if group is dirty
  5173. // FIXME __dirtyPath ?
  5174. if (el.__dirty) {
  5175. child.__dirty = true;
  5176. }
  5177. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5178. }
  5179. // Mark group clean here
  5180. el.__dirty = false;
  5181. }
  5182. else {
  5183. el.__clipPaths = clipPaths;
  5184. this._displayList[this._displayListLen++] = el;
  5185. }
  5186. },
  5187. /**
  5188. * 添加图形(Shape)或者组(Group)到根节点
  5189. * @param {module:zrender/Element} el
  5190. */
  5191. addRoot: function (el) {
  5192. if (el.__storage === this) {
  5193. return;
  5194. }
  5195. if (el instanceof Group) {
  5196. el.addChildrenToStorage(this);
  5197. }
  5198. this.addToStorage(el);
  5199. this._roots.push(el);
  5200. },
  5201. /**
  5202. * 删除指定的图形(Shape)或者组(Group)
  5203. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5204. */
  5205. delRoot: function (el) {
  5206. if (el == null) {
  5207. // 不指定el清空
  5208. for (var i = 0; i < this._roots.length; i++) {
  5209. var root = this._roots[i];
  5210. if (root instanceof Group) {
  5211. root.delChildrenFromStorage(this);
  5212. }
  5213. }
  5214. this._roots = [];
  5215. this._displayList = [];
  5216. this._displayListLen = 0;
  5217. return;
  5218. }
  5219. if (el instanceof Array) {
  5220. for (var i = 0, l = el.length; i < l; i++) {
  5221. this.delRoot(el[i]);
  5222. }
  5223. return;
  5224. }
  5225. var idx = indexOf(this._roots, el);
  5226. if (idx >= 0) {
  5227. this.delFromStorage(el);
  5228. this._roots.splice(idx, 1);
  5229. if (el instanceof Group) {
  5230. el.delChildrenFromStorage(this);
  5231. }
  5232. }
  5233. },
  5234. addToStorage: function (el) {
  5235. el.__storage = this;
  5236. el.dirty(false);
  5237. return this;
  5238. },
  5239. delFromStorage: function (el) {
  5240. if (el) {
  5241. el.__storage = null;
  5242. }
  5243. return this;
  5244. },
  5245. /**
  5246. * 清空并且释放Storage
  5247. */
  5248. dispose: function () {
  5249. this._renderList =
  5250. this._roots = null;
  5251. },
  5252. displayableSortFunc: shapeCompareFunc
  5253. };
  5254. var STYLE_COMMON_PROPS = [
  5255. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5256. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5257. ];
  5258. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5259. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5260. var Style = function (opts, host) {
  5261. this.extendFrom(opts, false);
  5262. this.host = host;
  5263. };
  5264. function createLinearGradient(ctx, obj, rect) {
  5265. var x = obj.x == null ? 0 : obj.x;
  5266. var x2 = obj.x2 == null ? 1 : obj.x2;
  5267. var y = obj.y == null ? 0 : obj.y;
  5268. var y2 = obj.y2 == null ? 0 : obj.y2;
  5269. if (!obj.global) {
  5270. x = x * rect.width + rect.x;
  5271. x2 = x2 * rect.width + rect.x;
  5272. y = y * rect.height + rect.y;
  5273. y2 = y2 * rect.height + rect.y;
  5274. }
  5275. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5276. return canvasGradient;
  5277. }
  5278. function createRadialGradient(ctx, obj, rect) {
  5279. var width = rect.width;
  5280. var height = rect.height;
  5281. var min = Math.min(width, height);
  5282. var x = obj.x == null ? 0.5 : obj.x;
  5283. var y = obj.y == null ? 0.5 : obj.y;
  5284. var r = obj.r == null ? 0.5 : obj.r;
  5285. if (!obj.global) {
  5286. x = x * width + rect.x;
  5287. y = y * height + rect.y;
  5288. r = r * min;
  5289. }
  5290. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5291. return canvasGradient;
  5292. }
  5293. Style.prototype = {
  5294. constructor: Style,
  5295. /**
  5296. * @type {module:zrender/graphic/Displayable}
  5297. */
  5298. host: null,
  5299. /**
  5300. * @type {string}
  5301. */
  5302. fill: '#000',
  5303. /**
  5304. * @type {string}
  5305. */
  5306. stroke: null,
  5307. /**
  5308. * @type {number}
  5309. */
  5310. opacity: 1,
  5311. /**
  5312. * @type {Array.<number>}
  5313. */
  5314. lineDash: null,
  5315. /**
  5316. * @type {number}
  5317. */
  5318. lineDashOffset: 0,
  5319. /**
  5320. * @type {number}
  5321. */
  5322. shadowBlur: 0,
  5323. /**
  5324. * @type {number}
  5325. */
  5326. shadowOffsetX: 0,
  5327. /**
  5328. * @type {number}
  5329. */
  5330. shadowOffsetY: 0,
  5331. /**
  5332. * @type {number}
  5333. */
  5334. lineWidth: 1,
  5335. /**
  5336. * If stroke ignore scale
  5337. * @type {Boolean}
  5338. */
  5339. strokeNoScale: false,
  5340. // Bounding rect text configuration
  5341. // Not affected by element transform
  5342. /**
  5343. * @type {string}
  5344. */
  5345. text: null,
  5346. /**
  5347. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5348. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5349. * So do not visit it directly in upper application (like echarts),
  5350. * but use `contain/text#makeFont` instead.
  5351. * @type {string}
  5352. */
  5353. font: null,
  5354. /**
  5355. * The same as font. Use font please.
  5356. * @deprecated
  5357. * @type {string}
  5358. */
  5359. textFont: null,
  5360. /**
  5361. * It helps merging respectively, rather than parsing an entire font string.
  5362. * @type {string}
  5363. */
  5364. fontStyle: null,
  5365. /**
  5366. * It helps merging respectively, rather than parsing an entire font string.
  5367. * @type {string}
  5368. */
  5369. fontWeight: null,
  5370. /**
  5371. * It helps merging respectively, rather than parsing an entire font string.
  5372. * Should be 12 but not '12px'.
  5373. * @type {number}
  5374. */
  5375. fontSize: null,
  5376. /**
  5377. * It helps merging respectively, rather than parsing an entire font string.
  5378. * @type {string}
  5379. */
  5380. fontFamily: null,
  5381. /**
  5382. * Reserved for special functinality, like 'hr'.
  5383. * @type {string}
  5384. */
  5385. textTag: null,
  5386. /**
  5387. * @type {string}
  5388. */
  5389. textFill: '#000',
  5390. /**
  5391. * @type {string}
  5392. */
  5393. textStroke: null,
  5394. /**
  5395. * @type {number}
  5396. */
  5397. textWidth: null,
  5398. /**
  5399. * Only for textBackground.
  5400. * @type {number}
  5401. */
  5402. textHeight: null,
  5403. /**
  5404. * textStroke may be set as some color as a default
  5405. * value in upper applicaion, where the default value
  5406. * of textStrokeWidth should be 0 to make sure that
  5407. * user can choose to do not use text stroke.
  5408. * @type {number}
  5409. */
  5410. textStrokeWidth: 0,
  5411. /**
  5412. * @type {number}
  5413. */
  5414. textLineHeight: null,
  5415. /**
  5416. * 'inside', 'left', 'right', 'top', 'bottom'
  5417. * [x, y]
  5418. * Based on x, y of rect.
  5419. * @type {string|Array.<number>}
  5420. * @default 'inside'
  5421. */
  5422. textPosition: 'inside',
  5423. /**
  5424. * If not specified, use the boundingRect of a `displayable`.
  5425. * @type {Object}
  5426. */
  5427. textRect: null,
  5428. /**
  5429. * [x, y]
  5430. * @type {Array.<number>}
  5431. */
  5432. textOffset: null,
  5433. /**
  5434. * @type {string}
  5435. */
  5436. textAlign: null,
  5437. /**
  5438. * @type {string}
  5439. */
  5440. textVerticalAlign: null,
  5441. /**
  5442. * @type {number}
  5443. */
  5444. textDistance: 5,
  5445. /**
  5446. * @type {string}
  5447. */
  5448. textShadowColor: 'transparent',
  5449. /**
  5450. * @type {number}
  5451. */
  5452. textShadowBlur: 0,
  5453. /**
  5454. * @type {number}
  5455. */
  5456. textShadowOffsetX: 0,
  5457. /**
  5458. * @type {number}
  5459. */
  5460. textShadowOffsetY: 0,
  5461. /**
  5462. * @type {string}
  5463. */
  5464. textBoxShadowColor: 'transparent',
  5465. /**
  5466. * @type {number}
  5467. */
  5468. textBoxShadowBlur: 0,
  5469. /**
  5470. * @type {number}
  5471. */
  5472. textBoxShadowOffsetX: 0,
  5473. /**
  5474. * @type {number}
  5475. */
  5476. textBoxShadowOffsetY: 0,
  5477. /**
  5478. * Whether transform text.
  5479. * Only useful in Path and Image element
  5480. * @type {boolean}
  5481. */
  5482. transformText: false,
  5483. /**
  5484. * Text rotate around position of Path or Image
  5485. * Only useful in Path and Image element and transformText is false.
  5486. */
  5487. textRotation: 0,
  5488. /**
  5489. * Text origin of text rotation, like [10, 40].
  5490. * Based on x, y of rect.
  5491. * Useful in label rotation of circular symbol.
  5492. * By default, this origin is textPosition.
  5493. * Can be 'center'.
  5494. * @type {string|Array.<number>}
  5495. */
  5496. textOrigin: null,
  5497. /**
  5498. * @type {string}
  5499. */
  5500. textBackgroundColor: null,
  5501. /**
  5502. * @type {string}
  5503. */
  5504. textBorderColor: null,
  5505. /**
  5506. * @type {number}
  5507. */
  5508. textBorderWidth: 0,
  5509. /**
  5510. * @type {number}
  5511. */
  5512. textBorderRadius: 0,
  5513. /**
  5514. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5515. * @type {number|Array.<number>}
  5516. */
  5517. textPadding: null,
  5518. /**
  5519. * Text styles for rich text.
  5520. * @type {Object}
  5521. */
  5522. rich: null,
  5523. /**
  5524. * {outerWidth, outerHeight, ellipsis, placeholder}
  5525. * @type {Object}
  5526. */
  5527. truncate: null,
  5528. /**
  5529. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5530. * @type {string}
  5531. */
  5532. blend: null,
  5533. /**
  5534. * @param {CanvasRenderingContext2D} ctx
  5535. */
  5536. bind: function (ctx, el, prevEl) {
  5537. var style = this;
  5538. var prevStyle = prevEl && prevEl.style;
  5539. var firstDraw = !prevStyle;
  5540. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5541. var prop = STYLE_COMMON_PROPS[i];
  5542. var styleName = prop[0];
  5543. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5544. // FIXME Invalid property value will cause style leak from previous element.
  5545. ctx[styleName] = style[styleName] || prop[1];
  5546. }
  5547. }
  5548. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5549. ctx.fillStyle = style.fill;
  5550. }
  5551. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5552. ctx.strokeStyle = style.stroke;
  5553. }
  5554. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5555. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5556. }
  5557. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5558. ctx.globalCompositeOperation = style.blend || 'source-over';
  5559. }
  5560. if (this.hasStroke()) {
  5561. var lineWidth = style.lineWidth;
  5562. ctx.lineWidth = lineWidth / (
  5563. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5564. );
  5565. }
  5566. },
  5567. hasFill: function () {
  5568. var fill = this.fill;
  5569. return fill != null && fill !== 'none';
  5570. },
  5571. hasStroke: function () {
  5572. var stroke = this.stroke;
  5573. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5574. },
  5575. /**
  5576. * Extend from other style
  5577. * @param {zrender/graphic/Style} otherStyle
  5578. * @param {boolean} overwrite true: overwrirte any way.
  5579. * false: overwrite only when !target.hasOwnProperty
  5580. * others: overwrite when property is not null/undefined.
  5581. */
  5582. extendFrom: function (otherStyle, overwrite) {
  5583. if (otherStyle) {
  5584. for (var name in otherStyle) {
  5585. if (otherStyle.hasOwnProperty(name)
  5586. && (overwrite === true
  5587. || (
  5588. overwrite === false
  5589. ? !this.hasOwnProperty(name)
  5590. : otherStyle[name] != null
  5591. )
  5592. )
  5593. ) {
  5594. this[name] = otherStyle[name];
  5595. }
  5596. }
  5597. }
  5598. },
  5599. /**
  5600. * Batch setting style with a given object
  5601. * @param {Object|string} obj
  5602. * @param {*} [obj]
  5603. */
  5604. set: function (obj, value) {
  5605. if (typeof obj === 'string') {
  5606. this[obj] = value;
  5607. }
  5608. else {
  5609. this.extendFrom(obj, true);
  5610. }
  5611. },
  5612. /**
  5613. * Clone
  5614. * @return {zrender/graphic/Style} [description]
  5615. */
  5616. clone: function () {
  5617. var newStyle = new this.constructor();
  5618. newStyle.extendFrom(this, true);
  5619. return newStyle;
  5620. },
  5621. getGradient: function (ctx, obj, rect) {
  5622. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5623. var canvasGradient = method(ctx, obj, rect);
  5624. var colorStops = obj.colorStops;
  5625. for (var i = 0; i < colorStops.length; i++) {
  5626. canvasGradient.addColorStop(
  5627. colorStops[i].offset, colorStops[i].color
  5628. );
  5629. }
  5630. return canvasGradient;
  5631. }
  5632. };
  5633. var styleProto = Style.prototype;
  5634. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5635. var prop = STYLE_COMMON_PROPS[i];
  5636. if (!(prop[0] in styleProto)) {
  5637. styleProto[prop[0]] = prop[1];
  5638. }
  5639. }
  5640. // Provide for others
  5641. Style.getGradient = styleProto.getGradient;
  5642. var Pattern = function (image, repeat) {
  5643. // Should do nothing more in this constructor. Because gradient can be
  5644. // declard by `color: {image: ...}`, where this constructor will not be called.
  5645. this.image = image;
  5646. this.repeat = repeat;
  5647. // Can be cloned
  5648. this.type = 'pattern';
  5649. };
  5650. Pattern.prototype.getCanvasPattern = function (ctx) {
  5651. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5652. };
  5653. /**
  5654. * @module zrender/Layer
  5655. * @author pissang(https://www.github.com/pissang)
  5656. */
  5657. function returnFalse() {
  5658. return false;
  5659. }
  5660. /**
  5661. * 创建dom
  5662. *
  5663. * @inner
  5664. * @param {string} id dom id 待用
  5665. * @param {Painter} painter painter instance
  5666. * @param {number} number
  5667. */
  5668. function createDom(id, painter, dpr) {
  5669. var newDom = createCanvas();
  5670. var width = painter.getWidth();
  5671. var height = painter.getHeight();
  5672. var newDomStyle = newDom.style;
  5673. // 没append呢,请原谅我这样写,清晰~
  5674. newDomStyle.position = 'absolute';
  5675. newDomStyle.left = 0;
  5676. newDomStyle.top = 0;
  5677. newDomStyle.width = width + 'px';
  5678. newDomStyle.height = height + 'px';
  5679. newDom.width = width * dpr;
  5680. newDom.height = height * dpr;
  5681. // id不作为索引用,避免可能造成的重名,定义为私有属性
  5682. newDom.setAttribute('data-zr-dom-id', id);
  5683. return newDom;
  5684. }
  5685. /**
  5686. * @alias module:zrender/Layer
  5687. * @constructor
  5688. * @extends module:zrender/mixin/Transformable
  5689. * @param {string} id
  5690. * @param {module:zrender/Painter} painter
  5691. * @param {number} [dpr]
  5692. */
  5693. var Layer = function(id, painter, dpr) {
  5694. var dom;
  5695. dpr = dpr || devicePixelRatio;
  5696. if (typeof id === 'string') {
  5697. dom = createDom(id, painter, dpr);
  5698. }
  5699. // Not using isDom because in node it will return false
  5700. else if (isObject(id)) {
  5701. dom = id;
  5702. id = dom.id;
  5703. }
  5704. this.id = id;
  5705. this.dom = dom;
  5706. var domStyle = dom.style;
  5707. if (domStyle) { // Not in node
  5708. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5709. domStyle['-webkit-user-select'] = 'none';
  5710. domStyle['user-select'] = 'none';
  5711. domStyle['-webkit-touch-callout'] = 'none';
  5712. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5713. domStyle['padding'] = 0;
  5714. domStyle['margin'] = 0;
  5715. domStyle['border-width'] = 0;
  5716. }
  5717. this.domBack = null;
  5718. this.ctxBack = null;
  5719. this.painter = painter;
  5720. this.config = null;
  5721. // Configs
  5722. /**
  5723. * 每次清空画布的颜色
  5724. * @type {string}
  5725. * @default 0
  5726. */
  5727. this.clearColor = 0;
  5728. /**
  5729. * 是否开启动态模糊
  5730. * @type {boolean}
  5731. * @default false
  5732. */
  5733. this.motionBlur = false;
  5734. /**
  5735. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5736. * @type {number}
  5737. * @default 0.7
  5738. */
  5739. this.lastFrameAlpha = 0.7;
  5740. /**
  5741. * Layer dpr
  5742. * @type {number}
  5743. */
  5744. this.dpr = dpr;
  5745. };
  5746. Layer.prototype = {
  5747. constructor: Layer,
  5748. elCount: 0,
  5749. __dirty: true,
  5750. initContext: function () {
  5751. this.ctx = this.dom.getContext('2d');
  5752. this.ctx.__currentValues = {};
  5753. this.ctx.dpr = this.dpr;
  5754. },
  5755. createBackBuffer: function () {
  5756. var dpr = this.dpr;
  5757. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5758. this.ctxBack = this.domBack.getContext('2d');
  5759. this.ctxBack.__currentValues = {};
  5760. if (dpr != 1) {
  5761. this.ctxBack.scale(dpr, dpr);
  5762. }
  5763. },
  5764. /**
  5765. * @param {number} width
  5766. * @param {number} height
  5767. */
  5768. resize: function (width, height) {
  5769. var dpr = this.dpr;
  5770. var dom = this.dom;
  5771. var domStyle = dom.style;
  5772. var domBack = this.domBack;
  5773. domStyle.width = width + 'px';
  5774. domStyle.height = height + 'px';
  5775. dom.width = width * dpr;
  5776. dom.height = height * dpr;
  5777. if (domBack) {
  5778. domBack.width = width * dpr;
  5779. domBack.height = height * dpr;
  5780. if (dpr != 1) {
  5781. this.ctxBack.scale(dpr, dpr);
  5782. }
  5783. }
  5784. },
  5785. /**
  5786. * 清空该层画布
  5787. * @param {boolean} clearAll Clear all with out motion blur
  5788. */
  5789. clear: function (clearAll) {
  5790. var dom = this.dom;
  5791. var ctx = this.ctx;
  5792. var width = dom.width;
  5793. var height = dom.height;
  5794. var clearColor = this.clearColor;
  5795. var haveMotionBLur = this.motionBlur && !clearAll;
  5796. var lastFrameAlpha = this.lastFrameAlpha;
  5797. var dpr = this.dpr;
  5798. if (haveMotionBLur) {
  5799. if (!this.domBack) {
  5800. this.createBackBuffer();
  5801. }
  5802. this.ctxBack.globalCompositeOperation = 'copy';
  5803. this.ctxBack.drawImage(
  5804. dom, 0, 0,
  5805. width / dpr,
  5806. height / dpr
  5807. );
  5808. }
  5809. ctx.clearRect(0, 0, width, height);
  5810. if (clearColor) {
  5811. var clearColorGradientOrPattern;
  5812. // Gradient
  5813. if (clearColor.colorStops) {
  5814. // Cache canvas gradient
  5815. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5816. x: 0,
  5817. y: 0,
  5818. width: width,
  5819. height: height
  5820. });
  5821. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5822. }
  5823. // Pattern
  5824. else if (clearColor.image) {
  5825. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5826. }
  5827. ctx.save();
  5828. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5829. ctx.fillRect(0, 0, width, height);
  5830. ctx.restore();
  5831. }
  5832. if (haveMotionBLur) {
  5833. var domBack = this.domBack;
  5834. ctx.save();
  5835. ctx.globalAlpha = lastFrameAlpha;
  5836. ctx.drawImage(domBack, 0, 0, width, height);
  5837. ctx.restore();
  5838. }
  5839. }
  5840. };
  5841. var requestAnimationFrame = (
  5842. typeof window !== 'undefined'
  5843. && (
  5844. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5845. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5846. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5847. || window.mozRequestAnimationFrame
  5848. || window.webkitRequestAnimationFrame
  5849. )
  5850. ) || function (func) {
  5851. setTimeout(func, 16);
  5852. };
  5853. var globalImageCache = new LRU(50);
  5854. /**
  5855. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5856. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5857. */
  5858. function findExistImage(newImageOrSrc) {
  5859. if (typeof newImageOrSrc === 'string') {
  5860. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5861. return cachedImgObj && cachedImgObj.image;
  5862. }
  5863. else {
  5864. return newImageOrSrc;
  5865. }
  5866. }
  5867. /**
  5868. * Caution: User should cache loaded images, but not just count on LRU.
  5869. * Consider if required images more than LRU size, will dead loop occur?
  5870. *
  5871. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5872. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  5873. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  5874. * @param {Function} [cb] params: (image, cbPayload)
  5875. * @param {Object} [cbPayload] Payload on cb calling.
  5876. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5877. */
  5878. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  5879. if (!newImageOrSrc) {
  5880. return image;
  5881. }
  5882. else if (typeof newImageOrSrc === 'string') {
  5883. // Image should not be loaded repeatly.
  5884. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  5885. return image;
  5886. }
  5887. // Only when there is no existent image or existent image src
  5888. // is different, this method is responsible for load.
  5889. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5890. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  5891. if (cachedImgObj) {
  5892. image = cachedImgObj.image;
  5893. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  5894. }
  5895. else {
  5896. !image && (image = new Image());
  5897. image.onload = imageOnLoad;
  5898. globalImageCache.put(
  5899. newImageOrSrc,
  5900. image.__cachedImgObj = {
  5901. image: image,
  5902. pending: [pendingWrap]
  5903. }
  5904. );
  5905. image.src = image.__zrImageSrc = newImageOrSrc;
  5906. }
  5907. return image;
  5908. }
  5909. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  5910. else {
  5911. return newImageOrSrc;
  5912. }
  5913. }
  5914. function imageOnLoad() {
  5915. var cachedImgObj = this.__cachedImgObj;
  5916. this.onload = this.__cachedImgObj = null;
  5917. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  5918. var pendingWrap = cachedImgObj.pending[i];
  5919. var cb = pendingWrap.cb;
  5920. cb && cb(this, pendingWrap.cbPayload);
  5921. pendingWrap.hostEl.dirty();
  5922. }
  5923. cachedImgObj.pending.length = 0;
  5924. }
  5925. function isImageReady(image) {
  5926. return image && image.width && image.height;
  5927. }
  5928. var textWidthCache = {};
  5929. var textWidthCacheCounter = 0;
  5930. var TEXT_CACHE_MAX = 5000;
  5931. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  5932. var DEFAULT_FONT = '12px sans-serif';
  5933. // Avoid assign to an exported variable, for transforming to cjs.
  5934. var methods$1 = {};
  5935. function $override$1(name, fn) {
  5936. methods$1[name] = fn;
  5937. }
  5938. /**
  5939. * @public
  5940. * @param {string} text
  5941. * @param {string} font
  5942. * @return {number} width
  5943. */
  5944. function getWidth(text, font) {
  5945. font = font || DEFAULT_FONT;
  5946. var key = text + ':' + font;
  5947. if (textWidthCache[key]) {
  5948. return textWidthCache[key];
  5949. }
  5950. var textLines = (text + '').split('\n');
  5951. var width = 0;
  5952. for (var i = 0, l = textLines.length; i < l; i++) {
  5953. // textContain.measureText may be overrided in SVG or VML
  5954. width = Math.max(measureText(textLines[i], font).width, width);
  5955. }
  5956. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  5957. textWidthCacheCounter = 0;
  5958. textWidthCache = {};
  5959. }
  5960. textWidthCacheCounter++;
  5961. textWidthCache[key] = width;
  5962. return width;
  5963. }
  5964. /**
  5965. * @public
  5966. * @param {string} text
  5967. * @param {string} font
  5968. * @param {string} [textAlign='left']
  5969. * @param {string} [textVerticalAlign='top']
  5970. * @param {Array.<number>} [textPadding]
  5971. * @param {Object} [rich]
  5972. * @param {Object} [truncate]
  5973. * @return {Object} {x, y, width, height, lineHeight}
  5974. */
  5975. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  5976. return rich
  5977. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  5978. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  5979. }
  5980. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  5981. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  5982. var outerWidth = getWidth(text, font);
  5983. if (textPadding) {
  5984. outerWidth += textPadding[1] + textPadding[3];
  5985. }
  5986. var outerHeight = contentBlock.outerHeight;
  5987. var x = adjustTextX(0, outerWidth, textAlign);
  5988. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  5989. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  5990. rect.lineHeight = contentBlock.lineHeight;
  5991. return rect;
  5992. }
  5993. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  5994. var contentBlock = parseRichText(text, {
  5995. rich: rich,
  5996. truncate: truncate,
  5997. font: font,
  5998. textAlign: textAlign,
  5999. textPadding: textPadding
  6000. });
  6001. var outerWidth = contentBlock.outerWidth;
  6002. var outerHeight = contentBlock.outerHeight;
  6003. var x = adjustTextX(0, outerWidth, textAlign);
  6004. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6005. return new BoundingRect(x, y, outerWidth, outerHeight);
  6006. }
  6007. /**
  6008. * @public
  6009. * @param {number} x
  6010. * @param {number} width
  6011. * @param {string} [textAlign='left']
  6012. * @return {number} Adjusted x.
  6013. */
  6014. function adjustTextX(x, width, textAlign) {
  6015. // FIXME Right to left language
  6016. if (textAlign === 'right') {
  6017. x -= width;
  6018. }
  6019. else if (textAlign === 'center') {
  6020. x -= width / 2;
  6021. }
  6022. return x;
  6023. }
  6024. /**
  6025. * @public
  6026. * @param {number} y
  6027. * @param {number} height
  6028. * @param {string} [textVerticalAlign='top']
  6029. * @return {number} Adjusted y.
  6030. */
  6031. function adjustTextY(y, height, textVerticalAlign) {
  6032. if (textVerticalAlign === 'middle') {
  6033. y -= height / 2;
  6034. }
  6035. else if (textVerticalAlign === 'bottom') {
  6036. y -= height;
  6037. }
  6038. return y;
  6039. }
  6040. /**
  6041. * @public
  6042. * @param {stirng} textPosition
  6043. * @param {Object} rect {x, y, width, height}
  6044. * @param {number} distance
  6045. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6046. */
  6047. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6048. var x = rect.x;
  6049. var y = rect.y;
  6050. var height = rect.height;
  6051. var width = rect.width;
  6052. var halfHeight = height / 2;
  6053. var textAlign = 'left';
  6054. var textVerticalAlign = 'top';
  6055. switch (textPosition) {
  6056. case 'left':
  6057. x -= distance;
  6058. y += halfHeight;
  6059. textAlign = 'right';
  6060. textVerticalAlign = 'middle';
  6061. break;
  6062. case 'right':
  6063. x += distance + width;
  6064. y += halfHeight;
  6065. textVerticalAlign = 'middle';
  6066. break;
  6067. case 'top':
  6068. x += width / 2;
  6069. y -= distance;
  6070. textAlign = 'center';
  6071. textVerticalAlign = 'bottom';
  6072. break;
  6073. case 'bottom':
  6074. x += width / 2;
  6075. y += height + distance;
  6076. textAlign = 'center';
  6077. break;
  6078. case 'inside':
  6079. x += width / 2;
  6080. y += halfHeight;
  6081. textAlign = 'center';
  6082. textVerticalAlign = 'middle';
  6083. break;
  6084. case 'insideLeft':
  6085. x += distance;
  6086. y += halfHeight;
  6087. textVerticalAlign = 'middle';
  6088. break;
  6089. case 'insideRight':
  6090. x += width - distance;
  6091. y += halfHeight;
  6092. textAlign = 'right';
  6093. textVerticalAlign = 'middle';
  6094. break;
  6095. case 'insideTop':
  6096. x += width / 2;
  6097. y += distance;
  6098. textAlign = 'center';
  6099. break;
  6100. case 'insideBottom':
  6101. x += width / 2;
  6102. y += height - distance;
  6103. textAlign = 'center';
  6104. textVerticalAlign = 'bottom';
  6105. break;
  6106. case 'insideTopLeft':
  6107. x += distance;
  6108. y += distance;
  6109. break;
  6110. case 'insideTopRight':
  6111. x += width - distance;
  6112. y += distance;
  6113. textAlign = 'right';
  6114. break;
  6115. case 'insideBottomLeft':
  6116. x += distance;
  6117. y += height - distance;
  6118. textVerticalAlign = 'bottom';
  6119. break;
  6120. case 'insideBottomRight':
  6121. x += width - distance;
  6122. y += height - distance;
  6123. textAlign = 'right';
  6124. textVerticalAlign = 'bottom';
  6125. break;
  6126. }
  6127. return {
  6128. x: x,
  6129. y: y,
  6130. textAlign: textAlign,
  6131. textVerticalAlign: textVerticalAlign
  6132. };
  6133. }
  6134. /**
  6135. * Show ellipsis if overflow.
  6136. *
  6137. * @public
  6138. * @param {string} text
  6139. * @param {string} containerWidth
  6140. * @param {string} font
  6141. * @param {number} [ellipsis='...']
  6142. * @param {Object} [options]
  6143. * @param {number} [options.maxIterations=3]
  6144. * @param {number} [options.minChar=0] If truncate result are less
  6145. * then minChar, ellipsis will not show, which is
  6146. * better for user hint in some cases.
  6147. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6148. * @return {string}
  6149. */
  6150. function truncateText(text, containerWidth, font, ellipsis, options) {
  6151. if (!containerWidth) {
  6152. return '';
  6153. }
  6154. var textLines = (text + '').split('\n');
  6155. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6156. // FIXME
  6157. // It is not appropriate that every line has '...' when truncate multiple lines.
  6158. for (var i = 0, len = textLines.length; i < len; i++) {
  6159. textLines[i] = truncateSingleLine(textLines[i], options);
  6160. }
  6161. return textLines.join('\n');
  6162. }
  6163. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6164. options = extend({}, options);
  6165. options.font = font;
  6166. var ellipsis = retrieve2(ellipsis, '...');
  6167. options.maxIterations = retrieve2(options.maxIterations, 2);
  6168. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6169. // FIXME
  6170. // Other languages?
  6171. options.cnCharWidth = getWidth('国', font);
  6172. // FIXME
  6173. // Consider proportional font?
  6174. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6175. options.placeholder = retrieve2(options.placeholder, '');
  6176. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6177. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6178. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6179. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6180. contentWidth -= ascCharWidth;
  6181. }
  6182. var ellipsisWidth = getWidth(ellipsis);
  6183. if (ellipsisWidth > contentWidth) {
  6184. ellipsis = '';
  6185. ellipsisWidth = 0;
  6186. }
  6187. contentWidth = containerWidth - ellipsisWidth;
  6188. options.ellipsis = ellipsis;
  6189. options.ellipsisWidth = ellipsisWidth;
  6190. options.contentWidth = contentWidth;
  6191. options.containerWidth = containerWidth;
  6192. return options;
  6193. }
  6194. function truncateSingleLine(textLine, options) {
  6195. var containerWidth = options.containerWidth;
  6196. var font = options.font;
  6197. var contentWidth = options.contentWidth;
  6198. if (!containerWidth) {
  6199. return '';
  6200. }
  6201. var lineWidth = getWidth(textLine, font);
  6202. if (lineWidth <= containerWidth) {
  6203. return textLine;
  6204. }
  6205. for (var j = 0;; j++) {
  6206. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6207. textLine += options.ellipsis;
  6208. break;
  6209. }
  6210. var subLength = j === 0
  6211. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6212. : lineWidth > 0
  6213. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6214. : 0;
  6215. textLine = textLine.substr(0, subLength);
  6216. lineWidth = getWidth(textLine, font);
  6217. }
  6218. if (textLine === '') {
  6219. textLine = options.placeholder;
  6220. }
  6221. return textLine;
  6222. }
  6223. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6224. var width = 0;
  6225. var i = 0;
  6226. for (var len = text.length; i < len && width < contentWidth; i++) {
  6227. var charCode = text.charCodeAt(i);
  6228. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6229. }
  6230. return i;
  6231. }
  6232. /**
  6233. * @public
  6234. * @param {string} font
  6235. * @return {number} line height
  6236. */
  6237. function getLineHeight(font) {
  6238. // FIXME A rough approach.
  6239. return getWidth('国', font);
  6240. }
  6241. /**
  6242. * @public
  6243. * @param {string} text
  6244. * @param {string} font
  6245. * @return {Object} width
  6246. */
  6247. function measureText(text, font) {
  6248. return methods$1.measureText(text, font);
  6249. }
  6250. // Avoid assign to an exported variable, for transforming to cjs.
  6251. methods$1.measureText = function (text, font) {
  6252. var ctx = getContext();
  6253. ctx.font = font || DEFAULT_FONT;
  6254. return ctx.measureText(text);
  6255. };
  6256. /**
  6257. * @public
  6258. * @param {string} text
  6259. * @param {string} font
  6260. * @param {Object} [truncate]
  6261. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6262. * Notice: for performance, do not calculate outerWidth util needed.
  6263. */
  6264. function parsePlainText(text, font, padding, truncate) {
  6265. text != null && (text += '');
  6266. var lineHeight = getLineHeight(font);
  6267. var lines = text ? text.split('\n') : [];
  6268. var height = lines.length * lineHeight;
  6269. var outerHeight = height;
  6270. if (padding) {
  6271. outerHeight += padding[0] + padding[2];
  6272. }
  6273. if (text && truncate) {
  6274. var truncOuterHeight = truncate.outerHeight;
  6275. var truncOuterWidth = truncate.outerWidth;
  6276. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6277. text = '';
  6278. lines = [];
  6279. }
  6280. else if (truncOuterWidth != null) {
  6281. var options = prepareTruncateOptions(
  6282. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6283. font,
  6284. truncate.ellipsis,
  6285. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6286. );
  6287. // FIXME
  6288. // It is not appropriate that every line has '...' when truncate multiple lines.
  6289. for (var i = 0, len = lines.length; i < len; i++) {
  6290. lines[i] = truncateSingleLine(lines[i], options);
  6291. }
  6292. }
  6293. }
  6294. return {
  6295. lines: lines,
  6296. height: height,
  6297. outerHeight: outerHeight,
  6298. lineHeight: lineHeight
  6299. };
  6300. }
  6301. /**
  6302. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6303. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6304. *
  6305. * @public
  6306. * @param {string} text
  6307. * @param {Object} style
  6308. * @return {Object} block
  6309. * {
  6310. * width,
  6311. * height,
  6312. * lines: [{
  6313. * lineHeight,
  6314. * width,
  6315. * tokens: [[{
  6316. * styleName,
  6317. * text,
  6318. * width, // include textPadding
  6319. * height, // include textPadding
  6320. * textWidth, // pure text width
  6321. * textHeight, // pure text height
  6322. * lineHeihgt,
  6323. * font,
  6324. * textAlign,
  6325. * textVerticalAlign
  6326. * }], [...], ...]
  6327. * }, ...]
  6328. * }
  6329. * If styleName is undefined, it is plain text.
  6330. */
  6331. function parseRichText(text, style) {
  6332. var contentBlock = {lines: [], width: 0, height: 0};
  6333. text != null && (text += '');
  6334. if (!text) {
  6335. return contentBlock;
  6336. }
  6337. var lastIndex = STYLE_REG.lastIndex = 0;
  6338. var result;
  6339. while ((result = STYLE_REG.exec(text)) != null) {
  6340. var matchedIndex = result.index;
  6341. if (matchedIndex > lastIndex) {
  6342. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6343. }
  6344. pushTokens(contentBlock, result[2], result[1]);
  6345. lastIndex = STYLE_REG.lastIndex;
  6346. }
  6347. if (lastIndex < text.length) {
  6348. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6349. }
  6350. var lines = contentBlock.lines;
  6351. var contentHeight = 0;
  6352. var contentWidth = 0;
  6353. // For `textWidth: 100%`
  6354. var pendingList = [];
  6355. var stlPadding = style.textPadding;
  6356. var truncate = style.truncate;
  6357. var truncateWidth = truncate && truncate.outerWidth;
  6358. var truncateHeight = truncate && truncate.outerHeight;
  6359. if (stlPadding) {
  6360. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6361. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6362. }
  6363. // Calculate layout info of tokens.
  6364. for (var i = 0; i < lines.length; i++) {
  6365. var line = lines[i];
  6366. var lineHeight = 0;
  6367. var lineWidth = 0;
  6368. for (var j = 0; j < line.tokens.length; j++) {
  6369. var token = line.tokens[j];
  6370. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6371. // textPadding should not inherit from style.
  6372. var textPadding = token.textPadding = tokenStyle.textPadding;
  6373. // textFont has been asigned to font by `normalizeStyle`.
  6374. var font = token.font = tokenStyle.font || style.font;
  6375. // textHeight can be used when textVerticalAlign is specified in token.
  6376. var tokenHeight = token.textHeight = retrieve2(
  6377. // textHeight should not be inherited, consider it can be specified
  6378. // as box height of the block.
  6379. tokenStyle.textHeight, getLineHeight(font)
  6380. );
  6381. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6382. token.height = tokenHeight;
  6383. token.lineHeight = retrieve3(
  6384. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6385. );
  6386. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6387. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6388. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6389. return {lines: [], width: 0, height: 0};
  6390. }
  6391. token.textWidth = getWidth(token.text, font);
  6392. var tokenWidth = tokenStyle.textWidth;
  6393. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6394. // Percent width, can be `100%`, can be used in drawing separate
  6395. // line when box width is needed to be auto.
  6396. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6397. token.percentWidth = tokenWidth;
  6398. pendingList.push(token);
  6399. tokenWidth = 0;
  6400. // Do not truncate in this case, because there is no user case
  6401. // and it is too complicated.
  6402. }
  6403. else {
  6404. if (tokenWidthNotSpecified) {
  6405. tokenWidth = token.textWidth;
  6406. // FIXME: If image is not loaded and textWidth is not specified, calling
  6407. // `getBoundingRect()` will not get correct result.
  6408. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6409. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6410. // Use cases:
  6411. // (1) If image is not loaded, it will be loaded at render phase and call
  6412. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6413. // image, and then the right size will be calculated here at the next tick.
  6414. // See `graphic/helper/text.js`.
  6415. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6416. // use `imageHelper.findExistImage` to find cached image.
  6417. // `imageHelper.findExistImage` will always be called here before
  6418. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6419. // which ensures that image will not be rendered before correct size calcualted.
  6420. if (bgImg) {
  6421. bgImg = findExistImage(bgImg);
  6422. if (isImageReady(bgImg)) {
  6423. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6424. }
  6425. }
  6426. }
  6427. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6428. tokenWidth += paddingW;
  6429. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6430. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6431. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6432. token.text = '';
  6433. token.textWidth = tokenWidth = 0;
  6434. }
  6435. else {
  6436. token.text = truncateText(
  6437. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6438. {minChar: truncate.minChar}
  6439. );
  6440. token.textWidth = getWidth(token.text, font);
  6441. tokenWidth = token.textWidth + paddingW;
  6442. }
  6443. }
  6444. }
  6445. lineWidth += (token.width = tokenWidth);
  6446. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6447. }
  6448. line.width = lineWidth;
  6449. line.lineHeight = lineHeight;
  6450. contentHeight += lineHeight;
  6451. contentWidth = Math.max(contentWidth, lineWidth);
  6452. }
  6453. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6454. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6455. if (stlPadding) {
  6456. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6457. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6458. }
  6459. for (var i = 0; i < pendingList.length; i++) {
  6460. var token = pendingList[i];
  6461. var percentWidth = token.percentWidth;
  6462. // Should not base on outerWidth, because token can not be placed out of padding.
  6463. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6464. }
  6465. return contentBlock;
  6466. }
  6467. function pushTokens(block, str, styleName) {
  6468. var isEmptyStr = str === '';
  6469. var strs = str.split('\n');
  6470. var lines = block.lines;
  6471. for (var i = 0; i < strs.length; i++) {
  6472. var text = strs[i];
  6473. var token = {
  6474. styleName: styleName,
  6475. text: text,
  6476. isLineHolder: !text && !isEmptyStr
  6477. };
  6478. // The first token should be appended to the last line.
  6479. if (!i) {
  6480. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6481. // Consider cases:
  6482. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6483. // (which is a placeholder) should be replaced by new token.
  6484. // (2) A image backage, where token likes {a|}.
  6485. // (3) A redundant '' will affect textAlign in line.
  6486. // (4) tokens with the same tplName should not be merged, because
  6487. // they should be displayed in different box (with border and padding).
  6488. var tokensLen = tokens.length;
  6489. (tokensLen === 1 && tokens[0].isLineHolder)
  6490. ? (tokens[0] = token)
  6491. // Consider text is '', only insert when it is the "lineHolder" or
  6492. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6493. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6494. }
  6495. // Other tokens always start a new line.
  6496. else {
  6497. // If there is '', insert it as a placeholder.
  6498. lines.push({tokens: [token]});
  6499. }
  6500. }
  6501. }
  6502. function makeFont(style) {
  6503. // FIXME in node-canvas fontWeight is before fontStyle
  6504. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6505. return (style.fontSize || style.fontFamily) && [
  6506. style.fontStyle,
  6507. style.fontWeight,
  6508. (style.fontSize || 12) + 'px',
  6509. // If font properties are defined, `fontFamily` should not be ignored.
  6510. style.fontFamily || 'sans-serif'
  6511. ].join(' ') || style.textFont || style.font;
  6512. }
  6513. function buildPath(ctx, shape) {
  6514. var x = shape.x;
  6515. var y = shape.y;
  6516. var width = shape.width;
  6517. var height = shape.height;
  6518. var r = shape.r;
  6519. var r1;
  6520. var r2;
  6521. var r3;
  6522. var r4;
  6523. // Convert width and height to positive for better borderRadius
  6524. if (width < 0) {
  6525. x = x + width;
  6526. width = -width;
  6527. }
  6528. if (height < 0) {
  6529. y = y + height;
  6530. height = -height;
  6531. }
  6532. if (typeof r === 'number') {
  6533. r1 = r2 = r3 = r4 = r;
  6534. }
  6535. else if (r instanceof Array) {
  6536. if (r.length === 1) {
  6537. r1 = r2 = r3 = r4 = r[0];
  6538. }
  6539. else if (r.length === 2) {
  6540. r1 = r3 = r[0];
  6541. r2 = r4 = r[1];
  6542. }
  6543. else if (r.length === 3) {
  6544. r1 = r[0];
  6545. r2 = r4 = r[1];
  6546. r3 = r[2];
  6547. }
  6548. else {
  6549. r1 = r[0];
  6550. r2 = r[1];
  6551. r3 = r[2];
  6552. r4 = r[3];
  6553. }
  6554. }
  6555. else {
  6556. r1 = r2 = r3 = r4 = 0;
  6557. }
  6558. var total;
  6559. if (r1 + r2 > width) {
  6560. total = r1 + r2;
  6561. r1 *= width / total;
  6562. r2 *= width / total;
  6563. }
  6564. if (r3 + r4 > width) {
  6565. total = r3 + r4;
  6566. r3 *= width / total;
  6567. r4 *= width / total;
  6568. }
  6569. if (r2 + r3 > height) {
  6570. total = r2 + r3;
  6571. r2 *= height / total;
  6572. r3 *= height / total;
  6573. }
  6574. if (r1 + r4 > height) {
  6575. total = r1 + r4;
  6576. r1 *= height / total;
  6577. r4 *= height / total;
  6578. }
  6579. ctx.moveTo(x + r1, y);
  6580. ctx.lineTo(x + width - r2, y);
  6581. r2 !== 0 && ctx.quadraticCurveTo(
  6582. x + width, y, x + width, y + r2
  6583. );
  6584. ctx.lineTo(x + width, y + height - r3);
  6585. r3 !== 0 && ctx.quadraticCurveTo(
  6586. x + width, y + height, x + width - r3, y + height
  6587. );
  6588. ctx.lineTo(x + r4, y + height);
  6589. r4 !== 0 && ctx.quadraticCurveTo(
  6590. x, y + height, x, y + height - r4
  6591. );
  6592. ctx.lineTo(x, y + r1);
  6593. r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y);
  6594. }
  6595. // TODO: Have not support 'start', 'end' yet.
  6596. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6597. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6598. /**
  6599. * @param {module:zrender/graphic/Style} style
  6600. * @return {module:zrender/graphic/Style} The input style.
  6601. */
  6602. function normalizeTextStyle(style) {
  6603. normalizeStyle(style);
  6604. each$1(style.rich, normalizeStyle);
  6605. return style;
  6606. }
  6607. function normalizeStyle(style) {
  6608. if (style) {
  6609. style.font = makeFont(style);
  6610. var textAlign = style.textAlign;
  6611. textAlign === 'middle' && (textAlign = 'center');
  6612. style.textAlign = (
  6613. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6614. ) ? textAlign : 'left';
  6615. // Compatible with textBaseline.
  6616. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6617. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6618. style.textVerticalAlign = (
  6619. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6620. ) ? textVerticalAlign : 'top';
  6621. var textPadding = style.textPadding;
  6622. if (textPadding) {
  6623. style.textPadding = normalizeCssArray(style.textPadding);
  6624. }
  6625. }
  6626. }
  6627. /**
  6628. * @param {CanvasRenderingContext2D} ctx
  6629. * @param {string} text
  6630. * @param {module:zrender/graphic/Style} style
  6631. * @param {Object|boolean} [rect] {x, y, width, height}
  6632. * If set false, rect text is not used.
  6633. */
  6634. function renderText(hostEl, ctx, text, style, rect) {
  6635. style.rich
  6636. ? renderRichText(hostEl, ctx, text, style, rect)
  6637. : renderPlainText(hostEl, ctx, text, style, rect);
  6638. }
  6639. function renderPlainText(hostEl, ctx, text, style, rect) {
  6640. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6641. var textPadding = style.textPadding;
  6642. var contentBlock = hostEl.__textCotentBlock;
  6643. if (!contentBlock || hostEl.__dirty) {
  6644. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6645. text, font, textPadding, style.truncate
  6646. );
  6647. }
  6648. var outerHeight = contentBlock.outerHeight;
  6649. var textLines = contentBlock.lines;
  6650. var lineHeight = contentBlock.lineHeight;
  6651. var boxPos = getBoxPosition(outerHeight, style, rect);
  6652. var baseX = boxPos.baseX;
  6653. var baseY = boxPos.baseY;
  6654. var textAlign = boxPos.textAlign;
  6655. var textVerticalAlign = boxPos.textVerticalAlign;
  6656. // Origin of textRotation should be the base point of text drawing.
  6657. applyTextRotation(ctx, style, rect, baseX, baseY);
  6658. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6659. var textX = baseX;
  6660. var textY = boxY;
  6661. var needDrawBg = needDrawBackground(style);
  6662. if (needDrawBg || textPadding) {
  6663. // Consider performance, do not call getTextWidth util necessary.
  6664. var textWidth = getWidth(text, font);
  6665. var outerWidth = textWidth;
  6666. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6667. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6668. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6669. if (textPadding) {
  6670. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6671. textY += textPadding[0];
  6672. }
  6673. }
  6674. setCtx(ctx, 'textAlign', textAlign || 'left');
  6675. // Force baseline to be "middle". Otherwise, if using "top", the
  6676. // text will offset downward a little bit in font "Microsoft YaHei".
  6677. setCtx(ctx, 'textBaseline', 'middle');
  6678. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6679. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6680. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6681. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6682. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6683. // `textBaseline` is set as 'middle'.
  6684. textY += lineHeight / 2;
  6685. var textStrokeWidth = style.textStrokeWidth;
  6686. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6687. var textFill = getFill(style.textFill);
  6688. if (textStroke) {
  6689. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6690. setCtx(ctx, 'strokeStyle', textStroke);
  6691. }
  6692. if (textFill) {
  6693. setCtx(ctx, 'fillStyle', textFill);
  6694. }
  6695. for (var i = 0; i < textLines.length; i++) {
  6696. // Fill after stroke so the outline will not cover the main part.
  6697. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6698. textFill && ctx.fillText(textLines[i], textX, textY);
  6699. textY += lineHeight;
  6700. }
  6701. }
  6702. function renderRichText(hostEl, ctx, text, style, rect) {
  6703. var contentBlock = hostEl.__textCotentBlock;
  6704. if (!contentBlock || hostEl.__dirty) {
  6705. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6706. }
  6707. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6708. }
  6709. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6710. var contentWidth = contentBlock.width;
  6711. var outerWidth = contentBlock.outerWidth;
  6712. var outerHeight = contentBlock.outerHeight;
  6713. var textPadding = style.textPadding;
  6714. var boxPos = getBoxPosition(outerHeight, style, rect);
  6715. var baseX = boxPos.baseX;
  6716. var baseY = boxPos.baseY;
  6717. var textAlign = boxPos.textAlign;
  6718. var textVerticalAlign = boxPos.textVerticalAlign;
  6719. // Origin of textRotation should be the base point of text drawing.
  6720. applyTextRotation(ctx, style, rect, baseX, baseY);
  6721. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6722. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6723. var xLeft = boxX;
  6724. var lineTop = boxY;
  6725. if (textPadding) {
  6726. xLeft += textPadding[3];
  6727. lineTop += textPadding[0];
  6728. }
  6729. var xRight = xLeft + contentWidth;
  6730. needDrawBackground(style) && drawBackground(
  6731. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6732. );
  6733. for (var i = 0; i < contentBlock.lines.length; i++) {
  6734. var line = contentBlock.lines[i];
  6735. var tokens = line.tokens;
  6736. var tokenCount = tokens.length;
  6737. var lineHeight = line.lineHeight;
  6738. var usedWidth = line.width;
  6739. var leftIndex = 0;
  6740. var lineXLeft = xLeft;
  6741. var lineXRight = xRight;
  6742. var rightIndex = tokenCount - 1;
  6743. var token;
  6744. while (
  6745. leftIndex < tokenCount
  6746. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6747. ) {
  6748. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6749. usedWidth -= token.width;
  6750. lineXLeft += token.width;
  6751. leftIndex++;
  6752. }
  6753. while (
  6754. rightIndex >= 0
  6755. && (token = tokens[rightIndex], token.textAlign === 'right')
  6756. ) {
  6757. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6758. usedWidth -= token.width;
  6759. lineXRight -= token.width;
  6760. rightIndex--;
  6761. }
  6762. // The other tokens are placed as textAlign 'center' if there is enough space.
  6763. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6764. while (leftIndex <= rightIndex) {
  6765. token = tokens[leftIndex];
  6766. // Consider width specified by user, use 'center' rather than 'left'.
  6767. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6768. lineXLeft += token.width;
  6769. leftIndex++;
  6770. }
  6771. lineTop += lineHeight;
  6772. }
  6773. }
  6774. function applyTextRotation(ctx, style, rect, x, y) {
  6775. // textRotation only apply in RectText.
  6776. if (rect && style.textRotation) {
  6777. var origin = style.textOrigin;
  6778. if (origin === 'center') {
  6779. x = rect.width / 2 + rect.x;
  6780. y = rect.height / 2 + rect.y;
  6781. }
  6782. else if (origin) {
  6783. x = origin[0] + rect.x;
  6784. y = origin[1] + rect.y;
  6785. }
  6786. ctx.translate(x, y);
  6787. // Positive: anticlockwise
  6788. ctx.rotate(-style.textRotation);
  6789. ctx.translate(-x, -y);
  6790. }
  6791. }
  6792. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6793. var tokenStyle = style.rich[token.styleName] || {};
  6794. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6795. // the bias of "Microsoft YaHei".
  6796. var textVerticalAlign = token.textVerticalAlign;
  6797. var y = lineTop + lineHeight / 2;
  6798. if (textVerticalAlign === 'top') {
  6799. y = lineTop + token.height / 2;
  6800. }
  6801. else if (textVerticalAlign === 'bottom') {
  6802. y = lineTop + lineHeight - token.height / 2;
  6803. }
  6804. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6805. hostEl,
  6806. ctx,
  6807. tokenStyle,
  6808. textAlign === 'right'
  6809. ? x - token.width
  6810. : textAlign === 'center'
  6811. ? x - token.width / 2
  6812. : x,
  6813. y - token.height / 2,
  6814. token.width,
  6815. token.height
  6816. );
  6817. var textPadding = token.textPadding;
  6818. if (textPadding) {
  6819. x = getTextXForPadding(x, textAlign, textPadding);
  6820. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6821. }
  6822. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6823. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6824. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6825. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6826. setCtx(ctx, 'textAlign', textAlign);
  6827. // Force baseline to be "middle". Otherwise, if using "top", the
  6828. // text will offset downward a little bit in font "Microsoft YaHei".
  6829. setCtx(ctx, 'textBaseline', 'middle');
  6830. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6831. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6832. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6833. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6834. // Fill after stroke so the outline will not cover the main part.
  6835. if (textStroke) {
  6836. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6837. setCtx(ctx, 'strokeStyle', textStroke);
  6838. ctx.strokeText(token.text, x, y);
  6839. }
  6840. if (textFill) {
  6841. setCtx(ctx, 'fillStyle', textFill);
  6842. ctx.fillText(token.text, x, y);
  6843. }
  6844. }
  6845. function needDrawBackground(style) {
  6846. return style.textBackgroundColor
  6847. || (style.textBorderWidth && style.textBorderColor);
  6848. }
  6849. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6850. // shape: {x, y, width, height}
  6851. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6852. var textBackgroundColor = style.textBackgroundColor;
  6853. var textBorderWidth = style.textBorderWidth;
  6854. var textBorderColor = style.textBorderColor;
  6855. var isPlainBg = isString(textBackgroundColor);
  6856. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6857. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6858. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6859. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6860. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6861. ctx.beginPath();
  6862. var textBorderRadius = style.textBorderRadius;
  6863. if (!textBorderRadius) {
  6864. ctx.rect(x, y, width, height);
  6865. }
  6866. else {
  6867. buildPath(ctx, {
  6868. x: x, y: y, width: width, height: height, r: textBorderRadius
  6869. });
  6870. }
  6871. ctx.closePath();
  6872. }
  6873. if (isPlainBg) {
  6874. setCtx(ctx, 'fillStyle', textBackgroundColor);
  6875. ctx.fill();
  6876. }
  6877. else if (isObject(textBackgroundColor)) {
  6878. var image = textBackgroundColor.image;
  6879. image = createOrUpdateImage(
  6880. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  6881. );
  6882. if (image && isImageReady(image)) {
  6883. ctx.drawImage(image, x, y, width, height);
  6884. }
  6885. }
  6886. if (textBorderWidth && textBorderColor) {
  6887. setCtx(ctx, 'lineWidth', textBorderWidth);
  6888. setCtx(ctx, 'strokeStyle', textBorderColor);
  6889. ctx.stroke();
  6890. }
  6891. }
  6892. function onBgImageLoaded(image, textBackgroundColor) {
  6893. // Replace image, so that `contain/text.js#parseRichText`
  6894. // will get correct result in next tick.
  6895. textBackgroundColor.image = image;
  6896. }
  6897. function getBoxPosition(blockHeiht, style, rect) {
  6898. var baseX = style.x || 0;
  6899. var baseY = style.y || 0;
  6900. var textAlign = style.textAlign;
  6901. var textVerticalAlign = style.textVerticalAlign;
  6902. // Text position represented by coord
  6903. if (rect) {
  6904. var textPosition = style.textPosition;
  6905. if (textPosition instanceof Array) {
  6906. // Percent
  6907. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  6908. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  6909. }
  6910. else {
  6911. var res = adjustTextPositionOnRect(
  6912. textPosition, rect, style.textDistance
  6913. );
  6914. baseX = res.x;
  6915. baseY = res.y;
  6916. // Default align and baseline when has textPosition
  6917. textAlign = textAlign || res.textAlign;
  6918. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  6919. }
  6920. // textOffset is only support in RectText, otherwise
  6921. // we have to adjust boundingRect for textOffset.
  6922. var textOffset = style.textOffset;
  6923. if (textOffset) {
  6924. baseX += textOffset[0];
  6925. baseY += textOffset[1];
  6926. }
  6927. }
  6928. return {
  6929. baseX: baseX,
  6930. baseY: baseY,
  6931. textAlign: textAlign,
  6932. textVerticalAlign: textVerticalAlign
  6933. };
  6934. }
  6935. function setCtx(ctx, prop, value) {
  6936. // FIXME ??? performance try
  6937. // if (ctx.__currentValues[prop] !== value) {
  6938. // ctx[prop] = ctx.__currentValues[prop] = value;
  6939. ctx[prop] = value;
  6940. // }
  6941. return ctx[prop];
  6942. }
  6943. /**
  6944. * @param {string} [stroke] If specified, do not check style.textStroke.
  6945. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  6946. * @param {number} style
  6947. */
  6948. function getStroke(stroke, lineWidth) {
  6949. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  6950. ? null
  6951. // TODO pattern and gradient?
  6952. : (stroke.image || stroke.colorStops)
  6953. ? '#000'
  6954. : stroke;
  6955. }
  6956. function getFill(fill) {
  6957. return (fill == null || fill === 'none')
  6958. ? null
  6959. // TODO pattern and gradient?
  6960. : (fill.image || fill.colorStops)
  6961. ? '#000'
  6962. : fill;
  6963. }
  6964. function parsePercent(value, maxValue) {
  6965. if (typeof value === 'string') {
  6966. if (value.lastIndexOf('%') >= 0) {
  6967. return parseFloat(value) / 100 * maxValue;
  6968. }
  6969. return parseFloat(value);
  6970. }
  6971. return value;
  6972. }
  6973. function getTextXForPadding(x, textAlign, textPadding) {
  6974. return textAlign === 'right'
  6975. ? (x - textPadding[1])
  6976. : textAlign === 'center'
  6977. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  6978. : (x + textPadding[3]);
  6979. }
  6980. /**
  6981. * @param {string} text
  6982. * @param {module:zrender/Style} style
  6983. * @return {boolean}
  6984. */
  6985. function needDrawText(text, style) {
  6986. return text != null
  6987. && (text
  6988. || style.textBackgroundColor
  6989. || (style.textBorderWidth && style.textBorderColor)
  6990. || style.textPadding
  6991. );
  6992. }
  6993. /**
  6994. * Mixin for drawing text in a element bounding rect
  6995. * @module zrender/mixin/RectText
  6996. */
  6997. var tmpRect$1 = new BoundingRect();
  6998. var RectText = function () {};
  6999. RectText.prototype = {
  7000. constructor: RectText,
  7001. /**
  7002. * Draw text in a rect with specified position.
  7003. * @param {CanvasRenderingContext2D} ctx
  7004. * @param {Object} rect Displayable rect
  7005. */
  7006. drawRectText: function (ctx, rect) {
  7007. var style = this.style;
  7008. rect = style.textRect || rect;
  7009. // Optimize, avoid normalize every time.
  7010. this.__dirty && normalizeTextStyle(style, true);
  7011. var text = style.text;
  7012. // Convert to string
  7013. text != null && (text += '');
  7014. if (!needDrawText(text, style)) {
  7015. return;
  7016. }
  7017. // FIXME
  7018. ctx.save();
  7019. // Transform rect to view space
  7020. var transform = this.transform;
  7021. if (!style.transformText) {
  7022. if (transform) {
  7023. tmpRect$1.copy(rect);
  7024. tmpRect$1.applyTransform(transform);
  7025. rect = tmpRect$1;
  7026. }
  7027. }
  7028. else {
  7029. this.setTransform(ctx);
  7030. }
  7031. // transformText and textRotation can not be used at the same time.
  7032. renderText(this, ctx, text, style, rect);
  7033. ctx.restore();
  7034. }
  7035. };
  7036. /**
  7037. * 可绘制的图形基类
  7038. * Base class of all displayable graphic objects
  7039. * @module zrender/graphic/Displayable
  7040. */
  7041. /**
  7042. * @alias module:zrender/graphic/Displayable
  7043. * @extends module:zrender/Element
  7044. * @extends module:zrender/graphic/mixin/RectText
  7045. */
  7046. function Displayable(opts) {
  7047. opts = opts || {};
  7048. Element.call(this, opts);
  7049. // Extend properties
  7050. for (var name in opts) {
  7051. if (
  7052. opts.hasOwnProperty(name) &&
  7053. name !== 'style'
  7054. ) {
  7055. this[name] = opts[name];
  7056. }
  7057. }
  7058. /**
  7059. * @type {module:zrender/graphic/Style}
  7060. */
  7061. this.style = new Style(opts.style, this);
  7062. this._rect = null;
  7063. // Shapes for cascade clipping.
  7064. this.__clipPaths = [];
  7065. // FIXME Stateful must be mixined after style is setted
  7066. // Stateful.call(this, opts);
  7067. }
  7068. Displayable.prototype = {
  7069. constructor: Displayable,
  7070. type: 'displayable',
  7071. /**
  7072. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7073. * Dirty flag. From which painter will determine if this displayable object needs brush
  7074. * @name module:zrender/graphic/Displayable#__dirty
  7075. * @type {boolean}
  7076. */
  7077. __dirty: true,
  7078. /**
  7079. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7080. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7081. * @name module:/zrender/graphic/Displayable#invisible
  7082. * @type {boolean}
  7083. * @default false
  7084. */
  7085. invisible: false,
  7086. /**
  7087. * @name module:/zrender/graphic/Displayable#z
  7088. * @type {number}
  7089. * @default 0
  7090. */
  7091. z: 0,
  7092. /**
  7093. * @name module:/zrender/graphic/Displayable#z
  7094. * @type {number}
  7095. * @default 0
  7096. */
  7097. z2: 0,
  7098. /**
  7099. * z层level,决定绘画在哪层canvas中
  7100. * @name module:/zrender/graphic/Displayable#zlevel
  7101. * @type {number}
  7102. * @default 0
  7103. */
  7104. zlevel: 0,
  7105. /**
  7106. * 是否可拖拽
  7107. * @name module:/zrender/graphic/Displayable#draggable
  7108. * @type {boolean}
  7109. * @default false
  7110. */
  7111. draggable: false,
  7112. /**
  7113. * 是否正在拖拽
  7114. * @name module:/zrender/graphic/Displayable#draggable
  7115. * @type {boolean}
  7116. * @default false
  7117. */
  7118. dragging: false,
  7119. /**
  7120. * 是否相应鼠标事件
  7121. * @name module:/zrender/graphic/Displayable#silent
  7122. * @type {boolean}
  7123. * @default false
  7124. */
  7125. silent: false,
  7126. /**
  7127. * If enable culling
  7128. * @type {boolean}
  7129. * @default false
  7130. */
  7131. culling: false,
  7132. /**
  7133. * Mouse cursor when hovered
  7134. * @name module:/zrender/graphic/Displayable#cursor
  7135. * @type {string}
  7136. */
  7137. cursor: 'pointer',
  7138. /**
  7139. * If hover area is bounding rect
  7140. * @name module:/zrender/graphic/Displayable#rectHover
  7141. * @type {string}
  7142. */
  7143. rectHover: false,
  7144. /**
  7145. * Render the element progressively when the value >= 0,
  7146. * usefull for large data.
  7147. * @type {number}
  7148. */
  7149. progressive: -1,
  7150. beforeBrush: function (ctx) {},
  7151. afterBrush: function (ctx) {},
  7152. /**
  7153. * 图形绘制方法
  7154. * @param {CanvasRenderingContext2D} ctx
  7155. */
  7156. // Interface
  7157. brush: function (ctx, prevEl) {},
  7158. /**
  7159. * 获取最小包围盒
  7160. * @return {module:zrender/core/BoundingRect}
  7161. */
  7162. // Interface
  7163. getBoundingRect: function () {},
  7164. /**
  7165. * 判断坐标 x, y 是否在图形上
  7166. * If displayable element contain coord x, y
  7167. * @param {number} x
  7168. * @param {number} y
  7169. * @return {boolean}
  7170. */
  7171. contain: function (x, y) {
  7172. return this.rectContain(x, y);
  7173. },
  7174. /**
  7175. * @param {Function} cb
  7176. * @param {} context
  7177. */
  7178. traverse: function (cb, context) {
  7179. cb.call(context, this);
  7180. },
  7181. /**
  7182. * 判断坐标 x, y 是否在图形的包围盒上
  7183. * If bounding rect of element contain coord x, y
  7184. * @param {number} x
  7185. * @param {number} y
  7186. * @return {boolean}
  7187. */
  7188. rectContain: function (x, y) {
  7189. var coord = this.transformCoordToLocal(x, y);
  7190. var rect = this.getBoundingRect();
  7191. return rect.contain(coord[0], coord[1]);
  7192. },
  7193. /**
  7194. * 标记图形元素为脏,并且在下一帧重绘
  7195. * Mark displayable element dirty and refresh next frame
  7196. */
  7197. dirty: function () {
  7198. this.__dirty = true;
  7199. this._rect = null;
  7200. this.__zr && this.__zr.refresh();
  7201. },
  7202. /**
  7203. * 图形是否会触发事件
  7204. * If displayable object binded any event
  7205. * @return {boolean}
  7206. */
  7207. // TODO, 通过 bind 绑定的事件
  7208. // isSilent: function () {
  7209. // return !(
  7210. // this.hoverable || this.draggable
  7211. // || this.onmousemove || this.onmouseover || this.onmouseout
  7212. // || this.onmousedown || this.onmouseup || this.onclick
  7213. // || this.ondragenter || this.ondragover || this.ondragleave
  7214. // || this.ondrop
  7215. // );
  7216. // },
  7217. /**
  7218. * Alias for animate('style')
  7219. * @param {boolean} loop
  7220. */
  7221. animateStyle: function (loop) {
  7222. return this.animate('style', loop);
  7223. },
  7224. attrKV: function (key, value) {
  7225. if (key !== 'style') {
  7226. Element.prototype.attrKV.call(this, key, value);
  7227. }
  7228. else {
  7229. this.style.set(value);
  7230. }
  7231. },
  7232. /**
  7233. * @param {Object|string} key
  7234. * @param {*} value
  7235. */
  7236. setStyle: function (key, value) {
  7237. this.style.set(key, value);
  7238. this.dirty(false);
  7239. return this;
  7240. },
  7241. /**
  7242. * Use given style object
  7243. * @param {Object} obj
  7244. */
  7245. useStyle: function (obj) {
  7246. this.style = new Style(obj, this);
  7247. this.dirty(false);
  7248. return this;
  7249. }
  7250. };
  7251. inherits(Displayable, Element);
  7252. mixin(Displayable, RectText);
  7253. /**
  7254. * @alias zrender/graphic/Image
  7255. * @extends module:zrender/graphic/Displayable
  7256. * @constructor
  7257. * @param {Object} opts
  7258. */
  7259. function ZImage(opts) {
  7260. Displayable.call(this, opts);
  7261. }
  7262. ZImage.prototype = {
  7263. constructor: ZImage,
  7264. type: 'image',
  7265. brush: function (ctx, prevEl) {
  7266. var style = this.style;
  7267. var src = style.image;
  7268. // Must bind each time
  7269. style.bind(ctx, this, prevEl);
  7270. var image = this._image = createOrUpdateImage(
  7271. src,
  7272. this._image,
  7273. this,
  7274. this.onload
  7275. );
  7276. if (!image || !isImageReady(image)) {
  7277. return;
  7278. }
  7279. // 图片已经加载完成
  7280. // if (image.nodeName.toUpperCase() == 'IMG') {
  7281. // if (!image.complete) {
  7282. // return;
  7283. // }
  7284. // }
  7285. // Else is canvas
  7286. var x = style.x || 0;
  7287. var y = style.y || 0;
  7288. var width = style.width;
  7289. var height = style.height;
  7290. var aspect = image.width / image.height;
  7291. if (width == null && height != null) {
  7292. // Keep image/height ratio
  7293. width = height * aspect;
  7294. }
  7295. else if (height == null && width != null) {
  7296. height = width / aspect;
  7297. }
  7298. else if (width == null && height == null) {
  7299. width = image.width;
  7300. height = image.height;
  7301. }
  7302. // 设置transform
  7303. this.setTransform(ctx);
  7304. if (style.sWidth && style.sHeight) {
  7305. var sx = style.sx || 0;
  7306. var sy = style.sy || 0;
  7307. ctx.drawImage(
  7308. image,
  7309. sx, sy, style.sWidth, style.sHeight,
  7310. x, y, width, height
  7311. );
  7312. }
  7313. else if (style.sx && style.sy) {
  7314. var sx = style.sx;
  7315. var sy = style.sy;
  7316. var sWidth = width - sx;
  7317. var sHeight = height - sy;
  7318. ctx.drawImage(
  7319. image,
  7320. sx, sy, sWidth, sHeight,
  7321. x, y, width, height
  7322. );
  7323. }
  7324. else {
  7325. ctx.drawImage(image, x, y, width, height);
  7326. }
  7327. this.restoreTransform(ctx);
  7328. // Draw rect text
  7329. if (style.text != null) {
  7330. this.drawRectText(ctx, this.getBoundingRect());
  7331. }
  7332. },
  7333. getBoundingRect: function () {
  7334. var style = this.style;
  7335. if (! this._rect) {
  7336. this._rect = new BoundingRect(
  7337. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7338. );
  7339. }
  7340. return this._rect;
  7341. }
  7342. };
  7343. inherits(ZImage, Displayable);
  7344. /**
  7345. * Default canvas painter
  7346. * @module zrender/Painter
  7347. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  7348. * errorrik (errorrik@gmail.com)
  7349. * pissang (https://www.github.com/pissang)
  7350. */
  7351. // PENDIGN
  7352. // Layer exceeds MAX_PROGRESSIVE_LAYER_NUMBER may have some problem when flush directly second time.
  7353. //
  7354. // Maximum progressive layer. When exceeding this number. All elements will be drawed in the last layer.
  7355. var MAX_PROGRESSIVE_LAYER_NUMBER = 5;
  7356. function parseInt10(val) {
  7357. return parseInt(val, 10);
  7358. }
  7359. function isLayerValid(layer) {
  7360. if (!layer) {
  7361. return false;
  7362. }
  7363. if (layer.__builtin__) {
  7364. return true;
  7365. }
  7366. if (typeof(layer.resize) !== 'function'
  7367. || typeof(layer.refresh) !== 'function'
  7368. ) {
  7369. return false;
  7370. }
  7371. return true;
  7372. }
  7373. function preProcessLayer(layer) {
  7374. layer.__unusedCount++;
  7375. }
  7376. function postProcessLayer(layer) {
  7377. if (layer.__unusedCount == 1) {
  7378. layer.clear();
  7379. }
  7380. }
  7381. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7382. var viewRect = new BoundingRect(0, 0, 0, 0);
  7383. function isDisplayableCulled(el, width, height) {
  7384. tmpRect.copy(el.getBoundingRect());
  7385. if (el.transform) {
  7386. tmpRect.applyTransform(el.transform);
  7387. }
  7388. viewRect.width = width;
  7389. viewRect.height = height;
  7390. return !tmpRect.intersect(viewRect);
  7391. }
  7392. function isClipPathChanged(clipPaths, prevClipPaths) {
  7393. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7394. return false;
  7395. }
  7396. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7397. return true;
  7398. }
  7399. for (var i = 0; i < clipPaths.length; i++) {
  7400. if (clipPaths[i] !== prevClipPaths[i]) {
  7401. return true;
  7402. }
  7403. }
  7404. }
  7405. function doClip(clipPaths, ctx) {
  7406. for (var i = 0; i < clipPaths.length; i++) {
  7407. var clipPath = clipPaths[i];
  7408. clipPath.setTransform(ctx);
  7409. ctx.beginPath();
  7410. clipPath.buildPath(ctx, clipPath.shape);
  7411. ctx.clip();
  7412. // Transform back
  7413. clipPath.restoreTransform(ctx);
  7414. }
  7415. }
  7416. function createRoot(width, height) {
  7417. var domRoot = document.createElement('div');
  7418. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7419. domRoot.style.cssText = [
  7420. 'position:relative',
  7421. 'overflow:hidden',
  7422. 'width:' + width + 'px',
  7423. 'height:' + height + 'px',
  7424. 'padding:0',
  7425. 'margin:0',
  7426. 'border-width:0'
  7427. ].join(';') + ';';
  7428. return domRoot;
  7429. }
  7430. /**
  7431. * @alias module:zrender/Painter
  7432. * @constructor
  7433. * @param {HTMLElement} root 绘图容器
  7434. * @param {module:zrender/Storage} storage
  7435. * @param {Object} opts
  7436. */
  7437. var Painter = function (root, storage, opts) {
  7438. this.type = 'canvas';
  7439. // In node environment using node-canvas
  7440. var singleCanvas = !root.nodeName // In node ?
  7441. || root.nodeName.toUpperCase() === 'CANVAS';
  7442. this._opts = opts = extend({}, opts || {});
  7443. /**
  7444. * @type {number}
  7445. */
  7446. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7447. /**
  7448. * @type {boolean}
  7449. * @private
  7450. */
  7451. this._singleCanvas = singleCanvas;
  7452. /**
  7453. * 绘图容器
  7454. * @type {HTMLElement}
  7455. */
  7456. this.root = root;
  7457. var rootStyle = root.style;
  7458. if (rootStyle) {
  7459. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7460. rootStyle['-webkit-user-select'] =
  7461. rootStyle['user-select'] =
  7462. rootStyle['-webkit-touch-callout'] = 'none';
  7463. root.innerHTML = '';
  7464. }
  7465. /**
  7466. * @type {module:zrender/Storage}
  7467. */
  7468. this.storage = storage;
  7469. /**
  7470. * @type {Array.<number>}
  7471. * @private
  7472. */
  7473. var zlevelList = this._zlevelList = [];
  7474. /**
  7475. * @type {Object.<string, module:zrender/Layer>}
  7476. * @private
  7477. */
  7478. var layers = this._layers = {};
  7479. /**
  7480. * @type {Object.<string, Object>}
  7481. * @type {private}
  7482. */
  7483. this._layerConfig = {};
  7484. if (!singleCanvas) {
  7485. this._width = this._getSize(0);
  7486. this._height = this._getSize(1);
  7487. var domRoot = this._domRoot = createRoot(
  7488. this._width, this._height
  7489. );
  7490. root.appendChild(domRoot);
  7491. }
  7492. else {
  7493. if (opts.width != null) {
  7494. root.width = opts.width;
  7495. }
  7496. if (opts.height != null) {
  7497. root.height = opts.height;
  7498. }
  7499. // Use canvas width and height directly
  7500. var width = root.width;
  7501. var height = root.height;
  7502. this._width = width;
  7503. this._height = height;
  7504. // Create layer if only one given canvas
  7505. // Device pixel ratio is fixed to 1 because given canvas has its specified width and height
  7506. var mainLayer = new Layer(root, this, 1);
  7507. mainLayer.initContext();
  7508. // FIXME Use canvas width and height
  7509. // mainLayer.resize(width, height);
  7510. layers[0] = mainLayer;
  7511. zlevelList.push(0);
  7512. this._domRoot = root;
  7513. }
  7514. // Layers for progressive rendering
  7515. this._progressiveLayers = [];
  7516. /**
  7517. * @type {module:zrender/Layer}
  7518. * @private
  7519. */
  7520. this._hoverlayer;
  7521. this._hoverElements = [];
  7522. };
  7523. Painter.prototype = {
  7524. constructor: Painter,
  7525. getType: function () {
  7526. return 'canvas';
  7527. },
  7528. /**
  7529. * If painter use a single canvas
  7530. * @return {boolean}
  7531. */
  7532. isSingleCanvas: function () {
  7533. return this._singleCanvas;
  7534. },
  7535. /**
  7536. * @return {HTMLDivElement}
  7537. */
  7538. getViewportRoot: function () {
  7539. return this._domRoot;
  7540. },
  7541. getViewportRootOffset: function () {
  7542. var viewportRoot = this.getViewportRoot();
  7543. if (viewportRoot) {
  7544. return {
  7545. offsetLeft: viewportRoot.offsetLeft || 0,
  7546. offsetTop: viewportRoot.offsetTop || 0
  7547. };
  7548. }
  7549. },
  7550. /**
  7551. * 刷新
  7552. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7553. */
  7554. refresh: function (paintAll) {
  7555. var list = this.storage.getDisplayList(true);
  7556. var zlevelList = this._zlevelList;
  7557. this._paintList(list, paintAll);
  7558. // Paint custum layers
  7559. for (var i = 0; i < zlevelList.length; i++) {
  7560. var z = zlevelList[i];
  7561. var layer = this._layers[z];
  7562. if (!layer.__builtin__ && layer.refresh) {
  7563. layer.refresh();
  7564. }
  7565. }
  7566. this.refreshHover();
  7567. if (this._progressiveLayers.length) {
  7568. this._startProgessive();
  7569. }
  7570. return this;
  7571. },
  7572. addHover: function (el, hoverStyle) {
  7573. if (el.__hoverMir) {
  7574. return;
  7575. }
  7576. var elMirror = new el.constructor({
  7577. style: el.style,
  7578. shape: el.shape
  7579. });
  7580. elMirror.__from = el;
  7581. el.__hoverMir = elMirror;
  7582. elMirror.setStyle(hoverStyle);
  7583. this._hoverElements.push(elMirror);
  7584. },
  7585. removeHover: function (el) {
  7586. var elMirror = el.__hoverMir;
  7587. var hoverElements = this._hoverElements;
  7588. var idx = indexOf(hoverElements, elMirror);
  7589. if (idx >= 0) {
  7590. hoverElements.splice(idx, 1);
  7591. }
  7592. el.__hoverMir = null;
  7593. },
  7594. clearHover: function (el) {
  7595. var hoverElements = this._hoverElements;
  7596. for (var i = 0; i < hoverElements.length; i++) {
  7597. var from = hoverElements[i].__from;
  7598. if (from) {
  7599. from.__hoverMir = null;
  7600. }
  7601. }
  7602. hoverElements.length = 0;
  7603. },
  7604. refreshHover: function () {
  7605. var hoverElements = this._hoverElements;
  7606. var len = hoverElements.length;
  7607. var hoverLayer = this._hoverlayer;
  7608. hoverLayer && hoverLayer.clear();
  7609. if (!len) {
  7610. return;
  7611. }
  7612. sort(hoverElements, this.storage.displayableSortFunc);
  7613. // Use a extream large zlevel
  7614. // FIXME?
  7615. if (!hoverLayer) {
  7616. hoverLayer = this._hoverlayer = this.getLayer(1e5);
  7617. }
  7618. var scope = {};
  7619. hoverLayer.ctx.save();
  7620. for (var i = 0; i < len;) {
  7621. var el = hoverElements[i];
  7622. var originalEl = el.__from;
  7623. // Original el is removed
  7624. // PENDING
  7625. if (!(originalEl && originalEl.__zr)) {
  7626. hoverElements.splice(i, 1);
  7627. originalEl.__hoverMir = null;
  7628. len--;
  7629. continue;
  7630. }
  7631. i++;
  7632. // Use transform
  7633. // FIXME style and shape ?
  7634. if (!originalEl.invisible) {
  7635. el.transform = originalEl.transform;
  7636. el.invTransform = originalEl.invTransform;
  7637. el.__clipPaths = originalEl.__clipPaths;
  7638. // el.
  7639. this._doPaintEl(el, hoverLayer, true, scope);
  7640. }
  7641. }
  7642. hoverLayer.ctx.restore();
  7643. },
  7644. _startProgessive: function () {
  7645. var self = this;
  7646. if (!self._furtherProgressive) {
  7647. return;
  7648. }
  7649. // Use a token to stop progress steps triggered by
  7650. // previous zr.refresh calling.
  7651. var token = self._progressiveToken = +new Date();
  7652. self._progress++;
  7653. requestAnimationFrame(step);
  7654. function step() {
  7655. // In case refreshed or disposed
  7656. if (token === self._progressiveToken && self.storage) {
  7657. self._doPaintList(self.storage.getDisplayList());
  7658. if (self._furtherProgressive) {
  7659. self._progress++;
  7660. requestAnimationFrame(step);
  7661. }
  7662. else {
  7663. self._progressiveToken = -1;
  7664. }
  7665. }
  7666. }
  7667. },
  7668. _clearProgressive: function () {
  7669. this._progressiveToken = -1;
  7670. this._progress = 0;
  7671. each$1(this._progressiveLayers, function (layer) {
  7672. layer.__dirty && layer.clear();
  7673. });
  7674. },
  7675. _paintList: function (list, paintAll) {
  7676. if (paintAll == null) {
  7677. paintAll = false;
  7678. }
  7679. this._updateLayerStatus(list);
  7680. this._clearProgressive();
  7681. this.eachBuiltinLayer(preProcessLayer);
  7682. this._doPaintList(list, paintAll);
  7683. this.eachBuiltinLayer(postProcessLayer);
  7684. },
  7685. _doPaintList: function (list, paintAll) {
  7686. var currentLayer;
  7687. var currentZLevel;
  7688. var ctx;
  7689. // var invTransform = [];
  7690. var scope;
  7691. var progressiveLayerIdx = 0;
  7692. var currentProgressiveLayer;
  7693. var width = this._width;
  7694. var height = this._height;
  7695. var layerProgress;
  7696. var frame = this._progress;
  7697. function flushProgressiveLayer(layer) {
  7698. var dpr = ctx.dpr || 1;
  7699. ctx.save();
  7700. ctx.globalAlpha = 1;
  7701. ctx.shadowBlur = 0;
  7702. // Avoid layer don't clear in next progressive frame
  7703. currentLayer.__dirty = true;
  7704. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7705. ctx.drawImage(layer.dom, 0, 0, width * dpr, height * dpr);
  7706. ctx.restore();
  7707. }
  7708. for (var i = 0, l = list.length; i < l; i++) {
  7709. var el = list[i];
  7710. var elZLevel = this._singleCanvas ? 0 : el.zlevel;
  7711. var elFrame = el.__frame;
  7712. // Flush at current context
  7713. // PENDING
  7714. if (elFrame < 0 && currentProgressiveLayer) {
  7715. flushProgressiveLayer(currentProgressiveLayer);
  7716. currentProgressiveLayer = null;
  7717. }
  7718. // Change draw layer
  7719. if (currentZLevel !== elZLevel) {
  7720. if (ctx) {
  7721. ctx.restore();
  7722. }
  7723. // Reset scope
  7724. scope = {};
  7725. // Only 0 zlevel if only has one canvas
  7726. currentZLevel = elZLevel;
  7727. currentLayer = this.getLayer(currentZLevel);
  7728. if (!currentLayer.__builtin__) {
  7729. zrLog(
  7730. 'ZLevel ' + currentZLevel
  7731. + ' has been used by unkown layer ' + currentLayer.id
  7732. );
  7733. }
  7734. ctx = currentLayer.ctx;
  7735. ctx.save();
  7736. // Reset the count
  7737. currentLayer.__unusedCount = 0;
  7738. if (currentLayer.__dirty || paintAll) {
  7739. currentLayer.clear();
  7740. }
  7741. }
  7742. if (!(currentLayer.__dirty || paintAll)) {
  7743. continue;
  7744. }
  7745. if (elFrame >= 0) {
  7746. // Progressive layer changed
  7747. if (!currentProgressiveLayer) {
  7748. currentProgressiveLayer = this._progressiveLayers[
  7749. Math.min(progressiveLayerIdx++, MAX_PROGRESSIVE_LAYER_NUMBER - 1)
  7750. ];
  7751. currentProgressiveLayer.ctx.save();
  7752. currentProgressiveLayer.renderScope = {};
  7753. if (currentProgressiveLayer
  7754. && (currentProgressiveLayer.__progress > currentProgressiveLayer.__maxProgress)
  7755. ) {
  7756. // flushProgressiveLayer(currentProgressiveLayer);
  7757. // Quick jump all progressive elements
  7758. // All progressive element are not dirty, jump over and flush directly
  7759. i = currentProgressiveLayer.__nextIdxNotProg - 1;
  7760. // currentProgressiveLayer = null;
  7761. continue;
  7762. }
  7763. layerProgress = currentProgressiveLayer.__progress;
  7764. if (!currentProgressiveLayer.__dirty) {
  7765. // Keep rendering
  7766. frame = layerProgress;
  7767. }
  7768. currentProgressiveLayer.__progress = frame + 1;
  7769. }
  7770. if (elFrame === frame) {
  7771. this._doPaintEl(el, currentProgressiveLayer, true, currentProgressiveLayer.renderScope);
  7772. }
  7773. }
  7774. else {
  7775. this._doPaintEl(el, currentLayer, paintAll, scope);
  7776. }
  7777. el.__dirty = false;
  7778. }
  7779. if (currentProgressiveLayer) {
  7780. flushProgressiveLayer(currentProgressiveLayer);
  7781. }
  7782. // Restore the lastLayer ctx
  7783. ctx && ctx.restore();
  7784. // If still has clipping state
  7785. // if (scope.prevElClipPaths) {
  7786. // ctx.restore();
  7787. // }
  7788. this._furtherProgressive = false;
  7789. each$1(this._progressiveLayers, function (layer) {
  7790. if (layer.__maxProgress >= layer.__progress) {
  7791. this._furtherProgressive = true;
  7792. }
  7793. }, this);
  7794. },
  7795. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7796. var ctx = currentLayer.ctx;
  7797. var m = el.transform;
  7798. if (
  7799. (currentLayer.__dirty || forcePaint)
  7800. // Ignore invisible element
  7801. && !el.invisible
  7802. // Ignore transparent element
  7803. && el.style.opacity !== 0
  7804. // Ignore scale 0 element, in some environment like node-canvas
  7805. // Draw a scale 0 element can cause all following draw wrong
  7806. // And setTransform with scale 0 will cause set back transform failed.
  7807. && !(m && !m[0] && !m[3])
  7808. // Ignore culled element
  7809. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7810. ) {
  7811. var clipPaths = el.__clipPaths;
  7812. // Optimize when clipping on group with several elements
  7813. if (scope.prevClipLayer !== currentLayer
  7814. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7815. ) {
  7816. // If has previous clipping state, restore from it
  7817. if (scope.prevElClipPaths) {
  7818. scope.prevClipLayer.ctx.restore();
  7819. scope.prevClipLayer = scope.prevElClipPaths = null;
  7820. // Reset prevEl since context has been restored
  7821. scope.prevEl = null;
  7822. }
  7823. // New clipping state
  7824. if (clipPaths) {
  7825. ctx.save();
  7826. doClip(clipPaths, ctx);
  7827. scope.prevClipLayer = currentLayer;
  7828. scope.prevElClipPaths = clipPaths;
  7829. }
  7830. }
  7831. el.beforeBrush && el.beforeBrush(ctx);
  7832. el.brush(ctx, scope.prevEl || null);
  7833. scope.prevEl = el;
  7834. el.afterBrush && el.afterBrush(ctx);
  7835. }
  7836. },
  7837. /**
  7838. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7839. * @param {number} zlevel
  7840. * @return {module:zrender/Layer}
  7841. */
  7842. getLayer: function (zlevel) {
  7843. if (this._singleCanvas) {
  7844. return this._layers[0];
  7845. }
  7846. var layer = this._layers[zlevel];
  7847. if (!layer) {
  7848. // Create a new layer
  7849. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7850. layer.__builtin__ = true;
  7851. if (this._layerConfig[zlevel]) {
  7852. merge(layer, this._layerConfig[zlevel], true);
  7853. }
  7854. this.insertLayer(zlevel, layer);
  7855. // Context is created after dom inserted to document
  7856. // Or excanvas will get 0px clientWidth and clientHeight
  7857. layer.initContext();
  7858. }
  7859. return layer;
  7860. },
  7861. insertLayer: function (zlevel, layer) {
  7862. var layersMap = this._layers;
  7863. var zlevelList = this._zlevelList;
  7864. var len = zlevelList.length;
  7865. var prevLayer = null;
  7866. var i = -1;
  7867. var domRoot = this._domRoot;
  7868. if (layersMap[zlevel]) {
  7869. zrLog('ZLevel ' + zlevel + ' has been used already');
  7870. return;
  7871. }
  7872. // Check if is a valid layer
  7873. if (!isLayerValid(layer)) {
  7874. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7875. return;
  7876. }
  7877. if (len > 0 && zlevel > zlevelList[0]) {
  7878. for (i = 0; i < len - 1; i++) {
  7879. if (
  7880. zlevelList[i] < zlevel
  7881. && zlevelList[i + 1] > zlevel
  7882. ) {
  7883. break;
  7884. }
  7885. }
  7886. prevLayer = layersMap[zlevelList[i]];
  7887. }
  7888. zlevelList.splice(i + 1, 0, zlevel);
  7889. layersMap[zlevel] = layer;
  7890. // Vitual layer will not directly show on the screen.
  7891. // (It can be a WebGL layer and assigned to a ZImage element)
  7892. // But it still under management of zrender.
  7893. if (!layer.virtual) {
  7894. if (prevLayer) {
  7895. var prevDom = prevLayer.dom;
  7896. if (prevDom.nextSibling) {
  7897. domRoot.insertBefore(
  7898. layer.dom,
  7899. prevDom.nextSibling
  7900. );
  7901. }
  7902. else {
  7903. domRoot.appendChild(layer.dom);
  7904. }
  7905. }
  7906. else {
  7907. if (domRoot.firstChild) {
  7908. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7909. }
  7910. else {
  7911. domRoot.appendChild(layer.dom);
  7912. }
  7913. }
  7914. }
  7915. },
  7916. // Iterate each layer
  7917. eachLayer: function (cb, context) {
  7918. var zlevelList = this._zlevelList;
  7919. var z;
  7920. var i;
  7921. for (i = 0; i < zlevelList.length; i++) {
  7922. z = zlevelList[i];
  7923. cb.call(context, this._layers[z], z);
  7924. }
  7925. },
  7926. // Iterate each buildin layer
  7927. eachBuiltinLayer: function (cb, context) {
  7928. var zlevelList = this._zlevelList;
  7929. var layer;
  7930. var z;
  7931. var i;
  7932. for (i = 0; i < zlevelList.length; i++) {
  7933. z = zlevelList[i];
  7934. layer = this._layers[z];
  7935. if (layer.__builtin__) {
  7936. cb.call(context, layer, z);
  7937. }
  7938. }
  7939. },
  7940. // Iterate each other layer except buildin layer
  7941. eachOtherLayer: function (cb, context) {
  7942. var zlevelList = this._zlevelList;
  7943. var layer;
  7944. var z;
  7945. var i;
  7946. for (i = 0; i < zlevelList.length; i++) {
  7947. z = zlevelList[i];
  7948. layer = this._layers[z];
  7949. if (!layer.__builtin__) {
  7950. cb.call(context, layer, z);
  7951. }
  7952. }
  7953. },
  7954. /**
  7955. * 获取所有已创建的层
  7956. * @param {Array.<module:zrender/Layer>} [prevLayer]
  7957. */
  7958. getLayers: function () {
  7959. return this._layers;
  7960. },
  7961. _updateLayerStatus: function (list) {
  7962. var layers = this._layers;
  7963. var progressiveLayers = this._progressiveLayers;
  7964. var elCountsLastFrame = {};
  7965. var progressiveElCountsLastFrame = {};
  7966. this.eachBuiltinLayer(function (layer, z) {
  7967. elCountsLastFrame[z] = layer.elCount;
  7968. layer.elCount = 0;
  7969. layer.__dirty = false;
  7970. });
  7971. each$1(progressiveLayers, function (layer, idx) {
  7972. progressiveElCountsLastFrame[idx] = layer.elCount;
  7973. layer.elCount = 0;
  7974. layer.__dirty = false;
  7975. });
  7976. var progressiveLayerCount = 0;
  7977. var currentProgressiveLayer;
  7978. var lastProgressiveKey;
  7979. var frameCount = 0;
  7980. for (var i = 0, l = list.length; i < l; i++) {
  7981. var el = list[i];
  7982. var zlevel = this._singleCanvas ? 0 : el.zlevel;
  7983. var layer = layers[zlevel];
  7984. var elProgress = el.progressive;
  7985. if (layer) {
  7986. layer.elCount++;
  7987. layer.__dirty = layer.__dirty || el.__dirty;
  7988. }
  7989. /////// Update progressive
  7990. if (elProgress >= 0) {
  7991. // Fix wrong progressive sequence problem.
  7992. if (lastProgressiveKey !== elProgress) {
  7993. lastProgressiveKey = elProgress;
  7994. frameCount++;
  7995. }
  7996. var elFrame = el.__frame = frameCount - 1;
  7997. if (!currentProgressiveLayer) {
  7998. var idx = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER - 1);
  7999. currentProgressiveLayer = progressiveLayers[idx];
  8000. if (!currentProgressiveLayer) {
  8001. currentProgressiveLayer = progressiveLayers[idx] = new Layer(
  8002. 'progressive', this, this.dpr
  8003. );
  8004. currentProgressiveLayer.initContext();
  8005. }
  8006. currentProgressiveLayer.__maxProgress = 0;
  8007. }
  8008. currentProgressiveLayer.__dirty = currentProgressiveLayer.__dirty || el.__dirty;
  8009. currentProgressiveLayer.elCount++;
  8010. currentProgressiveLayer.__maxProgress = Math.max(
  8011. currentProgressiveLayer.__maxProgress, elFrame
  8012. );
  8013. if (currentProgressiveLayer.__maxProgress >= currentProgressiveLayer.__progress) {
  8014. // Should keep rendering this layer because progressive rendering is not finished yet
  8015. layer.__dirty = true;
  8016. }
  8017. }
  8018. else {
  8019. el.__frame = -1;
  8020. if (currentProgressiveLayer) {
  8021. currentProgressiveLayer.__nextIdxNotProg = i;
  8022. progressiveLayerCount++;
  8023. currentProgressiveLayer = null;
  8024. }
  8025. }
  8026. }
  8027. if (currentProgressiveLayer) {
  8028. progressiveLayerCount++;
  8029. currentProgressiveLayer.__nextIdxNotProg = i;
  8030. }
  8031. // 层中的元素数量有发生变化
  8032. this.eachBuiltinLayer(function (layer, z) {
  8033. if (elCountsLastFrame[z] !== layer.elCount) {
  8034. layer.__dirty = true;
  8035. }
  8036. });
  8037. progressiveLayers.length = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER);
  8038. each$1(progressiveLayers, function (layer, idx) {
  8039. if (progressiveElCountsLastFrame[idx] !== layer.elCount) {
  8040. el.__dirty = true;
  8041. }
  8042. if (layer.__dirty) {
  8043. layer.__progress = 0;
  8044. }
  8045. });
  8046. },
  8047. /**
  8048. * 清除hover层外所有内容
  8049. */
  8050. clear: function () {
  8051. this.eachBuiltinLayer(this._clearLayer);
  8052. return this;
  8053. },
  8054. _clearLayer: function (layer) {
  8055. layer.clear();
  8056. },
  8057. /**
  8058. * 修改指定zlevel的绘制参数
  8059. *
  8060. * @param {string} zlevel
  8061. * @param {Object} config 配置对象
  8062. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8063. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8064. * @param {number} [config.lastFrameAlpha=0.7]
  8065. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8066. */
  8067. configLayer: function (zlevel, config) {
  8068. if (config) {
  8069. var layerConfig = this._layerConfig;
  8070. if (!layerConfig[zlevel]) {
  8071. layerConfig[zlevel] = config;
  8072. }
  8073. else {
  8074. merge(layerConfig[zlevel], config, true);
  8075. }
  8076. var layer = this._layers[zlevel];
  8077. if (layer) {
  8078. merge(layer, layerConfig[zlevel], true);
  8079. }
  8080. }
  8081. },
  8082. /**
  8083. * 删除指定层
  8084. * @param {number} zlevel 层所在的zlevel
  8085. */
  8086. delLayer: function (zlevel) {
  8087. var layers = this._layers;
  8088. var zlevelList = this._zlevelList;
  8089. var layer = layers[zlevel];
  8090. if (!layer) {
  8091. return;
  8092. }
  8093. layer.dom.parentNode.removeChild(layer.dom);
  8094. delete layers[zlevel];
  8095. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8096. },
  8097. /**
  8098. * 区域大小变化后重绘
  8099. */
  8100. resize: function (width, height) {
  8101. var domRoot = this._domRoot;
  8102. // FIXME Why ?
  8103. domRoot.style.display = 'none';
  8104. // Save input w/h
  8105. var opts = this._opts;
  8106. width != null && (opts.width = width);
  8107. height != null && (opts.height = height);
  8108. width = this._getSize(0);
  8109. height = this._getSize(1);
  8110. domRoot.style.display = '';
  8111. // 优化没有实际改变的resize
  8112. if (this._width != width || height != this._height) {
  8113. domRoot.style.width = width + 'px';
  8114. domRoot.style.height = height + 'px';
  8115. for (var id in this._layers) {
  8116. if (this._layers.hasOwnProperty(id)) {
  8117. this._layers[id].resize(width, height);
  8118. }
  8119. }
  8120. each$1(this._progressiveLayers, function (layer) {
  8121. layer.resize(width, height);
  8122. });
  8123. this.refresh(true);
  8124. }
  8125. this._width = width;
  8126. this._height = height;
  8127. return this;
  8128. },
  8129. /**
  8130. * 清除单独的一个层
  8131. * @param {number} zlevel
  8132. */
  8133. clearLayer: function (zlevel) {
  8134. var layer = this._layers[zlevel];
  8135. if (layer) {
  8136. layer.clear();
  8137. }
  8138. },
  8139. /**
  8140. * 释放
  8141. */
  8142. dispose: function () {
  8143. this.root.innerHTML = '';
  8144. this.root =
  8145. this.storage =
  8146. this._domRoot =
  8147. this._layers = null;
  8148. },
  8149. /**
  8150. * Get canvas which has all thing rendered
  8151. * @param {Object} opts
  8152. * @param {string} [opts.backgroundColor]
  8153. * @param {number} [opts.pixelRatio]
  8154. */
  8155. getRenderedCanvas: function (opts) {
  8156. opts = opts || {};
  8157. if (this._singleCanvas) {
  8158. return this._layers[0].dom;
  8159. }
  8160. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8161. imageLayer.initContext();
  8162. imageLayer.clearColor = opts.backgroundColor;
  8163. imageLayer.clear();
  8164. var displayList = this.storage.getDisplayList(true);
  8165. var scope = {};
  8166. var zlevel;
  8167. var self = this;
  8168. function findAndDrawOtherLayer(smaller, larger) {
  8169. var zlevelList = self._zlevelList;
  8170. if (smaller == null) {
  8171. smaller = -Infinity;
  8172. }
  8173. var intermediateLayer;
  8174. for (var i = 0; i < zlevelList.length; i++) {
  8175. var z = zlevelList[i];
  8176. var layer = self._layers[z];
  8177. if (!layer.__builtin__ && z > smaller && z < larger) {
  8178. intermediateLayer = layer;
  8179. break;
  8180. }
  8181. }
  8182. if (intermediateLayer && intermediateLayer.renderToCanvas) {
  8183. imageLayer.ctx.save();
  8184. intermediateLayer.renderToCanvas(imageLayer.ctx);
  8185. imageLayer.ctx.restore();
  8186. }
  8187. }
  8188. for (var i = 0; i < displayList.length; i++) {
  8189. var el = displayList[i];
  8190. if (el.zlevel !== zlevel) {
  8191. findAndDrawOtherLayer(zlevel, el.zlevel);
  8192. zlevel = el.zlevel;
  8193. }
  8194. this._doPaintEl(el, imageLayer, true, scope);
  8195. }
  8196. findAndDrawOtherLayer(zlevel, Infinity);
  8197. return imageLayer.dom;
  8198. },
  8199. /**
  8200. * 获取绘图区域宽度
  8201. */
  8202. getWidth: function () {
  8203. return this._width;
  8204. },
  8205. /**
  8206. * 获取绘图区域高度
  8207. */
  8208. getHeight: function () {
  8209. return this._height;
  8210. },
  8211. _getSize: function (whIdx) {
  8212. var opts = this._opts;
  8213. var wh = ['width', 'height'][whIdx];
  8214. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8215. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8216. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8217. if (opts[wh] != null && opts[wh] !== 'auto') {
  8218. return parseFloat(opts[wh]);
  8219. }
  8220. var root = this.root;
  8221. // IE8 does not support getComputedStyle, but it use VML.
  8222. var stl = document.defaultView.getComputedStyle(root);
  8223. return (
  8224. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8225. - (parseInt10(stl[plt]) || 0)
  8226. - (parseInt10(stl[prb]) || 0)
  8227. ) | 0;
  8228. },
  8229. pathToImage: function (path, dpr) {
  8230. dpr = dpr || this.dpr;
  8231. var canvas = document.createElement('canvas');
  8232. var ctx = canvas.getContext('2d');
  8233. var rect = path.getBoundingRect();
  8234. var style = path.style;
  8235. var shadowBlurSize = style.shadowBlur;
  8236. var shadowOffsetX = style.shadowOffsetX;
  8237. var shadowOffsetY = style.shadowOffsetY;
  8238. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8239. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8240. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8241. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8242. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8243. var width = rect.width + leftMargin + rightMargin;
  8244. var height = rect.height + topMargin + bottomMargin;
  8245. canvas.width = width * dpr;
  8246. canvas.height = height * dpr;
  8247. ctx.scale(dpr, dpr);
  8248. ctx.clearRect(0, 0, width, height);
  8249. ctx.dpr = dpr;
  8250. var pathTransform = {
  8251. position: path.position,
  8252. rotation: path.rotation,
  8253. scale: path.scale
  8254. };
  8255. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8256. path.rotation = 0;
  8257. path.scale = [1, 1];
  8258. path.updateTransform();
  8259. if (path) {
  8260. path.brush(ctx);
  8261. }
  8262. var ImageShape = ZImage;
  8263. var imgShape = new ImageShape({
  8264. style: {
  8265. x: 0,
  8266. y: 0,
  8267. image: canvas
  8268. }
  8269. });
  8270. if (pathTransform.position != null) {
  8271. imgShape.position = path.position = pathTransform.position;
  8272. }
  8273. if (pathTransform.rotation != null) {
  8274. imgShape.rotation = path.rotation = pathTransform.rotation;
  8275. }
  8276. if (pathTransform.scale != null) {
  8277. imgShape.scale = path.scale = pathTransform.scale;
  8278. }
  8279. return imgShape;
  8280. }
  8281. };
  8282. /**
  8283. * 事件辅助类
  8284. * @module zrender/core/event
  8285. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8286. */
  8287. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8288. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8289. function getBoundingClientRect(el) {
  8290. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8291. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8292. }
  8293. // `calculate` is optional, default false
  8294. function clientToLocal(el, e, out, calculate) {
  8295. out = out || {};
  8296. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8297. // to the padding edge of the target element. The only browser using this convention
  8298. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8299. // not support the properties.
  8300. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8301. // In zr painter.dom, padding edge equals to border edge.
  8302. // FIXME
  8303. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8304. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8305. // is too complex. So css-transfrom dont support in this case temporarily.
  8306. if (calculate || !env$1.canvasSupported) {
  8307. defaultGetZrXY(el, e, out);
  8308. }
  8309. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8310. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8311. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8312. // zoom-factor, overflow / opacity layers, transforms ...)
  8313. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8314. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8315. // BTW3, In ff, offsetX/offsetY is always 0.
  8316. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8317. out.zrX = e.layerX;
  8318. out.zrY = e.layerY;
  8319. }
  8320. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8321. else if (e.offsetX != null) {
  8322. out.zrX = e.offsetX;
  8323. out.zrY = e.offsetY;
  8324. }
  8325. // For some other device, e.g., IOS safari.
  8326. else {
  8327. defaultGetZrXY(el, e, out);
  8328. }
  8329. return out;
  8330. }
  8331. function defaultGetZrXY(el, e, out) {
  8332. // This well-known method below does not support css transform.
  8333. var box = getBoundingClientRect(el);
  8334. out.zrX = e.clientX - box.left;
  8335. out.zrY = e.clientY - box.top;
  8336. }
  8337. /**
  8338. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8339. * `calculate` is optional, default false.
  8340. */
  8341. function normalizeEvent(el, e, calculate) {
  8342. e = e || window.event;
  8343. if (e.zrX != null) {
  8344. return e;
  8345. }
  8346. var eventType = e.type;
  8347. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8348. if (!isTouch) {
  8349. clientToLocal(el, e, e, calculate);
  8350. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8351. }
  8352. else {
  8353. var touch = eventType != 'touchend'
  8354. ? e.targetTouches[0]
  8355. : e.changedTouches[0];
  8356. touch && clientToLocal(el, touch, e, calculate);
  8357. }
  8358. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8359. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8360. // If e.which has been defined, if may be readonly,
  8361. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8362. var button = e.button;
  8363. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8364. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8365. }
  8366. return e;
  8367. }
  8368. function addEventListener(el, name, handler) {
  8369. if (isDomLevel2) {
  8370. el.addEventListener(name, handler);
  8371. }
  8372. else {
  8373. el.attachEvent('on' + name, handler);
  8374. }
  8375. }
  8376. function removeEventListener(el, name, handler) {
  8377. if (isDomLevel2) {
  8378. el.removeEventListener(name, handler);
  8379. }
  8380. else {
  8381. el.detachEvent('on' + name, handler);
  8382. }
  8383. }
  8384. /**
  8385. * preventDefault and stopPropagation.
  8386. * Notice: do not do that in zrender. Upper application
  8387. * do that if necessary.
  8388. *
  8389. * @memberOf module:zrender/core/event
  8390. * @method
  8391. * @param {Event} e : event对象
  8392. */
  8393. var stop = isDomLevel2
  8394. ? function (e) {
  8395. e.preventDefault();
  8396. e.stopPropagation();
  8397. e.cancelBubble = true;
  8398. }
  8399. : function (e) {
  8400. e.returnValue = false;
  8401. e.cancelBubble = true;
  8402. };
  8403. function notLeftMouse(e) {
  8404. // If e.which is undefined, considered as left mouse event.
  8405. return e.which > 1;
  8406. }
  8407. /**
  8408. * 动画主类, 调度和管理所有动画控制器
  8409. *
  8410. * @module zrender/animation/Animation
  8411. * @author pissang(https://github.com/pissang)
  8412. */
  8413. // TODO Additive animation
  8414. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8415. // https://developer.apple.com/videos/wwdc2014/#236
  8416. /**
  8417. * @typedef {Object} IZRenderStage
  8418. * @property {Function} update
  8419. */
  8420. /**
  8421. * @alias module:zrender/animation/Animation
  8422. * @constructor
  8423. * @param {Object} [options]
  8424. * @param {Function} [options.onframe]
  8425. * @param {IZRenderStage} [options.stage]
  8426. * @example
  8427. * var animation = new Animation();
  8428. * var obj = {
  8429. * x: 100,
  8430. * y: 100
  8431. * };
  8432. * animation.animate(node.position)
  8433. * .when(1000, {
  8434. * x: 500,
  8435. * y: 500
  8436. * })
  8437. * .when(2000, {
  8438. * x: 100,
  8439. * y: 100
  8440. * })
  8441. * .start('spline');
  8442. */
  8443. var Animation = function (options) {
  8444. options = options || {};
  8445. this.stage = options.stage || {};
  8446. this.onframe = options.onframe || function() {};
  8447. // private properties
  8448. this._clips = [];
  8449. this._running = false;
  8450. this._time;
  8451. this._pausedTime;
  8452. this._pauseStart;
  8453. this._paused = false;
  8454. Eventful.call(this);
  8455. };
  8456. Animation.prototype = {
  8457. constructor: Animation,
  8458. /**
  8459. * 添加 clip
  8460. * @param {module:zrender/animation/Clip} clip
  8461. */
  8462. addClip: function (clip) {
  8463. this._clips.push(clip);
  8464. },
  8465. /**
  8466. * 添加 animator
  8467. * @param {module:zrender/animation/Animator} animator
  8468. */
  8469. addAnimator: function (animator) {
  8470. animator.animation = this;
  8471. var clips = animator.getClips();
  8472. for (var i = 0; i < clips.length; i++) {
  8473. this.addClip(clips[i]);
  8474. }
  8475. },
  8476. /**
  8477. * 删除动画片段
  8478. * @param {module:zrender/animation/Clip} clip
  8479. */
  8480. removeClip: function(clip) {
  8481. var idx = indexOf(this._clips, clip);
  8482. if (idx >= 0) {
  8483. this._clips.splice(idx, 1);
  8484. }
  8485. },
  8486. /**
  8487. * 删除动画片段
  8488. * @param {module:zrender/animation/Animator} animator
  8489. */
  8490. removeAnimator: function (animator) {
  8491. var clips = animator.getClips();
  8492. for (var i = 0; i < clips.length; i++) {
  8493. this.removeClip(clips[i]);
  8494. }
  8495. animator.animation = null;
  8496. },
  8497. _update: function() {
  8498. var time = new Date().getTime() - this._pausedTime;
  8499. var delta = time - this._time;
  8500. var clips = this._clips;
  8501. var len = clips.length;
  8502. var deferredEvents = [];
  8503. var deferredClips = [];
  8504. for (var i = 0; i < len; i++) {
  8505. var clip = clips[i];
  8506. var e = clip.step(time, delta);
  8507. // Throw out the events need to be called after
  8508. // stage.update, like destroy
  8509. if (e) {
  8510. deferredEvents.push(e);
  8511. deferredClips.push(clip);
  8512. }
  8513. }
  8514. // Remove the finished clip
  8515. for (var i = 0; i < len;) {
  8516. if (clips[i]._needsRemove) {
  8517. clips[i] = clips[len - 1];
  8518. clips.pop();
  8519. len--;
  8520. }
  8521. else {
  8522. i++;
  8523. }
  8524. }
  8525. len = deferredEvents.length;
  8526. for (var i = 0; i < len; i++) {
  8527. deferredClips[i].fire(deferredEvents[i]);
  8528. }
  8529. this._time = time;
  8530. this.onframe(delta);
  8531. this.trigger('frame', delta);
  8532. if (this.stage.update) {
  8533. this.stage.update();
  8534. }
  8535. },
  8536. _startLoop: function () {
  8537. var self = this;
  8538. this._running = true;
  8539. function step() {
  8540. if (self._running) {
  8541. requestAnimationFrame(step);
  8542. !self._paused && self._update();
  8543. }
  8544. }
  8545. requestAnimationFrame(step);
  8546. },
  8547. /**
  8548. * 开始运行动画
  8549. */
  8550. start: function () {
  8551. this._time = new Date().getTime();
  8552. this._pausedTime = 0;
  8553. this._startLoop();
  8554. },
  8555. /**
  8556. * 停止运行动画
  8557. */
  8558. stop: function () {
  8559. this._running = false;
  8560. },
  8561. /**
  8562. * Pause
  8563. */
  8564. pause: function () {
  8565. if (!this._paused) {
  8566. this._pauseStart = new Date().getTime();
  8567. this._paused = true;
  8568. }
  8569. },
  8570. /**
  8571. * Resume
  8572. */
  8573. resume: function () {
  8574. if (this._paused) {
  8575. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8576. this._paused = false;
  8577. }
  8578. },
  8579. /**
  8580. * 清除所有动画片段
  8581. */
  8582. clear: function () {
  8583. this._clips = [];
  8584. },
  8585. /**
  8586. * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画
  8587. * @param {Object} target
  8588. * @param {Object} options
  8589. * @param {boolean} [options.loop=false] 是否循环播放动画
  8590. * @param {Function} [options.getter=null]
  8591. * 如果指定getter函数,会通过getter函数取属性值
  8592. * @param {Function} [options.setter=null]
  8593. * 如果指定setter函数,会通过setter函数设置属性值
  8594. * @return {module:zrender/animation/Animation~Animator}
  8595. */
  8596. // TODO Gap
  8597. animate: function (target, options) {
  8598. options = options || {};
  8599. var animator = new Animator(
  8600. target,
  8601. options.loop,
  8602. options.getter,
  8603. options.setter
  8604. );
  8605. this.addAnimator(animator);
  8606. return animator;
  8607. }
  8608. };
  8609. mixin(Animation, Eventful);
  8610. /**
  8611. * Only implements needed gestures for mobile.
  8612. */
  8613. var GestureMgr = function () {
  8614. /**
  8615. * @private
  8616. * @type {Array.<Object>}
  8617. */
  8618. this._track = [];
  8619. };
  8620. GestureMgr.prototype = {
  8621. constructor: GestureMgr,
  8622. recognize: function (event, target, root) {
  8623. this._doTrack(event, target, root);
  8624. return this._recognize(event);
  8625. },
  8626. clear: function () {
  8627. this._track.length = 0;
  8628. return this;
  8629. },
  8630. _doTrack: function (event, target, root) {
  8631. var touches = event.touches;
  8632. if (!touches) {
  8633. return;
  8634. }
  8635. var trackItem = {
  8636. points: [],
  8637. touches: [],
  8638. target: target,
  8639. event: event
  8640. };
  8641. for (var i = 0, len = touches.length; i < len; i++) {
  8642. var touch = touches[i];
  8643. var pos = clientToLocal(root, touch, {});
  8644. trackItem.points.push([pos.zrX, pos.zrY]);
  8645. trackItem.touches.push(touch);
  8646. }
  8647. this._track.push(trackItem);
  8648. },
  8649. _recognize: function (event) {
  8650. for (var eventName in recognizers) {
  8651. if (recognizers.hasOwnProperty(eventName)) {
  8652. var gestureInfo = recognizers[eventName](this._track, event);
  8653. if (gestureInfo) {
  8654. return gestureInfo;
  8655. }
  8656. }
  8657. }
  8658. }
  8659. };
  8660. function dist$1(pointPair) {
  8661. var dx = pointPair[1][0] - pointPair[0][0];
  8662. var dy = pointPair[1][1] - pointPair[0][1];
  8663. return Math.sqrt(dx * dx + dy * dy);
  8664. }
  8665. function center(pointPair) {
  8666. return [
  8667. (pointPair[0][0] + pointPair[1][0]) / 2,
  8668. (pointPair[0][1] + pointPair[1][1]) / 2
  8669. ];
  8670. }
  8671. var recognizers = {
  8672. pinch: function (track, event) {
  8673. var trackLen = track.length;
  8674. if (!trackLen) {
  8675. return;
  8676. }
  8677. var pinchEnd = (track[trackLen - 1] || {}).points;
  8678. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8679. if (pinchPre
  8680. && pinchPre.length > 1
  8681. && pinchEnd
  8682. && pinchEnd.length > 1
  8683. ) {
  8684. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8685. !isFinite(pinchScale) && (pinchScale = 1);
  8686. event.pinchScale = pinchScale;
  8687. var pinchCenter = center(pinchEnd);
  8688. event.pinchX = pinchCenter[0];
  8689. event.pinchY = pinchCenter[1];
  8690. return {
  8691. type: 'pinch',
  8692. target: track[0].target,
  8693. event: event
  8694. };
  8695. }
  8696. }
  8697. // Only pinch currently.
  8698. };
  8699. var TOUCH_CLICK_DELAY = 300;
  8700. var mouseHandlerNames = [
  8701. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8702. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8703. ];
  8704. var touchHandlerNames = [
  8705. 'touchstart', 'touchend', 'touchmove'
  8706. ];
  8707. var pointerEventNames = {
  8708. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8709. };
  8710. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8711. var nm = name.replace('mouse', 'pointer');
  8712. return pointerEventNames[nm] ? nm : name;
  8713. });
  8714. function eventNameFix(name) {
  8715. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8716. }
  8717. function processGesture(proxy, event, stage) {
  8718. var gestureMgr = proxy._gestureMgr;
  8719. stage === 'start' && gestureMgr.clear();
  8720. var gestureInfo = gestureMgr.recognize(
  8721. event,
  8722. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8723. proxy.dom
  8724. );
  8725. stage === 'end' && gestureMgr.clear();
  8726. // Do not do any preventDefault here. Upper application do that if necessary.
  8727. if (gestureInfo) {
  8728. var type = gestureInfo.type;
  8729. event.gestureEvent = type;
  8730. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8731. }
  8732. }
  8733. // function onMSGestureChange(proxy, event) {
  8734. // if (event.translationX || event.translationY) {
  8735. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8736. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8737. // }
  8738. // if (event.scale !== 1) {
  8739. // event.pinchX = event.offsetX;
  8740. // event.pinchY = event.offsetY;
  8741. // event.pinchScale = event.scale;
  8742. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8743. // }
  8744. // }
  8745. /**
  8746. * Prevent mouse event from being dispatched after Touch Events action
  8747. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8748. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8749. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8750. * Result: Blocking Mouse Events for 700ms.
  8751. */
  8752. function setTouchTimer(instance) {
  8753. instance._touching = true;
  8754. clearTimeout(instance._touchTimer);
  8755. instance._touchTimer = setTimeout(function () {
  8756. instance._touching = false;
  8757. }, 700);
  8758. }
  8759. var domHandlers = {
  8760. /**
  8761. * Mouse move handler
  8762. * @inner
  8763. * @param {Event} event
  8764. */
  8765. mousemove: function (event) {
  8766. event = normalizeEvent(this.dom, event);
  8767. this.trigger('mousemove', event);
  8768. },
  8769. /**
  8770. * Mouse out handler
  8771. * @inner
  8772. * @param {Event} event
  8773. */
  8774. mouseout: function (event) {
  8775. event = normalizeEvent(this.dom, event);
  8776. var element = event.toElement || event.relatedTarget;
  8777. if (element != this.dom) {
  8778. while (element && element.nodeType != 9) {
  8779. // 忽略包含在root中的dom引起的mouseOut
  8780. if (element === this.dom) {
  8781. return;
  8782. }
  8783. element = element.parentNode;
  8784. }
  8785. }
  8786. this.trigger('mouseout', event);
  8787. },
  8788. /**
  8789. * Touch开始响应函数
  8790. * @inner
  8791. * @param {Event} event
  8792. */
  8793. touchstart: function (event) {
  8794. // Default mouse behaviour should not be disabled here.
  8795. // For example, page may needs to be slided.
  8796. event = normalizeEvent(this.dom, event);
  8797. // Mark touch, which is useful in distinguish touch and
  8798. // mouse event in upper applicatoin.
  8799. event.zrByTouch = true;
  8800. this._lastTouchMoment = new Date();
  8801. processGesture(this, event, 'start');
  8802. // In touch device, trigger `mousemove`(`mouseover`) should
  8803. // be triggered, and must before `mousedown` triggered.
  8804. domHandlers.mousemove.call(this, event);
  8805. domHandlers.mousedown.call(this, event);
  8806. setTouchTimer(this);
  8807. },
  8808. /**
  8809. * Touch移动响应函数
  8810. * @inner
  8811. * @param {Event} event
  8812. */
  8813. touchmove: function (event) {
  8814. event = normalizeEvent(this.dom, event);
  8815. // Mark touch, which is useful in distinguish touch and
  8816. // mouse event in upper applicatoin.
  8817. event.zrByTouch = true;
  8818. processGesture(this, event, 'change');
  8819. // Mouse move should always be triggered no matter whether
  8820. // there is gestrue event, because mouse move and pinch may
  8821. // be used at the same time.
  8822. domHandlers.mousemove.call(this, event);
  8823. setTouchTimer(this);
  8824. },
  8825. /**
  8826. * Touch结束响应函数
  8827. * @inner
  8828. * @param {Event} event
  8829. */
  8830. touchend: function (event) {
  8831. event = normalizeEvent(this.dom, event);
  8832. // Mark touch, which is useful in distinguish touch and
  8833. // mouse event in upper applicatoin.
  8834. event.zrByTouch = true;
  8835. processGesture(this, event, 'end');
  8836. domHandlers.mouseup.call(this, event);
  8837. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8838. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8839. // we can conveniently implement "hover style" in both PC and touch device just
  8840. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8841. // to remove "hover style" on an element, without any additional code for
  8842. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8843. // style" will remain for user view)
  8844. // click event should always be triggered no matter whether
  8845. // there is gestrue event. System click can not be prevented.
  8846. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8847. domHandlers.click.call(this, event);
  8848. }
  8849. setTouchTimer(this);
  8850. },
  8851. pointerdown: function (event) {
  8852. domHandlers.mousedown.call(this, event);
  8853. // if (useMSGuesture(this, event)) {
  8854. // this._msGesture.addPointer(event.pointerId);
  8855. // }
  8856. },
  8857. pointermove: function (event) {
  8858. // FIXME
  8859. // pointermove is so sensitive that it always triggered when
  8860. // tap(click) on touch screen, which affect some judgement in
  8861. // upper application. So, we dont support mousemove on MS touch
  8862. // device yet.
  8863. if (!isPointerFromTouch(event)) {
  8864. domHandlers.mousemove.call(this, event);
  8865. }
  8866. },
  8867. pointerup: function (event) {
  8868. domHandlers.mouseup.call(this, event);
  8869. },
  8870. pointerout: function (event) {
  8871. // pointerout will be triggered when tap on touch screen
  8872. // (IE11+/Edge on MS Surface) after click event triggered,
  8873. // which is inconsistent with the mousout behavior we defined
  8874. // in touchend. So we unify them.
  8875. // (check domHandlers.touchend for detailed explanation)
  8876. if (!isPointerFromTouch(event)) {
  8877. domHandlers.mouseout.call(this, event);
  8878. }
  8879. }
  8880. };
  8881. function isPointerFromTouch(event) {
  8882. var pointerType = event.pointerType;
  8883. return pointerType === 'pen' || pointerType === 'touch';
  8884. }
  8885. // function useMSGuesture(handlerProxy, event) {
  8886. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8887. // }
  8888. // Common handlers
  8889. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8890. domHandlers[name] = function (event) {
  8891. event = normalizeEvent(this.dom, event);
  8892. this.trigger(name, event);
  8893. };
  8894. });
  8895. /**
  8896. * 为控制类实例初始化dom 事件处理函数
  8897. *
  8898. * @inner
  8899. * @param {module:zrender/Handler} instance 控制类实例
  8900. */
  8901. function initDomHandler(instance) {
  8902. each$1(touchHandlerNames, function (name) {
  8903. instance._handlers[name] = bind(domHandlers[name], instance);
  8904. });
  8905. each$1(pointerHandlerNames, function (name) {
  8906. instance._handlers[name] = bind(domHandlers[name], instance);
  8907. });
  8908. each$1(mouseHandlerNames, function (name) {
  8909. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  8910. });
  8911. function makeMouseHandler(fn, instance) {
  8912. return function () {
  8913. if (instance._touching) {
  8914. return;
  8915. }
  8916. return fn.apply(instance, arguments);
  8917. };
  8918. }
  8919. }
  8920. function HandlerDomProxy(dom) {
  8921. Eventful.call(this);
  8922. this.dom = dom;
  8923. /**
  8924. * @private
  8925. * @type {boolean}
  8926. */
  8927. this._touching = false;
  8928. /**
  8929. * @private
  8930. * @type {number}
  8931. */
  8932. this._touchTimer;
  8933. /**
  8934. * @private
  8935. * @type {module:zrender/core/GestureMgr}
  8936. */
  8937. this._gestureMgr = new GestureMgr();
  8938. this._handlers = {};
  8939. initDomHandler(this);
  8940. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  8941. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  8942. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  8943. // at the same time.
  8944. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  8945. // screen, which do not occurs in pointer event.
  8946. // So we use pointer event to both detect touch gesture and mouse behavior.
  8947. mountHandlers(pointerHandlerNames, this);
  8948. // FIXME
  8949. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  8950. // which does not prevent defuault behavior occasionally (which may cause view port
  8951. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  8952. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  8953. // touch screen. And we only support click behavior on MS touch screen now.
  8954. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  8955. // We dont support touch on IE on win7.
  8956. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  8957. // if (typeof MSGesture === 'function') {
  8958. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  8959. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  8960. // }
  8961. }
  8962. else {
  8963. if (env$1.touchEventsSupported) {
  8964. mountHandlers(touchHandlerNames, this);
  8965. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  8966. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  8967. }
  8968. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  8969. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  8970. // mouse event can not be handle in those devices.
  8971. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  8972. // mouseevent after touch event triggered, see `setTouchTimer`.
  8973. mountHandlers(mouseHandlerNames, this);
  8974. }
  8975. function mountHandlers(handlerNames, instance) {
  8976. each$1(handlerNames, function (name) {
  8977. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  8978. }, instance);
  8979. }
  8980. }
  8981. var handlerDomProxyProto = HandlerDomProxy.prototype;
  8982. handlerDomProxyProto.dispose = function () {
  8983. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  8984. for (var i = 0; i < handlerNames.length; i++) {
  8985. var name = handlerNames[i];
  8986. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  8987. }
  8988. };
  8989. handlerDomProxyProto.setCursor = function (cursorStyle) {
  8990. this.dom.style.cursor = cursorStyle || 'default';
  8991. };
  8992. mixin(HandlerDomProxy, Eventful);
  8993. /*!
  8994. * ZRender, a high performance 2d drawing library.
  8995. *
  8996. * Copyright (c) 2013, Baidu Inc.
  8997. * All rights reserved.
  8998. *
  8999. * LICENSE
  9000. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9001. */
  9002. var useVML = !env$1.canvasSupported;
  9003. var painterCtors = {
  9004. canvas: Painter
  9005. };
  9006. var instances$1 = {}; // ZRender实例map索引
  9007. /**
  9008. * @type {string}
  9009. */
  9010. var version$1 = '3.7.3';
  9011. /**
  9012. * Initializing a zrender instance
  9013. * @param {HTMLElement} dom
  9014. * @param {Object} opts
  9015. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9016. * @param {number} [opts.devicePixelRatio]
  9017. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9018. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9019. * @return {module:zrender/ZRender}
  9020. */
  9021. function init$1(dom, opts) {
  9022. var zr = new ZRender(guid(), dom, opts);
  9023. instances$1[zr.id] = zr;
  9024. return zr;
  9025. }
  9026. /**
  9027. * Dispose zrender instance
  9028. * @param {module:zrender/ZRender} zr
  9029. */
  9030. function dispose$1(zr) {
  9031. if (zr) {
  9032. zr.dispose();
  9033. }
  9034. else {
  9035. for (var key in instances$1) {
  9036. if (instances$1.hasOwnProperty(key)) {
  9037. instances$1[key].dispose();
  9038. }
  9039. }
  9040. instances$1 = {};
  9041. }
  9042. return this;
  9043. }
  9044. /**
  9045. * Get zrender instance by id
  9046. * @param {string} id zrender instance id
  9047. * @return {module:zrender/ZRender}
  9048. */
  9049. function getInstance(id) {
  9050. return instances$1[id];
  9051. }
  9052. function registerPainter(name, Ctor) {
  9053. painterCtors[name] = Ctor;
  9054. }
  9055. function delInstance(id) {
  9056. delete instances$1[id];
  9057. }
  9058. /**
  9059. * @module zrender/ZRender
  9060. */
  9061. /**
  9062. * @constructor
  9063. * @alias module:zrender/ZRender
  9064. * @param {string} id
  9065. * @param {HTMLElement} dom
  9066. * @param {Object} opts
  9067. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9068. * @param {number} [opts.devicePixelRatio]
  9069. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9070. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9071. */
  9072. var ZRender = function (id, dom, opts) {
  9073. opts = opts || {};
  9074. /**
  9075. * @type {HTMLDomElement}
  9076. */
  9077. this.dom = dom;
  9078. /**
  9079. * @type {string}
  9080. */
  9081. this.id = id;
  9082. var self = this;
  9083. var storage = new Storage();
  9084. var rendererType = opts.renderer;
  9085. // TODO WebGL
  9086. if (useVML) {
  9087. if (!painterCtors.vml) {
  9088. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9089. }
  9090. rendererType = 'vml';
  9091. }
  9092. else if (!rendererType || !painterCtors[rendererType]) {
  9093. rendererType = 'canvas';
  9094. }
  9095. var painter = new painterCtors[rendererType](dom, storage, opts);
  9096. this.storage = storage;
  9097. this.painter = painter;
  9098. var handerProxy = !env$1.node ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9099. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9100. /**
  9101. * @type {module:zrender/animation/Animation}
  9102. */
  9103. this.animation = new Animation({
  9104. stage: {
  9105. update: bind(this.flush, this)
  9106. }
  9107. });
  9108. this.animation.start();
  9109. /**
  9110. * @type {boolean}
  9111. * @private
  9112. */
  9113. this._needsRefresh;
  9114. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9115. // FIXME 有点ugly
  9116. var oldDelFromStorage = storage.delFromStorage;
  9117. var oldAddToStorage = storage.addToStorage;
  9118. storage.delFromStorage = function (el) {
  9119. oldDelFromStorage.call(storage, el);
  9120. el && el.removeSelfFromZr(self);
  9121. };
  9122. storage.addToStorage = function (el) {
  9123. oldAddToStorage.call(storage, el);
  9124. el.addSelfToZr(self);
  9125. };
  9126. };
  9127. ZRender.prototype = {
  9128. constructor: ZRender,
  9129. /**
  9130. * 获取实例唯一标识
  9131. * @return {string}
  9132. */
  9133. getId: function () {
  9134. return this.id;
  9135. },
  9136. /**
  9137. * 添加元素
  9138. * @param {module:zrender/Element} el
  9139. */
  9140. add: function (el) {
  9141. this.storage.addRoot(el);
  9142. this._needsRefresh = true;
  9143. },
  9144. /**
  9145. * 删除元素
  9146. * @param {module:zrender/Element} el
  9147. */
  9148. remove: function (el) {
  9149. this.storage.delRoot(el);
  9150. this._needsRefresh = true;
  9151. },
  9152. /**
  9153. * Change configuration of layer
  9154. * @param {string} zLevel
  9155. * @param {Object} config
  9156. * @param {string} [config.clearColor=0] Clear color
  9157. * @param {string} [config.motionBlur=false] If enable motion blur
  9158. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9159. */
  9160. configLayer: function (zLevel, config) {
  9161. this.painter.configLayer(zLevel, config);
  9162. this._needsRefresh = true;
  9163. },
  9164. /**
  9165. * Repaint the canvas immediately
  9166. */
  9167. refreshImmediately: function () {
  9168. // var start = new Date();
  9169. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9170. // Or it will cause zrender refreshes again and again.
  9171. this._needsRefresh = false;
  9172. this.painter.refresh();
  9173. /**
  9174. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9175. */
  9176. this._needsRefresh = false;
  9177. // var end = new Date();
  9178. // var log = document.getElementById('log');
  9179. // if (log) {
  9180. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9181. // }
  9182. },
  9183. /**
  9184. * Mark and repaint the canvas in the next frame of browser
  9185. */
  9186. refresh: function() {
  9187. this._needsRefresh = true;
  9188. },
  9189. /**
  9190. * Perform all refresh
  9191. */
  9192. flush: function () {
  9193. if (this._needsRefresh) {
  9194. this.refreshImmediately();
  9195. }
  9196. if (this._needsRefreshHover) {
  9197. this.refreshHoverImmediately();
  9198. }
  9199. },
  9200. /**
  9201. * Add element to hover layer
  9202. * @param {module:zrender/Element} el
  9203. * @param {Object} style
  9204. */
  9205. addHover: function (el, style) {
  9206. if (this.painter.addHover) {
  9207. this.painter.addHover(el, style);
  9208. this.refreshHover();
  9209. }
  9210. },
  9211. /**
  9212. * Add element from hover layer
  9213. * @param {module:zrender/Element} el
  9214. */
  9215. removeHover: function (el) {
  9216. if (this.painter.removeHover) {
  9217. this.painter.removeHover(el);
  9218. this.refreshHover();
  9219. }
  9220. },
  9221. /**
  9222. * Clear all hover elements in hover layer
  9223. * @param {module:zrender/Element} el
  9224. */
  9225. clearHover: function () {
  9226. if (this.painter.clearHover) {
  9227. this.painter.clearHover();
  9228. this.refreshHover();
  9229. }
  9230. },
  9231. /**
  9232. * Refresh hover in next frame
  9233. */
  9234. refreshHover: function () {
  9235. this._needsRefreshHover = true;
  9236. },
  9237. /**
  9238. * Refresh hover immediately
  9239. */
  9240. refreshHoverImmediately: function () {
  9241. this._needsRefreshHover = false;
  9242. this.painter.refreshHover && this.painter.refreshHover();
  9243. },
  9244. /**
  9245. * Resize the canvas.
  9246. * Should be invoked when container size is changed
  9247. * @param {Object} [opts]
  9248. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9249. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9250. */
  9251. resize: function(opts) {
  9252. opts = opts || {};
  9253. this.painter.resize(opts.width, opts.height);
  9254. this.handler.resize();
  9255. },
  9256. /**
  9257. * Stop and clear all animation immediately
  9258. */
  9259. clearAnimation: function () {
  9260. this.animation.clear();
  9261. },
  9262. /**
  9263. * Get container width
  9264. */
  9265. getWidth: function() {
  9266. return this.painter.getWidth();
  9267. },
  9268. /**
  9269. * Get container height
  9270. */
  9271. getHeight: function() {
  9272. return this.painter.getHeight();
  9273. },
  9274. /**
  9275. * Export the canvas as Base64 URL
  9276. * @param {string} type
  9277. * @param {string} [backgroundColor='#fff']
  9278. * @return {string} Base64 URL
  9279. */
  9280. // toDataURL: function(type, backgroundColor) {
  9281. // return this.painter.getRenderedCanvas({
  9282. // backgroundColor: backgroundColor
  9283. // }).toDataURL(type);
  9284. // },
  9285. /**
  9286. * Converting a path to image.
  9287. * It has much better performance of drawing image rather than drawing a vector path.
  9288. * @param {module:zrender/graphic/Path} e
  9289. * @param {number} width
  9290. * @param {number} height
  9291. */
  9292. pathToImage: function(e, dpr) {
  9293. return this.painter.pathToImage(e, dpr);
  9294. },
  9295. /**
  9296. * Set default cursor
  9297. * @param {string} [cursorStyle='default'] 例如 crosshair
  9298. */
  9299. setCursorStyle: function (cursorStyle) {
  9300. this.handler.setCursorStyle(cursorStyle);
  9301. },
  9302. /**
  9303. * Find hovered element
  9304. * @param {number} x
  9305. * @param {number} y
  9306. * @return {Object} {target, topTarget}
  9307. */
  9308. findHover: function (x, y) {
  9309. return this.handler.findHover(x, y);
  9310. },
  9311. /**
  9312. * Bind event
  9313. *
  9314. * @param {string} eventName Event name
  9315. * @param {Function} eventHandler Handler function
  9316. * @param {Object} [context] Context object
  9317. */
  9318. on: function(eventName, eventHandler, context) {
  9319. this.handler.on(eventName, eventHandler, context);
  9320. },
  9321. /**
  9322. * Unbind event
  9323. * @param {string} eventName Event name
  9324. * @param {Function} [eventHandler] Handler function
  9325. */
  9326. off: function(eventName, eventHandler) {
  9327. this.handler.off(eventName, eventHandler);
  9328. },
  9329. /**
  9330. * Trigger event manually
  9331. *
  9332. * @param {string} eventName Event name
  9333. * @param {event=} event Event object
  9334. */
  9335. trigger: function (eventName, event) {
  9336. this.handler.trigger(eventName, event);
  9337. },
  9338. /**
  9339. * Clear all objects and the canvas.
  9340. */
  9341. clear: function () {
  9342. this.storage.delRoot();
  9343. this.painter.clear();
  9344. },
  9345. /**
  9346. * Dispose self.
  9347. */
  9348. dispose: function () {
  9349. this.animation.stop();
  9350. this.clear();
  9351. this.storage.dispose();
  9352. this.painter.dispose();
  9353. this.handler.dispose();
  9354. this.animation =
  9355. this.storage =
  9356. this.painter =
  9357. this.handler = null;
  9358. delInstance(this.id);
  9359. }
  9360. };
  9361. var zrender = (Object.freeze || Object)({
  9362. version: version$1,
  9363. init: init$1,
  9364. dispose: dispose$1,
  9365. getInstance: getInstance,
  9366. registerPainter: registerPainter
  9367. });
  9368. var RADIAN_EPSILON = 1e-4;
  9369. function _trim(str) {
  9370. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  9371. }
  9372. /**
  9373. * Linear mapping a value from domain to range
  9374. * @memberOf module:echarts/util/number
  9375. * @param {(number|Array.<number>)} val
  9376. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  9377. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  9378. * @param {boolean} clamp
  9379. * @return {(number|Array.<number>}
  9380. */
  9381. function linearMap(val, domain, range, clamp) {
  9382. var subDomain = domain[1] - domain[0];
  9383. var subRange = range[1] - range[0];
  9384. if (subDomain === 0) {
  9385. return subRange === 0
  9386. ? range[0]
  9387. : (range[0] + range[1]) / 2;
  9388. }
  9389. // Avoid accuracy problem in edge, such as
  9390. // 146.39 - 62.83 === 83.55999999999999.
  9391. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  9392. // It is a little verbose for efficiency considering this method
  9393. // is a hotspot.
  9394. if (clamp) {
  9395. if (subDomain > 0) {
  9396. if (val <= domain[0]) {
  9397. return range[0];
  9398. }
  9399. else if (val >= domain[1]) {
  9400. return range[1];
  9401. }
  9402. }
  9403. else {
  9404. if (val >= domain[0]) {
  9405. return range[0];
  9406. }
  9407. else if (val <= domain[1]) {
  9408. return range[1];
  9409. }
  9410. }
  9411. }
  9412. else {
  9413. if (val === domain[0]) {
  9414. return range[0];
  9415. }
  9416. if (val === domain[1]) {
  9417. return range[1];
  9418. }
  9419. }
  9420. return (val - domain[0]) / subDomain * subRange + range[0];
  9421. }
  9422. /**
  9423. * Convert a percent string to absolute number.
  9424. * Returns NaN if percent is not a valid string or number
  9425. * @memberOf module:echarts/util/number
  9426. * @param {string|number} percent
  9427. * @param {number} all
  9428. * @return {number}
  9429. */
  9430. function parsePercent$1(percent, all) {
  9431. switch (percent) {
  9432. case 'center':
  9433. case 'middle':
  9434. percent = '50%';
  9435. break;
  9436. case 'left':
  9437. case 'top':
  9438. percent = '0%';
  9439. break;
  9440. case 'right':
  9441. case 'bottom':
  9442. percent = '100%';
  9443. break;
  9444. }
  9445. if (typeof percent === 'string') {
  9446. if (_trim(percent).match(/%$/)) {
  9447. return parseFloat(percent) / 100 * all;
  9448. }
  9449. return parseFloat(percent);
  9450. }
  9451. return percent == null ? NaN : +percent;
  9452. }
  9453. /**
  9454. * (1) Fix rounding error of float numbers.
  9455. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  9456. *
  9457. * @param {number} x
  9458. * @param {number} [precision]
  9459. * @param {boolean} [returnStr]
  9460. * @return {number|string}
  9461. */
  9462. function round(x, precision, returnStr) {
  9463. if (precision == null) {
  9464. precision = 10;
  9465. }
  9466. // Avoid range error
  9467. precision = Math.min(Math.max(0, precision), 20);
  9468. x = (+x).toFixed(precision);
  9469. return returnStr ? x : +x;
  9470. }
  9471. function asc(arr) {
  9472. arr.sort(function (a, b) {
  9473. return a - b;
  9474. });
  9475. return arr;
  9476. }
  9477. /**
  9478. * Get precision
  9479. * @param {number} val
  9480. */
  9481. function getPrecision(val) {
  9482. val = +val;
  9483. if (isNaN(val)) {
  9484. return 0;
  9485. }
  9486. // It is much faster than methods converting number to string as follows
  9487. // var tmp = val.toString();
  9488. // return tmp.length - 1 - tmp.indexOf('.');
  9489. // especially when precision is low
  9490. var e = 1;
  9491. var count = 0;
  9492. while (Math.round(val * e) / e !== val) {
  9493. e *= 10;
  9494. count++;
  9495. }
  9496. return count;
  9497. }
  9498. /**
  9499. * @param {string|number} val
  9500. * @return {number}
  9501. */
  9502. function getPrecisionSafe(val) {
  9503. var str = val.toString();
  9504. // Consider scientific notation: '3.4e-12' '3.4e+12'
  9505. var eIndex = str.indexOf('e');
  9506. if (eIndex > 0) {
  9507. var precision = +str.slice(eIndex + 1);
  9508. return precision < 0 ? -precision : 0;
  9509. }
  9510. else {
  9511. var dotIndex = str.indexOf('.');
  9512. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  9513. }
  9514. }
  9515. /**
  9516. * Minimal dicernible data precisioin according to a single pixel.
  9517. *
  9518. * @param {Array.<number>} dataExtent
  9519. * @param {Array.<number>} pixelExtent
  9520. * @return {number} precision
  9521. */
  9522. function getPixelPrecision(dataExtent, pixelExtent) {
  9523. var log = Math.log;
  9524. var LN10 = Math.LN10;
  9525. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  9526. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  9527. // toFixed() digits argument must be between 0 and 20.
  9528. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  9529. return !isFinite(precision) ? 20 : precision;
  9530. }
  9531. /**
  9532. * Get a data of given precision, assuring the sum of percentages
  9533. * in valueList is 1.
  9534. * The largest remainer method is used.
  9535. * https://en.wikipedia.org/wiki/Largest_remainder_method
  9536. *
  9537. * @param {Array.<number>} valueList a list of all data
  9538. * @param {number} idx index of the data to be processed in valueList
  9539. * @param {number} precision integer number showing digits of precision
  9540. * @return {number} percent ranging from 0 to 100
  9541. */
  9542. function getPercentWithPrecision(valueList, idx, precision) {
  9543. if (!valueList[idx]) {
  9544. return 0;
  9545. }
  9546. var sum = reduce(valueList, function (acc, val) {
  9547. return acc + (isNaN(val) ? 0 : val);
  9548. }, 0);
  9549. if (sum === 0) {
  9550. return 0;
  9551. }
  9552. var digits = Math.pow(10, precision);
  9553. var votesPerQuota = map(valueList, function (val) {
  9554. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  9555. });
  9556. var targetSeats = digits * 100;
  9557. var seats = map(votesPerQuota, function (votes) {
  9558. // Assign automatic seats.
  9559. return Math.floor(votes);
  9560. });
  9561. var currentSum = reduce(seats, function (acc, val) {
  9562. return acc + val;
  9563. }, 0);
  9564. var remainder = map(votesPerQuota, function (votes, idx) {
  9565. return votes - seats[idx];
  9566. });
  9567. // Has remainding votes.
  9568. while (currentSum < targetSeats) {
  9569. // Find next largest remainder.
  9570. var max = Number.NEGATIVE_INFINITY;
  9571. var maxId = null;
  9572. for (var i = 0, len = remainder.length; i < len; ++i) {
  9573. if (remainder[i] > max) {
  9574. max = remainder[i];
  9575. maxId = i;
  9576. }
  9577. }
  9578. // Add a vote to max remainder.
  9579. ++seats[maxId];
  9580. remainder[maxId] = 0;
  9581. ++currentSum;
  9582. }
  9583. return seats[idx] / digits;
  9584. }
  9585. // Number.MAX_SAFE_INTEGER, ie do not support.
  9586. var MAX_SAFE_INTEGER = 9007199254740991;
  9587. /**
  9588. * To 0 - 2 * PI, considering negative radian.
  9589. * @param {number} radian
  9590. * @return {number}
  9591. */
  9592. function remRadian(radian) {
  9593. var pi2 = Math.PI * 2;
  9594. return (radian % pi2 + pi2) % pi2;
  9595. }
  9596. /**
  9597. * @param {type} radian
  9598. * @return {boolean}
  9599. */
  9600. function isRadianAroundZero(val) {
  9601. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  9602. }
  9603. 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
  9604. /**
  9605. * @param {string|Date|number} value These values can be accepted:
  9606. * + An instance of Date, represent a time in its own time zone.
  9607. * + Or string in a subset of ISO 8601, only including:
  9608. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  9609. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  9610. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  9611. * all of which will be treated as local time if time zone is not specified
  9612. * (see <https://momentjs.com/>).
  9613. * + Or other string format, including (all of which will be treated as loacal time):
  9614. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  9615. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  9616. * + a timestamp, which represent a time in UTC.
  9617. * @return {Date} date
  9618. */
  9619. function parseDate(value) {
  9620. if (value instanceof Date) {
  9621. return value;
  9622. }
  9623. else if (typeof value === 'string') {
  9624. // Different browsers parse date in different way, so we parse it manually.
  9625. // Some other issues:
  9626. // new Date('1970-01-01') is UTC,
  9627. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  9628. // See issue #3623
  9629. var match = TIME_REG.exec(value);
  9630. if (!match) {
  9631. // return Invalid Date.
  9632. return new Date(NaN);
  9633. }
  9634. // Use local time when no timezone offset specifed.
  9635. if (!match[8]) {
  9636. // match[n] can only be string or undefined.
  9637. // But take care of '12' + 1 => '121'.
  9638. return new Date(
  9639. +match[1],
  9640. +(match[2] || 1) - 1,
  9641. +match[3] || 1,
  9642. +match[4] || 0,
  9643. +(match[5] || 0),
  9644. +match[6] || 0,
  9645. +match[7] || 0
  9646. );
  9647. }
  9648. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  9649. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  9650. // For example, system timezone is set as "Time Zone: America/Toronto",
  9651. // then these code will get different result:
  9652. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  9653. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  9654. // So we should not use `new Date`, but use `Date.UTC`.
  9655. else {
  9656. var hour = +match[4] || 0;
  9657. if (match[8].toUpperCase() !== 'Z') {
  9658. hour -= match[8].slice(0, 3);
  9659. }
  9660. return new Date(Date.UTC(
  9661. +match[1],
  9662. +(match[2] || 1) - 1,
  9663. +match[3] || 1,
  9664. hour,
  9665. +(match[5] || 0),
  9666. +match[6] || 0,
  9667. +match[7] || 0
  9668. ));
  9669. }
  9670. }
  9671. else if (value == null) {
  9672. return new Date(NaN);
  9673. }
  9674. return new Date(Math.round(value));
  9675. }
  9676. /**
  9677. * Quantity of a number. e.g. 0.1, 1, 10, 100
  9678. *
  9679. * @param {number} val
  9680. * @return {number}
  9681. */
  9682. function quantity(val) {
  9683. return Math.pow(10, quantityExponent(val));
  9684. }
  9685. function quantityExponent(val) {
  9686. return Math.floor(Math.log(val) / Math.LN10);
  9687. }
  9688. /**
  9689. * find a “nice” number approximately equal to x. Round the number if round = true,
  9690. * take ceiling if round = false. The primary observation is that the “nicest”
  9691. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  9692. *
  9693. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  9694. *
  9695. * @param {number} val Non-negative value.
  9696. * @param {boolean} round
  9697. * @return {number}
  9698. */
  9699. function nice(val, round) {
  9700. var exponent = quantityExponent(val);
  9701. var exp10 = Math.pow(10, exponent);
  9702. var f = val / exp10; // 1 <= f < 10
  9703. var nf;
  9704. if (round) {
  9705. if (f < 1.5) { nf = 1; }
  9706. else if (f < 2.5) { nf = 2; }
  9707. else if (f < 4) { nf = 3; }
  9708. else if (f < 7) { nf = 5; }
  9709. else { nf = 10; }
  9710. }
  9711. else {
  9712. if (f < 1) { nf = 1; }
  9713. else if (f < 2) { nf = 2; }
  9714. else if (f < 3) { nf = 3; }
  9715. else if (f < 5) { nf = 5; }
  9716. else { nf = 10; }
  9717. }
  9718. val = nf * exp10;
  9719. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  9720. // 20 is the uppper bound of toFixed.
  9721. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  9722. }
  9723. /**
  9724. * Order intervals asc, and split them when overlap.
  9725. * expect(numberUtil.reformIntervals([
  9726. * {interval: [18, 62], close: [1, 1]},
  9727. * {interval: [-Infinity, -70], close: [0, 0]},
  9728. * {interval: [-70, -26], close: [1, 1]},
  9729. * {interval: [-26, 18], close: [1, 1]},
  9730. * {interval: [62, 150], close: [1, 1]},
  9731. * {interval: [106, 150], close: [1, 1]},
  9732. * {interval: [150, Infinity], close: [0, 0]}
  9733. * ])).toEqual([
  9734. * {interval: [-Infinity, -70], close: [0, 0]},
  9735. * {interval: [-70, -26], close: [1, 1]},
  9736. * {interval: [-26, 18], close: [0, 1]},
  9737. * {interval: [18, 62], close: [0, 1]},
  9738. * {interval: [62, 150], close: [0, 1]},
  9739. * {interval: [150, Infinity], close: [0, 0]}
  9740. * ]);
  9741. * @param {Array.<Object>} list, where `close` mean open or close
  9742. * of the interval, and Infinity can be used.
  9743. * @return {Array.<Object>} The origin list, which has been reformed.
  9744. */
  9745. function reformIntervals(list) {
  9746. list.sort(function (a, b) {
  9747. return littleThan(a, b, 0) ? -1 : 1;
  9748. });
  9749. var curr = -Infinity;
  9750. var currClose = 1;
  9751. for (var i = 0; i < list.length;) {
  9752. var interval = list[i].interval;
  9753. var close = list[i].close;
  9754. for (var lg = 0; lg < 2; lg++) {
  9755. if (interval[lg] <= curr) {
  9756. interval[lg] = curr;
  9757. close[lg] = !lg ? 1 - currClose : 1;
  9758. }
  9759. curr = interval[lg];
  9760. currClose = close[lg];
  9761. }
  9762. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  9763. list.splice(i, 1);
  9764. }
  9765. else {
  9766. i++;
  9767. }
  9768. }
  9769. return list;
  9770. function littleThan(a, b, lg) {
  9771. return a.interval[lg] < b.interval[lg]
  9772. || (
  9773. a.interval[lg] === b.interval[lg]
  9774. && (
  9775. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  9776. || (!lg && littleThan(a, b, 1))
  9777. )
  9778. );
  9779. }
  9780. }
  9781. /**
  9782. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  9783. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  9784. * subtraction forces infinities to NaN
  9785. *
  9786. * @param {*} v
  9787. * @return {boolean}
  9788. */
  9789. function isNumeric(v) {
  9790. return v - parseFloat(v) >= 0;
  9791. }
  9792. var number = (Object.freeze || Object)({
  9793. linearMap: linearMap,
  9794. parsePercent: parsePercent$1,
  9795. round: round,
  9796. asc: asc,
  9797. getPrecision: getPrecision,
  9798. getPrecisionSafe: getPrecisionSafe,
  9799. getPixelPrecision: getPixelPrecision,
  9800. getPercentWithPrecision: getPercentWithPrecision,
  9801. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  9802. remRadian: remRadian,
  9803. isRadianAroundZero: isRadianAroundZero,
  9804. parseDate: parseDate,
  9805. quantity: quantity,
  9806. nice: nice,
  9807. reformIntervals: reformIntervals,
  9808. isNumeric: isNumeric
  9809. });
  9810. /**
  9811. * 每三位默认加,格式化
  9812. * @param {string|number} x
  9813. * @return {string}
  9814. */
  9815. function addCommas(x) {
  9816. if (isNaN(x)) {
  9817. return '-';
  9818. }
  9819. x = (x + '').split('.');
  9820. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  9821. + (x.length > 1 ? ('.' + x[1]) : '');
  9822. }
  9823. /**
  9824. * @param {string} str
  9825. * @param {boolean} [upperCaseFirst=false]
  9826. * @return {string} str
  9827. */
  9828. function toCamelCase(str, upperCaseFirst) {
  9829. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  9830. return group1.toUpperCase();
  9831. });
  9832. if (upperCaseFirst && str) {
  9833. str = str.charAt(0).toUpperCase() + str.slice(1);
  9834. }
  9835. return str;
  9836. }
  9837. var normalizeCssArray$1 = normalizeCssArray;
  9838. function encodeHTML(source) {
  9839. return String(source)
  9840. .replace(/&/g, '&amp;')
  9841. .replace(/</g, '&lt;')
  9842. .replace(/>/g, '&gt;')
  9843. .replace(/"/g, '&quot;')
  9844. .replace(/'/g, '&#39;');
  9845. }
  9846. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  9847. var wrapVar = function (varName, seriesIdx) {
  9848. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  9849. };
  9850. /**
  9851. * Template formatter
  9852. * @param {string} tpl
  9853. * @param {Array.<Object>|Object} paramsList
  9854. * @param {boolean} [encode=false]
  9855. * @return {string}
  9856. */
  9857. function formatTpl(tpl, paramsList, encode) {
  9858. if (!isArray(paramsList)) {
  9859. paramsList = [paramsList];
  9860. }
  9861. var seriesLen = paramsList.length;
  9862. if (!seriesLen) {
  9863. return '';
  9864. }
  9865. var $vars = paramsList[0].$vars || [];
  9866. for (var i = 0; i < $vars.length; i++) {
  9867. var alias = TPL_VAR_ALIAS[i];
  9868. var val = wrapVar(alias, 0);
  9869. tpl = tpl.replace(wrapVar(alias), encode ? encodeHTML(val) : val);
  9870. }
  9871. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  9872. for (var k = 0; k < $vars.length; k++) {
  9873. var val = paramsList[seriesIdx][$vars[k]];
  9874. tpl = tpl.replace(
  9875. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  9876. encode ? encodeHTML(val) : val
  9877. );
  9878. }
  9879. }
  9880. return tpl;
  9881. }
  9882. /**
  9883. * simple Template formatter
  9884. *
  9885. * @param {string} tpl
  9886. * @param {Object} param
  9887. * @param {boolean} [encode=false]
  9888. * @return {string}
  9889. */
  9890. function formatTplSimple(tpl, param, encode) {
  9891. each$1(param, function (value, key) {
  9892. tpl = tpl.replace(
  9893. '{' + key + '}',
  9894. encode ? encodeHTML(value) : value
  9895. );
  9896. });
  9897. return tpl;
  9898. }
  9899. /**
  9900. * @param {string} color
  9901. * @param {string} [extraCssText]
  9902. * @return {string}
  9903. */
  9904. function getTooltipMarker(color, extraCssText) {
  9905. return color
  9906. ? '<span style="display:inline-block;margin-right:5px;'
  9907. + 'border-radius:10px;width:9px;height:9px;background-color:'
  9908. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  9909. : '';
  9910. }
  9911. /**
  9912. * @param {string} str
  9913. * @return {string}
  9914. * @inner
  9915. */
  9916. var s2d = function (str) {
  9917. return str < 10 ? ('0' + str) : str;
  9918. };
  9919. /**
  9920. * ISO Date format
  9921. * @param {string} tpl
  9922. * @param {number} value
  9923. * @param {boolean} [isUTC=false] Default in local time.
  9924. * see `module:echarts/scale/Time`
  9925. * and `module:echarts/util/number#parseDate`.
  9926. * @inner
  9927. */
  9928. function formatTime(tpl, value, isUTC) {
  9929. if (tpl === 'week'
  9930. || tpl === 'month'
  9931. || tpl === 'quarter'
  9932. || tpl === 'half-year'
  9933. || tpl === 'year'
  9934. ) {
  9935. tpl = 'MM-dd\nyyyy';
  9936. }
  9937. var date = parseDate(value);
  9938. var utc = isUTC ? 'UTC' : '';
  9939. var y = date['get' + utc + 'FullYear']();
  9940. var M = date['get' + utc + 'Month']() + 1;
  9941. var d = date['get' + utc + 'Date']();
  9942. var h = date['get' + utc + 'Hours']();
  9943. var m = date['get' + utc + 'Minutes']();
  9944. var s = date['get' + utc + 'Seconds']();
  9945. tpl = tpl.replace('MM', s2d(M))
  9946. .replace('M', M)
  9947. .replace('yyyy', y)
  9948. .replace('yy', y % 100)
  9949. .replace('dd', s2d(d))
  9950. .replace('d', d)
  9951. .replace('hh', s2d(h))
  9952. .replace('h', h)
  9953. .replace('mm', s2d(m))
  9954. .replace('m', m)
  9955. .replace('ss', s2d(s))
  9956. .replace('s', s);
  9957. return tpl;
  9958. }
  9959. /**
  9960. * Capital first
  9961. * @param {string} str
  9962. * @return {string}
  9963. */
  9964. function capitalFirst(str) {
  9965. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  9966. }
  9967. var truncateText$1 = truncateText;
  9968. var getTextRect = getBoundingRect;
  9969. var format = (Object.freeze || Object)({
  9970. addCommas: addCommas,
  9971. toCamelCase: toCamelCase,
  9972. normalizeCssArray: normalizeCssArray$1,
  9973. encodeHTML: encodeHTML,
  9974. formatTpl: formatTpl,
  9975. formatTplSimple: formatTplSimple,
  9976. getTooltipMarker: getTooltipMarker,
  9977. formatTime: formatTime,
  9978. capitalFirst: capitalFirst,
  9979. truncateText: truncateText$1,
  9980. getTextRect: getTextRect
  9981. });
  9982. var TYPE_DELIMITER = '.';
  9983. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9984. var MEMBER_PRIFIX = '\0ec_\0';
  9985. /**
  9986. * Hide private class member.
  9987. * The same behavior as `host[name] = value;` (can be right-value)
  9988. * @public
  9989. */
  9990. function set$1(host, name, value) {
  9991. return (host[MEMBER_PRIFIX + name] = value);
  9992. }
  9993. /**
  9994. * Hide private class member.
  9995. * The same behavior as `host[name];`
  9996. * @public
  9997. */
  9998. function get(host, name) {
  9999. return host[MEMBER_PRIFIX + name];
  10000. }
  10001. /**
  10002. * For hidden private class member.
  10003. * The same behavior as `host.hasOwnProperty(name);`
  10004. * @public
  10005. */
  10006. function hasOwn(host, name) {
  10007. return host.hasOwnProperty(MEMBER_PRIFIX + name);
  10008. }
  10009. /**
  10010. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10011. * @public
  10012. */
  10013. function parseClassType$1(componentType) {
  10014. var ret = {main: '', sub: ''};
  10015. if (componentType) {
  10016. componentType = componentType.split(TYPE_DELIMITER);
  10017. ret.main = componentType[0] || '';
  10018. ret.sub = componentType[1] || '';
  10019. }
  10020. return ret;
  10021. }
  10022. /**
  10023. * @public
  10024. */
  10025. function checkClassType(componentType) {
  10026. assert(
  10027. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10028. 'componentType "' + componentType + '" illegal'
  10029. );
  10030. }
  10031. /**
  10032. * @public
  10033. */
  10034. function enableClassExtend(RootClass, mandatoryMethods) {
  10035. RootClass.$constructor = RootClass;
  10036. RootClass.extend = function (proto) {
  10037. if (__DEV__) {
  10038. each$1(mandatoryMethods, function (method) {
  10039. if (!proto[method]) {
  10040. console.warn(
  10041. 'Method `' + method + '` should be implemented'
  10042. + (proto.type ? ' in ' + proto.type : '') + '.'
  10043. );
  10044. }
  10045. });
  10046. }
  10047. var superClass = this;
  10048. var ExtendedClass = function () {
  10049. if (!proto.$constructor) {
  10050. superClass.apply(this, arguments);
  10051. }
  10052. else {
  10053. proto.$constructor.apply(this, arguments);
  10054. }
  10055. };
  10056. extend(ExtendedClass.prototype, proto);
  10057. ExtendedClass.extend = this.extend;
  10058. ExtendedClass.superCall = superCall;
  10059. ExtendedClass.superApply = superApply;
  10060. inherits(ExtendedClass, this);
  10061. ExtendedClass.superClass = superClass;
  10062. return ExtendedClass;
  10063. };
  10064. }
  10065. // superCall should have class info, which can not be fetch from 'this'.
  10066. // Consider this case:
  10067. // class A has method f,
  10068. // class B inherits class A, overrides method f, f call superApply('f'),
  10069. // class C inherits class B, do not overrides method f,
  10070. // then when method of class C is called, dead loop occured.
  10071. function superCall(context, methodName) {
  10072. var args = slice(arguments, 2);
  10073. return this.superClass.prototype[methodName].apply(context, args);
  10074. }
  10075. function superApply(context, methodName, args) {
  10076. return this.superClass.prototype[methodName].apply(context, args);
  10077. }
  10078. /**
  10079. * @param {Object} entity
  10080. * @param {Object} options
  10081. * @param {boolean} [options.registerWhenExtend]
  10082. * @public
  10083. */
  10084. function enableClassManagement(entity, options) {
  10085. options = options || {};
  10086. /**
  10087. * Component model classes
  10088. * key: componentType,
  10089. * value:
  10090. * componentClass, when componentType is 'xxx'
  10091. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10092. * @type {Object}
  10093. */
  10094. var storage = {};
  10095. entity.registerClass = function (Clazz, componentType) {
  10096. if (componentType) {
  10097. checkClassType(componentType);
  10098. componentType = parseClassType$1(componentType);
  10099. if (!componentType.sub) {
  10100. if (__DEV__) {
  10101. if (storage[componentType.main]) {
  10102. console.warn(componentType.main + ' exists.');
  10103. }
  10104. }
  10105. storage[componentType.main] = Clazz;
  10106. }
  10107. else if (componentType.sub !== IS_CONTAINER) {
  10108. var container = makeContainer(componentType);
  10109. container[componentType.sub] = Clazz;
  10110. }
  10111. }
  10112. return Clazz;
  10113. };
  10114. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10115. var Clazz = storage[componentMainType];
  10116. if (Clazz && Clazz[IS_CONTAINER]) {
  10117. Clazz = subType ? Clazz[subType] : null;
  10118. }
  10119. if (throwWhenNotFound && !Clazz) {
  10120. throw new Error(
  10121. !subType
  10122. ? componentMainType + '.' + 'type should be specified.'
  10123. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10124. );
  10125. }
  10126. return Clazz;
  10127. };
  10128. entity.getClassesByMainType = function (componentType) {
  10129. componentType = parseClassType$1(componentType);
  10130. var result = [];
  10131. var obj = storage[componentType.main];
  10132. if (obj && obj[IS_CONTAINER]) {
  10133. each$1(obj, function (o, type) {
  10134. type !== IS_CONTAINER && result.push(o);
  10135. });
  10136. }
  10137. else {
  10138. result.push(obj);
  10139. }
  10140. return result;
  10141. };
  10142. entity.hasClass = function (componentType) {
  10143. // Just consider componentType.main.
  10144. componentType = parseClassType$1(componentType);
  10145. return !!storage[componentType.main];
  10146. };
  10147. /**
  10148. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10149. */
  10150. entity.getAllClassMainTypes = function () {
  10151. var types = [];
  10152. each$1(storage, function (obj, type) {
  10153. types.push(type);
  10154. });
  10155. return types;
  10156. };
  10157. /**
  10158. * If a main type is container and has sub types
  10159. * @param {string} mainType
  10160. * @return {boolean}
  10161. */
  10162. entity.hasSubTypes = function (componentType) {
  10163. componentType = parseClassType$1(componentType);
  10164. var obj = storage[componentType.main];
  10165. return obj && obj[IS_CONTAINER];
  10166. };
  10167. entity.parseClassType = parseClassType$1;
  10168. function makeContainer(componentType) {
  10169. var container = storage[componentType.main];
  10170. if (!container || !container[IS_CONTAINER]) {
  10171. container = storage[componentType.main] = {};
  10172. container[IS_CONTAINER] = true;
  10173. }
  10174. return container;
  10175. }
  10176. if (options.registerWhenExtend) {
  10177. var originalExtend = entity.extend;
  10178. if (originalExtend) {
  10179. entity.extend = function (proto) {
  10180. var ExtendedClass = originalExtend.call(this, proto);
  10181. return entity.registerClass(ExtendedClass, proto.type);
  10182. };
  10183. }
  10184. }
  10185. return entity;
  10186. }
  10187. /**
  10188. * @param {string|Array.<string>} properties
  10189. */
  10190. // TODO Parse shadow style
  10191. // TODO Only shallow path support
  10192. var makeStyleMapper = function (properties) {
  10193. // Normalize
  10194. for (var i = 0; i < properties.length; i++) {
  10195. if (!properties[i][1]) {
  10196. properties[i][1] = properties[i][0];
  10197. }
  10198. }
  10199. return function (model, excludes, includes) {
  10200. var style = {};
  10201. for (var i = 0; i < properties.length; i++) {
  10202. var propName = properties[i][1];
  10203. if ((excludes && indexOf(excludes, propName) >= 0)
  10204. || (includes && indexOf(includes, propName) < 0)
  10205. ) {
  10206. continue;
  10207. }
  10208. var val = model.getShallow(propName);
  10209. if (val != null) {
  10210. style[properties[i][0]] = val;
  10211. }
  10212. }
  10213. return style;
  10214. };
  10215. };
  10216. var getLineStyle = makeStyleMapper(
  10217. [
  10218. ['lineWidth', 'width'],
  10219. ['stroke', 'color'],
  10220. ['opacity'],
  10221. ['shadowBlur'],
  10222. ['shadowOffsetX'],
  10223. ['shadowOffsetY'],
  10224. ['shadowColor']
  10225. ]
  10226. );
  10227. var lineStyleMixin = {
  10228. getLineStyle: function (excludes) {
  10229. var style = getLineStyle(this, excludes);
  10230. var lineDash = this.getLineDash(style.lineWidth);
  10231. lineDash && (style.lineDash = lineDash);
  10232. return style;
  10233. },
  10234. getLineDash: function (lineWidth) {
  10235. if (lineWidth == null) {
  10236. lineWidth = 1;
  10237. }
  10238. var lineType = this.get('type');
  10239. var dotSize = Math.max(lineWidth, 2);
  10240. var dashSize = lineWidth * 4;
  10241. return (lineType === 'solid' || lineType == null) ? null
  10242. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10243. }
  10244. };
  10245. var getAreaStyle = makeStyleMapper(
  10246. [
  10247. ['fill', 'color'],
  10248. ['shadowBlur'],
  10249. ['shadowOffsetX'],
  10250. ['shadowOffsetY'],
  10251. ['opacity'],
  10252. ['shadowColor']
  10253. ]
  10254. );
  10255. var areaStyleMixin = {
  10256. getAreaStyle: function (excludes, includes) {
  10257. return getAreaStyle(this, excludes, includes);
  10258. }
  10259. };
  10260. /**
  10261. * 曲线辅助模块
  10262. * @module zrender/core/curve
  10263. * @author pissang(https://www.github.com/pissang)
  10264. */
  10265. var mathPow = Math.pow;
  10266. var mathSqrt$2 = Math.sqrt;
  10267. var EPSILON$1 = 1e-8;
  10268. var EPSILON_NUMERIC = 1e-4;
  10269. var THREE_SQRT = mathSqrt$2(3);
  10270. var ONE_THIRD = 1 / 3;
  10271. // 临时变量
  10272. var _v0 = create();
  10273. var _v1 = create();
  10274. var _v2 = create();
  10275. function isAroundZero(val) {
  10276. return val > -EPSILON$1 && val < EPSILON$1;
  10277. }
  10278. function isNotAroundZero$1(val) {
  10279. return val > EPSILON$1 || val < -EPSILON$1;
  10280. }
  10281. /**
  10282. * 计算三次贝塞尔值
  10283. * @memberOf module:zrender/core/curve
  10284. * @param {number} p0
  10285. * @param {number} p1
  10286. * @param {number} p2
  10287. * @param {number} p3
  10288. * @param {number} t
  10289. * @return {number}
  10290. */
  10291. function cubicAt(p0, p1, p2, p3, t) {
  10292. var onet = 1 - t;
  10293. return onet * onet * (onet * p0 + 3 * t * p1)
  10294. + t * t * (t * p3 + 3 * onet * p2);
  10295. }
  10296. /**
  10297. * 计算三次贝塞尔导数值
  10298. * @memberOf module:zrender/core/curve
  10299. * @param {number} p0
  10300. * @param {number} p1
  10301. * @param {number} p2
  10302. * @param {number} p3
  10303. * @param {number} t
  10304. * @return {number}
  10305. */
  10306. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10307. var onet = 1 - t;
  10308. return 3 * (
  10309. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10310. + (p3 - p2) * t * t
  10311. );
  10312. }
  10313. /**
  10314. * 计算三次贝塞尔方程根,使用盛金公式
  10315. * @memberOf module:zrender/core/curve
  10316. * @param {number} p0
  10317. * @param {number} p1
  10318. * @param {number} p2
  10319. * @param {number} p3
  10320. * @param {number} val
  10321. * @param {Array.<number>} roots
  10322. * @return {number} 有效根数目
  10323. */
  10324. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10325. // Evaluate roots of cubic functions
  10326. var a = p3 + 3 * (p1 - p2) - p0;
  10327. var b = 3 * (p2 - p1 * 2 + p0);
  10328. var c = 3 * (p1 - p0);
  10329. var d = p0 - val;
  10330. var A = b * b - 3 * a * c;
  10331. var B = b * c - 9 * a * d;
  10332. var C = c * c - 3 * b * d;
  10333. var n = 0;
  10334. if (isAroundZero(A) && isAroundZero(B)) {
  10335. if (isAroundZero(b)) {
  10336. roots[0] = 0;
  10337. }
  10338. else {
  10339. var t1 = -c / b; //t1, t2, t3, b is not zero
  10340. if (t1 >= 0 && t1 <= 1) {
  10341. roots[n++] = t1;
  10342. }
  10343. }
  10344. }
  10345. else {
  10346. var disc = B * B - 4 * A * C;
  10347. if (isAroundZero(disc)) {
  10348. var K = B / A;
  10349. var t1 = -b / a + K; // t1, a is not zero
  10350. var t2 = -K / 2; // t2, t3
  10351. if (t1 >= 0 && t1 <= 1) {
  10352. roots[n++] = t1;
  10353. }
  10354. if (t2 >= 0 && t2 <= 1) {
  10355. roots[n++] = t2;
  10356. }
  10357. }
  10358. else if (disc > 0) {
  10359. var discSqrt = mathSqrt$2(disc);
  10360. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10361. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10362. if (Y1 < 0) {
  10363. Y1 = -mathPow(-Y1, ONE_THIRD);
  10364. }
  10365. else {
  10366. Y1 = mathPow(Y1, ONE_THIRD);
  10367. }
  10368. if (Y2 < 0) {
  10369. Y2 = -mathPow(-Y2, ONE_THIRD);
  10370. }
  10371. else {
  10372. Y2 = mathPow(Y2, ONE_THIRD);
  10373. }
  10374. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10375. if (t1 >= 0 && t1 <= 1) {
  10376. roots[n++] = t1;
  10377. }
  10378. }
  10379. else {
  10380. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10381. var theta = Math.acos(T) / 3;
  10382. var ASqrt = mathSqrt$2(A);
  10383. var tmp = Math.cos(theta);
  10384. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10385. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10386. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10387. if (t1 >= 0 && t1 <= 1) {
  10388. roots[n++] = t1;
  10389. }
  10390. if (t2 >= 0 && t2 <= 1) {
  10391. roots[n++] = t2;
  10392. }
  10393. if (t3 >= 0 && t3 <= 1) {
  10394. roots[n++] = t3;
  10395. }
  10396. }
  10397. }
  10398. return n;
  10399. }
  10400. /**
  10401. * 计算三次贝塞尔方程极限值的位置
  10402. * @memberOf module:zrender/core/curve
  10403. * @param {number} p0
  10404. * @param {number} p1
  10405. * @param {number} p2
  10406. * @param {number} p3
  10407. * @param {Array.<number>} extrema
  10408. * @return {number} 有效数目
  10409. */
  10410. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10411. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10412. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10413. var c = 3 * p1 - 3 * p0;
  10414. var n = 0;
  10415. if (isAroundZero(a)) {
  10416. if (isNotAroundZero$1(b)) {
  10417. var t1 = -c / b;
  10418. if (t1 >= 0 && t1 <=1) {
  10419. extrema[n++] = t1;
  10420. }
  10421. }
  10422. }
  10423. else {
  10424. var disc = b * b - 4 * a * c;
  10425. if (isAroundZero(disc)) {
  10426. extrema[0] = -b / (2 * a);
  10427. }
  10428. else if (disc > 0) {
  10429. var discSqrt = mathSqrt$2(disc);
  10430. var t1 = (-b + discSqrt) / (2 * a);
  10431. var t2 = (-b - discSqrt) / (2 * a);
  10432. if (t1 >= 0 && t1 <= 1) {
  10433. extrema[n++] = t1;
  10434. }
  10435. if (t2 >= 0 && t2 <= 1) {
  10436. extrema[n++] = t2;
  10437. }
  10438. }
  10439. }
  10440. return n;
  10441. }
  10442. /**
  10443. * 细分三次贝塞尔曲线
  10444. * @memberOf module:zrender/core/curve
  10445. * @param {number} p0
  10446. * @param {number} p1
  10447. * @param {number} p2
  10448. * @param {number} p3
  10449. * @param {number} t
  10450. * @param {Array.<number>} out
  10451. */
  10452. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10453. var p01 = (p1 - p0) * t + p0;
  10454. var p12 = (p2 - p1) * t + p1;
  10455. var p23 = (p3 - p2) * t + p2;
  10456. var p012 = (p12 - p01) * t + p01;
  10457. var p123 = (p23 - p12) * t + p12;
  10458. var p0123 = (p123 - p012) * t + p012;
  10459. // Seg0
  10460. out[0] = p0;
  10461. out[1] = p01;
  10462. out[2] = p012;
  10463. out[3] = p0123;
  10464. // Seg1
  10465. out[4] = p0123;
  10466. out[5] = p123;
  10467. out[6] = p23;
  10468. out[7] = p3;
  10469. }
  10470. /**
  10471. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10472. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10473. * @param {number} x0
  10474. * @param {number} y0
  10475. * @param {number} x1
  10476. * @param {number} y1
  10477. * @param {number} x2
  10478. * @param {number} y2
  10479. * @param {number} x3
  10480. * @param {number} y3
  10481. * @param {number} x
  10482. * @param {number} y
  10483. * @param {Array.<number>} [out] 投射点
  10484. * @return {number}
  10485. */
  10486. function cubicProjectPoint(
  10487. x0, y0, x1, y1, x2, y2, x3, y3,
  10488. x, y, out
  10489. ) {
  10490. // http://pomax.github.io/bezierinfo/#projections
  10491. var t;
  10492. var interval = 0.005;
  10493. var d = Infinity;
  10494. var prev;
  10495. var next;
  10496. var d1;
  10497. var d2;
  10498. _v0[0] = x;
  10499. _v0[1] = y;
  10500. // 先粗略估计一下可能的最小距离的 t 值
  10501. // PENDING
  10502. for (var _t = 0; _t < 1; _t += 0.05) {
  10503. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10504. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10505. d1 = distSquare(_v0, _v1);
  10506. if (d1 < d) {
  10507. t = _t;
  10508. d = d1;
  10509. }
  10510. }
  10511. d = Infinity;
  10512. // At most 32 iteration
  10513. for (var i = 0; i < 32; i++) {
  10514. if (interval < EPSILON_NUMERIC) {
  10515. break;
  10516. }
  10517. prev = t - interval;
  10518. next = t + interval;
  10519. // t - interval
  10520. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10521. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10522. d1 = distSquare(_v1, _v0);
  10523. if (prev >= 0 && d1 < d) {
  10524. t = prev;
  10525. d = d1;
  10526. }
  10527. else {
  10528. // t + interval
  10529. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10530. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10531. d2 = distSquare(_v2, _v0);
  10532. if (next <= 1 && d2 < d) {
  10533. t = next;
  10534. d = d2;
  10535. }
  10536. else {
  10537. interval *= 0.5;
  10538. }
  10539. }
  10540. }
  10541. // t
  10542. if (out) {
  10543. out[0] = cubicAt(x0, x1, x2, x3, t);
  10544. out[1] = cubicAt(y0, y1, y2, y3, t);
  10545. }
  10546. // console.log(interval, i);
  10547. return mathSqrt$2(d);
  10548. }
  10549. /**
  10550. * 计算二次方贝塞尔值
  10551. * @param {number} p0
  10552. * @param {number} p1
  10553. * @param {number} p2
  10554. * @param {number} t
  10555. * @return {number}
  10556. */
  10557. function quadraticAt(p0, p1, p2, t) {
  10558. var onet = 1 - t;
  10559. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10560. }
  10561. /**
  10562. * 计算二次方贝塞尔导数值
  10563. * @param {number} p0
  10564. * @param {number} p1
  10565. * @param {number} p2
  10566. * @param {number} t
  10567. * @return {number}
  10568. */
  10569. function quadraticDerivativeAt(p0, p1, p2, t) {
  10570. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10571. }
  10572. /**
  10573. * 计算二次方贝塞尔方程根
  10574. * @param {number} p0
  10575. * @param {number} p1
  10576. * @param {number} p2
  10577. * @param {number} t
  10578. * @param {Array.<number>} roots
  10579. * @return {number} 有效根数目
  10580. */
  10581. function quadraticRootAt(p0, p1, p2, val, roots) {
  10582. var a = p0 - 2 * p1 + p2;
  10583. var b = 2 * (p1 - p0);
  10584. var c = p0 - val;
  10585. var n = 0;
  10586. if (isAroundZero(a)) {
  10587. if (isNotAroundZero$1(b)) {
  10588. var t1 = -c / b;
  10589. if (t1 >= 0 && t1 <= 1) {
  10590. roots[n++] = t1;
  10591. }
  10592. }
  10593. }
  10594. else {
  10595. var disc = b * b - 4 * a * c;
  10596. if (isAroundZero(disc)) {
  10597. var t1 = -b / (2 * a);
  10598. if (t1 >= 0 && t1 <= 1) {
  10599. roots[n++] = t1;
  10600. }
  10601. }
  10602. else if (disc > 0) {
  10603. var discSqrt = mathSqrt$2(disc);
  10604. var t1 = (-b + discSqrt) / (2 * a);
  10605. var t2 = (-b - discSqrt) / (2 * a);
  10606. if (t1 >= 0 && t1 <= 1) {
  10607. roots[n++] = t1;
  10608. }
  10609. if (t2 >= 0 && t2 <= 1) {
  10610. roots[n++] = t2;
  10611. }
  10612. }
  10613. }
  10614. return n;
  10615. }
  10616. /**
  10617. * 计算二次贝塞尔方程极限值
  10618. * @memberOf module:zrender/core/curve
  10619. * @param {number} p0
  10620. * @param {number} p1
  10621. * @param {number} p2
  10622. * @return {number}
  10623. */
  10624. function quadraticExtremum(p0, p1, p2) {
  10625. var divider = p0 + p2 - 2 * p1;
  10626. if (divider === 0) {
  10627. // p1 is center of p0 and p2
  10628. return 0.5;
  10629. }
  10630. else {
  10631. return (p0 - p1) / divider;
  10632. }
  10633. }
  10634. /**
  10635. * 细分二次贝塞尔曲线
  10636. * @memberOf module:zrender/core/curve
  10637. * @param {number} p0
  10638. * @param {number} p1
  10639. * @param {number} p2
  10640. * @param {number} t
  10641. * @param {Array.<number>} out
  10642. */
  10643. function quadraticSubdivide(p0, p1, p2, t, out) {
  10644. var p01 = (p1 - p0) * t + p0;
  10645. var p12 = (p2 - p1) * t + p1;
  10646. var p012 = (p12 - p01) * t + p01;
  10647. // Seg0
  10648. out[0] = p0;
  10649. out[1] = p01;
  10650. out[2] = p012;
  10651. // Seg1
  10652. out[3] = p012;
  10653. out[4] = p12;
  10654. out[5] = p2;
  10655. }
  10656. /**
  10657. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10658. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10659. * @param {number} x0
  10660. * @param {number} y0
  10661. * @param {number} x1
  10662. * @param {number} y1
  10663. * @param {number} x2
  10664. * @param {number} y2
  10665. * @param {number} x
  10666. * @param {number} y
  10667. * @param {Array.<number>} out 投射点
  10668. * @return {number}
  10669. */
  10670. function quadraticProjectPoint(
  10671. x0, y0, x1, y1, x2, y2,
  10672. x, y, out
  10673. ) {
  10674. // http://pomax.github.io/bezierinfo/#projections
  10675. var t;
  10676. var interval = 0.005;
  10677. var d = Infinity;
  10678. _v0[0] = x;
  10679. _v0[1] = y;
  10680. // 先粗略估计一下可能的最小距离的 t 值
  10681. // PENDING
  10682. for (var _t = 0; _t < 1; _t += 0.05) {
  10683. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10684. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10685. var d1 = distSquare(_v0, _v1);
  10686. if (d1 < d) {
  10687. t = _t;
  10688. d = d1;
  10689. }
  10690. }
  10691. d = Infinity;
  10692. // At most 32 iteration
  10693. for (var i = 0; i < 32; i++) {
  10694. if (interval < EPSILON_NUMERIC) {
  10695. break;
  10696. }
  10697. var prev = t - interval;
  10698. var next = t + interval;
  10699. // t - interval
  10700. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10701. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10702. var d1 = distSquare(_v1, _v0);
  10703. if (prev >= 0 && d1 < d) {
  10704. t = prev;
  10705. d = d1;
  10706. }
  10707. else {
  10708. // t + interval
  10709. _v2[0] = quadraticAt(x0, x1, x2, next);
  10710. _v2[1] = quadraticAt(y0, y1, y2, next);
  10711. var d2 = distSquare(_v2, _v0);
  10712. if (next <= 1 && d2 < d) {
  10713. t = next;
  10714. d = d2;
  10715. }
  10716. else {
  10717. interval *= 0.5;
  10718. }
  10719. }
  10720. }
  10721. // t
  10722. if (out) {
  10723. out[0] = quadraticAt(x0, x1, x2, t);
  10724. out[1] = quadraticAt(y0, y1, y2, t);
  10725. }
  10726. // console.log(interval, i);
  10727. return mathSqrt$2(d);
  10728. }
  10729. /**
  10730. * @author Yi Shen(https://github.com/pissang)
  10731. */
  10732. var mathMin$3 = Math.min;
  10733. var mathMax$3 = Math.max;
  10734. var mathSin$2 = Math.sin;
  10735. var mathCos$2 = Math.cos;
  10736. var PI2 = Math.PI * 2;
  10737. var start = create();
  10738. var end = create();
  10739. var extremity = create();
  10740. /**
  10741. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10742. * @module zrender/core/bbox
  10743. * @param {Array<Object>} points 顶点数组
  10744. * @param {number} min
  10745. * @param {number} max
  10746. */
  10747. function fromPoints(points, min$$1, max$$1) {
  10748. if (points.length === 0) {
  10749. return;
  10750. }
  10751. var p = points[0];
  10752. var left = p[0];
  10753. var right = p[0];
  10754. var top = p[1];
  10755. var bottom = p[1];
  10756. var i;
  10757. for (i = 1; i < points.length; i++) {
  10758. p = points[i];
  10759. left = mathMin$3(left, p[0]);
  10760. right = mathMax$3(right, p[0]);
  10761. top = mathMin$3(top, p[1]);
  10762. bottom = mathMax$3(bottom, p[1]);
  10763. }
  10764. min$$1[0] = left;
  10765. min$$1[1] = top;
  10766. max$$1[0] = right;
  10767. max$$1[1] = bottom;
  10768. }
  10769. /**
  10770. * @memberOf module:zrender/core/bbox
  10771. * @param {number} x0
  10772. * @param {number} y0
  10773. * @param {number} x1
  10774. * @param {number} y1
  10775. * @param {Array.<number>} min
  10776. * @param {Array.<number>} max
  10777. */
  10778. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10779. min$$1[0] = mathMin$3(x0, x1);
  10780. min$$1[1] = mathMin$3(y0, y1);
  10781. max$$1[0] = mathMax$3(x0, x1);
  10782. max$$1[1] = mathMax$3(y0, y1);
  10783. }
  10784. var xDim = [];
  10785. var yDim = [];
  10786. /**
  10787. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10788. * @memberOf module:zrender/core/bbox
  10789. * @param {number} x0
  10790. * @param {number} y0
  10791. * @param {number} x1
  10792. * @param {number} y1
  10793. * @param {number} x2
  10794. * @param {number} y2
  10795. * @param {number} x3
  10796. * @param {number} y3
  10797. * @param {Array.<number>} min
  10798. * @param {Array.<number>} max
  10799. */
  10800. function fromCubic(
  10801. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10802. ) {
  10803. var cubicExtrema$$1 = cubicExtrema;
  10804. var cubicAt$$1 = cubicAt;
  10805. var i;
  10806. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10807. min$$1[0] = Infinity;
  10808. min$$1[1] = Infinity;
  10809. max$$1[0] = -Infinity;
  10810. max$$1[1] = -Infinity;
  10811. for (i = 0; i < n; i++) {
  10812. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10813. min$$1[0] = mathMin$3(x, min$$1[0]);
  10814. max$$1[0] = mathMax$3(x, max$$1[0]);
  10815. }
  10816. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10817. for (i = 0; i < n; i++) {
  10818. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10819. min$$1[1] = mathMin$3(y, min$$1[1]);
  10820. max$$1[1] = mathMax$3(y, max$$1[1]);
  10821. }
  10822. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10823. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10824. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10825. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10826. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10827. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10828. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10829. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10830. }
  10831. /**
  10832. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10833. * @memberOf module:zrender/core/bbox
  10834. * @param {number} x0
  10835. * @param {number} y0
  10836. * @param {number} x1
  10837. * @param {number} y1
  10838. * @param {number} x2
  10839. * @param {number} y2
  10840. * @param {Array.<number>} min
  10841. * @param {Array.<number>} max
  10842. */
  10843. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10844. var quadraticExtremum$$1 = quadraticExtremum;
  10845. var quadraticAt$$1 = quadraticAt;
  10846. // Find extremities, where derivative in x dim or y dim is zero
  10847. var tx =
  10848. mathMax$3(
  10849. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10850. );
  10851. var ty =
  10852. mathMax$3(
  10853. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10854. );
  10855. var x = quadraticAt$$1(x0, x1, x2, tx);
  10856. var y = quadraticAt$$1(y0, y1, y2, ty);
  10857. min$$1[0] = mathMin$3(x0, x2, x);
  10858. min$$1[1] = mathMin$3(y0, y2, y);
  10859. max$$1[0] = mathMax$3(x0, x2, x);
  10860. max$$1[1] = mathMax$3(y0, y2, y);
  10861. }
  10862. /**
  10863. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10864. * @method
  10865. * @memberOf module:zrender/core/bbox
  10866. * @param {number} x
  10867. * @param {number} y
  10868. * @param {number} rx
  10869. * @param {number} ry
  10870. * @param {number} startAngle
  10871. * @param {number} endAngle
  10872. * @param {number} anticlockwise
  10873. * @param {Array.<number>} min
  10874. * @param {Array.<number>} max
  10875. */
  10876. function fromArc(
  10877. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10878. ) {
  10879. var vec2Min = min;
  10880. var vec2Max = max;
  10881. var diff = Math.abs(startAngle - endAngle);
  10882. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10883. // Is a circle
  10884. min$$1[0] = x - rx;
  10885. min$$1[1] = y - ry;
  10886. max$$1[0] = x + rx;
  10887. max$$1[1] = y + ry;
  10888. return;
  10889. }
  10890. start[0] = mathCos$2(startAngle) * rx + x;
  10891. start[1] = mathSin$2(startAngle) * ry + y;
  10892. end[0] = mathCos$2(endAngle) * rx + x;
  10893. end[1] = mathSin$2(endAngle) * ry + y;
  10894. vec2Min(min$$1, start, end);
  10895. vec2Max(max$$1, start, end);
  10896. // Thresh to [0, Math.PI * 2]
  10897. startAngle = startAngle % (PI2);
  10898. if (startAngle < 0) {
  10899. startAngle = startAngle + PI2;
  10900. }
  10901. endAngle = endAngle % (PI2);
  10902. if (endAngle < 0) {
  10903. endAngle = endAngle + PI2;
  10904. }
  10905. if (startAngle > endAngle && !anticlockwise) {
  10906. endAngle += PI2;
  10907. }
  10908. else if (startAngle < endAngle && anticlockwise) {
  10909. startAngle += PI2;
  10910. }
  10911. if (anticlockwise) {
  10912. var tmp = endAngle;
  10913. endAngle = startAngle;
  10914. startAngle = tmp;
  10915. }
  10916. // var number = 0;
  10917. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10918. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10919. if (angle > startAngle) {
  10920. extremity[0] = mathCos$2(angle) * rx + x;
  10921. extremity[1] = mathSin$2(angle) * ry + y;
  10922. vec2Min(min$$1, extremity, min$$1);
  10923. vec2Max(max$$1, extremity, max$$1);
  10924. }
  10925. }
  10926. }
  10927. /**
  10928. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10929. * 可以用于 isInsidePath 判断以及获取boundingRect
  10930. *
  10931. * @module zrender/core/PathProxy
  10932. * @author Yi Shen (http://www.github.com/pissang)
  10933. */
  10934. // TODO getTotalLength, getPointAtLength
  10935. var CMD = {
  10936. M: 1,
  10937. L: 2,
  10938. C: 3,
  10939. Q: 4,
  10940. A: 5,
  10941. Z: 6,
  10942. // Rect
  10943. R: 7
  10944. };
  10945. // var CMD_MEM_SIZE = {
  10946. // M: 3,
  10947. // L: 3,
  10948. // C: 7,
  10949. // Q: 5,
  10950. // A: 9,
  10951. // R: 5,
  10952. // Z: 1
  10953. // };
  10954. var min$1 = [];
  10955. var max$1 = [];
  10956. var min2 = [];
  10957. var max2 = [];
  10958. var mathMin$2 = Math.min;
  10959. var mathMax$2 = Math.max;
  10960. var mathCos$1 = Math.cos;
  10961. var mathSin$1 = Math.sin;
  10962. var mathSqrt$1 = Math.sqrt;
  10963. var mathAbs = Math.abs;
  10964. var hasTypedArray = typeof Float32Array != 'undefined';
  10965. /**
  10966. * @alias module:zrender/core/PathProxy
  10967. * @constructor
  10968. */
  10969. var PathProxy = function (notSaveData) {
  10970. this._saveData = !(notSaveData || false);
  10971. if (this._saveData) {
  10972. /**
  10973. * Path data. Stored as flat array
  10974. * @type {Array.<Object>}
  10975. */
  10976. this.data = [];
  10977. }
  10978. this._ctx = null;
  10979. };
  10980. /**
  10981. * 快速计算Path包围盒(并不是最小包围盒)
  10982. * @return {Object}
  10983. */
  10984. PathProxy.prototype = {
  10985. constructor: PathProxy,
  10986. _xi: 0,
  10987. _yi: 0,
  10988. _x0: 0,
  10989. _y0: 0,
  10990. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10991. _ux: 0,
  10992. _uy: 0,
  10993. _len: 0,
  10994. _lineDash: null,
  10995. _dashOffset: 0,
  10996. _dashIdx: 0,
  10997. _dashSum: 0,
  10998. /**
  10999. * @readOnly
  11000. */
  11001. setScale: function (sx, sy) {
  11002. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11003. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11004. },
  11005. getContext: function () {
  11006. return this._ctx;
  11007. },
  11008. /**
  11009. * @param {CanvasRenderingContext2D} ctx
  11010. * @return {module:zrender/core/PathProxy}
  11011. */
  11012. beginPath: function (ctx) {
  11013. this._ctx = ctx;
  11014. ctx && ctx.beginPath();
  11015. ctx && (this.dpr = ctx.dpr);
  11016. // Reset
  11017. if (this._saveData) {
  11018. this._len = 0;
  11019. }
  11020. if (this._lineDash) {
  11021. this._lineDash = null;
  11022. this._dashOffset = 0;
  11023. }
  11024. return this;
  11025. },
  11026. /**
  11027. * @param {number} x
  11028. * @param {number} y
  11029. * @return {module:zrender/core/PathProxy}
  11030. */
  11031. moveTo: function (x, y) {
  11032. this.addData(CMD.M, x, y);
  11033. this._ctx && this._ctx.moveTo(x, y);
  11034. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11035. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11036. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11037. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11038. this._x0 = x;
  11039. this._y0 = y;
  11040. this._xi = x;
  11041. this._yi = y;
  11042. return this;
  11043. },
  11044. /**
  11045. * @param {number} x
  11046. * @param {number} y
  11047. * @return {module:zrender/core/PathProxy}
  11048. */
  11049. lineTo: function (x, y) {
  11050. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11051. || mathAbs(y - this._yi) > this._uy
  11052. // Force draw the first segment
  11053. || this._len < 5;
  11054. this.addData(CMD.L, x, y);
  11055. if (this._ctx && exceedUnit) {
  11056. this._needsDash() ? this._dashedLineTo(x, y)
  11057. : this._ctx.lineTo(x, y);
  11058. }
  11059. if (exceedUnit) {
  11060. this._xi = x;
  11061. this._yi = y;
  11062. }
  11063. return this;
  11064. },
  11065. /**
  11066. * @param {number} x1
  11067. * @param {number} y1
  11068. * @param {number} x2
  11069. * @param {number} y2
  11070. * @param {number} x3
  11071. * @param {number} y3
  11072. * @return {module:zrender/core/PathProxy}
  11073. */
  11074. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11075. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11076. if (this._ctx) {
  11077. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11078. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11079. }
  11080. this._xi = x3;
  11081. this._yi = y3;
  11082. return this;
  11083. },
  11084. /**
  11085. * @param {number} x1
  11086. * @param {number} y1
  11087. * @param {number} x2
  11088. * @param {number} y2
  11089. * @return {module:zrender/core/PathProxy}
  11090. */
  11091. quadraticCurveTo: function (x1, y1, x2, y2) {
  11092. this.addData(CMD.Q, x1, y1, x2, y2);
  11093. if (this._ctx) {
  11094. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11095. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11096. }
  11097. this._xi = x2;
  11098. this._yi = y2;
  11099. return this;
  11100. },
  11101. /**
  11102. * @param {number} cx
  11103. * @param {number} cy
  11104. * @param {number} r
  11105. * @param {number} startAngle
  11106. * @param {number} endAngle
  11107. * @param {boolean} anticlockwise
  11108. * @return {module:zrender/core/PathProxy}
  11109. */
  11110. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11111. this.addData(
  11112. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11113. );
  11114. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11115. this._xi = mathCos$1(endAngle) * r + cx;
  11116. this._yi = mathSin$1(endAngle) * r + cx;
  11117. return this;
  11118. },
  11119. // TODO
  11120. arcTo: function (x1, y1, x2, y2, radius) {
  11121. if (this._ctx) {
  11122. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11123. }
  11124. return this;
  11125. },
  11126. // TODO
  11127. rect: function (x, y, w, h) {
  11128. this._ctx && this._ctx.rect(x, y, w, h);
  11129. this.addData(CMD.R, x, y, w, h);
  11130. return this;
  11131. },
  11132. /**
  11133. * @return {module:zrender/core/PathProxy}
  11134. */
  11135. closePath: function () {
  11136. this.addData(CMD.Z);
  11137. var ctx = this._ctx;
  11138. var x0 = this._x0;
  11139. var y0 = this._y0;
  11140. if (ctx) {
  11141. this._needsDash() && this._dashedLineTo(x0, y0);
  11142. ctx.closePath();
  11143. }
  11144. this._xi = x0;
  11145. this._yi = y0;
  11146. return this;
  11147. },
  11148. /**
  11149. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11150. * stroke 同样
  11151. * @param {CanvasRenderingContext2D} ctx
  11152. * @return {module:zrender/core/PathProxy}
  11153. */
  11154. fill: function (ctx) {
  11155. ctx && ctx.fill();
  11156. this.toStatic();
  11157. },
  11158. /**
  11159. * @param {CanvasRenderingContext2D} ctx
  11160. * @return {module:zrender/core/PathProxy}
  11161. */
  11162. stroke: function (ctx) {
  11163. ctx && ctx.stroke();
  11164. this.toStatic();
  11165. },
  11166. /**
  11167. * 必须在其它绘制命令前调用
  11168. * Must be invoked before all other path drawing methods
  11169. * @return {module:zrender/core/PathProxy}
  11170. */
  11171. setLineDash: function (lineDash) {
  11172. if (lineDash instanceof Array) {
  11173. this._lineDash = lineDash;
  11174. this._dashIdx = 0;
  11175. var lineDashSum = 0;
  11176. for (var i = 0; i < lineDash.length; i++) {
  11177. lineDashSum += lineDash[i];
  11178. }
  11179. this._dashSum = lineDashSum;
  11180. }
  11181. return this;
  11182. },
  11183. /**
  11184. * 必须在其它绘制命令前调用
  11185. * Must be invoked before all other path drawing methods
  11186. * @return {module:zrender/core/PathProxy}
  11187. */
  11188. setLineDashOffset: function (offset) {
  11189. this._dashOffset = offset;
  11190. return this;
  11191. },
  11192. /**
  11193. *
  11194. * @return {boolean}
  11195. */
  11196. len: function () {
  11197. return this._len;
  11198. },
  11199. /**
  11200. * 直接设置 Path 数据
  11201. */
  11202. setData: function (data) {
  11203. var len$$1 = data.length;
  11204. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11205. this.data = new Float32Array(len$$1);
  11206. }
  11207. for (var i = 0; i < len$$1; i++) {
  11208. this.data[i] = data[i];
  11209. }
  11210. this._len = len$$1;
  11211. },
  11212. /**
  11213. * 添加子路径
  11214. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11215. */
  11216. appendPath: function (path) {
  11217. if (!(path instanceof Array)) {
  11218. path = [path];
  11219. }
  11220. var len$$1 = path.length;
  11221. var appendSize = 0;
  11222. var offset = this._len;
  11223. for (var i = 0; i < len$$1; i++) {
  11224. appendSize += path[i].len();
  11225. }
  11226. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11227. this.data = new Float32Array(offset + appendSize);
  11228. }
  11229. for (var i = 0; i < len$$1; i++) {
  11230. var appendPathData = path[i].data;
  11231. for (var k = 0; k < appendPathData.length; k++) {
  11232. this.data[offset++] = appendPathData[k];
  11233. }
  11234. }
  11235. this._len = offset;
  11236. },
  11237. /**
  11238. * 填充 Path 数据。
  11239. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11240. */
  11241. addData: function (cmd) {
  11242. if (!this._saveData) {
  11243. return;
  11244. }
  11245. var data = this.data;
  11246. if (this._len + arguments.length > data.length) {
  11247. // 因为之前的数组已经转换成静态的 Float32Array
  11248. // 所以不够用时需要扩展一个新的动态数组
  11249. this._expandData();
  11250. data = this.data;
  11251. }
  11252. for (var i = 0; i < arguments.length; i++) {
  11253. data[this._len++] = arguments[i];
  11254. }
  11255. this._prevCmd = cmd;
  11256. },
  11257. _expandData: function () {
  11258. // Only if data is Float32Array
  11259. if (!(this.data instanceof Array)) {
  11260. var newData = [];
  11261. for (var i = 0; i < this._len; i++) {
  11262. newData[i] = this.data[i];
  11263. }
  11264. this.data = newData;
  11265. }
  11266. },
  11267. /**
  11268. * If needs js implemented dashed line
  11269. * @return {boolean}
  11270. * @private
  11271. */
  11272. _needsDash: function () {
  11273. return this._lineDash;
  11274. },
  11275. _dashedLineTo: function (x1, y1) {
  11276. var dashSum = this._dashSum;
  11277. var offset = this._dashOffset;
  11278. var lineDash = this._lineDash;
  11279. var ctx = this._ctx;
  11280. var x0 = this._xi;
  11281. var y0 = this._yi;
  11282. var dx = x1 - x0;
  11283. var dy = y1 - y0;
  11284. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11285. var x = x0;
  11286. var y = y0;
  11287. var dash;
  11288. var nDash = lineDash.length;
  11289. var idx;
  11290. dx /= dist$$1;
  11291. dy /= dist$$1;
  11292. if (offset < 0) {
  11293. // Convert to positive offset
  11294. offset = dashSum + offset;
  11295. }
  11296. offset %= dashSum;
  11297. x -= offset * dx;
  11298. y -= offset * dy;
  11299. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11300. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11301. idx = this._dashIdx;
  11302. dash = lineDash[idx];
  11303. x += dx * dash;
  11304. y += dy * dash;
  11305. this._dashIdx = (idx + 1) % nDash;
  11306. // Skip positive offset
  11307. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11308. continue;
  11309. }
  11310. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11311. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11312. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11313. );
  11314. }
  11315. // Offset for next lineTo
  11316. dx = x - x1;
  11317. dy = y - y1;
  11318. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11319. },
  11320. // Not accurate dashed line to
  11321. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11322. var dashSum = this._dashSum;
  11323. var offset = this._dashOffset;
  11324. var lineDash = this._lineDash;
  11325. var ctx = this._ctx;
  11326. var x0 = this._xi;
  11327. var y0 = this._yi;
  11328. var t;
  11329. var dx;
  11330. var dy;
  11331. var cubicAt$$1 = cubicAt;
  11332. var bezierLen = 0;
  11333. var idx = this._dashIdx;
  11334. var nDash = lineDash.length;
  11335. var x;
  11336. var y;
  11337. var tmpLen = 0;
  11338. if (offset < 0) {
  11339. // Convert to positive offset
  11340. offset = dashSum + offset;
  11341. }
  11342. offset %= dashSum;
  11343. // Bezier approx length
  11344. for (t = 0; t < 1; t += 0.1) {
  11345. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11346. - cubicAt$$1(x0, x1, x2, x3, t);
  11347. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11348. - cubicAt$$1(y0, y1, y2, y3, t);
  11349. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11350. }
  11351. // Find idx after add offset
  11352. for (; idx < nDash; idx++) {
  11353. tmpLen += lineDash[idx];
  11354. if (tmpLen > offset) {
  11355. break;
  11356. }
  11357. }
  11358. t = (tmpLen - offset) / bezierLen;
  11359. while (t <= 1) {
  11360. x = cubicAt$$1(x0, x1, x2, x3, t);
  11361. y = cubicAt$$1(y0, y1, y2, y3, t);
  11362. // Use line to approximate dashed bezier
  11363. // Bad result if dash is long
  11364. idx % 2 ? ctx.moveTo(x, y)
  11365. : ctx.lineTo(x, y);
  11366. t += lineDash[idx] / bezierLen;
  11367. idx = (idx + 1) % nDash;
  11368. }
  11369. // Finish the last segment and calculate the new offset
  11370. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11371. dx = x3 - x;
  11372. dy = y3 - y;
  11373. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11374. },
  11375. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11376. // Convert quadratic to cubic using degree elevation
  11377. var x3 = x2;
  11378. var y3 = y2;
  11379. x2 = (x2 + 2 * x1) / 3;
  11380. y2 = (y2 + 2 * y1) / 3;
  11381. x1 = (this._xi + 2 * x1) / 3;
  11382. y1 = (this._yi + 2 * y1) / 3;
  11383. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11384. },
  11385. /**
  11386. * 转成静态的 Float32Array 减少堆内存占用
  11387. * Convert dynamic array to static Float32Array
  11388. */
  11389. toStatic: function () {
  11390. var data = this.data;
  11391. if (data instanceof Array) {
  11392. data.length = this._len;
  11393. if (hasTypedArray) {
  11394. this.data = new Float32Array(data);
  11395. }
  11396. }
  11397. },
  11398. /**
  11399. * @return {module:zrender/core/BoundingRect}
  11400. */
  11401. getBoundingRect: function () {
  11402. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11403. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11404. var data = this.data;
  11405. var xi = 0;
  11406. var yi = 0;
  11407. var x0 = 0;
  11408. var y0 = 0;
  11409. for (var i = 0; i < data.length;) {
  11410. var cmd = data[i++];
  11411. if (i == 1) {
  11412. // 如果第一个命令是 L, C, Q
  11413. // 则 previous point 同绘制命令的第一个 point
  11414. //
  11415. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11416. xi = data[i];
  11417. yi = data[i + 1];
  11418. x0 = xi;
  11419. y0 = yi;
  11420. }
  11421. switch (cmd) {
  11422. case CMD.M:
  11423. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11424. // 在 closePath 的时候使用
  11425. x0 = data[i++];
  11426. y0 = data[i++];
  11427. xi = x0;
  11428. yi = y0;
  11429. min2[0] = x0;
  11430. min2[1] = y0;
  11431. max2[0] = x0;
  11432. max2[1] = y0;
  11433. break;
  11434. case CMD.L:
  11435. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11436. xi = data[i++];
  11437. yi = data[i++];
  11438. break;
  11439. case CMD.C:
  11440. fromCubic(
  11441. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11442. min2, max2
  11443. );
  11444. xi = data[i++];
  11445. yi = data[i++];
  11446. break;
  11447. case CMD.Q:
  11448. fromQuadratic(
  11449. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11450. min2, max2
  11451. );
  11452. xi = data[i++];
  11453. yi = data[i++];
  11454. break;
  11455. case CMD.A:
  11456. // TODO Arc 判断的开销比较大
  11457. var cx = data[i++];
  11458. var cy = data[i++];
  11459. var rx = data[i++];
  11460. var ry = data[i++];
  11461. var startAngle = data[i++];
  11462. var endAngle = data[i++] + startAngle;
  11463. // TODO Arc 旋转
  11464. var psi = data[i++];
  11465. var anticlockwise = 1 - data[i++];
  11466. if (i == 1) {
  11467. // 直接使用 arc 命令
  11468. // 第一个命令起点还未定义
  11469. x0 = mathCos$1(startAngle) * rx + cx;
  11470. y0 = mathSin$1(startAngle) * ry + cy;
  11471. }
  11472. fromArc(
  11473. cx, cy, rx, ry, startAngle, endAngle,
  11474. anticlockwise, min2, max2
  11475. );
  11476. xi = mathCos$1(endAngle) * rx + cx;
  11477. yi = mathSin$1(endAngle) * ry + cy;
  11478. break;
  11479. case CMD.R:
  11480. x0 = xi = data[i++];
  11481. y0 = yi = data[i++];
  11482. var width = data[i++];
  11483. var height = data[i++];
  11484. // Use fromLine
  11485. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11486. break;
  11487. case CMD.Z:
  11488. xi = x0;
  11489. yi = y0;
  11490. break;
  11491. }
  11492. // Union
  11493. min(min$1, min$1, min2);
  11494. max(max$1, max$1, max2);
  11495. }
  11496. // No data
  11497. if (i === 0) {
  11498. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11499. }
  11500. return new BoundingRect(
  11501. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11502. );
  11503. },
  11504. /**
  11505. * Rebuild path from current data
  11506. * Rebuild path will not consider javascript implemented line dash.
  11507. * @param {CanvasRenderingContext2D} ctx
  11508. */
  11509. rebuildPath: function (ctx) {
  11510. var d = this.data;
  11511. var x0, y0;
  11512. var xi, yi;
  11513. var x, y;
  11514. var ux = this._ux;
  11515. var uy = this._uy;
  11516. var len$$1 = this._len;
  11517. for (var i = 0; i < len$$1;) {
  11518. var cmd = d[i++];
  11519. if (i == 1) {
  11520. // 如果第一个命令是 L, C, Q
  11521. // 则 previous point 同绘制命令的第一个 point
  11522. //
  11523. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11524. xi = d[i];
  11525. yi = d[i + 1];
  11526. x0 = xi;
  11527. y0 = yi;
  11528. }
  11529. switch (cmd) {
  11530. case CMD.M:
  11531. x0 = xi = d[i++];
  11532. y0 = yi = d[i++];
  11533. ctx.moveTo(xi, yi);
  11534. break;
  11535. case CMD.L:
  11536. x = d[i++];
  11537. y = d[i++];
  11538. // Not draw too small seg between
  11539. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11540. ctx.lineTo(x, y);
  11541. xi = x;
  11542. yi = y;
  11543. }
  11544. break;
  11545. case CMD.C:
  11546. ctx.bezierCurveTo(
  11547. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11548. );
  11549. xi = d[i - 2];
  11550. yi = d[i - 1];
  11551. break;
  11552. case CMD.Q:
  11553. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11554. xi = d[i - 2];
  11555. yi = d[i - 1];
  11556. break;
  11557. case CMD.A:
  11558. var cx = d[i++];
  11559. var cy = d[i++];
  11560. var rx = d[i++];
  11561. var ry = d[i++];
  11562. var theta = d[i++];
  11563. var dTheta = d[i++];
  11564. var psi = d[i++];
  11565. var fs = d[i++];
  11566. var r = (rx > ry) ? rx : ry;
  11567. var scaleX = (rx > ry) ? 1 : rx / ry;
  11568. var scaleY = (rx > ry) ? ry / rx : 1;
  11569. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11570. var endAngle = theta + dTheta;
  11571. if (isEllipse) {
  11572. ctx.translate(cx, cy);
  11573. ctx.rotate(psi);
  11574. ctx.scale(scaleX, scaleY);
  11575. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11576. ctx.scale(1 / scaleX, 1 / scaleY);
  11577. ctx.rotate(-psi);
  11578. ctx.translate(-cx, -cy);
  11579. }
  11580. else {
  11581. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11582. }
  11583. if (i == 1) {
  11584. // 直接使用 arc 命令
  11585. // 第一个命令起点还未定义
  11586. x0 = mathCos$1(theta) * rx + cx;
  11587. y0 = mathSin$1(theta) * ry + cy;
  11588. }
  11589. xi = mathCos$1(endAngle) * rx + cx;
  11590. yi = mathSin$1(endAngle) * ry + cy;
  11591. break;
  11592. case CMD.R:
  11593. x0 = xi = d[i];
  11594. y0 = yi = d[i + 1];
  11595. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11596. break;
  11597. case CMD.Z:
  11598. ctx.closePath();
  11599. xi = x0;
  11600. yi = y0;
  11601. }
  11602. }
  11603. }
  11604. };
  11605. PathProxy.CMD = CMD;
  11606. /**
  11607. * 线段包含判断
  11608. * @param {number} x0
  11609. * @param {number} y0
  11610. * @param {number} x1
  11611. * @param {number} y1
  11612. * @param {number} lineWidth
  11613. * @param {number} x
  11614. * @param {number} y
  11615. * @return {boolean}
  11616. */
  11617. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11618. if (lineWidth === 0) {
  11619. return false;
  11620. }
  11621. var _l = lineWidth;
  11622. var _a = 0;
  11623. var _b = x0;
  11624. // Quick reject
  11625. if (
  11626. (y > y0 + _l && y > y1 + _l)
  11627. || (y < y0 - _l && y < y1 - _l)
  11628. || (x > x0 + _l && x > x1 + _l)
  11629. || (x < x0 - _l && x < x1 - _l)
  11630. ) {
  11631. return false;
  11632. }
  11633. if (x0 !== x1) {
  11634. _a = (y0 - y1) / (x0 - x1);
  11635. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11636. }
  11637. else {
  11638. return Math.abs(x - x0) <= _l / 2;
  11639. }
  11640. var tmp = _a * x - y + _b;
  11641. var _s = tmp * tmp / (_a * _a + 1);
  11642. return _s <= _l / 2 * _l / 2;
  11643. }
  11644. /**
  11645. * 三次贝塞尔曲线描边包含判断
  11646. * @param {number} x0
  11647. * @param {number} y0
  11648. * @param {number} x1
  11649. * @param {number} y1
  11650. * @param {number} x2
  11651. * @param {number} y2
  11652. * @param {number} x3
  11653. * @param {number} y3
  11654. * @param {number} lineWidth
  11655. * @param {number} x
  11656. * @param {number} y
  11657. * @return {boolean}
  11658. */
  11659. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11660. if (lineWidth === 0) {
  11661. return false;
  11662. }
  11663. var _l = lineWidth;
  11664. // Quick reject
  11665. if (
  11666. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11667. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11668. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11669. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11670. ) {
  11671. return false;
  11672. }
  11673. var d = cubicProjectPoint(
  11674. x0, y0, x1, y1, x2, y2, x3, y3,
  11675. x, y, null
  11676. );
  11677. return d <= _l / 2;
  11678. }
  11679. /**
  11680. * 二次贝塞尔曲线描边包含判断
  11681. * @param {number} x0
  11682. * @param {number} y0
  11683. * @param {number} x1
  11684. * @param {number} y1
  11685. * @param {number} x2
  11686. * @param {number} y2
  11687. * @param {number} lineWidth
  11688. * @param {number} x
  11689. * @param {number} y
  11690. * @return {boolean}
  11691. */
  11692. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11693. if (lineWidth === 0) {
  11694. return false;
  11695. }
  11696. var _l = lineWidth;
  11697. // Quick reject
  11698. if (
  11699. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11700. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11701. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11702. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11703. ) {
  11704. return false;
  11705. }
  11706. var d = quadraticProjectPoint(
  11707. x0, y0, x1, y1, x2, y2,
  11708. x, y, null
  11709. );
  11710. return d <= _l / 2;
  11711. }
  11712. var PI2$3 = Math.PI * 2;
  11713. function normalizeRadian(angle) {
  11714. angle %= PI2$3;
  11715. if (angle < 0) {
  11716. angle += PI2$3;
  11717. }
  11718. return angle;
  11719. }
  11720. var PI2$2 = Math.PI * 2;
  11721. /**
  11722. * 圆弧描边包含判断
  11723. * @param {number} cx
  11724. * @param {number} cy
  11725. * @param {number} r
  11726. * @param {number} startAngle
  11727. * @param {number} endAngle
  11728. * @param {boolean} anticlockwise
  11729. * @param {number} lineWidth
  11730. * @param {number} x
  11731. * @param {number} y
  11732. * @return {Boolean}
  11733. */
  11734. function containStroke$4(
  11735. cx, cy, r, startAngle, endAngle, anticlockwise,
  11736. lineWidth, x, y
  11737. ) {
  11738. if (lineWidth === 0) {
  11739. return false;
  11740. }
  11741. var _l = lineWidth;
  11742. x -= cx;
  11743. y -= cy;
  11744. var d = Math.sqrt(x * x + y * y);
  11745. if ((d - _l > r) || (d + _l < r)) {
  11746. return false;
  11747. }
  11748. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11749. // Is a circle
  11750. return true;
  11751. }
  11752. if (anticlockwise) {
  11753. var tmp = startAngle;
  11754. startAngle = normalizeRadian(endAngle);
  11755. endAngle = normalizeRadian(tmp);
  11756. } else {
  11757. startAngle = normalizeRadian(startAngle);
  11758. endAngle = normalizeRadian(endAngle);
  11759. }
  11760. if (startAngle > endAngle) {
  11761. endAngle += PI2$2;
  11762. }
  11763. var angle = Math.atan2(y, x);
  11764. if (angle < 0) {
  11765. angle += PI2$2;
  11766. }
  11767. return (angle >= startAngle && angle <= endAngle)
  11768. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11769. }
  11770. function windingLine(x0, y0, x1, y1, x, y) {
  11771. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11772. return 0;
  11773. }
  11774. // Ignore horizontal line
  11775. if (y1 === y0) {
  11776. return 0;
  11777. }
  11778. var dir = y1 < y0 ? 1 : -1;
  11779. var t = (y - y0) / (y1 - y0);
  11780. // Avoid winding error when intersection point is the connect point of two line of polygon
  11781. if (t === 1 || t === 0) {
  11782. dir = y1 < y0 ? 0.5 : -0.5;
  11783. }
  11784. var x_ = t * (x1 - x0) + x0;
  11785. return x_ > x ? dir : 0;
  11786. }
  11787. var CMD$1 = PathProxy.CMD;
  11788. var PI2$1 = Math.PI * 2;
  11789. var EPSILON$2 = 1e-4;
  11790. function isAroundEqual(a, b) {
  11791. return Math.abs(a - b) < EPSILON$2;
  11792. }
  11793. // 临时数组
  11794. var roots = [-1, -1, -1];
  11795. var extrema = [-1, -1];
  11796. function swapExtrema() {
  11797. var tmp = extrema[0];
  11798. extrema[0] = extrema[1];
  11799. extrema[1] = tmp;
  11800. }
  11801. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11802. // Quick reject
  11803. if (
  11804. (y > y0 && y > y1 && y > y2 && y > y3)
  11805. || (y < y0 && y < y1 && y < y2 && y < y3)
  11806. ) {
  11807. return 0;
  11808. }
  11809. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11810. if (nRoots === 0) {
  11811. return 0;
  11812. }
  11813. else {
  11814. var w = 0;
  11815. var nExtrema = -1;
  11816. var y0_, y1_;
  11817. for (var i = 0; i < nRoots; i++) {
  11818. var t = roots[i];
  11819. // Avoid winding error when intersection point is the connect point of two line of polygon
  11820. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11821. var x_ = cubicAt(x0, x1, x2, x3, t);
  11822. if (x_ < x) { // Quick reject
  11823. continue;
  11824. }
  11825. if (nExtrema < 0) {
  11826. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11827. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11828. swapExtrema();
  11829. }
  11830. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11831. if (nExtrema > 1) {
  11832. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11833. }
  11834. }
  11835. if (nExtrema == 2) {
  11836. // 分成三段单调函数
  11837. if (t < extrema[0]) {
  11838. w += y0_ < y0 ? unit : -unit;
  11839. }
  11840. else if (t < extrema[1]) {
  11841. w += y1_ < y0_ ? unit : -unit;
  11842. }
  11843. else {
  11844. w += y3 < y1_ ? unit : -unit;
  11845. }
  11846. }
  11847. else {
  11848. // 分成两段单调函数
  11849. if (t < extrema[0]) {
  11850. w += y0_ < y0 ? unit : -unit;
  11851. }
  11852. else {
  11853. w += y3 < y0_ ? unit : -unit;
  11854. }
  11855. }
  11856. }
  11857. return w;
  11858. }
  11859. }
  11860. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11861. // Quick reject
  11862. if (
  11863. (y > y0 && y > y1 && y > y2)
  11864. || (y < y0 && y < y1 && y < y2)
  11865. ) {
  11866. return 0;
  11867. }
  11868. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11869. if (nRoots === 0) {
  11870. return 0;
  11871. }
  11872. else {
  11873. var t = quadraticExtremum(y0, y1, y2);
  11874. if (t >= 0 && t <= 1) {
  11875. var w = 0;
  11876. var y_ = quadraticAt(y0, y1, y2, t);
  11877. for (var i = 0; i < nRoots; i++) {
  11878. // Remove one endpoint.
  11879. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11880. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11881. if (x_ < x) { // Quick reject
  11882. continue;
  11883. }
  11884. if (roots[i] < t) {
  11885. w += y_ < y0 ? unit : -unit;
  11886. }
  11887. else {
  11888. w += y2 < y_ ? unit : -unit;
  11889. }
  11890. }
  11891. return w;
  11892. }
  11893. else {
  11894. // Remove one endpoint.
  11895. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11896. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11897. if (x_ < x) { // Quick reject
  11898. return 0;
  11899. }
  11900. return y2 < y0 ? unit : -unit;
  11901. }
  11902. }
  11903. }
  11904. // TODO
  11905. // Arc 旋转
  11906. function windingArc(
  11907. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11908. ) {
  11909. y -= cy;
  11910. if (y > r || y < -r) {
  11911. return 0;
  11912. }
  11913. var tmp = Math.sqrt(r * r - y * y);
  11914. roots[0] = -tmp;
  11915. roots[1] = tmp;
  11916. var diff = Math.abs(startAngle - endAngle);
  11917. if (diff < 1e-4) {
  11918. return 0;
  11919. }
  11920. if (diff % PI2$1 < 1e-4) {
  11921. // Is a circle
  11922. startAngle = 0;
  11923. endAngle = PI2$1;
  11924. var dir = anticlockwise ? 1 : -1;
  11925. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11926. return dir;
  11927. } else {
  11928. return 0;
  11929. }
  11930. }
  11931. if (anticlockwise) {
  11932. var tmp = startAngle;
  11933. startAngle = normalizeRadian(endAngle);
  11934. endAngle = normalizeRadian(tmp);
  11935. }
  11936. else {
  11937. startAngle = normalizeRadian(startAngle);
  11938. endAngle = normalizeRadian(endAngle);
  11939. }
  11940. if (startAngle > endAngle) {
  11941. endAngle += PI2$1;
  11942. }
  11943. var w = 0;
  11944. for (var i = 0; i < 2; i++) {
  11945. var x_ = roots[i];
  11946. if (x_ + cx > x) {
  11947. var angle = Math.atan2(y, x_);
  11948. var dir = anticlockwise ? 1 : -1;
  11949. if (angle < 0) {
  11950. angle = PI2$1 + angle;
  11951. }
  11952. if (
  11953. (angle >= startAngle && angle <= endAngle)
  11954. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11955. ) {
  11956. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11957. dir = -dir;
  11958. }
  11959. w += dir;
  11960. }
  11961. }
  11962. }
  11963. return w;
  11964. }
  11965. function containPath(data, lineWidth, isStroke, x, y) {
  11966. var w = 0;
  11967. var xi = 0;
  11968. var yi = 0;
  11969. var x0 = 0;
  11970. var y0 = 0;
  11971. for (var i = 0; i < data.length;) {
  11972. var cmd = data[i++];
  11973. // Begin a new subpath
  11974. if (cmd === CMD$1.M && i > 1) {
  11975. // Close previous subpath
  11976. if (!isStroke) {
  11977. w += windingLine(xi, yi, x0, y0, x, y);
  11978. }
  11979. // 如果被任何一个 subpath 包含
  11980. // if (w !== 0) {
  11981. // return true;
  11982. // }
  11983. }
  11984. if (i == 1) {
  11985. // 如果第一个命令是 L, C, Q
  11986. // 则 previous point 同绘制命令的第一个 point
  11987. //
  11988. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11989. xi = data[i];
  11990. yi = data[i + 1];
  11991. x0 = xi;
  11992. y0 = yi;
  11993. }
  11994. switch (cmd) {
  11995. case CMD$1.M:
  11996. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11997. // 在 closePath 的时候使用
  11998. x0 = data[i++];
  11999. y0 = data[i++];
  12000. xi = x0;
  12001. yi = y0;
  12002. break;
  12003. case CMD$1.L:
  12004. if (isStroke) {
  12005. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12006. return true;
  12007. }
  12008. }
  12009. else {
  12010. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12011. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12012. }
  12013. xi = data[i++];
  12014. yi = data[i++];
  12015. break;
  12016. case CMD$1.C:
  12017. if (isStroke) {
  12018. if (containStroke$2(xi, yi,
  12019. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12020. lineWidth, x, y
  12021. )) {
  12022. return true;
  12023. }
  12024. }
  12025. else {
  12026. w += windingCubic(
  12027. xi, yi,
  12028. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12029. x, y
  12030. ) || 0;
  12031. }
  12032. xi = data[i++];
  12033. yi = data[i++];
  12034. break;
  12035. case CMD$1.Q:
  12036. if (isStroke) {
  12037. if (containStroke$3(xi, yi,
  12038. data[i++], data[i++], data[i], data[i + 1],
  12039. lineWidth, x, y
  12040. )) {
  12041. return true;
  12042. }
  12043. }
  12044. else {
  12045. w += windingQuadratic(
  12046. xi, yi,
  12047. data[i++], data[i++], data[i], data[i + 1],
  12048. x, y
  12049. ) || 0;
  12050. }
  12051. xi = data[i++];
  12052. yi = data[i++];
  12053. break;
  12054. case CMD$1.A:
  12055. // TODO Arc 判断的开销比较大
  12056. var cx = data[i++];
  12057. var cy = data[i++];
  12058. var rx = data[i++];
  12059. var ry = data[i++];
  12060. var theta = data[i++];
  12061. var dTheta = data[i++];
  12062. // TODO Arc 旋转
  12063. var psi = data[i++];
  12064. var anticlockwise = 1 - data[i++];
  12065. var x1 = Math.cos(theta) * rx + cx;
  12066. var y1 = Math.sin(theta) * ry + cy;
  12067. // 不是直接使用 arc 命令
  12068. if (i > 1) {
  12069. w += windingLine(xi, yi, x1, y1, x, y);
  12070. }
  12071. else {
  12072. // 第一个命令起点还未定义
  12073. x0 = x1;
  12074. y0 = y1;
  12075. }
  12076. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12077. var _x = (x - cx) * ry / rx + cx;
  12078. if (isStroke) {
  12079. if (containStroke$4(
  12080. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12081. lineWidth, _x, y
  12082. )) {
  12083. return true;
  12084. }
  12085. }
  12086. else {
  12087. w += windingArc(
  12088. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12089. _x, y
  12090. );
  12091. }
  12092. xi = Math.cos(theta + dTheta) * rx + cx;
  12093. yi = Math.sin(theta + dTheta) * ry + cy;
  12094. break;
  12095. case CMD$1.R:
  12096. x0 = xi = data[i++];
  12097. y0 = yi = data[i++];
  12098. var width = data[i++];
  12099. var height = data[i++];
  12100. var x1 = x0 + width;
  12101. var y1 = y0 + height;
  12102. if (isStroke) {
  12103. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12104. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12105. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12106. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12107. ) {
  12108. return true;
  12109. }
  12110. }
  12111. else {
  12112. // FIXME Clockwise ?
  12113. w += windingLine(x1, y0, x1, y1, x, y);
  12114. w += windingLine(x0, y1, x0, y0, x, y);
  12115. }
  12116. break;
  12117. case CMD$1.Z:
  12118. if (isStroke) {
  12119. if (containStroke$1(
  12120. xi, yi, x0, y0, lineWidth, x, y
  12121. )) {
  12122. return true;
  12123. }
  12124. }
  12125. else {
  12126. // Close a subpath
  12127. w += windingLine(xi, yi, x0, y0, x, y);
  12128. // 如果被任何一个 subpath 包含
  12129. // FIXME subpaths may overlap
  12130. // if (w !== 0) {
  12131. // return true;
  12132. // }
  12133. }
  12134. xi = x0;
  12135. yi = y0;
  12136. break;
  12137. }
  12138. }
  12139. if (!isStroke && !isAroundEqual(yi, y0)) {
  12140. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12141. }
  12142. return w !== 0;
  12143. }
  12144. function contain(pathData, x, y) {
  12145. return containPath(pathData, 0, false, x, y);
  12146. }
  12147. function containStroke(pathData, lineWidth, x, y) {
  12148. return containPath(pathData, lineWidth, true, x, y);
  12149. }
  12150. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12151. var abs = Math.abs;
  12152. var pathProxyForDraw = new PathProxy(true);
  12153. /**
  12154. * @alias module:zrender/graphic/Path
  12155. * @extends module:zrender/graphic/Displayable
  12156. * @constructor
  12157. * @param {Object} opts
  12158. */
  12159. function Path(opts) {
  12160. Displayable.call(this, opts);
  12161. /**
  12162. * @type {module:zrender/core/PathProxy}
  12163. * @readOnly
  12164. */
  12165. this.path = null;
  12166. }
  12167. Path.prototype = {
  12168. constructor: Path,
  12169. type: 'path',
  12170. __dirtyPath: true,
  12171. strokeContainThreshold: 5,
  12172. brush: function (ctx, prevEl) {
  12173. var style = this.style;
  12174. var path = this.path || pathProxyForDraw;
  12175. var hasStroke = style.hasStroke();
  12176. var hasFill = style.hasFill();
  12177. var fill = style.fill;
  12178. var stroke = style.stroke;
  12179. var hasFillGradient = hasFill && !!(fill.colorStops);
  12180. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12181. var hasFillPattern = hasFill && !!(fill.image);
  12182. var hasStrokePattern = hasStroke && !!(stroke.image);
  12183. style.bind(ctx, this, prevEl);
  12184. this.setTransform(ctx);
  12185. if (this.__dirty) {
  12186. var rect;
  12187. // Update gradient because bounding rect may changed
  12188. if (hasFillGradient) {
  12189. rect = rect || this.getBoundingRect();
  12190. this._fillGradient = style.getGradient(ctx, fill, rect);
  12191. }
  12192. if (hasStrokeGradient) {
  12193. rect = rect || this.getBoundingRect();
  12194. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12195. }
  12196. }
  12197. // Use the gradient or pattern
  12198. if (hasFillGradient) {
  12199. // PENDING If may have affect the state
  12200. ctx.fillStyle = this._fillGradient;
  12201. }
  12202. else if (hasFillPattern) {
  12203. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12204. }
  12205. if (hasStrokeGradient) {
  12206. ctx.strokeStyle = this._strokeGradient;
  12207. }
  12208. else if (hasStrokePattern) {
  12209. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12210. }
  12211. var lineDash = style.lineDash;
  12212. var lineDashOffset = style.lineDashOffset;
  12213. var ctxLineDash = !!ctx.setLineDash;
  12214. // Update path sx, sy
  12215. var scale = this.getGlobalScale();
  12216. path.setScale(scale[0], scale[1]);
  12217. // Proxy context
  12218. // Rebuild path in following 2 cases
  12219. // 1. Path is dirty
  12220. // 2. Path needs javascript implemented lineDash stroking.
  12221. // In this case, lineDash information will not be saved in PathProxy
  12222. if (this.__dirtyPath
  12223. || (lineDash && !ctxLineDash && hasStroke)
  12224. ) {
  12225. path.beginPath(ctx);
  12226. // Setting line dash before build path
  12227. if (lineDash && !ctxLineDash) {
  12228. path.setLineDash(lineDash);
  12229. path.setLineDashOffset(lineDashOffset);
  12230. }
  12231. this.buildPath(path, this.shape, false);
  12232. // Clear path dirty flag
  12233. if (this.path) {
  12234. this.__dirtyPath = false;
  12235. }
  12236. }
  12237. else {
  12238. // Replay path building
  12239. ctx.beginPath();
  12240. this.path.rebuildPath(ctx);
  12241. }
  12242. hasFill && path.fill(ctx);
  12243. if (lineDash && ctxLineDash) {
  12244. ctx.setLineDash(lineDash);
  12245. ctx.lineDashOffset = lineDashOffset;
  12246. }
  12247. hasStroke && path.stroke(ctx);
  12248. if (lineDash && ctxLineDash) {
  12249. // PENDING
  12250. // Remove lineDash
  12251. ctx.setLineDash([]);
  12252. }
  12253. this.restoreTransform(ctx);
  12254. // Draw rect text
  12255. if (style.text != null) {
  12256. this.drawRectText(ctx, this.getBoundingRect());
  12257. }
  12258. },
  12259. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12260. // Like in circle
  12261. buildPath: function (ctx, shapeCfg, inBundle) {},
  12262. createPathProxy: function () {
  12263. this.path = new PathProxy();
  12264. },
  12265. getBoundingRect: function () {
  12266. var rect = this._rect;
  12267. var style = this.style;
  12268. var needsUpdateRect = !rect;
  12269. if (needsUpdateRect) {
  12270. var path = this.path;
  12271. if (!path) {
  12272. // Create path on demand.
  12273. path = this.path = new PathProxy();
  12274. }
  12275. if (this.__dirtyPath) {
  12276. path.beginPath();
  12277. this.buildPath(path, this.shape, false);
  12278. }
  12279. rect = path.getBoundingRect();
  12280. }
  12281. this._rect = rect;
  12282. if (style.hasStroke()) {
  12283. // Needs update rect with stroke lineWidth when
  12284. // 1. Element changes scale or lineWidth
  12285. // 2. Shape is changed
  12286. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12287. if (this.__dirty || needsUpdateRect) {
  12288. rectWithStroke.copy(rect);
  12289. // FIXME Must after updateTransform
  12290. var w = style.lineWidth;
  12291. // PENDING, Min line width is needed when line is horizontal or vertical
  12292. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12293. // Only add extra hover lineWidth when there are no fill
  12294. if (!style.hasFill()) {
  12295. w = Math.max(w, this.strokeContainThreshold || 4);
  12296. }
  12297. // Consider line width
  12298. // Line scale can't be 0;
  12299. if (lineScale > 1e-10) {
  12300. rectWithStroke.width += w / lineScale;
  12301. rectWithStroke.height += w / lineScale;
  12302. rectWithStroke.x -= w / lineScale / 2;
  12303. rectWithStroke.y -= w / lineScale / 2;
  12304. }
  12305. }
  12306. // Return rect with stroke
  12307. return rectWithStroke;
  12308. }
  12309. return rect;
  12310. },
  12311. contain: function (x, y) {
  12312. var localPos = this.transformCoordToLocal(x, y);
  12313. var rect = this.getBoundingRect();
  12314. var style = this.style;
  12315. x = localPos[0];
  12316. y = localPos[1];
  12317. if (rect.contain(x, y)) {
  12318. var pathData = this.path.data;
  12319. if (style.hasStroke()) {
  12320. var lineWidth = style.lineWidth;
  12321. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12322. // Line scale can't be 0;
  12323. if (lineScale > 1e-10) {
  12324. // Only add extra hover lineWidth when there are no fill
  12325. if (!style.hasFill()) {
  12326. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12327. }
  12328. if (containStroke(
  12329. pathData, lineWidth / lineScale, x, y
  12330. )) {
  12331. return true;
  12332. }
  12333. }
  12334. }
  12335. if (style.hasFill()) {
  12336. return contain(pathData, x, y);
  12337. }
  12338. }
  12339. return false;
  12340. },
  12341. /**
  12342. * @param {boolean} dirtyPath
  12343. */
  12344. dirty: function (dirtyPath) {
  12345. if (dirtyPath == null) {
  12346. dirtyPath = true;
  12347. }
  12348. // Only mark dirty, not mark clean
  12349. if (dirtyPath) {
  12350. this.__dirtyPath = dirtyPath;
  12351. this._rect = null;
  12352. }
  12353. this.__dirty = true;
  12354. this.__zr && this.__zr.refresh();
  12355. // Used as a clipping path
  12356. if (this.__clipTarget) {
  12357. this.__clipTarget.dirty();
  12358. }
  12359. },
  12360. /**
  12361. * Alias for animate('shape')
  12362. * @param {boolean} loop
  12363. */
  12364. animateShape: function (loop) {
  12365. return this.animate('shape', loop);
  12366. },
  12367. // Overwrite attrKV
  12368. attrKV: function (key, value) {
  12369. // FIXME
  12370. if (key === 'shape') {
  12371. this.setShape(value);
  12372. this.__dirtyPath = true;
  12373. this._rect = null;
  12374. }
  12375. else {
  12376. Displayable.prototype.attrKV.call(this, key, value);
  12377. }
  12378. },
  12379. /**
  12380. * @param {Object|string} key
  12381. * @param {*} value
  12382. */
  12383. setShape: function (key, value) {
  12384. var shape = this.shape;
  12385. // Path from string may not have shape
  12386. if (shape) {
  12387. if (isObject(key)) {
  12388. for (var name in key) {
  12389. if (key.hasOwnProperty(name)) {
  12390. shape[name] = key[name];
  12391. }
  12392. }
  12393. }
  12394. else {
  12395. shape[key] = value;
  12396. }
  12397. this.dirty(true);
  12398. }
  12399. return this;
  12400. },
  12401. getLineScale: function () {
  12402. var m = this.transform;
  12403. // Get the line scale.
  12404. // Determinant of `m` means how much the area is enlarged by the
  12405. // transformation. So its square root can be used as a scale factor
  12406. // for width.
  12407. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12408. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12409. : 1;
  12410. }
  12411. };
  12412. /**
  12413. * 扩展一个 Path element, 比如星形,圆等。
  12414. * Extend a path element
  12415. * @param {Object} props
  12416. * @param {string} props.type Path type
  12417. * @param {Function} props.init Initialize
  12418. * @param {Function} props.buildPath Overwrite buildPath method
  12419. * @param {Object} [props.style] Extended default style config
  12420. * @param {Object} [props.shape] Extended default shape config
  12421. */
  12422. Path.extend = function (defaults$$1) {
  12423. var Sub = function (opts) {
  12424. Path.call(this, opts);
  12425. if (defaults$$1.style) {
  12426. // Extend default style
  12427. this.style.extendFrom(defaults$$1.style, false);
  12428. }
  12429. // Extend default shape
  12430. var defaultShape = defaults$$1.shape;
  12431. if (defaultShape) {
  12432. this.shape = this.shape || {};
  12433. var thisShape = this.shape;
  12434. for (var name in defaultShape) {
  12435. if (
  12436. ! thisShape.hasOwnProperty(name)
  12437. && defaultShape.hasOwnProperty(name)
  12438. ) {
  12439. thisShape[name] = defaultShape[name];
  12440. }
  12441. }
  12442. }
  12443. defaults$$1.init && defaults$$1.init.call(this, opts);
  12444. };
  12445. inherits(Sub, Path);
  12446. // FIXME 不能 extend position, rotation 等引用对象
  12447. for (var name in defaults$$1) {
  12448. // Extending prototype values and methods
  12449. if (name !== 'style' && name !== 'shape') {
  12450. Sub.prototype[name] = defaults$$1[name];
  12451. }
  12452. }
  12453. return Sub;
  12454. };
  12455. inherits(Path, Displayable);
  12456. var CMD$2 = PathProxy.CMD;
  12457. var points = [[], [], []];
  12458. var mathSqrt$3 = Math.sqrt;
  12459. var mathAtan2 = Math.atan2;
  12460. var transformPath = function (path, m) {
  12461. var data = path.data;
  12462. var cmd;
  12463. var nPoint;
  12464. var i;
  12465. var j;
  12466. var k;
  12467. var p;
  12468. var M = CMD$2.M;
  12469. var C = CMD$2.C;
  12470. var L = CMD$2.L;
  12471. var R = CMD$2.R;
  12472. var A = CMD$2.A;
  12473. var Q = CMD$2.Q;
  12474. for (i = 0, j = 0; i < data.length;) {
  12475. cmd = data[i++];
  12476. j = i;
  12477. nPoint = 0;
  12478. switch (cmd) {
  12479. case M:
  12480. nPoint = 1;
  12481. break;
  12482. case L:
  12483. nPoint = 1;
  12484. break;
  12485. case C:
  12486. nPoint = 3;
  12487. break;
  12488. case Q:
  12489. nPoint = 2;
  12490. break;
  12491. case A:
  12492. var x = m[4];
  12493. var y = m[5];
  12494. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12495. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12496. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12497. // cx
  12498. data[i] *= sx;
  12499. data[i++] += x;
  12500. // cy
  12501. data[i] *= sy;
  12502. data[i++] += y;
  12503. // Scale rx and ry
  12504. // FIXME Assume psi is 0 here
  12505. data[i++] *= sx;
  12506. data[i++] *= sy;
  12507. // Start angle
  12508. data[i++] += angle;
  12509. // end angle
  12510. data[i++] += angle;
  12511. // FIXME psi
  12512. i += 2;
  12513. j = i;
  12514. break;
  12515. case R:
  12516. // x0, y0
  12517. p[0] = data[i++];
  12518. p[1] = data[i++];
  12519. applyTransform(p, p, m);
  12520. data[j++] = p[0];
  12521. data[j++] = p[1];
  12522. // x1, y1
  12523. p[0] += data[i++];
  12524. p[1] += data[i++];
  12525. applyTransform(p, p, m);
  12526. data[j++] = p[0];
  12527. data[j++] = p[1];
  12528. }
  12529. for (k = 0; k < nPoint; k++) {
  12530. var p = points[k];
  12531. p[0] = data[i++];
  12532. p[1] = data[i++];
  12533. applyTransform(p, p, m);
  12534. // Write back
  12535. data[j++] = p[0];
  12536. data[j++] = p[1];
  12537. }
  12538. }
  12539. };
  12540. // command chars
  12541. var cc = [
  12542. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12543. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12544. ];
  12545. var mathSqrt = Math.sqrt;
  12546. var mathSin = Math.sin;
  12547. var mathCos = Math.cos;
  12548. var PI = Math.PI;
  12549. var vMag = function(v) {
  12550. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12551. };
  12552. var vRatio = function(u, v) {
  12553. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12554. };
  12555. var vAngle = function(u, v) {
  12556. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12557. * Math.acos(vRatio(u, v));
  12558. };
  12559. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12560. var psi = psiDeg * (PI / 180.0);
  12561. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12562. + mathSin(psi) * (y1 - y2) / 2.0;
  12563. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12564. + mathCos(psi) * (y1 - y2) / 2.0;
  12565. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12566. if (lambda > 1) {
  12567. rx *= mathSqrt(lambda);
  12568. ry *= mathSqrt(lambda);
  12569. }
  12570. var f = (fa === fs ? -1 : 1)
  12571. * mathSqrt((((rx * rx) * (ry * ry))
  12572. - ((rx * rx) * (yp * yp))
  12573. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12574. + (ry * ry) * (xp * xp))
  12575. ) || 0;
  12576. var cxp = f * rx * yp / ry;
  12577. var cyp = f * -ry * xp / rx;
  12578. var cx = (x1 + x2) / 2.0
  12579. + mathCos(psi) * cxp
  12580. - mathSin(psi) * cyp;
  12581. var cy = (y1 + y2) / 2.0
  12582. + mathSin(psi) * cxp
  12583. + mathCos(psi) * cyp;
  12584. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12585. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12586. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12587. var dTheta = vAngle(u, v);
  12588. if (vRatio(u, v) <= -1) {
  12589. dTheta = PI;
  12590. }
  12591. if (vRatio(u, v) >= 1) {
  12592. dTheta = 0;
  12593. }
  12594. if (fs === 0 && dTheta > 0) {
  12595. dTheta = dTheta - 2 * PI;
  12596. }
  12597. if (fs === 1 && dTheta < 0) {
  12598. dTheta = dTheta + 2 * PI;
  12599. }
  12600. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12601. }
  12602. function createPathProxyFromString(data) {
  12603. if (!data) {
  12604. return [];
  12605. }
  12606. // command string
  12607. var cs = data.replace(/-/g, ' -')
  12608. .replace(/ /g, ' ')
  12609. .replace(/ /g, ',')
  12610. .replace(/,,/g, ',');
  12611. var n;
  12612. // create pipes so that we can split the data
  12613. for (n = 0; n < cc.length; n++) {
  12614. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12615. }
  12616. // create array
  12617. var arr = cs.split('|');
  12618. // init context point
  12619. var cpx = 0;
  12620. var cpy = 0;
  12621. var path = new PathProxy();
  12622. var CMD = PathProxy.CMD;
  12623. var prevCmd;
  12624. for (n = 1; n < arr.length; n++) {
  12625. var str = arr[n];
  12626. var c = str.charAt(0);
  12627. var off = 0;
  12628. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12629. var cmd;
  12630. if (p.length > 0 && p[0] === '') {
  12631. p.shift();
  12632. }
  12633. for (var i = 0; i < p.length; i++) {
  12634. p[i] = parseFloat(p[i]);
  12635. }
  12636. while (off < p.length && !isNaN(p[off])) {
  12637. if (isNaN(p[0])) {
  12638. break;
  12639. }
  12640. var ctlPtx;
  12641. var ctlPty;
  12642. var rx;
  12643. var ry;
  12644. var psi;
  12645. var fa;
  12646. var fs;
  12647. var x1 = cpx;
  12648. var y1 = cpy;
  12649. // convert l, H, h, V, and v to L
  12650. switch (c) {
  12651. case 'l':
  12652. cpx += p[off++];
  12653. cpy += p[off++];
  12654. cmd = CMD.L;
  12655. path.addData(cmd, cpx, cpy);
  12656. break;
  12657. case 'L':
  12658. cpx = p[off++];
  12659. cpy = p[off++];
  12660. cmd = CMD.L;
  12661. path.addData(cmd, cpx, cpy);
  12662. break;
  12663. case 'm':
  12664. cpx += p[off++];
  12665. cpy += p[off++];
  12666. cmd = CMD.M;
  12667. path.addData(cmd, cpx, cpy);
  12668. c = 'l';
  12669. break;
  12670. case 'M':
  12671. cpx = p[off++];
  12672. cpy = p[off++];
  12673. cmd = CMD.M;
  12674. path.addData(cmd, cpx, cpy);
  12675. c = 'L';
  12676. break;
  12677. case 'h':
  12678. cpx += p[off++];
  12679. cmd = CMD.L;
  12680. path.addData(cmd, cpx, cpy);
  12681. break;
  12682. case 'H':
  12683. cpx = p[off++];
  12684. cmd = CMD.L;
  12685. path.addData(cmd, cpx, cpy);
  12686. break;
  12687. case 'v':
  12688. cpy += p[off++];
  12689. cmd = CMD.L;
  12690. path.addData(cmd, cpx, cpy);
  12691. break;
  12692. case 'V':
  12693. cpy = p[off++];
  12694. cmd = CMD.L;
  12695. path.addData(cmd, cpx, cpy);
  12696. break;
  12697. case 'C':
  12698. cmd = CMD.C;
  12699. path.addData(
  12700. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12701. );
  12702. cpx = p[off - 2];
  12703. cpy = p[off - 1];
  12704. break;
  12705. case 'c':
  12706. cmd = CMD.C;
  12707. path.addData(
  12708. cmd,
  12709. p[off++] + cpx, p[off++] + cpy,
  12710. p[off++] + cpx, p[off++] + cpy,
  12711. p[off++] + cpx, p[off++] + cpy
  12712. );
  12713. cpx += p[off - 2];
  12714. cpy += p[off - 1];
  12715. break;
  12716. case 'S':
  12717. ctlPtx = cpx;
  12718. ctlPty = cpy;
  12719. var len = path.len();
  12720. var pathData = path.data;
  12721. if (prevCmd === CMD.C) {
  12722. ctlPtx += cpx - pathData[len - 4];
  12723. ctlPty += cpy - pathData[len - 3];
  12724. }
  12725. cmd = CMD.C;
  12726. x1 = p[off++];
  12727. y1 = p[off++];
  12728. cpx = p[off++];
  12729. cpy = p[off++];
  12730. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12731. break;
  12732. case 's':
  12733. ctlPtx = cpx;
  12734. ctlPty = cpy;
  12735. var len = path.len();
  12736. var pathData = path.data;
  12737. if (prevCmd === CMD.C) {
  12738. ctlPtx += cpx - pathData[len - 4];
  12739. ctlPty += cpy - pathData[len - 3];
  12740. }
  12741. cmd = CMD.C;
  12742. x1 = cpx + p[off++];
  12743. y1 = cpy + p[off++];
  12744. cpx += p[off++];
  12745. cpy += p[off++];
  12746. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12747. break;
  12748. case 'Q':
  12749. x1 = p[off++];
  12750. y1 = p[off++];
  12751. cpx = p[off++];
  12752. cpy = p[off++];
  12753. cmd = CMD.Q;
  12754. path.addData(cmd, x1, y1, cpx, cpy);
  12755. break;
  12756. case 'q':
  12757. x1 = p[off++] + cpx;
  12758. y1 = p[off++] + cpy;
  12759. cpx += p[off++];
  12760. cpy += p[off++];
  12761. cmd = CMD.Q;
  12762. path.addData(cmd, x1, y1, cpx, cpy);
  12763. break;
  12764. case 'T':
  12765. ctlPtx = cpx;
  12766. ctlPty = cpy;
  12767. var len = path.len();
  12768. var pathData = path.data;
  12769. if (prevCmd === CMD.Q) {
  12770. ctlPtx += cpx - pathData[len - 4];
  12771. ctlPty += cpy - pathData[len - 3];
  12772. }
  12773. cpx = p[off++];
  12774. cpy = p[off++];
  12775. cmd = CMD.Q;
  12776. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12777. break;
  12778. case 't':
  12779. ctlPtx = cpx;
  12780. ctlPty = cpy;
  12781. var len = path.len();
  12782. var pathData = path.data;
  12783. if (prevCmd === CMD.Q) {
  12784. ctlPtx += cpx - pathData[len - 4];
  12785. ctlPty += cpy - pathData[len - 3];
  12786. }
  12787. cpx += p[off++];
  12788. cpy += p[off++];
  12789. cmd = CMD.Q;
  12790. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12791. break;
  12792. case 'A':
  12793. rx = p[off++];
  12794. ry = p[off++];
  12795. psi = p[off++];
  12796. fa = p[off++];
  12797. fs = p[off++];
  12798. x1 = cpx, y1 = cpy;
  12799. cpx = p[off++];
  12800. cpy = p[off++];
  12801. cmd = CMD.A;
  12802. processArc(
  12803. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12804. );
  12805. break;
  12806. case 'a':
  12807. rx = p[off++];
  12808. ry = p[off++];
  12809. psi = p[off++];
  12810. fa = p[off++];
  12811. fs = p[off++];
  12812. x1 = cpx, y1 = cpy;
  12813. cpx += p[off++];
  12814. cpy += p[off++];
  12815. cmd = CMD.A;
  12816. processArc(
  12817. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12818. );
  12819. break;
  12820. }
  12821. }
  12822. if (c === 'z' || c === 'Z') {
  12823. cmd = CMD.Z;
  12824. path.addData(cmd);
  12825. }
  12826. prevCmd = cmd;
  12827. }
  12828. path.toStatic();
  12829. return path;
  12830. }
  12831. // TODO Optimize double memory cost problem
  12832. function createPathOptions(str, opts) {
  12833. var pathProxy = createPathProxyFromString(str);
  12834. opts = opts || {};
  12835. opts.buildPath = function (path) {
  12836. if (path.setData) {
  12837. path.setData(pathProxy.data);
  12838. // Svg and vml renderer don't have context
  12839. var ctx = path.getContext();
  12840. if (ctx) {
  12841. path.rebuildPath(ctx);
  12842. }
  12843. }
  12844. else {
  12845. var ctx = path;
  12846. pathProxy.rebuildPath(ctx);
  12847. }
  12848. };
  12849. opts.applyTransform = function (m) {
  12850. transformPath(pathProxy, m);
  12851. this.dirty(true);
  12852. };
  12853. return opts;
  12854. }
  12855. /**
  12856. * Create a Path object from path string data
  12857. * http://www.w3.org/TR/SVG/paths.html#PathData
  12858. * @param {Object} opts Other options
  12859. */
  12860. function createFromString(str, opts) {
  12861. return new Path(createPathOptions(str, opts));
  12862. }
  12863. /**
  12864. * Create a Path class from path string data
  12865. * @param {string} str
  12866. * @param {Object} opts Other options
  12867. */
  12868. function extendFromString(str, opts) {
  12869. return Path.extend(createPathOptions(str, opts));
  12870. }
  12871. /**
  12872. * Merge multiple paths
  12873. */
  12874. // TODO Apply transform
  12875. // TODO stroke dash
  12876. // TODO Optimize double memory cost problem
  12877. function mergePath$1(pathEls, opts) {
  12878. var pathList = [];
  12879. var len = pathEls.length;
  12880. for (var i = 0; i < len; i++) {
  12881. var pathEl = pathEls[i];
  12882. if (!pathEl.path) {
  12883. pathEl.createPathProxy();
  12884. }
  12885. if (pathEl.__dirtyPath) {
  12886. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12887. }
  12888. pathList.push(pathEl.path);
  12889. }
  12890. var pathBundle = new Path(opts);
  12891. // Need path proxy.
  12892. pathBundle.createPathProxy();
  12893. pathBundle.buildPath = function (path) {
  12894. path.appendPath(pathList);
  12895. // Svg and vml renderer don't have context
  12896. var ctx = path.getContext();
  12897. if (ctx) {
  12898. path.rebuildPath(ctx);
  12899. }
  12900. };
  12901. return pathBundle;
  12902. }
  12903. /**
  12904. * @alias zrender/graphic/Text
  12905. * @extends module:zrender/graphic/Displayable
  12906. * @constructor
  12907. * @param {Object} opts
  12908. */
  12909. var Text = function (opts) { // jshint ignore:line
  12910. Displayable.call(this, opts);
  12911. };
  12912. Text.prototype = {
  12913. constructor: Text,
  12914. type: 'text',
  12915. brush: function (ctx, prevEl) {
  12916. var style = this.style;
  12917. // Optimize, avoid normalize every time.
  12918. this.__dirty && normalizeTextStyle(style, true);
  12919. // Use props with prefix 'text'.
  12920. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12921. style.shadowOffsetX = style.shadowOffsetY = null;
  12922. var text = style.text;
  12923. // Convert to string
  12924. text != null && (text += '');
  12925. // Always bind style
  12926. style.bind(ctx, this, prevEl);
  12927. if (!needDrawText(text, style)) {
  12928. return;
  12929. }
  12930. this.setTransform(ctx);
  12931. renderText(this, ctx, text, style);
  12932. this.restoreTransform(ctx);
  12933. },
  12934. getBoundingRect: function () {
  12935. var style = this.style;
  12936. // Optimize, avoid normalize every time.
  12937. this.__dirty && normalizeTextStyle(style, true);
  12938. if (!this._rect) {
  12939. var text = style.text;
  12940. text != null ? (text += '') : (text = '');
  12941. var rect = getBoundingRect(
  12942. style.text + '',
  12943. style.font,
  12944. style.textAlign,
  12945. style.textVerticalAlign,
  12946. style.textPadding,
  12947. style.rich
  12948. );
  12949. rect.x += style.x || 0;
  12950. rect.y += style.y || 0;
  12951. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12952. var w = style.textStrokeWidth;
  12953. rect.x -= w / 2;
  12954. rect.y -= w / 2;
  12955. rect.width += w;
  12956. rect.height += w;
  12957. }
  12958. this._rect = rect;
  12959. }
  12960. return this._rect;
  12961. }
  12962. };
  12963. inherits(Text, Displayable);
  12964. /**
  12965. * 圆形
  12966. * @module zrender/shape/Circle
  12967. */
  12968. var Circle = Path.extend({
  12969. type: 'circle',
  12970. shape: {
  12971. cx: 0,
  12972. cy: 0,
  12973. r: 0
  12974. },
  12975. buildPath : function (ctx, shape, inBundle) {
  12976. // Better stroking in ShapeBundle
  12977. // Always do it may have performence issue ( fill may be 2x more cost)
  12978. if (inBundle) {
  12979. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12980. }
  12981. // else {
  12982. // if (ctx.allocate && !ctx.data.length) {
  12983. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12984. // }
  12985. // }
  12986. // Better stroking in ShapeBundle
  12987. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12988. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12989. }
  12990. });
  12991. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12992. // where exception "unexpected call to method or property access"
  12993. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12994. // whose area size is zero is drawn and ctx.clip() is called and
  12995. // shadowBlur is set. See #4572, #3112, #5777.
  12996. // (e.g.,
  12997. // ctx.moveTo(10, 10);
  12998. // ctx.lineTo(20, 10);
  12999. // ctx.closePath();
  13000. // ctx.clip();
  13001. // ctx.shadowBlur = 10;
  13002. // ...
  13003. // ctx.fill();
  13004. // )
  13005. var shadowTemp = [
  13006. ['shadowBlur', 0],
  13007. ['shadowColor', '#000'],
  13008. ['shadowOffsetX', 0],
  13009. ['shadowOffsetY', 0]
  13010. ];
  13011. var fixClipWithShadow = function (orignalBrush) {
  13012. // version string can be: '11.0'
  13013. return (env$1.browser.ie && env$1.browser.version >= 11)
  13014. ? function () {
  13015. var clipPaths = this.__clipPaths;
  13016. var style = this.style;
  13017. var modified;
  13018. if (clipPaths) {
  13019. for (var i = 0; i < clipPaths.length; i++) {
  13020. var clipPath = clipPaths[i];
  13021. var shape = clipPath && clipPath.shape;
  13022. var type = clipPath && clipPath.type;
  13023. if (shape && (
  13024. (type === 'sector' && shape.startAngle === shape.endAngle)
  13025. || (type === 'rect' && (!shape.width || !shape.height))
  13026. )) {
  13027. for (var j = 0; j < shadowTemp.length; j++) {
  13028. // It is save to put shadowTemp static, because shadowTemp
  13029. // will be all modified each item brush called.
  13030. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13031. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13032. }
  13033. modified = true;
  13034. break;
  13035. }
  13036. }
  13037. }
  13038. orignalBrush.apply(this, arguments);
  13039. if (modified) {
  13040. for (var j = 0; j < shadowTemp.length; j++) {
  13041. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13042. }
  13043. }
  13044. }
  13045. : orignalBrush;
  13046. };
  13047. /**
  13048. * 扇形
  13049. * @module zrender/graphic/shape/Sector
  13050. */
  13051. var Sector = Path.extend({
  13052. type: 'sector',
  13053. shape: {
  13054. cx: 0,
  13055. cy: 0,
  13056. r0: 0,
  13057. r: 0,
  13058. startAngle: 0,
  13059. endAngle: Math.PI * 2,
  13060. clockwise: true
  13061. },
  13062. brush: fixClipWithShadow(Path.prototype.brush),
  13063. buildPath: function (ctx, shape) {
  13064. var x = shape.cx;
  13065. var y = shape.cy;
  13066. var r0 = Math.max(shape.r0 || 0, 0);
  13067. var r = Math.max(shape.r, 0);
  13068. var startAngle = shape.startAngle;
  13069. var endAngle = shape.endAngle;
  13070. var clockwise = shape.clockwise;
  13071. var unitX = Math.cos(startAngle);
  13072. var unitY = Math.sin(startAngle);
  13073. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13074. ctx.lineTo(unitX * r + x, unitY * r + y);
  13075. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13076. ctx.lineTo(
  13077. Math.cos(endAngle) * r0 + x,
  13078. Math.sin(endAngle) * r0 + y
  13079. );
  13080. if (r0 !== 0) {
  13081. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13082. }
  13083. ctx.closePath();
  13084. }
  13085. });
  13086. /**
  13087. * 圆环
  13088. * @module zrender/graphic/shape/Ring
  13089. */
  13090. var Ring = Path.extend({
  13091. type: 'ring',
  13092. shape: {
  13093. cx: 0,
  13094. cy: 0,
  13095. r: 0,
  13096. r0: 0
  13097. },
  13098. buildPath: function (ctx, shape) {
  13099. var x = shape.cx;
  13100. var y = shape.cy;
  13101. var PI2 = Math.PI * 2;
  13102. ctx.moveTo(x + shape.r, y);
  13103. ctx.arc(x, y, shape.r, 0, PI2, false);
  13104. ctx.moveTo(x + shape.r0, y);
  13105. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13106. }
  13107. });
  13108. /**
  13109. * Catmull-Rom spline 插值折线
  13110. * @module zrender/shape/util/smoothSpline
  13111. * @author pissang (https://www.github.com/pissang)
  13112. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13113. * errorrik (errorrik@gmail.com)
  13114. */
  13115. /**
  13116. * @inner
  13117. */
  13118. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13119. var v0 = (p2 - p0) * 0.5;
  13120. var v1 = (p3 - p1) * 0.5;
  13121. return (2 * (p1 - p2) + v0 + v1) * t3
  13122. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13123. + v0 * t + p1;
  13124. }
  13125. /**
  13126. * @alias module:zrender/shape/util/smoothSpline
  13127. * @param {Array} points 线段顶点数组
  13128. * @param {boolean} isLoop
  13129. * @return {Array}
  13130. */
  13131. var smoothSpline = function (points, isLoop) {
  13132. var len$$1 = points.length;
  13133. var ret = [];
  13134. var distance$$1 = 0;
  13135. for (var i = 1; i < len$$1; i++) {
  13136. distance$$1 += distance(points[i - 1], points[i]);
  13137. }
  13138. var segs = distance$$1 / 2;
  13139. segs = segs < len$$1 ? len$$1 : segs;
  13140. for (var i = 0; i < segs; i++) {
  13141. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13142. var idx = Math.floor(pos);
  13143. var w = pos - idx;
  13144. var p0;
  13145. var p1 = points[idx % len$$1];
  13146. var p2;
  13147. var p3;
  13148. if (!isLoop) {
  13149. p0 = points[idx === 0 ? idx : idx - 1];
  13150. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13151. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13152. }
  13153. else {
  13154. p0 = points[(idx - 1 + len$$1) % len$$1];
  13155. p2 = points[(idx + 1) % len$$1];
  13156. p3 = points[(idx + 2) % len$$1];
  13157. }
  13158. var w2 = w * w;
  13159. var w3 = w * w2;
  13160. ret.push([
  13161. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13162. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13163. ]);
  13164. }
  13165. return ret;
  13166. };
  13167. /**
  13168. * 贝塞尔平滑曲线
  13169. * @module zrender/shape/util/smoothBezier
  13170. * @author pissang (https://www.github.com/pissang)
  13171. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13172. * errorrik (errorrik@gmail.com)
  13173. */
  13174. /**
  13175. * 贝塞尔平滑曲线
  13176. * @alias module:zrender/shape/util/smoothBezier
  13177. * @param {Array} points 线段顶点数组
  13178. * @param {number} smooth 平滑等级, 0-1
  13179. * @param {boolean} isLoop
  13180. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13181. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13182. * 整个折线的包围盒做一个并集用来约束控制点。
  13183. * @param {Array} 计算出来的控制点数组
  13184. */
  13185. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13186. var cps = [];
  13187. var v = [];
  13188. var v1 = [];
  13189. var v2 = [];
  13190. var prevPoint;
  13191. var nextPoint;
  13192. var min$$1, max$$1;
  13193. if (constraint) {
  13194. min$$1 = [Infinity, Infinity];
  13195. max$$1 = [-Infinity, -Infinity];
  13196. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13197. min(min$$1, min$$1, points[i]);
  13198. max(max$$1, max$$1, points[i]);
  13199. }
  13200. // 与指定的包围盒做并集
  13201. min(min$$1, min$$1, constraint[0]);
  13202. max(max$$1, max$$1, constraint[1]);
  13203. }
  13204. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13205. var point = points[i];
  13206. if (isLoop) {
  13207. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13208. nextPoint = points[(i + 1) % len$$1];
  13209. }
  13210. else {
  13211. if (i === 0 || i === len$$1 - 1) {
  13212. cps.push(clone$1(points[i]));
  13213. continue;
  13214. }
  13215. else {
  13216. prevPoint = points[i - 1];
  13217. nextPoint = points[i + 1];
  13218. }
  13219. }
  13220. sub(v, nextPoint, prevPoint);
  13221. // use degree to scale the handle length
  13222. scale(v, v, smooth);
  13223. var d0 = distance(point, prevPoint);
  13224. var d1 = distance(point, nextPoint);
  13225. var sum = d0 + d1;
  13226. if (sum !== 0) {
  13227. d0 /= sum;
  13228. d1 /= sum;
  13229. }
  13230. scale(v1, v, -d0);
  13231. scale(v2, v, d1);
  13232. var cp0 = add([], point, v1);
  13233. var cp1 = add([], point, v2);
  13234. if (constraint) {
  13235. max(cp0, cp0, min$$1);
  13236. min(cp0, cp0, max$$1);
  13237. max(cp1, cp1, min$$1);
  13238. min(cp1, cp1, max$$1);
  13239. }
  13240. cps.push(cp0);
  13241. cps.push(cp1);
  13242. }
  13243. if (isLoop) {
  13244. cps.push(cps.shift());
  13245. }
  13246. return cps;
  13247. };
  13248. function buildPath$1(ctx, shape, closePath) {
  13249. var points = shape.points;
  13250. var smooth = shape.smooth;
  13251. if (points && points.length >= 2) {
  13252. if (smooth && smooth !== 'spline') {
  13253. var controlPoints = smoothBezier(
  13254. points, smooth, closePath, shape.smoothConstraint
  13255. );
  13256. ctx.moveTo(points[0][0], points[0][1]);
  13257. var len = points.length;
  13258. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13259. var cp1 = controlPoints[i * 2];
  13260. var cp2 = controlPoints[i * 2 + 1];
  13261. var p = points[(i + 1) % len];
  13262. ctx.bezierCurveTo(
  13263. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13264. );
  13265. }
  13266. }
  13267. else {
  13268. if (smooth === 'spline') {
  13269. points = smoothSpline(points, closePath);
  13270. }
  13271. ctx.moveTo(points[0][0], points[0][1]);
  13272. for (var i = 1, l = points.length; i < l; i++) {
  13273. ctx.lineTo(points[i][0], points[i][1]);
  13274. }
  13275. }
  13276. closePath && ctx.closePath();
  13277. }
  13278. }
  13279. /**
  13280. * 多边形
  13281. * @module zrender/shape/Polygon
  13282. */
  13283. var Polygon = Path.extend({
  13284. type: 'polygon',
  13285. shape: {
  13286. points: null,
  13287. smooth: false,
  13288. smoothConstraint: null
  13289. },
  13290. buildPath: function (ctx, shape) {
  13291. buildPath$1(ctx, shape, true);
  13292. }
  13293. });
  13294. /**
  13295. * @module zrender/graphic/shape/Polyline
  13296. */
  13297. var Polyline = Path.extend({
  13298. type: 'polyline',
  13299. shape: {
  13300. points: null,
  13301. smooth: false,
  13302. smoothConstraint: null
  13303. },
  13304. style: {
  13305. stroke: '#000',
  13306. fill: null
  13307. },
  13308. buildPath: function (ctx, shape) {
  13309. buildPath$1(ctx, shape, false);
  13310. }
  13311. });
  13312. /**
  13313. * 矩形
  13314. * @module zrender/graphic/shape/Rect
  13315. */
  13316. var Rect = Path.extend({
  13317. type: 'rect',
  13318. shape: {
  13319. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13320. // r缩写为1 相当于 [1, 1, 1, 1]
  13321. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13322. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13323. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13324. r: 0,
  13325. x: 0,
  13326. y: 0,
  13327. width: 0,
  13328. height: 0
  13329. },
  13330. buildPath: function (ctx, shape) {
  13331. var x = shape.x;
  13332. var y = shape.y;
  13333. var width = shape.width;
  13334. var height = shape.height;
  13335. if (!shape.r) {
  13336. ctx.rect(x, y, width, height);
  13337. }
  13338. else {
  13339. buildPath(ctx, shape);
  13340. }
  13341. ctx.closePath();
  13342. return;
  13343. }
  13344. });
  13345. /**
  13346. * 直线
  13347. * @module zrender/graphic/shape/Line
  13348. */
  13349. var Line = Path.extend({
  13350. type: 'line',
  13351. shape: {
  13352. // Start point
  13353. x1: 0,
  13354. y1: 0,
  13355. // End point
  13356. x2: 0,
  13357. y2: 0,
  13358. percent: 1
  13359. },
  13360. style: {
  13361. stroke: '#000',
  13362. fill: null
  13363. },
  13364. buildPath: function (ctx, shape) {
  13365. var x1 = shape.x1;
  13366. var y1 = shape.y1;
  13367. var x2 = shape.x2;
  13368. var y2 = shape.y2;
  13369. var percent = shape.percent;
  13370. if (percent === 0) {
  13371. return;
  13372. }
  13373. ctx.moveTo(x1, y1);
  13374. if (percent < 1) {
  13375. x2 = x1 * (1 - percent) + x2 * percent;
  13376. y2 = y1 * (1 - percent) + y2 * percent;
  13377. }
  13378. ctx.lineTo(x2, y2);
  13379. },
  13380. /**
  13381. * Get point at percent
  13382. * @param {number} percent
  13383. * @return {Array.<number>}
  13384. */
  13385. pointAt: function (p) {
  13386. var shape = this.shape;
  13387. return [
  13388. shape.x1 * (1 - p) + shape.x2 * p,
  13389. shape.y1 * (1 - p) + shape.y2 * p
  13390. ];
  13391. }
  13392. });
  13393. /**
  13394. * 贝塞尔曲线
  13395. * @module zrender/shape/BezierCurve
  13396. */
  13397. var out = [];
  13398. function someVectorAt(shape, t, isTangent) {
  13399. var cpx2 = shape.cpx2;
  13400. var cpy2 = shape.cpy2;
  13401. if (cpx2 === null || cpy2 === null) {
  13402. return [
  13403. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13404. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13405. ];
  13406. }
  13407. else {
  13408. return [
  13409. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13410. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13411. ];
  13412. }
  13413. }
  13414. var BezierCurve = Path.extend({
  13415. type: 'bezier-curve',
  13416. shape: {
  13417. x1: 0,
  13418. y1: 0,
  13419. x2: 0,
  13420. y2: 0,
  13421. cpx1: 0,
  13422. cpy1: 0,
  13423. // cpx2: 0,
  13424. // cpy2: 0
  13425. // Curve show percent, for animating
  13426. percent: 1
  13427. },
  13428. style: {
  13429. stroke: '#000',
  13430. fill: null
  13431. },
  13432. buildPath: function (ctx, shape) {
  13433. var x1 = shape.x1;
  13434. var y1 = shape.y1;
  13435. var x2 = shape.x2;
  13436. var y2 = shape.y2;
  13437. var cpx1 = shape.cpx1;
  13438. var cpy1 = shape.cpy1;
  13439. var cpx2 = shape.cpx2;
  13440. var cpy2 = shape.cpy2;
  13441. var percent = shape.percent;
  13442. if (percent === 0) {
  13443. return;
  13444. }
  13445. ctx.moveTo(x1, y1);
  13446. if (cpx2 == null || cpy2 == null) {
  13447. if (percent < 1) {
  13448. quadraticSubdivide(
  13449. x1, cpx1, x2, percent, out
  13450. );
  13451. cpx1 = out[1];
  13452. x2 = out[2];
  13453. quadraticSubdivide(
  13454. y1, cpy1, y2, percent, out
  13455. );
  13456. cpy1 = out[1];
  13457. y2 = out[2];
  13458. }
  13459. ctx.quadraticCurveTo(
  13460. cpx1, cpy1,
  13461. x2, y2
  13462. );
  13463. }
  13464. else {
  13465. if (percent < 1) {
  13466. cubicSubdivide(
  13467. x1, cpx1, cpx2, x2, percent, out
  13468. );
  13469. cpx1 = out[1];
  13470. cpx2 = out[2];
  13471. x2 = out[3];
  13472. cubicSubdivide(
  13473. y1, cpy1, cpy2, y2, percent, out
  13474. );
  13475. cpy1 = out[1];
  13476. cpy2 = out[2];
  13477. y2 = out[3];
  13478. }
  13479. ctx.bezierCurveTo(
  13480. cpx1, cpy1,
  13481. cpx2, cpy2,
  13482. x2, y2
  13483. );
  13484. }
  13485. },
  13486. /**
  13487. * Get point at percent
  13488. * @param {number} t
  13489. * @return {Array.<number>}
  13490. */
  13491. pointAt: function (t) {
  13492. return someVectorAt(this.shape, t, false);
  13493. },
  13494. /**
  13495. * Get tangent at percent
  13496. * @param {number} t
  13497. * @return {Array.<number>}
  13498. */
  13499. tangentAt: function (t) {
  13500. var p = someVectorAt(this.shape, t, true);
  13501. return normalize(p, p);
  13502. }
  13503. });
  13504. /**
  13505. * 圆弧
  13506. * @module zrender/graphic/shape/Arc
  13507. */
  13508. var Arc = Path.extend({
  13509. type: 'arc',
  13510. shape: {
  13511. cx: 0,
  13512. cy: 0,
  13513. r: 0,
  13514. startAngle: 0,
  13515. endAngle: Math.PI * 2,
  13516. clockwise: true
  13517. },
  13518. style: {
  13519. stroke: '#000',
  13520. fill: null
  13521. },
  13522. buildPath: function (ctx, shape) {
  13523. var x = shape.cx;
  13524. var y = shape.cy;
  13525. var r = Math.max(shape.r, 0);
  13526. var startAngle = shape.startAngle;
  13527. var endAngle = shape.endAngle;
  13528. var clockwise = shape.clockwise;
  13529. var unitX = Math.cos(startAngle);
  13530. var unitY = Math.sin(startAngle);
  13531. ctx.moveTo(unitX * r + x, unitY * r + y);
  13532. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13533. }
  13534. });
  13535. // CompoundPath to improve performance
  13536. var CompoundPath = Path.extend({
  13537. type: 'compound',
  13538. shape: {
  13539. paths: null
  13540. },
  13541. _updatePathDirty: function () {
  13542. var dirtyPath = this.__dirtyPath;
  13543. var paths = this.shape.paths;
  13544. for (var i = 0; i < paths.length; i++) {
  13545. // Mark as dirty if any subpath is dirty
  13546. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13547. }
  13548. this.__dirtyPath = dirtyPath;
  13549. this.__dirty = this.__dirty || dirtyPath;
  13550. },
  13551. beforeBrush: function () {
  13552. this._updatePathDirty();
  13553. var paths = this.shape.paths || [];
  13554. var scale = this.getGlobalScale();
  13555. // Update path scale
  13556. for (var i = 0; i < paths.length; i++) {
  13557. if (!paths[i].path) {
  13558. paths[i].createPathProxy();
  13559. }
  13560. paths[i].path.setScale(scale[0], scale[1]);
  13561. }
  13562. },
  13563. buildPath: function (ctx, shape) {
  13564. var paths = shape.paths || [];
  13565. for (var i = 0; i < paths.length; i++) {
  13566. paths[i].buildPath(ctx, paths[i].shape, true);
  13567. }
  13568. },
  13569. afterBrush: function () {
  13570. var paths = this.shape.paths || [];
  13571. for (var i = 0; i < paths.length; i++) {
  13572. paths[i].__dirtyPath = false;
  13573. }
  13574. },
  13575. getBoundingRect: function () {
  13576. this._updatePathDirty();
  13577. return Path.prototype.getBoundingRect.call(this);
  13578. }
  13579. });
  13580. /**
  13581. * @param {Array.<Object>} colorStops
  13582. */
  13583. var Gradient = function (colorStops) {
  13584. this.colorStops = colorStops || [];
  13585. };
  13586. Gradient.prototype = {
  13587. constructor: Gradient,
  13588. addColorStop: function (offset, color) {
  13589. this.colorStops.push({
  13590. offset: offset,
  13591. color: color
  13592. });
  13593. }
  13594. };
  13595. /**
  13596. * x, y, x2, y2 are all percent from 0 to 1
  13597. * @param {number} [x=0]
  13598. * @param {number} [y=0]
  13599. * @param {number} [x2=1]
  13600. * @param {number} [y2=0]
  13601. * @param {Array.<Object>} colorStops
  13602. * @param {boolean} [globalCoord=false]
  13603. */
  13604. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13605. // Should do nothing more in this constructor. Because gradient can be
  13606. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13607. // this constructor will not be called.
  13608. this.x = x == null ? 0 : x;
  13609. this.y = y == null ? 0 : y;
  13610. this.x2 = x2 == null ? 1 : x2;
  13611. this.y2 = y2 == null ? 0 : y2;
  13612. // Can be cloned
  13613. this.type = 'linear';
  13614. // If use global coord
  13615. this.global = globalCoord || false;
  13616. Gradient.call(this, colorStops);
  13617. };
  13618. LinearGradient.prototype = {
  13619. constructor: LinearGradient
  13620. };
  13621. inherits(LinearGradient, Gradient);
  13622. /**
  13623. * x, y, r are all percent from 0 to 1
  13624. * @param {number} [x=0.5]
  13625. * @param {number} [y=0.5]
  13626. * @param {number} [r=0.5]
  13627. * @param {Array.<Object>} [colorStops]
  13628. * @param {boolean} [globalCoord=false]
  13629. */
  13630. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13631. // Should do nothing more in this constructor. Because gradient can be
  13632. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13633. // this constructor will not be called.
  13634. this.x = x == null ? 0.5 : x;
  13635. this.y = y == null ? 0.5 : y;
  13636. this.r = r == null ? 0.5 : r;
  13637. // Can be cloned
  13638. this.type = 'radial';
  13639. // If use global coord
  13640. this.global = globalCoord || false;
  13641. Gradient.call(this, colorStops);
  13642. };
  13643. RadialGradient.prototype = {
  13644. constructor: RadialGradient
  13645. };
  13646. inherits(RadialGradient, Gradient);
  13647. var round$1 = Math.round;
  13648. var mathMax$1 = Math.max;
  13649. var mathMin$1 = Math.min;
  13650. var EMPTY_OBJ = {};
  13651. /**
  13652. * Extend shape with parameters
  13653. */
  13654. function extendShape(opts) {
  13655. return Path.extend(opts);
  13656. }
  13657. /**
  13658. * Extend path
  13659. */
  13660. function extendPath(pathData, opts) {
  13661. return extendFromString(pathData, opts);
  13662. }
  13663. /**
  13664. * Create a path element from path data string
  13665. * @param {string} pathData
  13666. * @param {Object} opts
  13667. * @param {module:zrender/core/BoundingRect} rect
  13668. * @param {string} [layout=cover] 'center' or 'cover'
  13669. */
  13670. function makePath(pathData, opts, rect, layout) {
  13671. var path = createFromString(pathData, opts);
  13672. var boundingRect = path.getBoundingRect();
  13673. if (rect) {
  13674. if (layout === 'center') {
  13675. rect = centerGraphic(rect, boundingRect);
  13676. }
  13677. resizePath(path, rect);
  13678. }
  13679. return path;
  13680. }
  13681. /**
  13682. * Create a image element from image url
  13683. * @param {string} imageUrl image url
  13684. * @param {Object} opts options
  13685. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13686. * @param {string} [layout=cover] 'center' or 'cover'
  13687. */
  13688. function makeImage(imageUrl, rect, layout) {
  13689. var path = new ZImage({
  13690. style: {
  13691. image: imageUrl,
  13692. x: rect.x,
  13693. y: rect.y,
  13694. width: rect.width,
  13695. height: rect.height
  13696. },
  13697. onload: function (img) {
  13698. if (layout === 'center') {
  13699. var boundingRect = {
  13700. width: img.width,
  13701. height: img.height
  13702. };
  13703. path.setStyle(centerGraphic(rect, boundingRect));
  13704. }
  13705. }
  13706. });
  13707. return path;
  13708. }
  13709. /**
  13710. * Get position of centered element in bounding box.
  13711. *
  13712. * @param {Object} rect element local bounding box
  13713. * @param {Object} boundingRect constraint bounding box
  13714. * @return {Object} element position containing x, y, width, and height
  13715. */
  13716. function centerGraphic(rect, boundingRect) {
  13717. // Set rect to center, keep width / height ratio.
  13718. var aspect = boundingRect.width / boundingRect.height;
  13719. var width = rect.height * aspect;
  13720. var height;
  13721. if (width <= rect.width) {
  13722. height = rect.height;
  13723. }
  13724. else {
  13725. width = rect.width;
  13726. height = width / aspect;
  13727. }
  13728. var cx = rect.x + rect.width / 2;
  13729. var cy = rect.y + rect.height / 2;
  13730. return {
  13731. x: cx - width / 2,
  13732. y: cy - height / 2,
  13733. width: width,
  13734. height: height
  13735. };
  13736. }
  13737. var mergePath = mergePath$1;
  13738. /**
  13739. * Resize a path to fit the rect
  13740. * @param {module:zrender/graphic/Path} path
  13741. * @param {Object} rect
  13742. */
  13743. function resizePath(path, rect) {
  13744. if (!path.applyTransform) {
  13745. return;
  13746. }
  13747. var pathRect = path.getBoundingRect();
  13748. var m = pathRect.calculateTransform(rect);
  13749. path.applyTransform(m);
  13750. }
  13751. /**
  13752. * Sub pixel optimize line for canvas
  13753. *
  13754. * @param {Object} param
  13755. * @param {Object} [param.shape]
  13756. * @param {number} [param.shape.x1]
  13757. * @param {number} [param.shape.y1]
  13758. * @param {number} [param.shape.x2]
  13759. * @param {number} [param.shape.y2]
  13760. * @param {Object} [param.style]
  13761. * @param {number} [param.style.lineWidth]
  13762. * @return {Object} Modified param
  13763. */
  13764. function subPixelOptimizeLine(param) {
  13765. var shape = param.shape;
  13766. var lineWidth = param.style.lineWidth;
  13767. if (round$1(shape.x1 * 2) === round$1(shape.x2 * 2)) {
  13768. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13769. }
  13770. if (round$1(shape.y1 * 2) === round$1(shape.y2 * 2)) {
  13771. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13772. }
  13773. return param;
  13774. }
  13775. /**
  13776. * Sub pixel optimize rect for canvas
  13777. *
  13778. * @param {Object} param
  13779. * @param {Object} [param.shape]
  13780. * @param {number} [param.shape.x]
  13781. * @param {number} [param.shape.y]
  13782. * @param {number} [param.shape.width]
  13783. * @param {number} [param.shape.height]
  13784. * @param {Object} [param.style]
  13785. * @param {number} [param.style.lineWidth]
  13786. * @return {Object} Modified param
  13787. */
  13788. function subPixelOptimizeRect(param) {
  13789. var shape = param.shape;
  13790. var lineWidth = param.style.lineWidth;
  13791. var originX = shape.x;
  13792. var originY = shape.y;
  13793. var originWidth = shape.width;
  13794. var originHeight = shape.height;
  13795. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13796. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13797. shape.width = Math.max(
  13798. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13799. originWidth === 0 ? 0 : 1
  13800. );
  13801. shape.height = Math.max(
  13802. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13803. originHeight === 0 ? 0 : 1
  13804. );
  13805. return param;
  13806. }
  13807. /**
  13808. * Sub pixel optimize for canvas
  13809. *
  13810. * @param {number} position Coordinate, such as x, y
  13811. * @param {number} lineWidth Should be nonnegative integer.
  13812. * @param {boolean=} positiveOrNegative Default false (negative).
  13813. * @return {number} Optimized position.
  13814. */
  13815. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13816. // Assure that (position + lineWidth / 2) is near integer edge,
  13817. // otherwise line will be fuzzy in canvas.
  13818. var doubledPosition = round$1(position * 2);
  13819. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13820. ? doubledPosition / 2
  13821. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13822. }
  13823. function hasFillOrStroke(fillOrStroke) {
  13824. return fillOrStroke != null && fillOrStroke != 'none';
  13825. }
  13826. function liftColor(color) {
  13827. return typeof color === 'string' ? lift(color, -0.1) : color;
  13828. }
  13829. /**
  13830. * @private
  13831. */
  13832. function cacheElementStl(el) {
  13833. if (el.__hoverStlDirty) {
  13834. var stroke = el.style.stroke;
  13835. var fill = el.style.fill;
  13836. // Create hoverStyle on mouseover
  13837. var hoverStyle = el.__hoverStl;
  13838. hoverStyle.fill = hoverStyle.fill
  13839. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13840. hoverStyle.stroke = hoverStyle.stroke
  13841. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13842. var normalStyle = {};
  13843. for (var name in hoverStyle) {
  13844. // See comment in `doSingleEnterHover`.
  13845. if (hoverStyle[name] != null) {
  13846. normalStyle[name] = el.style[name];
  13847. }
  13848. }
  13849. el.__normalStl = normalStyle;
  13850. el.__hoverStlDirty = false;
  13851. }
  13852. }
  13853. /**
  13854. * @private
  13855. */
  13856. function doSingleEnterHover(el) {
  13857. if (el.__isHover) {
  13858. return;
  13859. }
  13860. cacheElementStl(el);
  13861. if (el.useHoverLayer) {
  13862. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13863. }
  13864. else {
  13865. var style = el.style;
  13866. var insideRollbackOpt = style.insideRollbackOpt;
  13867. // Consider case: only `position: 'top'` is set on emphasis, then text
  13868. // color should be returned to `autoColor`, rather than remain '#fff'.
  13869. // So we should rollback then apply again after style merging.
  13870. insideRollbackOpt && rollbackInsideStyle(style);
  13871. // styles can be:
  13872. // {
  13873. // label: {
  13874. // normal: {
  13875. // show: false,
  13876. // position: 'outside',
  13877. // fontSize: 18
  13878. // },
  13879. // emphasis: {
  13880. // show: true
  13881. // }
  13882. // }
  13883. // },
  13884. // where properties of `emphasis` may not appear in `normal`. We previously use
  13885. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13886. // But consider rich text and setOption in merge mode, it is impossible to cover
  13887. // all properties in merge. So we use merge mode when setting style here, where
  13888. // only properties that is not `null/undefined` can be set. The disadventage:
  13889. // null/undefined can not be used to remove style any more in `emphasis`.
  13890. style.extendFrom(el.__hoverStl);
  13891. // Do not save `insideRollback`.
  13892. if (insideRollbackOpt) {
  13893. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13894. // textFill may be rollbacked to null.
  13895. if (style.textFill == null) {
  13896. style.textFill = insideRollbackOpt.autoColor;
  13897. }
  13898. }
  13899. el.dirty(false);
  13900. el.z2 += 1;
  13901. }
  13902. el.__isHover = true;
  13903. }
  13904. /**
  13905. * @inner
  13906. */
  13907. function doSingleLeaveHover(el) {
  13908. if (!el.__isHover) {
  13909. return;
  13910. }
  13911. var normalStl = el.__normalStl;
  13912. if (el.useHoverLayer) {
  13913. el.__zr && el.__zr.removeHover(el);
  13914. }
  13915. else {
  13916. // Consider null/undefined value, should use
  13917. // `setStyle` but not `extendFrom(stl, true)`.
  13918. normalStl && el.setStyle(normalStl);
  13919. el.z2 -= 1;
  13920. }
  13921. el.__isHover = false;
  13922. }
  13923. /**
  13924. * @inner
  13925. */
  13926. function doEnterHover(el) {
  13927. el.type === 'group'
  13928. ? el.traverse(function (child) {
  13929. if (child.type !== 'group') {
  13930. doSingleEnterHover(child);
  13931. }
  13932. })
  13933. : doSingleEnterHover(el);
  13934. }
  13935. function doLeaveHover(el) {
  13936. el.type === 'group'
  13937. ? el.traverse(function (child) {
  13938. if (child.type !== 'group') {
  13939. doSingleLeaveHover(child);
  13940. }
  13941. })
  13942. : doSingleLeaveHover(el);
  13943. }
  13944. /**
  13945. * @inner
  13946. */
  13947. function setElementHoverStl(el, hoverStl) {
  13948. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13949. // Often used when item group has a label element and it's hoverStyle is different
  13950. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13951. el.__hoverStlDirty = true;
  13952. if (el.__isHover) {
  13953. cacheElementStl(el);
  13954. }
  13955. }
  13956. /**
  13957. * @inner
  13958. */
  13959. function onElementMouseOver(e) {
  13960. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13961. return;
  13962. }
  13963. // Only if element is not in emphasis status
  13964. !this.__isEmphasis && doEnterHover(this);
  13965. }
  13966. /**
  13967. * @inner
  13968. */
  13969. function onElementMouseOut(e) {
  13970. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13971. return;
  13972. }
  13973. // Only if element is not in emphasis status
  13974. !this.__isEmphasis && doLeaveHover(this);
  13975. }
  13976. /**
  13977. * @inner
  13978. */
  13979. function enterEmphasis() {
  13980. this.__isEmphasis = true;
  13981. doEnterHover(this);
  13982. }
  13983. /**
  13984. * @inner
  13985. */
  13986. function leaveEmphasis() {
  13987. this.__isEmphasis = false;
  13988. doLeaveHover(this);
  13989. }
  13990. /**
  13991. * Set hover style of element.
  13992. * This method can be called repeatly without side-effects.
  13993. * @param {module:zrender/Element} el
  13994. * @param {Object} [hoverStyle]
  13995. * @param {Object} [opt]
  13996. * @param {boolean} [opt.hoverSilentOnTouch=false]
  13997. * In touch device, mouseover event will be trigger on touchstart event
  13998. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  13999. * conviniently use hoverStyle when tap on touch screen without additional
  14000. * code for compatibility.
  14001. * But if the chart/component has select feature, which usually also use
  14002. * hoverStyle, there might be conflict between 'select-highlight' and
  14003. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14004. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14005. * on touch device.
  14006. */
  14007. function setHoverStyle(el, hoverStyle, opt) {
  14008. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14009. el.type === 'group'
  14010. ? el.traverse(function (child) {
  14011. if (child.type !== 'group') {
  14012. setElementHoverStl(child, hoverStyle);
  14013. }
  14014. })
  14015. : setElementHoverStl(el, hoverStyle);
  14016. // Duplicated function will be auto-ignored, see Eventful.js.
  14017. el.on('mouseover', onElementMouseOver)
  14018. .on('mouseout', onElementMouseOut);
  14019. // Emphasis, normal can be triggered manually
  14020. el.on('emphasis', enterEmphasis)
  14021. .on('normal', leaveEmphasis);
  14022. }
  14023. /**
  14024. * @param {Object|module:zrender/graphic/Style} normalStyle
  14025. * @param {Object} emphasisStyle
  14026. * @param {module:echarts/model/Model} normalModel
  14027. * @param {module:echarts/model/Model} emphasisModel
  14028. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14029. * @param {Object} [opt.defaultText]
  14030. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14031. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14032. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14033. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14034. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14035. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14036. * @param {Object} [normalSpecified]
  14037. * @param {Object} [emphasisSpecified]
  14038. */
  14039. function setLabelStyle(
  14040. normalStyle, emphasisStyle,
  14041. normalModel, emphasisModel,
  14042. opt,
  14043. normalSpecified, emphasisSpecified
  14044. ) {
  14045. opt = opt || EMPTY_OBJ;
  14046. var labelFetcher = opt.labelFetcher;
  14047. var labelDataIndex = opt.labelDataIndex;
  14048. var labelDimIndex = opt.labelDimIndex;
  14049. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14050. // is not supported util someone requests.
  14051. var showNormal = normalModel.getShallow('show');
  14052. var showEmphasis = emphasisModel.getShallow('show');
  14053. // Consider performance, only fetch label when necessary.
  14054. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14055. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14056. var baseText = (showNormal || showEmphasis)
  14057. ? retrieve2(
  14058. labelFetcher
  14059. ? labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex)
  14060. : null,
  14061. opt.defaultText
  14062. )
  14063. : null;
  14064. var normalStyleText = showNormal ? baseText : null;
  14065. var emphasisStyleText = showEmphasis
  14066. ? retrieve2(
  14067. labelFetcher
  14068. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14069. : null,
  14070. baseText
  14071. )
  14072. : null;
  14073. // Optimize: If style.text is null, text will not be drawn.
  14074. if (normalStyleText != null || emphasisStyleText != null) {
  14075. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14076. // values have to be set on `normalStyle`.
  14077. // If we set default values on `emphasisStyle`, consider case:
  14078. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14079. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14080. // Then the 'red' will not work on emphasis.
  14081. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14082. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14083. }
  14084. normalStyle.text = normalStyleText;
  14085. emphasisStyle.text = emphasisStyleText;
  14086. }
  14087. /**
  14088. * Set basic textStyle properties.
  14089. * @param {Object|module:zrender/graphic/Style} textStyle
  14090. * @param {module:echarts/model/Model} model
  14091. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14092. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14093. * @param {boolean} [isEmphasis]
  14094. */
  14095. function setTextStyle(
  14096. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14097. ) {
  14098. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14099. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14100. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14101. return textStyle;
  14102. }
  14103. /**
  14104. * Set text option in the style.
  14105. * @deprecated
  14106. * @param {Object} textStyle
  14107. * @param {module:echarts/model/Model} labelModel
  14108. * @param {string|boolean} defaultColor Default text color.
  14109. * If set as false, it will be processed as a emphasis style.
  14110. */
  14111. function setText(textStyle, labelModel, defaultColor) {
  14112. var opt = {isRectText: true};
  14113. var isEmphasis;
  14114. if (defaultColor === false) {
  14115. isEmphasis = true;
  14116. }
  14117. else {
  14118. // Support setting color as 'auto' to get visual color.
  14119. opt.autoColor = defaultColor;
  14120. }
  14121. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14122. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14123. }
  14124. /**
  14125. * {
  14126. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14127. * isRectText: boolean,
  14128. * autoColor: string, specify a color when color is 'auto',
  14129. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14130. * If autoColor specified, it is used as default textFill.
  14131. * useInsideStyle:
  14132. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14133. * if `textFill` is not specified.
  14134. * `false`: Do not use inside style.
  14135. * `null/undefined`: use inside style if `isRectText` is true and
  14136. * `textFill` is not specified and textPosition contains `'inside'`.
  14137. * forceRich: boolean
  14138. * }
  14139. */
  14140. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14141. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14142. opt = opt || EMPTY_OBJ;
  14143. if (opt.isRectText) {
  14144. var textPosition = textStyleModel.getShallow('position')
  14145. || (isEmphasis ? null : 'inside');
  14146. // 'outside' is not a valid zr textPostion value, but used
  14147. // in bar series, and magric type should be considered.
  14148. textPosition === 'outside' && (textPosition = 'top');
  14149. textStyle.textPosition = textPosition;
  14150. textStyle.textOffset = textStyleModel.getShallow('offset');
  14151. var labelRotate = textStyleModel.getShallow('rotate');
  14152. labelRotate != null && (labelRotate *= Math.PI / 180);
  14153. textStyle.textRotation = labelRotate;
  14154. textStyle.textDistance = retrieve2(
  14155. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14156. );
  14157. }
  14158. var ecModel = textStyleModel.ecModel;
  14159. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14160. // Consider case:
  14161. // {
  14162. // data: [{
  14163. // value: 12,
  14164. // label: {
  14165. // normal: {
  14166. // rich: {
  14167. // // no 'a' here but using parent 'a'.
  14168. // }
  14169. // }
  14170. // }
  14171. // }],
  14172. // rich: {
  14173. // a: { ... }
  14174. // }
  14175. // }
  14176. var richItemNames = getRichItemNames(textStyleModel);
  14177. var richResult;
  14178. if (richItemNames) {
  14179. richResult = {};
  14180. for (var name in richItemNames) {
  14181. if (richItemNames.hasOwnProperty(name)) {
  14182. // Cascade is supported in rich.
  14183. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14184. // In rich, never `disableBox`.
  14185. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14186. }
  14187. }
  14188. }
  14189. textStyle.rich = richResult;
  14190. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14191. if (opt.forceRich && !opt.textStyle) {
  14192. opt.textStyle = {};
  14193. }
  14194. return textStyle;
  14195. }
  14196. // Consider case:
  14197. // {
  14198. // data: [{
  14199. // value: 12,
  14200. // label: {
  14201. // normal: {
  14202. // rich: {
  14203. // // no 'a' here but using parent 'a'.
  14204. // }
  14205. // }
  14206. // }
  14207. // }],
  14208. // rich: {
  14209. // a: { ... }
  14210. // }
  14211. // }
  14212. function getRichItemNames(textStyleModel) {
  14213. // Use object to remove duplicated names.
  14214. var richItemNameMap;
  14215. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14216. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14217. if (rich) {
  14218. richItemNameMap = richItemNameMap || {};
  14219. for (var name in rich) {
  14220. if (rich.hasOwnProperty(name)) {
  14221. richItemNameMap[name] = 1;
  14222. }
  14223. }
  14224. }
  14225. textStyleModel = textStyleModel.parentModel;
  14226. }
  14227. return richItemNameMap;
  14228. }
  14229. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14230. // In merge mode, default value should not be given.
  14231. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14232. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14233. || globalTextStyle.color;
  14234. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14235. || globalTextStyle.textBorderColor;
  14236. textStyle.textStrokeWidth = retrieve2(
  14237. textStyleModel.getShallow('textBorderWidth'),
  14238. globalTextStyle.textBorderWidth
  14239. );
  14240. if (!isEmphasis) {
  14241. if (isBlock) {
  14242. // Always set `insideRollback`, for clearing previous.
  14243. var originalTextPosition = textStyle.textPosition;
  14244. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14245. // Save original textPosition, because style.textPosition will be repalced by
  14246. // real location (like [10, 30]) in zrender.
  14247. textStyle.insideOriginalTextPosition = originalTextPosition;
  14248. textStyle.insideRollbackOpt = opt;
  14249. }
  14250. // Set default finally.
  14251. if (textStyle.textFill == null) {
  14252. textStyle.textFill = opt.autoColor;
  14253. }
  14254. }
  14255. // Do not use `getFont` here, because merge should be supported, where
  14256. // part of these properties may be changed in emphasis style, and the
  14257. // others should remain their original value got from normal style.
  14258. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14259. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14260. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14261. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14262. textStyle.textAlign = textStyleModel.getShallow('align');
  14263. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14264. || textStyleModel.getShallow('baseline');
  14265. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14266. textStyle.textWidth = textStyleModel.getShallow('width');
  14267. textStyle.textHeight = textStyleModel.getShallow('height');
  14268. textStyle.textTag = textStyleModel.getShallow('tag');
  14269. if (!isBlock || !opt.disableBox) {
  14270. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14271. textStyle.textPadding = textStyleModel.getShallow('padding');
  14272. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14273. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14274. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14275. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14276. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14277. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14278. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14279. }
  14280. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14281. || globalTextStyle.textShadowColor;
  14282. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14283. || globalTextStyle.textShadowBlur;
  14284. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14285. || globalTextStyle.textShadowOffsetX;
  14286. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14287. || globalTextStyle.textShadowOffsetY;
  14288. }
  14289. function getAutoColor(color, opt) {
  14290. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14291. }
  14292. function applyInsideStyle(textStyle, textPosition, opt) {
  14293. var useInsideStyle = opt.useInsideStyle;
  14294. var insideRollback;
  14295. if (textStyle.textFill == null
  14296. && useInsideStyle !== false
  14297. && (useInsideStyle === true
  14298. || (opt.isRectText
  14299. && textPosition
  14300. // textPosition can be [10, 30]
  14301. && typeof textPosition === 'string'
  14302. && textPosition.indexOf('inside') >= 0
  14303. )
  14304. )
  14305. ) {
  14306. insideRollback = {
  14307. textFill: null,
  14308. textStroke: textStyle.textStroke,
  14309. textStrokeWidth: textStyle.textStrokeWidth
  14310. };
  14311. textStyle.textFill = '#fff';
  14312. // Consider text with #fff overflow its container.
  14313. if (textStyle.textStroke == null) {
  14314. textStyle.textStroke = opt.autoColor;
  14315. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14316. }
  14317. }
  14318. return insideRollback;
  14319. }
  14320. function rollbackInsideStyle(style) {
  14321. var insideRollback = style.insideRollback;
  14322. if (insideRollback) {
  14323. style.textFill = insideRollback.textFill;
  14324. style.textStroke = insideRollback.textStroke;
  14325. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14326. }
  14327. }
  14328. function getFont(opt, ecModel) {
  14329. // ecModel or default text style model.
  14330. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14331. return [
  14332. // FIXME in node-canvas fontWeight is before fontStyle
  14333. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14334. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14335. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14336. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14337. ].join(' ');
  14338. }
  14339. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14340. if (typeof dataIndex === 'function') {
  14341. cb = dataIndex;
  14342. dataIndex = null;
  14343. }
  14344. // Do not check 'animation' property directly here. Consider this case:
  14345. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14346. // but its parent model (`seriesModel`) does.
  14347. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14348. if (animationEnabled) {
  14349. var postfix = isUpdate ? 'Update' : '';
  14350. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14351. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14352. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14353. if (typeof animationDelay === 'function') {
  14354. animationDelay = animationDelay(
  14355. dataIndex,
  14356. animatableModel.getAnimationDelayParams
  14357. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14358. : null
  14359. );
  14360. }
  14361. if (typeof duration === 'function') {
  14362. duration = duration(dataIndex);
  14363. }
  14364. duration > 0
  14365. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14366. : (el.stopAnimation(), el.attr(props), cb && cb());
  14367. }
  14368. else {
  14369. el.stopAnimation();
  14370. el.attr(props);
  14371. cb && cb();
  14372. }
  14373. }
  14374. /**
  14375. * Update graphic element properties with or without animation according to the
  14376. * configuration in series.
  14377. *
  14378. * Caution: this method will stop previous animation.
  14379. * So if do not use this method to one element twice before
  14380. * animation starts, unless you know what you are doing.
  14381. *
  14382. * @param {module:zrender/Element} el
  14383. * @param {Object} props
  14384. * @param {module:echarts/model/Model} [animatableModel]
  14385. * @param {number} [dataIndex]
  14386. * @param {Function} [cb]
  14387. * @example
  14388. * graphic.updateProps(el, {
  14389. * position: [100, 100]
  14390. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14391. * // Or
  14392. * graphic.updateProps(el, {
  14393. * position: [100, 100]
  14394. * }, seriesModel, function () { console.log('Animation done!'); });
  14395. */
  14396. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14397. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14398. }
  14399. /**
  14400. * Init graphic element properties with or without animation according to the
  14401. * configuration in series.
  14402. *
  14403. * Caution: this method will stop previous animation.
  14404. * So if do not use this method to one element twice before
  14405. * animation starts, unless you know what you are doing.
  14406. *
  14407. * @param {module:zrender/Element} el
  14408. * @param {Object} props
  14409. * @param {module:echarts/model/Model} [animatableModel]
  14410. * @param {number} [dataIndex]
  14411. * @param {Function} cb
  14412. */
  14413. function initProps(el, props, animatableModel, dataIndex, cb) {
  14414. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14415. }
  14416. /**
  14417. * Get transform matrix of target (param target),
  14418. * in coordinate of its ancestor (param ancestor)
  14419. *
  14420. * @param {module:zrender/mixin/Transformable} target
  14421. * @param {module:zrender/mixin/Transformable} [ancestor]
  14422. */
  14423. function getTransform(target, ancestor) {
  14424. var mat = identity([]);
  14425. while (target && target !== ancestor) {
  14426. mul$1(mat, target.getLocalTransform(), mat);
  14427. target = target.parent;
  14428. }
  14429. return mat;
  14430. }
  14431. /**
  14432. * Apply transform to an vertex.
  14433. * @param {Array.<number>} target [x, y]
  14434. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14435. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14436. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14437. * @param {boolean=} invert Whether use invert matrix.
  14438. * @return {Array.<number>} [x, y]
  14439. */
  14440. function applyTransform$1(target, transform, invert$$1) {
  14441. if (transform && !isArrayLike(transform)) {
  14442. transform = Transformable.getLocalTransform(transform);
  14443. }
  14444. if (invert$$1) {
  14445. transform = invert([], transform);
  14446. }
  14447. return applyTransform([], target, transform);
  14448. }
  14449. /**
  14450. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14451. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14452. * @param {boolean=} invert Whether use invert matrix.
  14453. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14454. */
  14455. function transformDirection(direction, transform, invert$$1) {
  14456. // Pick a base, ensure that transform result will not be (0, 0).
  14457. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14458. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14459. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14460. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14461. var vertex = [
  14462. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14463. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14464. ];
  14465. vertex = applyTransform$1(vertex, transform, invert$$1);
  14466. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14467. ? (vertex[0] > 0 ? 'right' : 'left')
  14468. : (vertex[1] > 0 ? 'bottom' : 'top');
  14469. }
  14470. /**
  14471. * Apply group transition animation from g1 to g2.
  14472. * If no animatableModel, no animation.
  14473. */
  14474. function groupTransition(g1, g2, animatableModel, cb) {
  14475. if (!g1 || !g2) {
  14476. return;
  14477. }
  14478. function getElMap(g) {
  14479. var elMap = {};
  14480. g.traverse(function (el) {
  14481. if (!el.isGroup && el.anid) {
  14482. elMap[el.anid] = el;
  14483. }
  14484. });
  14485. return elMap;
  14486. }
  14487. function getAnimatableProps(el) {
  14488. var obj = {
  14489. position: clone$1(el.position),
  14490. rotation: el.rotation
  14491. };
  14492. if (el.shape) {
  14493. obj.shape = extend({}, el.shape);
  14494. }
  14495. return obj;
  14496. }
  14497. var elMap1 = getElMap(g1);
  14498. g2.traverse(function (el) {
  14499. if (!el.isGroup && el.anid) {
  14500. var oldEl = elMap1[el.anid];
  14501. if (oldEl) {
  14502. var newProp = getAnimatableProps(el);
  14503. el.attr(getAnimatableProps(oldEl));
  14504. updateProps(el, newProp, animatableModel, el.dataIndex);
  14505. }
  14506. // else {
  14507. // if (el.previousProps) {
  14508. // graphic.updateProps
  14509. // }
  14510. // }
  14511. }
  14512. });
  14513. }
  14514. /**
  14515. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14516. * @param {Object} rect {x, y, width, height}
  14517. * @return {Array.<Array.<number>>} A new clipped points.
  14518. */
  14519. function clipPointsByRect(points, rect) {
  14520. return map(points, function (point) {
  14521. var x = point[0];
  14522. x = mathMax$1(x, rect.x);
  14523. x = mathMin$1(x, rect.x + rect.width);
  14524. var y = point[1];
  14525. y = mathMax$1(y, rect.y);
  14526. y = mathMin$1(y, rect.y + rect.height);
  14527. return [x, y];
  14528. });
  14529. }
  14530. /**
  14531. * @param {Object} targetRect {x, y, width, height}
  14532. * @param {Object} rect {x, y, width, height}
  14533. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14534. */
  14535. function clipRectByRect(targetRect, rect) {
  14536. var x = mathMax$1(targetRect.x, rect.x);
  14537. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14538. var y = mathMax$1(targetRect.y, rect.y);
  14539. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14540. if (x2 >= x && y2 >= y) {
  14541. return {
  14542. x: x,
  14543. y: y,
  14544. width: x2 - x,
  14545. height: y2 - y
  14546. };
  14547. }
  14548. }
  14549. /**
  14550. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14551. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14552. * @param {Object} [rect] {x, y, width, height}
  14553. * @return {module:zrender/Element} Icon path or image element.
  14554. */
  14555. function createIcon(iconStr, opt, rect) {
  14556. opt = extend({rectHover: true}, opt);
  14557. var style = opt.style = {strokeNoScale: true};
  14558. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14559. if (iconStr) {
  14560. return iconStr.indexOf('image://') === 0
  14561. ? (
  14562. style.image = iconStr.slice(8),
  14563. defaults(style, rect),
  14564. new ZImage(opt)
  14565. )
  14566. : (
  14567. makePath(
  14568. iconStr.replace('path://', ''),
  14569. opt,
  14570. rect,
  14571. 'center'
  14572. )
  14573. );
  14574. }
  14575. }
  14576. var graphic = (Object.freeze || Object)({
  14577. extendShape: extendShape,
  14578. extendPath: extendPath,
  14579. makePath: makePath,
  14580. makeImage: makeImage,
  14581. mergePath: mergePath,
  14582. resizePath: resizePath,
  14583. subPixelOptimizeLine: subPixelOptimizeLine,
  14584. subPixelOptimizeRect: subPixelOptimizeRect,
  14585. subPixelOptimize: subPixelOptimize,
  14586. setHoverStyle: setHoverStyle,
  14587. setLabelStyle: setLabelStyle,
  14588. setTextStyle: setTextStyle,
  14589. setText: setText,
  14590. getFont: getFont,
  14591. updateProps: updateProps,
  14592. initProps: initProps,
  14593. getTransform: getTransform,
  14594. applyTransform: applyTransform$1,
  14595. transformDirection: transformDirection,
  14596. groupTransition: groupTransition,
  14597. clipPointsByRect: clipPointsByRect,
  14598. clipRectByRect: clipRectByRect,
  14599. createIcon: createIcon,
  14600. Group: Group,
  14601. Image: ZImage,
  14602. Text: Text,
  14603. Circle: Circle,
  14604. Sector: Sector,
  14605. Ring: Ring,
  14606. Polygon: Polygon,
  14607. Polyline: Polyline,
  14608. Rect: Rect,
  14609. Line: Line,
  14610. BezierCurve: BezierCurve,
  14611. Arc: Arc,
  14612. CompoundPath: CompoundPath,
  14613. LinearGradient: LinearGradient,
  14614. RadialGradient: RadialGradient,
  14615. BoundingRect: BoundingRect
  14616. });
  14617. var PATH_COLOR = ['textStyle', 'color'];
  14618. var textStyleMixin = {
  14619. /**
  14620. * Get color property or get color from option.textStyle.color
  14621. * @param {boolean} [isEmphasis]
  14622. * @return {string}
  14623. */
  14624. getTextColor: function (isEmphasis) {
  14625. var ecModel = this.ecModel;
  14626. return this.getShallow('color')
  14627. || (
  14628. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14629. );
  14630. },
  14631. /**
  14632. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14633. * @return {string}
  14634. */
  14635. getFont: function () {
  14636. return getFont({
  14637. fontStyle: this.getShallow('fontStyle'),
  14638. fontWeight: this.getShallow('fontWeight'),
  14639. fontSize: this.getShallow('fontSize'),
  14640. fontFamily: this.getShallow('fontFamily')
  14641. }, this.ecModel);
  14642. },
  14643. getTextRect: function (text) {
  14644. return getBoundingRect(
  14645. text,
  14646. this.getFont(),
  14647. this.getShallow('align'),
  14648. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14649. this.getShallow('padding'),
  14650. this.getShallow('rich'),
  14651. this.getShallow('truncateText')
  14652. );
  14653. }
  14654. };
  14655. var getItemStyle = makeStyleMapper(
  14656. [
  14657. ['fill', 'color'],
  14658. ['stroke', 'borderColor'],
  14659. ['lineWidth', 'borderWidth'],
  14660. ['opacity'],
  14661. ['shadowBlur'],
  14662. ['shadowOffsetX'],
  14663. ['shadowOffsetY'],
  14664. ['shadowColor'],
  14665. ['textPosition'],
  14666. ['textAlign']
  14667. ]
  14668. );
  14669. var itemStyleMixin = {
  14670. getItemStyle: function (excludes, includes) {
  14671. var style = getItemStyle(this, excludes, includes);
  14672. var lineDash = this.getBorderLineDash();
  14673. lineDash && (style.lineDash = lineDash);
  14674. return style;
  14675. },
  14676. getBorderLineDash: function () {
  14677. var lineType = this.get('borderType');
  14678. return (lineType === 'solid' || lineType == null) ? null
  14679. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14680. }
  14681. };
  14682. /**
  14683. * @module echarts/model/Model
  14684. */
  14685. var mixin$1 = mixin;
  14686. /**
  14687. * @alias module:echarts/model/Model
  14688. * @constructor
  14689. * @param {Object} option
  14690. * @param {module:echarts/model/Model} [parentModel]
  14691. * @param {module:echarts/model/Global} [ecModel]
  14692. */
  14693. function Model(option, parentModel, ecModel) {
  14694. /**
  14695. * @type {module:echarts/model/Model}
  14696. * @readOnly
  14697. */
  14698. this.parentModel = parentModel;
  14699. /**
  14700. * @type {module:echarts/model/Global}
  14701. * @readOnly
  14702. */
  14703. this.ecModel = ecModel;
  14704. /**
  14705. * @type {Object}
  14706. * @protected
  14707. */
  14708. this.option = option;
  14709. // Simple optimization
  14710. // if (this.init) {
  14711. // if (arguments.length <= 4) {
  14712. // this.init(option, parentModel, ecModel, extraOpt);
  14713. // }
  14714. // else {
  14715. // this.init.apply(this, arguments);
  14716. // }
  14717. // }
  14718. }
  14719. Model.prototype = {
  14720. constructor: Model,
  14721. /**
  14722. * Model 的初始化函数
  14723. * @param {Object} option
  14724. */
  14725. init: null,
  14726. /**
  14727. * 从新的 Option merge
  14728. */
  14729. mergeOption: function (option) {
  14730. merge(this.option, option, true);
  14731. },
  14732. /**
  14733. * @param {string|Array.<string>} path
  14734. * @param {boolean} [ignoreParent=false]
  14735. * @return {*}
  14736. */
  14737. get: function (path, ignoreParent) {
  14738. if (path == null) {
  14739. return this.option;
  14740. }
  14741. return doGet(
  14742. this.option,
  14743. this.parsePath(path),
  14744. !ignoreParent && getParent(this, path)
  14745. );
  14746. },
  14747. /**
  14748. * @param {string} key
  14749. * @param {boolean} [ignoreParent=false]
  14750. * @return {*}
  14751. */
  14752. getShallow: function (key, ignoreParent) {
  14753. var option = this.option;
  14754. var val = option == null ? option : option[key];
  14755. var parentModel = !ignoreParent && getParent(this, key);
  14756. if (val == null && parentModel) {
  14757. val = parentModel.getShallow(key);
  14758. }
  14759. return val;
  14760. },
  14761. /**
  14762. * @param {string|Array.<string>} [path]
  14763. * @param {module:echarts/model/Model} [parentModel]
  14764. * @return {module:echarts/model/Model}
  14765. */
  14766. getModel: function (path, parentModel) {
  14767. var obj = path == null
  14768. ? this.option
  14769. : doGet(this.option, path = this.parsePath(path));
  14770. var thisParentModel;
  14771. parentModel = parentModel || (
  14772. (thisParentModel = getParent(this, path))
  14773. && thisParentModel.getModel(path)
  14774. );
  14775. return new Model(obj, parentModel, this.ecModel);
  14776. },
  14777. /**
  14778. * If model has option
  14779. */
  14780. isEmpty: function () {
  14781. return this.option == null;
  14782. },
  14783. restoreData: function () {},
  14784. // Pending
  14785. clone: function () {
  14786. var Ctor = this.constructor;
  14787. return new Ctor(clone(this.option));
  14788. },
  14789. setReadOnly: function (properties) {
  14790. },
  14791. // If path is null/undefined, return null/undefined.
  14792. parsePath: function(path) {
  14793. if (typeof path === 'string') {
  14794. path = path.split('.');
  14795. }
  14796. return path;
  14797. },
  14798. /**
  14799. * @param {Function} getParentMethod
  14800. * param {Array.<string>|string} path
  14801. * return {module:echarts/model/Model}
  14802. */
  14803. customizeGetParent: function (getParentMethod) {
  14804. set$1(this, 'getParent', getParentMethod);
  14805. },
  14806. isAnimationEnabled: function () {
  14807. if (!env$1.node) {
  14808. if (this.option.animation != null) {
  14809. return !!this.option.animation;
  14810. }
  14811. else if (this.parentModel) {
  14812. return this.parentModel.isAnimationEnabled();
  14813. }
  14814. }
  14815. }
  14816. };
  14817. function doGet(obj, pathArr, parentModel) {
  14818. for (var i = 0; i < pathArr.length; i++) {
  14819. // Ignore empty
  14820. if (!pathArr[i]) {
  14821. continue;
  14822. }
  14823. // obj could be number/string/... (like 0)
  14824. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14825. if (obj == null) {
  14826. break;
  14827. }
  14828. }
  14829. if (obj == null && parentModel) {
  14830. obj = parentModel.get(pathArr);
  14831. }
  14832. return obj;
  14833. }
  14834. // `path` can be null/undefined
  14835. function getParent(model, path) {
  14836. var getParentMethod = get(model, 'getParent');
  14837. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14838. }
  14839. // Enable Model.extend.
  14840. enableClassExtend(Model);
  14841. mixin$1(Model, lineStyleMixin);
  14842. mixin$1(Model, areaStyleMixin);
  14843. mixin$1(Model, textStyleMixin);
  14844. mixin$1(Model, itemStyleMixin);
  14845. var each$3 = each$1;
  14846. var isObject$2 = isObject;
  14847. /**
  14848. * If value is not array, then translate it to array.
  14849. * @param {*} value
  14850. * @return {Array} [value] or value
  14851. */
  14852. function normalizeToArray(value) {
  14853. return value instanceof Array
  14854. ? value
  14855. : value == null
  14856. ? []
  14857. : [value];
  14858. }
  14859. /**
  14860. * Sync default option between normal and emphasis like `position` and `show`
  14861. * In case some one will write code like
  14862. * label: {
  14863. * normal: {
  14864. * show: false,
  14865. * position: 'outside',
  14866. * fontSize: 18
  14867. * },
  14868. * emphasis: {
  14869. * show: true
  14870. * }
  14871. * }
  14872. * @param {Object} opt
  14873. * @param {Array.<string>} subOpts
  14874. */
  14875. function defaultEmphasis(opt, subOpts) {
  14876. if (opt) {
  14877. var emphasisOpt = opt.emphasis = opt.emphasis || {};
  14878. var normalOpt = opt.normal = opt.normal || {};
  14879. // Default emphasis option from normal
  14880. for (var i = 0, len = subOpts.length; i < len; i++) {
  14881. var subOptName = subOpts[i];
  14882. if (!emphasisOpt.hasOwnProperty(subOptName)
  14883. && normalOpt.hasOwnProperty(subOptName)
  14884. ) {
  14885. emphasisOpt[subOptName] = normalOpt[subOptName];
  14886. }
  14887. }
  14888. }
  14889. }
  14890. var TEXT_STYLE_OPTIONS = [
  14891. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  14892. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  14893. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  14894. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  14895. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  14896. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  14897. ];
  14898. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  14899. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  14900. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  14901. // // FIXME: deprecated, check and remove it.
  14902. // 'textStyle'
  14903. // ]);
  14904. /**
  14905. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  14906. * This helper method retieves value from data.
  14907. * @param {string|number|Date|Array|Object} dataItem
  14908. * @return {number|string|Date|Array.<number|string|Date>}
  14909. */
  14910. function getDataItemValue(dataItem) {
  14911. // Performance sensitive.
  14912. return dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  14913. }
  14914. /**
  14915. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  14916. * This helper method determine if dataItem has extra option besides value
  14917. * @param {string|number|Date|Array|Object} dataItem
  14918. */
  14919. function isDataItemOption(dataItem) {
  14920. return isObject$2(dataItem)
  14921. && !(dataItem instanceof Array);
  14922. // // markLine data can be array
  14923. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  14924. }
  14925. /**
  14926. * This helper method convert value in data.
  14927. * @param {string|number|Date} value
  14928. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  14929. */
  14930. function converDataValue(value, dimInfo) {
  14931. // Performance sensitive.
  14932. var dimType = dimInfo && dimInfo.type;
  14933. if (dimType === 'ordinal') {
  14934. return value;
  14935. }
  14936. if (dimType === 'time'
  14937. // spead up when using timestamp
  14938. && typeof value !== 'number'
  14939. && value != null
  14940. && value !== '-'
  14941. ) {
  14942. value = +parseDate(value);
  14943. }
  14944. // dimType defaults 'number'.
  14945. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  14946. // parse to NaN.
  14947. return (value == null || value === '')
  14948. ? NaN : +value; // If string (like '-'), using '+' parse to NaN
  14949. }
  14950. /**
  14951. * Create a model proxy to be used in tooltip for edge data, markLine data, markPoint data.
  14952. * @param {module:echarts/data/List} data
  14953. * @param {Object} opt
  14954. * @param {string} [opt.seriesIndex]
  14955. * @param {Object} [opt.name]
  14956. * @param {Object} [opt.mainType]
  14957. * @param {Object} [opt.subType]
  14958. */
  14959. // PENDING A little ugly
  14960. var dataFormatMixin = {
  14961. /**
  14962. * Get params for formatter
  14963. * @param {number} dataIndex
  14964. * @param {string} [dataType]
  14965. * @return {Object}
  14966. */
  14967. getDataParams: function (dataIndex, dataType) {
  14968. var data = this.getData(dataType);
  14969. var rawValue = this.getRawValue(dataIndex, dataType);
  14970. var rawDataIndex = data.getRawIndex(dataIndex);
  14971. var name = data.getName(dataIndex, true);
  14972. var itemOpt = data.getRawDataItem(dataIndex);
  14973. var color = data.getItemVisual(dataIndex, 'color');
  14974. return {
  14975. componentType: this.mainType,
  14976. componentSubType: this.subType,
  14977. seriesType: this.mainType === 'series' ? this.subType : null,
  14978. seriesIndex: this.seriesIndex,
  14979. seriesId: this.id,
  14980. seriesName: this.name,
  14981. name: name,
  14982. dataIndex: rawDataIndex,
  14983. data: itemOpt,
  14984. dataType: dataType,
  14985. value: rawValue,
  14986. color: color,
  14987. marker: getTooltipMarker(color),
  14988. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  14989. $vars: ['seriesName', 'name', 'value']
  14990. };
  14991. },
  14992. /**
  14993. * Format label
  14994. * @param {number} dataIndex
  14995. * @param {string} [status='normal'] 'normal' or 'emphasis'
  14996. * @param {string} [dataType]
  14997. * @param {number} [dimIndex]
  14998. * @param {string} [labelProp='label']
  14999. * @return {string}
  15000. */
  15001. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  15002. status = status || 'normal';
  15003. var data = this.getData(dataType);
  15004. var itemModel = data.getItemModel(dataIndex);
  15005. var params = this.getDataParams(dataIndex, dataType);
  15006. if (dimIndex != null && (params.value instanceof Array)) {
  15007. params.value = params.value[dimIndex];
  15008. }
  15009. var formatter = itemModel.get([labelProp || 'label', status, 'formatter']);
  15010. if (typeof formatter === 'function') {
  15011. params.status = status;
  15012. return formatter(params);
  15013. }
  15014. else if (typeof formatter === 'string') {
  15015. return formatTpl(formatter, params);
  15016. }
  15017. },
  15018. /**
  15019. * Get raw value in option
  15020. * @param {number} idx
  15021. * @param {string} [dataType]
  15022. * @return {Object}
  15023. */
  15024. getRawValue: function (idx, dataType) {
  15025. var data = this.getData(dataType);
  15026. var dataItem = data.getRawDataItem(idx);
  15027. if (dataItem != null) {
  15028. return (isObject$2(dataItem) && !(dataItem instanceof Array))
  15029. ? dataItem.value : dataItem;
  15030. }
  15031. },
  15032. /**
  15033. * Should be implemented.
  15034. * @param {number} dataIndex
  15035. * @param {boolean} [multipleSeries=false]
  15036. * @param {number} [dataType]
  15037. * @return {string} tooltip string
  15038. */
  15039. formatTooltip: noop
  15040. };
  15041. /**
  15042. * Mapping to exists for merge.
  15043. *
  15044. * @public
  15045. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  15046. * @param {Object|Array.<Object>} newCptOptions
  15047. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  15048. * index of which is the same as exists.
  15049. */
  15050. function mappingToExists(exists, newCptOptions) {
  15051. // Mapping by the order by original option (but not order of
  15052. // new option) in merge mode. Because we should ensure
  15053. // some specified index (like xAxisIndex) is consistent with
  15054. // original option, which is easy to understand, espatially in
  15055. // media query. And in most case, merge option is used to
  15056. // update partial option but not be expected to change order.
  15057. newCptOptions = (newCptOptions || []).slice();
  15058. var result = map(exists || [], function (obj, index) {
  15059. return {exist: obj};
  15060. });
  15061. // Mapping by id or name if specified.
  15062. each$3(newCptOptions, function (cptOption, index) {
  15063. if (!isObject$2(cptOption)) {
  15064. return;
  15065. }
  15066. // id has highest priority.
  15067. for (var i = 0; i < result.length; i++) {
  15068. if (!result[i].option // Consider name: two map to one.
  15069. && cptOption.id != null
  15070. && result[i].exist.id === cptOption.id + ''
  15071. ) {
  15072. result[i].option = cptOption;
  15073. newCptOptions[index] = null;
  15074. return;
  15075. }
  15076. }
  15077. for (var i = 0; i < result.length; i++) {
  15078. var exist = result[i].exist;
  15079. if (!result[i].option // Consider name: two map to one.
  15080. // Can not match when both ids exist but different.
  15081. && (exist.id == null || cptOption.id == null)
  15082. && cptOption.name != null
  15083. && !isIdInner(cptOption)
  15084. && !isIdInner(exist)
  15085. && exist.name === cptOption.name + ''
  15086. ) {
  15087. result[i].option = cptOption;
  15088. newCptOptions[index] = null;
  15089. return;
  15090. }
  15091. }
  15092. });
  15093. // Otherwise mapping by index.
  15094. each$3(newCptOptions, function (cptOption, index) {
  15095. if (!isObject$2(cptOption)) {
  15096. return;
  15097. }
  15098. var i = 0;
  15099. for (; i < result.length; i++) {
  15100. var exist = result[i].exist;
  15101. if (!result[i].option
  15102. // Existing model that already has id should be able to
  15103. // mapped to (because after mapping performed model may
  15104. // be assigned with a id, whish should not affect next
  15105. // mapping), except those has inner id.
  15106. && !isIdInner(exist)
  15107. // Caution:
  15108. // Do not overwrite id. But name can be overwritten,
  15109. // because axis use name as 'show label text'.
  15110. // 'exist' always has id and name and we dont
  15111. // need to check it.
  15112. && cptOption.id == null
  15113. ) {
  15114. result[i].option = cptOption;
  15115. break;
  15116. }
  15117. }
  15118. if (i >= result.length) {
  15119. result.push({option: cptOption});
  15120. }
  15121. });
  15122. return result;
  15123. }
  15124. /**
  15125. * Make id and name for mapping result (result of mappingToExists)
  15126. * into `keyInfo` field.
  15127. *
  15128. * @public
  15129. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  15130. * which order is the same as exists.
  15131. * @return {Array.<Object>} The input.
  15132. */
  15133. function makeIdAndName(mapResult) {
  15134. // We use this id to hash component models and view instances
  15135. // in echarts. id can be specified by user, or auto generated.
  15136. // The id generation rule ensures new view instance are able
  15137. // to mapped to old instance when setOption are called in
  15138. // no-merge mode. So we generate model id by name and plus
  15139. // type in view id.
  15140. // name can be duplicated among components, which is convenient
  15141. // to specify multi components (like series) by one name.
  15142. // Ensure that each id is distinct.
  15143. var idMap = createHashMap();
  15144. each$3(mapResult, function (item, index) {
  15145. var existCpt = item.exist;
  15146. existCpt && idMap.set(existCpt.id, item);
  15147. });
  15148. each$3(mapResult, function (item, index) {
  15149. var opt = item.option;
  15150. assert(
  15151. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  15152. 'id duplicates: ' + (opt && opt.id)
  15153. );
  15154. opt && opt.id != null && idMap.set(opt.id, item);
  15155. !item.keyInfo && (item.keyInfo = {});
  15156. });
  15157. // Make name and id.
  15158. each$3(mapResult, function (item, index) {
  15159. var existCpt = item.exist;
  15160. var opt = item.option;
  15161. var keyInfo = item.keyInfo;
  15162. if (!isObject$2(opt)) {
  15163. return;
  15164. }
  15165. // name can be overwitten. Consider case: axis.name = '20km'.
  15166. // But id generated by name will not be changed, which affect
  15167. // only in that case: setOption with 'not merge mode' and view
  15168. // instance will be recreated, which can be accepted.
  15169. keyInfo.name = opt.name != null
  15170. ? opt.name + ''
  15171. : existCpt
  15172. ? existCpt.name
  15173. : '\0-'; // name may be displayed on screen, so use '-'.
  15174. if (existCpt) {
  15175. keyInfo.id = existCpt.id;
  15176. }
  15177. else if (opt.id != null) {
  15178. keyInfo.id = opt.id + '';
  15179. }
  15180. else {
  15181. // Consider this situatoin:
  15182. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  15183. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  15184. // Series with the same name between optionA and optionB
  15185. // should be mapped.
  15186. var idNum = 0;
  15187. do {
  15188. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  15189. }
  15190. while (idMap.get(keyInfo.id));
  15191. }
  15192. idMap.set(keyInfo.id, item);
  15193. });
  15194. }
  15195. /**
  15196. * @public
  15197. * @param {Object} cptOption
  15198. * @return {boolean}
  15199. */
  15200. function isIdInner(cptOption) {
  15201. return isObject$2(cptOption)
  15202. && cptOption.id
  15203. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  15204. }
  15205. /**
  15206. * A helper for removing duplicate items between batchA and batchB,
  15207. * and in themselves, and categorize by series.
  15208. *
  15209. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  15210. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  15211. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  15212. */
  15213. function compressBatches(batchA, batchB) {
  15214. var mapA = {};
  15215. var mapB = {};
  15216. makeMap(batchA || [], mapA);
  15217. makeMap(batchB || [], mapB, mapA);
  15218. return [mapToArray(mapA), mapToArray(mapB)];
  15219. function makeMap(sourceBatch, map$$1, otherMap) {
  15220. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  15221. var seriesId = sourceBatch[i].seriesId;
  15222. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  15223. var otherDataIndices = otherMap && otherMap[seriesId];
  15224. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  15225. var dataIndex = dataIndices[j];
  15226. if (otherDataIndices && otherDataIndices[dataIndex]) {
  15227. otherDataIndices[dataIndex] = null;
  15228. }
  15229. else {
  15230. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  15231. }
  15232. }
  15233. }
  15234. }
  15235. function mapToArray(map$$1, isData) {
  15236. var result = [];
  15237. for (var i in map$$1) {
  15238. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  15239. if (isData) {
  15240. result.push(+i);
  15241. }
  15242. else {
  15243. var dataIndices = mapToArray(map$$1[i], true);
  15244. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  15245. }
  15246. }
  15247. }
  15248. return result;
  15249. }
  15250. }
  15251. /**
  15252. * @param {module:echarts/data/List} data
  15253. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  15254. * each of which can be Array or primary type.
  15255. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  15256. */
  15257. function queryDataIndex(data, payload) {
  15258. if (payload.dataIndexInside != null) {
  15259. return payload.dataIndexInside;
  15260. }
  15261. else if (payload.dataIndex != null) {
  15262. return isArray(payload.dataIndex)
  15263. ? map(payload.dataIndex, function (value) {
  15264. return data.indexOfRawIndex(value);
  15265. })
  15266. : data.indexOfRawIndex(payload.dataIndex);
  15267. }
  15268. else if (payload.name != null) {
  15269. return isArray(payload.name)
  15270. ? map(payload.name, function (value) {
  15271. return data.indexOfName(value);
  15272. })
  15273. : data.indexOfName(payload.name);
  15274. }
  15275. }
  15276. /**
  15277. * Enable property storage to any host object.
  15278. * Notice: Serialization is not supported.
  15279. *
  15280. * For example:
  15281. * var get = modelUitl.makeGetter();
  15282. *
  15283. * function some(hostObj) {
  15284. * get(hostObj)._someProperty = 1212;
  15285. * ...
  15286. * }
  15287. *
  15288. * @return {Function}
  15289. */
  15290. var makeGetter = (function () {
  15291. var index = 0;
  15292. return function () {
  15293. var key = '\0__ec_prop_getter_' + index++;
  15294. return function (hostObj) {
  15295. return hostObj[key] || (hostObj[key] = {});
  15296. };
  15297. };
  15298. })();
  15299. /**
  15300. * @param {module:echarts/model/Global} ecModel
  15301. * @param {string|Object} finder
  15302. * If string, e.g., 'geo', means {geoIndex: 0}.
  15303. * If Object, could contain some of these properties below:
  15304. * {
  15305. * seriesIndex, seriesId, seriesName,
  15306. * geoIndex, geoId, geoName,
  15307. * bmapIndex, bmapId, bmapName,
  15308. * xAxisIndex, xAxisId, xAxisName,
  15309. * yAxisIndex, yAxisId, yAxisName,
  15310. * gridIndex, gridId, gridName,
  15311. * ... (can be extended)
  15312. * }
  15313. * Each properties can be number|string|Array.<number>|Array.<string>
  15314. * For example, a finder could be
  15315. * {
  15316. * seriesIndex: 3,
  15317. * geoId: ['aa', 'cc'],
  15318. * gridName: ['xx', 'rr']
  15319. * }
  15320. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  15321. * If nothing or null/undefined specified, return nothing.
  15322. * @param {Object} [opt]
  15323. * @param {string} [opt.defaultMainType]
  15324. * @param {Array.<string>} [opt.includeMainTypes]
  15325. * @return {Object} result like:
  15326. * {
  15327. * seriesModels: [seriesModel1, seriesModel2],
  15328. * seriesModel: seriesModel1, // The first model
  15329. * geoModels: [geoModel1, geoModel2],
  15330. * geoModel: geoModel1, // The first model
  15331. * ...
  15332. * }
  15333. */
  15334. function parseFinder(ecModel, finder, opt) {
  15335. if (isString(finder)) {
  15336. var obj = {};
  15337. obj[finder + 'Index'] = 0;
  15338. finder = obj;
  15339. }
  15340. var defaultMainType = opt && opt.defaultMainType;
  15341. if (defaultMainType
  15342. && !has(finder, defaultMainType + 'Index')
  15343. && !has(finder, defaultMainType + 'Id')
  15344. && !has(finder, defaultMainType + 'Name')
  15345. ) {
  15346. finder[defaultMainType + 'Index'] = 0;
  15347. }
  15348. var result = {};
  15349. each$3(finder, function (value, key) {
  15350. var value = finder[key];
  15351. // Exclude 'dataIndex' and other illgal keys.
  15352. if (key === 'dataIndex' || key === 'dataIndexInside') {
  15353. result[key] = value;
  15354. return;
  15355. }
  15356. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  15357. var mainType = parsedKey[1];
  15358. var queryType = (parsedKey[2] || '').toLowerCase();
  15359. if (!mainType
  15360. || !queryType
  15361. || value == null
  15362. || (queryType === 'index' && value === 'none')
  15363. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  15364. ) {
  15365. return;
  15366. }
  15367. var queryParam = {mainType: mainType};
  15368. if (queryType !== 'index' || value !== 'all') {
  15369. queryParam[queryType] = value;
  15370. }
  15371. var models = ecModel.queryComponents(queryParam);
  15372. result[mainType + 'Models'] = models;
  15373. result[mainType + 'Model'] = models[0];
  15374. });
  15375. return result;
  15376. }
  15377. /**
  15378. * @see {module:echarts/data/helper/completeDimensions}
  15379. * @param {module:echarts/data/List} data
  15380. * @param {string|number} dataDim
  15381. * @return {string}
  15382. */
  15383. function dataDimToCoordDim(data, dataDim) {
  15384. var dimensions = data.dimensions;
  15385. dataDim = data.getDimension(dataDim);
  15386. for (var i = 0; i < dimensions.length; i++) {
  15387. var dimItem = data.getDimensionInfo(dimensions[i]);
  15388. if (dimItem.name === dataDim) {
  15389. return dimItem.coordDim;
  15390. }
  15391. }
  15392. }
  15393. /**
  15394. * @see {module:echarts/data/helper/completeDimensions}
  15395. * @param {module:echarts/data/List} data
  15396. * @param {string} coordDim
  15397. * @return {Array.<string>} data dimensions on the coordDim.
  15398. */
  15399. function coordDimToDataDim(data, coordDim) {
  15400. var dataDim = [];
  15401. each$3(data.dimensions, function (dimName) {
  15402. var dimItem = data.getDimensionInfo(dimName);
  15403. if (dimItem.coordDim === coordDim) {
  15404. dataDim[dimItem.coordDimIndex] = dimItem.name;
  15405. }
  15406. });
  15407. return dataDim;
  15408. }
  15409. /**
  15410. * @see {module:echarts/data/helper/completeDimensions}
  15411. * @param {module:echarts/data/List} data
  15412. * @param {string} otherDim Can be `otherDims`
  15413. * like 'label' or 'tooltip'.
  15414. * @return {Array.<string>} data dimensions on the otherDim.
  15415. */
  15416. function otherDimToDataDim(data, otherDim) {
  15417. var dataDim = [];
  15418. each$3(data.dimensions, function (dimName) {
  15419. var dimItem = data.getDimensionInfo(dimName);
  15420. var otherDims = dimItem.otherDims;
  15421. var dimIndex = otherDims[otherDim];
  15422. if (dimIndex != null && dimIndex !== false) {
  15423. dataDim[dimIndex] = dimItem.name;
  15424. }
  15425. });
  15426. return dataDim;
  15427. }
  15428. function has(obj, prop) {
  15429. return obj && obj.hasOwnProperty(prop);
  15430. }
  15431. var base = 0;
  15432. var DELIMITER = '_';
  15433. /**
  15434. * @public
  15435. * @param {string} type
  15436. * @return {string}
  15437. */
  15438. function getUID(type) {
  15439. // Considering the case of crossing js context,
  15440. // use Math.random to make id as unique as possible.
  15441. return [(type || ''), base++, Math.random()].join(DELIMITER);
  15442. }
  15443. /**
  15444. * @inner
  15445. */
  15446. function enableSubTypeDefaulter(entity) {
  15447. var subTypeDefaulters = {};
  15448. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15449. componentType = parseClassType$1(componentType);
  15450. subTypeDefaulters[componentType.main] = defaulter;
  15451. };
  15452. entity.determineSubType = function (componentType, option) {
  15453. var type = option.type;
  15454. if (!type) {
  15455. var componentTypeMain = parseClassType$1(componentType).main;
  15456. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15457. type = subTypeDefaulters[componentTypeMain](option);
  15458. }
  15459. }
  15460. return type;
  15461. };
  15462. return entity;
  15463. }
  15464. /**
  15465. * Topological travel on Activity Network (Activity On Vertices).
  15466. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15467. *
  15468. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15469. *
  15470. * If there is circle dependencey, Error will be thrown.
  15471. *
  15472. */
  15473. function enableTopologicalTravel(entity, dependencyGetter) {
  15474. /**
  15475. * @public
  15476. * @param {Array.<string>} targetNameList Target Component type list.
  15477. * Can be ['aa', 'bb', 'aa.xx']
  15478. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15479. * @param {Function} callback Params: componentType, dependencies.
  15480. * @param {Object} context Scope of callback.
  15481. */
  15482. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15483. if (!targetNameList.length) {
  15484. return;
  15485. }
  15486. var result = makeDepndencyGraph(fullNameList);
  15487. var graph = result.graph;
  15488. var stack = result.noEntryList;
  15489. var targetNameSet = {};
  15490. each$1(targetNameList, function (name) {
  15491. targetNameSet[name] = true;
  15492. });
  15493. while (stack.length) {
  15494. var currComponentType = stack.pop();
  15495. var currVertex = graph[currComponentType];
  15496. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15497. if (isInTargetNameSet) {
  15498. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15499. delete targetNameSet[currComponentType];
  15500. }
  15501. each$1(
  15502. currVertex.successor,
  15503. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15504. );
  15505. }
  15506. each$1(targetNameSet, function () {
  15507. throw new Error('Circle dependency may exists');
  15508. });
  15509. function removeEdge(succComponentType) {
  15510. graph[succComponentType].entryCount--;
  15511. if (graph[succComponentType].entryCount === 0) {
  15512. stack.push(succComponentType);
  15513. }
  15514. }
  15515. // Consider this case: legend depends on series, and we call
  15516. // chart.setOption({series: [...]}), where only series is in option.
  15517. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15518. // not be called, but only sereis.mergeOption is called. Thus legend
  15519. // have no chance to update its local record about series (like which
  15520. // name of series is available in legend).
  15521. function removeEdgeAndAdd(succComponentType) {
  15522. targetNameSet[succComponentType] = true;
  15523. removeEdge(succComponentType);
  15524. }
  15525. };
  15526. /**
  15527. * DepndencyGraph: {Object}
  15528. * key: conponentType,
  15529. * value: {
  15530. * successor: [conponentTypes...],
  15531. * originalDeps: [conponentTypes...],
  15532. * entryCount: {number}
  15533. * }
  15534. */
  15535. function makeDepndencyGraph(fullNameList) {
  15536. var graph = {};
  15537. var noEntryList = [];
  15538. each$1(fullNameList, function (name) {
  15539. var thisItem = createDependencyGraphItem(graph, name);
  15540. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15541. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15542. thisItem.entryCount = availableDeps.length;
  15543. if (thisItem.entryCount === 0) {
  15544. noEntryList.push(name);
  15545. }
  15546. each$1(availableDeps, function (dependentName) {
  15547. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15548. thisItem.predecessor.push(dependentName);
  15549. }
  15550. var thatItem = createDependencyGraphItem(graph, dependentName);
  15551. if (indexOf(thatItem.successor, dependentName) < 0) {
  15552. thatItem.successor.push(name);
  15553. }
  15554. });
  15555. });
  15556. return {graph: graph, noEntryList: noEntryList};
  15557. }
  15558. function createDependencyGraphItem(graph, name) {
  15559. if (!graph[name]) {
  15560. graph[name] = {predecessor: [], successor: []};
  15561. }
  15562. return graph[name];
  15563. }
  15564. function getAvailableDependencies(originalDeps, fullNameList) {
  15565. var availableDeps = [];
  15566. each$1(originalDeps, function (dep) {
  15567. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15568. });
  15569. return availableDeps;
  15570. }
  15571. }
  15572. // Layout helpers for each component positioning
  15573. var each$4 = each$1;
  15574. /**
  15575. * @public
  15576. */
  15577. var LOCATION_PARAMS = [
  15578. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15579. ];
  15580. /**
  15581. * @public
  15582. */
  15583. var HV_NAMES = [
  15584. ['width', 'left', 'right'],
  15585. ['height', 'top', 'bottom']
  15586. ];
  15587. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15588. var x = 0;
  15589. var y = 0;
  15590. if (maxWidth == null) {
  15591. maxWidth = Infinity;
  15592. }
  15593. if (maxHeight == null) {
  15594. maxHeight = Infinity;
  15595. }
  15596. var currentLineMaxSize = 0;
  15597. group.eachChild(function (child, idx) {
  15598. var position = child.position;
  15599. var rect = child.getBoundingRect();
  15600. var nextChild = group.childAt(idx + 1);
  15601. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15602. var nextX;
  15603. var nextY;
  15604. if (orient === 'horizontal') {
  15605. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15606. nextX = x + moveX;
  15607. // Wrap when width exceeds maxWidth or meet a `newline` group
  15608. // FIXME compare before adding gap?
  15609. if (nextX > maxWidth || child.newline) {
  15610. x = 0;
  15611. nextX = moveX;
  15612. y += currentLineMaxSize + gap;
  15613. currentLineMaxSize = rect.height;
  15614. }
  15615. else {
  15616. // FIXME: consider rect.y is not `0`?
  15617. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15618. }
  15619. }
  15620. else {
  15621. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15622. nextY = y + moveY;
  15623. // Wrap when width exceeds maxHeight or meet a `newline` group
  15624. if (nextY > maxHeight || child.newline) {
  15625. x += currentLineMaxSize + gap;
  15626. y = 0;
  15627. nextY = moveY;
  15628. currentLineMaxSize = rect.width;
  15629. }
  15630. else {
  15631. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15632. }
  15633. }
  15634. if (child.newline) {
  15635. return;
  15636. }
  15637. position[0] = x;
  15638. position[1] = y;
  15639. orient === 'horizontal'
  15640. ? (x = nextX + gap)
  15641. : (y = nextY + gap);
  15642. });
  15643. }
  15644. /**
  15645. * VBox or HBox layouting
  15646. * @param {string} orient
  15647. * @param {module:zrender/container/Group} group
  15648. * @param {number} gap
  15649. * @param {number} [width=Infinity]
  15650. * @param {number} [height=Infinity]
  15651. */
  15652. var box = boxLayout;
  15653. /**
  15654. * VBox layouting
  15655. * @param {module:zrender/container/Group} group
  15656. * @param {number} gap
  15657. * @param {number} [width=Infinity]
  15658. * @param {number} [height=Infinity]
  15659. */
  15660. var vbox = curry(boxLayout, 'vertical');
  15661. /**
  15662. * HBox layouting
  15663. * @param {module:zrender/container/Group} group
  15664. * @param {number} gap
  15665. * @param {number} [width=Infinity]
  15666. * @param {number} [height=Infinity]
  15667. */
  15668. var hbox = curry(boxLayout, 'horizontal');
  15669. /**
  15670. * If x or x2 is not specified or 'center' 'left' 'right',
  15671. * the width would be as long as possible.
  15672. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15673. * the height would be as long as possible.
  15674. *
  15675. * @param {Object} positionInfo
  15676. * @param {number|string} [positionInfo.x]
  15677. * @param {number|string} [positionInfo.y]
  15678. * @param {number|string} [positionInfo.x2]
  15679. * @param {number|string} [positionInfo.y2]
  15680. * @param {Object} containerRect {width, height}
  15681. * @param {string|number} margin
  15682. * @return {Object} {width, height}
  15683. */
  15684. function getAvailableSize(positionInfo, containerRect, margin) {
  15685. var containerWidth = containerRect.width;
  15686. var containerHeight = containerRect.height;
  15687. var x = parsePercent$1(positionInfo.x, containerWidth);
  15688. var y = parsePercent$1(positionInfo.y, containerHeight);
  15689. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  15690. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  15691. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  15692. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  15693. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  15694. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  15695. margin = normalizeCssArray$1(margin || 0);
  15696. return {
  15697. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15698. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15699. };
  15700. }
  15701. /**
  15702. * Parse position info.
  15703. *
  15704. * @param {Object} positionInfo
  15705. * @param {number|string} [positionInfo.left]
  15706. * @param {number|string} [positionInfo.top]
  15707. * @param {number|string} [positionInfo.right]
  15708. * @param {number|string} [positionInfo.bottom]
  15709. * @param {number|string} [positionInfo.width]
  15710. * @param {number|string} [positionInfo.height]
  15711. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15712. * @param {Object} containerRect
  15713. * @param {string|number} [margin]
  15714. *
  15715. * @return {module:zrender/core/BoundingRect}
  15716. */
  15717. function getLayoutRect(
  15718. positionInfo, containerRect, margin
  15719. ) {
  15720. margin = normalizeCssArray$1(margin || 0);
  15721. var containerWidth = containerRect.width;
  15722. var containerHeight = containerRect.height;
  15723. var left = parsePercent$1(positionInfo.left, containerWidth);
  15724. var top = parsePercent$1(positionInfo.top, containerHeight);
  15725. var right = parsePercent$1(positionInfo.right, containerWidth);
  15726. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15727. var width = parsePercent$1(positionInfo.width, containerWidth);
  15728. var height = parsePercent$1(positionInfo.height, containerHeight);
  15729. var verticalMargin = margin[2] + margin[0];
  15730. var horizontalMargin = margin[1] + margin[3];
  15731. var aspect = positionInfo.aspect;
  15732. // If width is not specified, calculate width from left and right
  15733. if (isNaN(width)) {
  15734. width = containerWidth - right - horizontalMargin - left;
  15735. }
  15736. if (isNaN(height)) {
  15737. height = containerHeight - bottom - verticalMargin - top;
  15738. }
  15739. if (aspect != null) {
  15740. // If width and height are not given
  15741. // 1. Graph should not exceeds the container
  15742. // 2. Aspect must be keeped
  15743. // 3. Graph should take the space as more as possible
  15744. // FIXME
  15745. // Margin is not considered, because there is no case that both
  15746. // using margin and aspect so far.
  15747. if (isNaN(width) && isNaN(height)) {
  15748. if (aspect > containerWidth / containerHeight) {
  15749. width = containerWidth * 0.8;
  15750. }
  15751. else {
  15752. height = containerHeight * 0.8;
  15753. }
  15754. }
  15755. // Calculate width or height with given aspect
  15756. if (isNaN(width)) {
  15757. width = aspect * height;
  15758. }
  15759. if (isNaN(height)) {
  15760. height = width / aspect;
  15761. }
  15762. }
  15763. // If left is not specified, calculate left from right and width
  15764. if (isNaN(left)) {
  15765. left = containerWidth - right - width - horizontalMargin;
  15766. }
  15767. if (isNaN(top)) {
  15768. top = containerHeight - bottom - height - verticalMargin;
  15769. }
  15770. // Align left and top
  15771. switch (positionInfo.left || positionInfo.right) {
  15772. case 'center':
  15773. left = containerWidth / 2 - width / 2 - margin[3];
  15774. break;
  15775. case 'right':
  15776. left = containerWidth - width - horizontalMargin;
  15777. break;
  15778. }
  15779. switch (positionInfo.top || positionInfo.bottom) {
  15780. case 'middle':
  15781. case 'center':
  15782. top = containerHeight / 2 - height / 2 - margin[0];
  15783. break;
  15784. case 'bottom':
  15785. top = containerHeight - height - verticalMargin;
  15786. break;
  15787. }
  15788. // If something is wrong and left, top, width, height are calculated as NaN
  15789. left = left || 0;
  15790. top = top || 0;
  15791. if (isNaN(width)) {
  15792. // Width may be NaN if only one value is given except width
  15793. width = containerWidth - horizontalMargin - left - (right || 0);
  15794. }
  15795. if (isNaN(height)) {
  15796. // Height may be NaN if only one value is given except height
  15797. height = containerHeight - verticalMargin - top - (bottom || 0);
  15798. }
  15799. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15800. rect.margin = margin;
  15801. return rect;
  15802. }
  15803. /**
  15804. * Position a zr element in viewport
  15805. * Group position is specified by either
  15806. * {left, top}, {right, bottom}
  15807. * If all properties exists, right and bottom will be igonred.
  15808. *
  15809. * Logic:
  15810. * 1. Scale (against origin point in parent coord)
  15811. * 2. Rotate (against origin point in parent coord)
  15812. * 3. Traslate (with el.position by this method)
  15813. * So this method only fixes the last step 'Traslate', which does not affect
  15814. * scaling and rotating.
  15815. *
  15816. * If be called repeatly with the same input el, the same result will be gotten.
  15817. *
  15818. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15819. * @param {Object} positionInfo
  15820. * @param {number|string} [positionInfo.left]
  15821. * @param {number|string} [positionInfo.top]
  15822. * @param {number|string} [positionInfo.right]
  15823. * @param {number|string} [positionInfo.bottom]
  15824. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15825. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15826. * @param {Object} containerRect
  15827. * @param {string|number} margin
  15828. * @param {Object} [opt]
  15829. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15830. * @param {Array.<number>} [opt.boundingMode='all']
  15831. * Specify how to calculate boundingRect when locating.
  15832. * 'all': Position the boundingRect that is transformed and uioned
  15833. * both itself and its descendants.
  15834. * This mode simplies confine the elements in the bounding
  15835. * of their container (e.g., using 'right: 0').
  15836. * 'raw': Position the boundingRect that is not transformed and only itself.
  15837. * This mode is useful when you want a element can overflow its
  15838. * container. (Consider a rotated circle needs to be located in a corner.)
  15839. * In this mode positionInfo.width/height can only be number.
  15840. */
  15841. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15842. var h = !opt || !opt.hv || opt.hv[0];
  15843. var v = !opt || !opt.hv || opt.hv[1];
  15844. var boundingMode = opt && opt.boundingMode || 'all';
  15845. if (!h && !v) {
  15846. return;
  15847. }
  15848. var rect;
  15849. if (boundingMode === 'raw') {
  15850. rect = el.type === 'group'
  15851. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15852. : el.getBoundingRect();
  15853. }
  15854. else {
  15855. rect = el.getBoundingRect();
  15856. if (el.needLocalTransform()) {
  15857. var transform = el.getLocalTransform();
  15858. // Notice: raw rect may be inner object of el,
  15859. // which should not be modified.
  15860. rect = rect.clone();
  15861. rect.applyTransform(transform);
  15862. }
  15863. }
  15864. // The real width and height can not be specified but calculated by the given el.
  15865. positionInfo = getLayoutRect(
  15866. defaults(
  15867. {width: rect.width, height: rect.height},
  15868. positionInfo
  15869. ),
  15870. containerRect,
  15871. margin
  15872. );
  15873. // Because 'tranlate' is the last step in transform
  15874. // (see zrender/core/Transformable#getLocalTransfrom),
  15875. // we can just only modify el.position to get final result.
  15876. var elPos = el.position;
  15877. var dx = h ? positionInfo.x - rect.x : 0;
  15878. var dy = v ? positionInfo.y - rect.y : 0;
  15879. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15880. }
  15881. /**
  15882. * @param {Object} option Contains some of the properties in HV_NAMES.
  15883. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15884. */
  15885. function sizeCalculable(option, hvIdx) {
  15886. return option[HV_NAMES[hvIdx][0]] != null
  15887. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  15888. }
  15889. /**
  15890. * Consider Case:
  15891. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15892. * through setOption or media query, using normal zrUtil.merge will cause
  15893. * {right: 0} does not take effect.
  15894. *
  15895. * @example
  15896. * ComponentModel.extend({
  15897. * init: function () {
  15898. * ...
  15899. * var inputPositionParams = layout.getLayoutParams(option);
  15900. * this.mergeOption(inputPositionParams);
  15901. * },
  15902. * mergeOption: function (newOption) {
  15903. * newOption && zrUtil.merge(thisOption, newOption, true);
  15904. * layout.mergeLayoutParam(thisOption, newOption);
  15905. * }
  15906. * });
  15907. *
  15908. * @param {Object} targetOption
  15909. * @param {Object} newOption
  15910. * @param {Object|string} [opt]
  15911. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15912. * that width (or height) should not be calculated by left and right (or top and bottom).
  15913. */
  15914. function mergeLayoutParam(targetOption, newOption, opt) {
  15915. !isObject(opt) && (opt = {});
  15916. var ignoreSize = opt.ignoreSize;
  15917. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15918. var hResult = merge$$1(HV_NAMES[0], 0);
  15919. var vResult = merge$$1(HV_NAMES[1], 1);
  15920. copy(HV_NAMES[0], targetOption, hResult);
  15921. copy(HV_NAMES[1], targetOption, vResult);
  15922. function merge$$1(names, hvIdx) {
  15923. var newParams = {};
  15924. var newValueCount = 0;
  15925. var merged = {};
  15926. var mergedValueCount = 0;
  15927. var enoughParamNumber = 2;
  15928. each$4(names, function (name) {
  15929. merged[name] = targetOption[name];
  15930. });
  15931. each$4(names, function (name) {
  15932. // Consider case: newOption.width is null, which is
  15933. // set by user for removing width setting.
  15934. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15935. hasValue(newParams, name) && newValueCount++;
  15936. hasValue(merged, name) && mergedValueCount++;
  15937. });
  15938. if (ignoreSize[hvIdx]) {
  15939. // Only one of left/right is premitted to exist.
  15940. if (hasValue(newOption, names[1])) {
  15941. merged[names[2]] = null;
  15942. }
  15943. else if (hasValue(newOption, names[2])) {
  15944. merged[names[1]] = null;
  15945. }
  15946. return merged;
  15947. }
  15948. // Case: newOption: {width: ..., right: ...},
  15949. // or targetOption: {right: ...} and newOption: {width: ...},
  15950. // There is no conflict when merged only has params count
  15951. // little than enoughParamNumber.
  15952. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15953. return merged;
  15954. }
  15955. // Case: newOption: {width: ..., right: ...},
  15956. // Than we can make sure user only want those two, and ignore
  15957. // all origin params in targetOption.
  15958. else if (newValueCount >= enoughParamNumber) {
  15959. return newParams;
  15960. }
  15961. else {
  15962. // Chose another param from targetOption by priority.
  15963. for (var i = 0; i < names.length; i++) {
  15964. var name = names[i];
  15965. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  15966. newParams[name] = targetOption[name];
  15967. break;
  15968. }
  15969. }
  15970. return newParams;
  15971. }
  15972. }
  15973. function hasProp(obj, name) {
  15974. return obj.hasOwnProperty(name);
  15975. }
  15976. function hasValue(obj, name) {
  15977. return obj[name] != null && obj[name] !== 'auto';
  15978. }
  15979. function copy(names, target, source) {
  15980. each$4(names, function (name) {
  15981. target[name] = source[name];
  15982. });
  15983. }
  15984. }
  15985. /**
  15986. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15987. * @param {Object} source
  15988. * @return {Object} Result contains those props.
  15989. */
  15990. function getLayoutParams(source) {
  15991. return copyLayoutParams({}, source);
  15992. }
  15993. /**
  15994. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15995. * @param {Object} source
  15996. * @return {Object} Result contains those props.
  15997. */
  15998. function copyLayoutParams(target, source) {
  15999. source && target && each$4(LOCATION_PARAMS, function (name) {
  16000. source.hasOwnProperty(name) && (target[name] = source[name]);
  16001. });
  16002. return target;
  16003. }
  16004. var boxLayoutMixin = {
  16005. getBoxLayoutParams: function () {
  16006. return {
  16007. left: this.get('left'),
  16008. top: this.get('top'),
  16009. right: this.get('right'),
  16010. bottom: this.get('bottom'),
  16011. width: this.get('width'),
  16012. height: this.get('height')
  16013. };
  16014. }
  16015. };
  16016. /**
  16017. * Component model
  16018. *
  16019. * @module echarts/model/Component
  16020. */
  16021. var arrayPush = Array.prototype.push;
  16022. /**
  16023. * @alias module:echarts/model/Component
  16024. * @constructor
  16025. * @param {Object} option
  16026. * @param {module:echarts/model/Model} parentModel
  16027. * @param {module:echarts/model/Model} ecModel
  16028. */
  16029. var ComponentModel = Model.extend({
  16030. type: 'component',
  16031. /**
  16032. * @readOnly
  16033. * @type {string}
  16034. */
  16035. id: '',
  16036. /**
  16037. * @readOnly
  16038. */
  16039. name: '',
  16040. /**
  16041. * @readOnly
  16042. * @type {string}
  16043. */
  16044. mainType: '',
  16045. /**
  16046. * @readOnly
  16047. * @type {string}
  16048. */
  16049. subType: '',
  16050. /**
  16051. * @readOnly
  16052. * @type {number}
  16053. */
  16054. componentIndex: 0,
  16055. /**
  16056. * @type {Object}
  16057. * @protected
  16058. */
  16059. defaultOption: null,
  16060. /**
  16061. * @type {module:echarts/model/Global}
  16062. * @readOnly
  16063. */
  16064. ecModel: null,
  16065. /**
  16066. * key: componentType
  16067. * value: Component model list, can not be null.
  16068. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16069. * @readOnly
  16070. */
  16071. dependentModels: [],
  16072. /**
  16073. * @type {string}
  16074. * @readOnly
  16075. */
  16076. uid: null,
  16077. /**
  16078. * Support merge layout params.
  16079. * Only support 'box' now (left/right/top/bottom/width/height).
  16080. * @type {string|Object} Object can be {ignoreSize: true}
  16081. * @readOnly
  16082. */
  16083. layoutMode: null,
  16084. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16085. Model.call(this, option, parentModel, ecModel, extraOpt);
  16086. this.uid = getUID('componentModel');
  16087. },
  16088. init: function (option, parentModel, ecModel, extraOpt) {
  16089. this.mergeDefaultAndTheme(option, ecModel);
  16090. },
  16091. mergeDefaultAndTheme: function (option, ecModel) {
  16092. var layoutMode = this.layoutMode;
  16093. var inputPositionParams = layoutMode
  16094. ? getLayoutParams(option) : {};
  16095. var themeModel = ecModel.getTheme();
  16096. merge(option, themeModel.get(this.mainType));
  16097. merge(option, this.getDefaultOption());
  16098. if (layoutMode) {
  16099. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16100. }
  16101. },
  16102. mergeOption: function (option, extraOpt) {
  16103. merge(this.option, option, true);
  16104. var layoutMode = this.layoutMode;
  16105. if (layoutMode) {
  16106. mergeLayoutParam(this.option, option, layoutMode);
  16107. }
  16108. },
  16109. // Hooker after init or mergeOption
  16110. optionUpdated: function (newCptOption, isInit) {},
  16111. getDefaultOption: function () {
  16112. if (!hasOwn(this, '__defaultOption')) {
  16113. var optList = [];
  16114. var Class = this.constructor;
  16115. while (Class) {
  16116. var opt = Class.prototype.defaultOption;
  16117. opt && optList.push(opt);
  16118. Class = Class.superClass;
  16119. }
  16120. var defaultOption = {};
  16121. for (var i = optList.length - 1; i >= 0; i--) {
  16122. defaultOption = merge(defaultOption, optList[i], true);
  16123. }
  16124. set$1(this, '__defaultOption', defaultOption);
  16125. }
  16126. return get(this, '__defaultOption');
  16127. },
  16128. getReferringComponents: function (mainType) {
  16129. return this.ecModel.queryComponents({
  16130. mainType: mainType,
  16131. index: this.get(mainType + 'Index', true),
  16132. id: this.get(mainType + 'Id', true)
  16133. });
  16134. }
  16135. });
  16136. // Reset ComponentModel.extend, add preConstruct.
  16137. // clazzUtil.enableClassExtend(
  16138. // ComponentModel,
  16139. // function (option, parentModel, ecModel, extraOpt) {
  16140. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16141. // zrUtil.extend(this, extraOpt);
  16142. // this.uid = componentUtil.getUID('componentModel');
  16143. // // this.setReadOnly([
  16144. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16145. // // 'dependentModels', 'componentIndex'
  16146. // // ]);
  16147. // }
  16148. // );
  16149. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16150. enableClassManagement(
  16151. ComponentModel, {registerWhenExtend: true}
  16152. );
  16153. enableSubTypeDefaulter(ComponentModel);
  16154. // Add capability of ComponentModel.topologicalTravel.
  16155. enableTopologicalTravel(ComponentModel, getDependencies);
  16156. function getDependencies(componentType) {
  16157. var deps = [];
  16158. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16159. arrayPush.apply(deps, Clazz.prototype.dependencies || []);
  16160. });
  16161. // Ensure main type
  16162. return map(deps, function (type) {
  16163. return parseClassType$1(type).main;
  16164. });
  16165. }
  16166. mixin(ComponentModel, boxLayoutMixin);
  16167. var platform = '';
  16168. // Navigator not exists in node
  16169. if (typeof navigator !== 'undefined') {
  16170. platform = navigator.platform || '';
  16171. }
  16172. var globalDefault = {
  16173. // 全图默认背景
  16174. // backgroundColor: 'rgba(0,0,0,0)',
  16175. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16176. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16177. // 浅色
  16178. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16179. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16180. // 深色
  16181. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16182. // 默认需要 Grid 配置项
  16183. // grid: {},
  16184. // 主题,主题
  16185. textStyle: {
  16186. // color: '#000',
  16187. // decoration: 'none',
  16188. // PENDING
  16189. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16190. // fontFamily: 'Arial, Verdana, sans-serif',
  16191. fontSize: 12,
  16192. fontStyle: 'normal',
  16193. fontWeight: 'normal'
  16194. },
  16195. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16196. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16197. // Default is source-over
  16198. blendMode: null,
  16199. animation: 'auto',
  16200. animationDuration: 1000,
  16201. animationDurationUpdate: 300,
  16202. animationEasing: 'exponentialOut',
  16203. animationEasingUpdate: 'cubicOut',
  16204. animationThreshold: 2000,
  16205. // Configuration for progressive/incremental rendering
  16206. progressiveThreshold: 3000,
  16207. progressive: 400,
  16208. // Threshold of if use single hover layer to optimize.
  16209. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16210. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16211. // which is unexpected.
  16212. // see example <echarts/test/heatmap-large.html>.
  16213. hoverLayerThreshold: 3000,
  16214. // See: module:echarts/scale/Time
  16215. useUTC: false
  16216. };
  16217. var colorPaletteMixin = {
  16218. clearColorPalette: function () {
  16219. set$1(this, 'colorIdx', 0);
  16220. set$1(this, 'colorNameMap', {});
  16221. },
  16222. getColorFromPalette: function (name, scope) {
  16223. scope = scope || this;
  16224. var colorIdx = get(scope, 'colorIdx') || 0;
  16225. var colorNameMap = get(scope, 'colorNameMap') || set$1(scope, 'colorNameMap', {});
  16226. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16227. if (colorNameMap.hasOwnProperty(name)) {
  16228. return colorNameMap[name];
  16229. }
  16230. var colorPalette = this.get('color', true) || [];
  16231. if (!colorPalette.length) {
  16232. return;
  16233. }
  16234. var color = colorPalette[colorIdx];
  16235. if (name) {
  16236. colorNameMap[name] = color;
  16237. }
  16238. set$1(scope, 'colorIdx', (colorIdx + 1) % colorPalette.length);
  16239. return color;
  16240. }
  16241. };
  16242. /**
  16243. * ECharts global model
  16244. *
  16245. * @module {echarts/model/Global}
  16246. */
  16247. /**
  16248. * Caution: If the mechanism should be changed some day, these cases
  16249. * should be considered:
  16250. *
  16251. * (1) In `merge option` mode, if using the same option to call `setOption`
  16252. * many times, the result should be the same (try our best to ensure that).
  16253. * (2) In `merge option` mode, if a component has no id/name specified, it
  16254. * will be merged by index, and the result sequence of the components is
  16255. * consistent to the original sequence.
  16256. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  16257. * `mergeOption` in module:echarts/model/OptionManager.
  16258. */
  16259. var each$2 = each$1;
  16260. var filter$1 = filter;
  16261. var map$1 = map;
  16262. var isArray$1 = isArray;
  16263. var indexOf$1 = indexOf;
  16264. var isObject$1 = isObject;
  16265. var OPTION_INNER_KEY = '\0_ec_inner';
  16266. /**
  16267. * @alias module:echarts/model/Global
  16268. *
  16269. * @param {Object} option
  16270. * @param {module:echarts/model/Model} parentModel
  16271. * @param {Object} theme
  16272. */
  16273. var GlobalModel = Model.extend({
  16274. constructor: GlobalModel,
  16275. init: function (option, parentModel, theme, optionManager) {
  16276. theme = theme || {};
  16277. this.option = null; // Mark as not initialized.
  16278. /**
  16279. * @type {module:echarts/model/Model}
  16280. * @private
  16281. */
  16282. this._theme = new Model(theme);
  16283. /**
  16284. * @type {module:echarts/model/OptionManager}
  16285. */
  16286. this._optionManager = optionManager;
  16287. },
  16288. setOption: function (option, optionPreprocessorFuncs) {
  16289. assert(
  16290. !(OPTION_INNER_KEY in option),
  16291. 'please use chart.getOption()'
  16292. );
  16293. this._optionManager.setOption(option, optionPreprocessorFuncs);
  16294. this.resetOption(null);
  16295. },
  16296. /**
  16297. * @param {string} type null/undefined: reset all.
  16298. * 'recreate': force recreate all.
  16299. * 'timeline': only reset timeline option
  16300. * 'media': only reset media query option
  16301. * @return {boolean} Whether option changed.
  16302. */
  16303. resetOption: function (type) {
  16304. var optionChanged = false;
  16305. var optionManager = this._optionManager;
  16306. if (!type || type === 'recreate') {
  16307. var baseOption = optionManager.mountOption(type === 'recreate');
  16308. if (!this.option || type === 'recreate') {
  16309. initBase.call(this, baseOption);
  16310. }
  16311. else {
  16312. this.restoreData();
  16313. this.mergeOption(baseOption);
  16314. }
  16315. optionChanged = true;
  16316. }
  16317. if (type === 'timeline' || type === 'media') {
  16318. this.restoreData();
  16319. }
  16320. if (!type || type === 'recreate' || type === 'timeline') {
  16321. var timelineOption = optionManager.getTimelineOption(this);
  16322. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  16323. }
  16324. if (!type || type === 'recreate' || type === 'media') {
  16325. var mediaOptions = optionManager.getMediaOption(this, this._api);
  16326. if (mediaOptions.length) {
  16327. each$2(mediaOptions, function (mediaOption) {
  16328. this.mergeOption(mediaOption, optionChanged = true);
  16329. }, this);
  16330. }
  16331. }
  16332. return optionChanged;
  16333. },
  16334. /**
  16335. * @protected
  16336. */
  16337. mergeOption: function (newOption) {
  16338. var option = this.option;
  16339. var componentsMap = this._componentsMap;
  16340. var newCptTypes = [];
  16341. // 如果不存在对应的 component model 则直接 merge
  16342. each$2(newOption, function (componentOption, mainType) {
  16343. if (componentOption == null) {
  16344. return;
  16345. }
  16346. if (!ComponentModel.hasClass(mainType)) {
  16347. option[mainType] = option[mainType] == null
  16348. ? clone(componentOption)
  16349. : merge(option[mainType], componentOption, true);
  16350. }
  16351. else {
  16352. newCptTypes.push(mainType);
  16353. }
  16354. });
  16355. // FIXME OPTION 同步是否要改回原来的
  16356. ComponentModel.topologicalTravel(
  16357. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  16358. );
  16359. this._seriesIndices = this._seriesIndices || [];
  16360. function visitComponent(mainType, dependencies) {
  16361. var newCptOptionList = normalizeToArray(newOption[mainType]);
  16362. var mapResult = mappingToExists(
  16363. componentsMap.get(mainType), newCptOptionList
  16364. );
  16365. makeIdAndName(mapResult);
  16366. // Set mainType and complete subType.
  16367. each$2(mapResult, function (item, index) {
  16368. var opt = item.option;
  16369. if (isObject$1(opt)) {
  16370. item.keyInfo.mainType = mainType;
  16371. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  16372. }
  16373. });
  16374. var dependentModels = getComponentsByTypes(
  16375. componentsMap, dependencies
  16376. );
  16377. option[mainType] = [];
  16378. componentsMap.set(mainType, []);
  16379. each$2(mapResult, function (resultItem, index) {
  16380. var componentModel = resultItem.exist;
  16381. var newCptOption = resultItem.option;
  16382. assert(
  16383. isObject$1(newCptOption) || componentModel,
  16384. 'Empty component definition'
  16385. );
  16386. // Consider where is no new option and should be merged using {},
  16387. // see removeEdgeAndAdd in topologicalTravel and
  16388. // ComponentModel.getAllClassMainTypes.
  16389. if (!newCptOption) {
  16390. componentModel.mergeOption({}, this);
  16391. componentModel.optionUpdated({}, false);
  16392. }
  16393. else {
  16394. var ComponentModelClass = ComponentModel.getClass(
  16395. mainType, resultItem.keyInfo.subType, true
  16396. );
  16397. if (componentModel && componentModel instanceof ComponentModelClass) {
  16398. componentModel.name = resultItem.keyInfo.name;
  16399. componentModel.mergeOption(newCptOption, this);
  16400. componentModel.optionUpdated(newCptOption, false);
  16401. }
  16402. else {
  16403. // PENDING Global as parent ?
  16404. var extraOpt = extend(
  16405. {
  16406. dependentModels: dependentModels,
  16407. componentIndex: index
  16408. },
  16409. resultItem.keyInfo
  16410. );
  16411. componentModel = new ComponentModelClass(
  16412. newCptOption, this, this, extraOpt
  16413. );
  16414. extend(componentModel, extraOpt);
  16415. componentModel.init(newCptOption, this, this, extraOpt);
  16416. // Call optionUpdated after init.
  16417. // newCptOption has been used as componentModel.option
  16418. // and may be merged with theme and default, so pass null
  16419. // to avoid confusion.
  16420. componentModel.optionUpdated(null, true);
  16421. }
  16422. }
  16423. componentsMap.get(mainType)[index] = componentModel;
  16424. option[mainType][index] = componentModel.option;
  16425. }, this);
  16426. // Backup series for filtering.
  16427. if (mainType === 'series') {
  16428. this._seriesIndices = createSeriesIndices(componentsMap.get('series'));
  16429. }
  16430. }
  16431. },
  16432. /**
  16433. * Get option for output (cloned option and inner info removed)
  16434. * @public
  16435. * @return {Object}
  16436. */
  16437. getOption: function () {
  16438. var option = clone(this.option);
  16439. each$2(option, function (opts, mainType) {
  16440. if (ComponentModel.hasClass(mainType)) {
  16441. var opts = normalizeToArray(opts);
  16442. for (var i = opts.length - 1; i >= 0; i--) {
  16443. // Remove options with inner id.
  16444. if (isIdInner(opts[i])) {
  16445. opts.splice(i, 1);
  16446. }
  16447. }
  16448. option[mainType] = opts;
  16449. }
  16450. });
  16451. delete option[OPTION_INNER_KEY];
  16452. return option;
  16453. },
  16454. /**
  16455. * @return {module:echarts/model/Model}
  16456. */
  16457. getTheme: function () {
  16458. return this._theme;
  16459. },
  16460. /**
  16461. * @param {string} mainType
  16462. * @param {number} [idx=0]
  16463. * @return {module:echarts/model/Component}
  16464. */
  16465. getComponent: function (mainType, idx) {
  16466. var list = this._componentsMap.get(mainType);
  16467. if (list) {
  16468. return list[idx || 0];
  16469. }
  16470. },
  16471. /**
  16472. * If none of index and id and name used, return all components with mainType.
  16473. * @param {Object} condition
  16474. * @param {string} condition.mainType
  16475. * @param {string} [condition.subType] If ignore, only query by mainType
  16476. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  16477. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  16478. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  16479. * @return {Array.<module:echarts/model/Component>}
  16480. */
  16481. queryComponents: function (condition) {
  16482. var mainType = condition.mainType;
  16483. if (!mainType) {
  16484. return [];
  16485. }
  16486. var index = condition.index;
  16487. var id = condition.id;
  16488. var name = condition.name;
  16489. var cpts = this._componentsMap.get(mainType);
  16490. if (!cpts || !cpts.length) {
  16491. return [];
  16492. }
  16493. var result;
  16494. if (index != null) {
  16495. if (!isArray$1(index)) {
  16496. index = [index];
  16497. }
  16498. result = filter$1(map$1(index, function (idx) {
  16499. return cpts[idx];
  16500. }), function (val) {
  16501. return !!val;
  16502. });
  16503. }
  16504. else if (id != null) {
  16505. var isIdArray = isArray$1(id);
  16506. result = filter$1(cpts, function (cpt) {
  16507. return (isIdArray && indexOf$1(id, cpt.id) >= 0)
  16508. || (!isIdArray && cpt.id === id);
  16509. });
  16510. }
  16511. else if (name != null) {
  16512. var isNameArray = isArray$1(name);
  16513. result = filter$1(cpts, function (cpt) {
  16514. return (isNameArray && indexOf$1(name, cpt.name) >= 0)
  16515. || (!isNameArray && cpt.name === name);
  16516. });
  16517. }
  16518. else {
  16519. // Return all components with mainType
  16520. result = cpts.slice();
  16521. }
  16522. return filterBySubType(result, condition);
  16523. },
  16524. /**
  16525. * The interface is different from queryComponents,
  16526. * which is convenient for inner usage.
  16527. *
  16528. * @usage
  16529. * var result = findComponents(
  16530. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16531. * );
  16532. * var result = findComponents(
  16533. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16534. * );
  16535. * var result = findComponents(
  16536. * {mainType: 'series'},
  16537. * function (model, index) {...}
  16538. * );
  16539. * // result like [component0, componnet1, ...]
  16540. *
  16541. * @param {Object} condition
  16542. * @param {string} condition.mainType Mandatory.
  16543. * @param {string} [condition.subType] Optional.
  16544. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  16545. * where xxx is mainType.
  16546. * If query attribute is null/undefined or has no index/id/name,
  16547. * do not filtering by query conditions, which is convenient for
  16548. * no-payload situations or when target of action is global.
  16549. * @param {Function} [condition.filter] parameter: component, return boolean.
  16550. * @return {Array.<module:echarts/model/Component>}
  16551. */
  16552. findComponents: function (condition) {
  16553. var query = condition.query;
  16554. var mainType = condition.mainType;
  16555. var queryCond = getQueryCond(query);
  16556. var result = queryCond
  16557. ? this.queryComponents(queryCond)
  16558. : this._componentsMap.get(mainType);
  16559. return doFilter(filterBySubType(result, condition));
  16560. function getQueryCond(q) {
  16561. var indexAttr = mainType + 'Index';
  16562. var idAttr = mainType + 'Id';
  16563. var nameAttr = mainType + 'Name';
  16564. return q && (
  16565. q[indexAttr] != null
  16566. || q[idAttr] != null
  16567. || q[nameAttr] != null
  16568. )
  16569. ? {
  16570. mainType: mainType,
  16571. // subType will be filtered finally.
  16572. index: q[indexAttr],
  16573. id: q[idAttr],
  16574. name: q[nameAttr]
  16575. }
  16576. : null;
  16577. }
  16578. function doFilter(res) {
  16579. return condition.filter
  16580. ? filter$1(res, condition.filter)
  16581. : res;
  16582. }
  16583. },
  16584. /**
  16585. * @usage
  16586. * eachComponent('legend', function (legendModel, index) {
  16587. * ...
  16588. * });
  16589. * eachComponent(function (componentType, model, index) {
  16590. * // componentType does not include subType
  16591. * // (componentType is 'xxx' but not 'xxx.aa')
  16592. * });
  16593. * eachComponent(
  16594. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  16595. * function (model, index) {...}
  16596. * );
  16597. * eachComponent(
  16598. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  16599. * function (model, index) {...}
  16600. * );
  16601. *
  16602. * @param {string|Object=} mainType When mainType is object, the definition
  16603. * is the same as the method 'findComponents'.
  16604. * @param {Function} cb
  16605. * @param {*} context
  16606. */
  16607. eachComponent: function (mainType, cb, context) {
  16608. var componentsMap = this._componentsMap;
  16609. if (typeof mainType === 'function') {
  16610. context = cb;
  16611. cb = mainType;
  16612. componentsMap.each(function (components, componentType) {
  16613. each$2(components, function (component, index) {
  16614. cb.call(context, componentType, component, index);
  16615. });
  16616. });
  16617. }
  16618. else if (isString(mainType)) {
  16619. each$2(componentsMap.get(mainType), cb, context);
  16620. }
  16621. else if (isObject$1(mainType)) {
  16622. var queryResult = this.findComponents(mainType);
  16623. each$2(queryResult, cb, context);
  16624. }
  16625. },
  16626. /**
  16627. * @param {string} name
  16628. * @return {Array.<module:echarts/model/Series>}
  16629. */
  16630. getSeriesByName: function (name) {
  16631. var series = this._componentsMap.get('series');
  16632. return filter$1(series, function (oneSeries) {
  16633. return oneSeries.name === name;
  16634. });
  16635. },
  16636. /**
  16637. * @param {number} seriesIndex
  16638. * @return {module:echarts/model/Series}
  16639. */
  16640. getSeriesByIndex: function (seriesIndex) {
  16641. return this._componentsMap.get('series')[seriesIndex];
  16642. },
  16643. /**
  16644. * @param {string} subType
  16645. * @return {Array.<module:echarts/model/Series>}
  16646. */
  16647. getSeriesByType: function (subType) {
  16648. var series = this._componentsMap.get('series');
  16649. return filter$1(series, function (oneSeries) {
  16650. return oneSeries.subType === subType;
  16651. });
  16652. },
  16653. /**
  16654. * @return {Array.<module:echarts/model/Series>}
  16655. */
  16656. getSeries: function () {
  16657. return this._componentsMap.get('series').slice();
  16658. },
  16659. /**
  16660. * After filtering, series may be different
  16661. * frome raw series.
  16662. *
  16663. * @param {Function} cb
  16664. * @param {*} context
  16665. */
  16666. eachSeries: function (cb, context) {
  16667. assertSeriesInitialized(this);
  16668. each$2(this._seriesIndices, function (rawSeriesIndex) {
  16669. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16670. cb.call(context, series, rawSeriesIndex);
  16671. }, this);
  16672. },
  16673. /**
  16674. * Iterate raw series before filtered.
  16675. *
  16676. * @param {Function} cb
  16677. * @param {*} context
  16678. */
  16679. eachRawSeries: function (cb, context) {
  16680. each$2(this._componentsMap.get('series'), cb, context);
  16681. },
  16682. /**
  16683. * After filtering, series may be different.
  16684. * frome raw series.
  16685. *
  16686. * @parma {string} subType
  16687. * @param {Function} cb
  16688. * @param {*} context
  16689. */
  16690. eachSeriesByType: function (subType, cb, context) {
  16691. assertSeriesInitialized(this);
  16692. each$2(this._seriesIndices, function (rawSeriesIndex) {
  16693. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16694. if (series.subType === subType) {
  16695. cb.call(context, series, rawSeriesIndex);
  16696. }
  16697. }, this);
  16698. },
  16699. /**
  16700. * Iterate raw series before filtered of given type.
  16701. *
  16702. * @parma {string} subType
  16703. * @param {Function} cb
  16704. * @param {*} context
  16705. */
  16706. eachRawSeriesByType: function (subType, cb, context) {
  16707. return each$2(this.getSeriesByType(subType), cb, context);
  16708. },
  16709. /**
  16710. * @param {module:echarts/model/Series} seriesModel
  16711. */
  16712. isSeriesFiltered: function (seriesModel) {
  16713. assertSeriesInitialized(this);
  16714. return indexOf(this._seriesIndices, seriesModel.componentIndex) < 0;
  16715. },
  16716. /**
  16717. * @return {Array.<number>}
  16718. */
  16719. getCurrentSeriesIndices: function () {
  16720. return (this._seriesIndices || []).slice();
  16721. },
  16722. /**
  16723. * @param {Function} cb
  16724. * @param {*} context
  16725. */
  16726. filterSeries: function (cb, context) {
  16727. assertSeriesInitialized(this);
  16728. var filteredSeries = filter$1(
  16729. this._componentsMap.get('series'), cb, context
  16730. );
  16731. this._seriesIndices = createSeriesIndices(filteredSeries);
  16732. },
  16733. restoreData: function () {
  16734. var componentsMap = this._componentsMap;
  16735. this._seriesIndices = createSeriesIndices(componentsMap.get('series'));
  16736. var componentTypes = [];
  16737. componentsMap.each(function (components, componentType) {
  16738. componentTypes.push(componentType);
  16739. });
  16740. ComponentModel.topologicalTravel(
  16741. componentTypes,
  16742. ComponentModel.getAllClassMainTypes(),
  16743. function (componentType, dependencies) {
  16744. each$2(componentsMap.get(componentType), function (component) {
  16745. component.restoreData();
  16746. });
  16747. }
  16748. );
  16749. }
  16750. });
  16751. /**
  16752. * @inner
  16753. */
  16754. function mergeTheme(option, theme) {
  16755. each$1(theme, function (themeItem, name) {
  16756. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  16757. if (!ComponentModel.hasClass(name)) {
  16758. if (typeof themeItem === 'object') {
  16759. option[name] = !option[name]
  16760. ? clone(themeItem)
  16761. : merge(option[name], themeItem, false);
  16762. }
  16763. else {
  16764. if (option[name] == null) {
  16765. option[name] = themeItem;
  16766. }
  16767. }
  16768. }
  16769. });
  16770. }
  16771. function initBase(baseOption) {
  16772. baseOption = baseOption;
  16773. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  16774. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  16775. this.option = {};
  16776. this.option[OPTION_INNER_KEY] = 1;
  16777. /**
  16778. * Init with series: [], in case of calling findSeries method
  16779. * before series initialized.
  16780. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16781. * @private
  16782. */
  16783. this._componentsMap = createHashMap({series: []});
  16784. /**
  16785. * Mapping between filtered series list and raw series list.
  16786. * key: filtered series indices, value: raw series indices.
  16787. * @type {Array.<nubmer>}
  16788. * @private
  16789. */
  16790. this._seriesIndices = null;
  16791. mergeTheme(baseOption, this._theme.option);
  16792. // TODO Needs clone when merging to the unexisted property
  16793. merge(baseOption, globalDefault, false);
  16794. this.mergeOption(baseOption);
  16795. }
  16796. /**
  16797. * @inner
  16798. * @param {Array.<string>|string} types model types
  16799. * @return {Object} key: {string} type, value: {Array.<Object>} models
  16800. */
  16801. function getComponentsByTypes(componentsMap, types) {
  16802. if (!isArray(types)) {
  16803. types = types ? [types] : [];
  16804. }
  16805. var ret = {};
  16806. each$2(types, function (type) {
  16807. ret[type] = (componentsMap.get(type) || []).slice();
  16808. });
  16809. return ret;
  16810. }
  16811. /**
  16812. * @inner
  16813. */
  16814. function determineSubType(mainType, newCptOption, existComponent) {
  16815. var subType = newCptOption.type
  16816. ? newCptOption.type
  16817. : existComponent
  16818. ? existComponent.subType
  16819. // Use determineSubType only when there is no existComponent.
  16820. : ComponentModel.determineSubType(mainType, newCptOption);
  16821. // tooltip, markline, markpoint may always has no subType
  16822. return subType;
  16823. }
  16824. /**
  16825. * @inner
  16826. */
  16827. function createSeriesIndices(seriesModels) {
  16828. return map$1(seriesModels, function (series) {
  16829. return series.componentIndex;
  16830. }) || [];
  16831. }
  16832. /**
  16833. * @inner
  16834. */
  16835. function filterBySubType(components, condition) {
  16836. // Using hasOwnProperty for restrict. Consider
  16837. // subType is undefined in user payload.
  16838. return condition.hasOwnProperty('subType')
  16839. ? filter$1(components, function (cpt) {
  16840. return cpt.subType === condition.subType;
  16841. })
  16842. : components;
  16843. }
  16844. /**
  16845. * @inner
  16846. */
  16847. function assertSeriesInitialized(ecModel) {
  16848. // Components that use _seriesIndices should depends on series component,
  16849. // which make sure that their initialization is after series.
  16850. if (__DEV__) {
  16851. if (!ecModel._seriesIndices) {
  16852. throw new Error('Option should contains series.');
  16853. }
  16854. }
  16855. }
  16856. mixin(GlobalModel, colorPaletteMixin);
  16857. var echartsAPIList = [
  16858. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  16859. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  16860. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  16861. ];
  16862. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  16863. function ExtensionAPI(chartInstance) {
  16864. each$1(echartsAPIList, function (name) {
  16865. this[name] = bind(chartInstance[name], chartInstance);
  16866. }, this);
  16867. }
  16868. var coordinateSystemCreators = {};
  16869. function CoordinateSystemManager() {
  16870. this._coordinateSystems = [];
  16871. }
  16872. CoordinateSystemManager.prototype = {
  16873. constructor: CoordinateSystemManager,
  16874. create: function (ecModel, api) {
  16875. var coordinateSystems = [];
  16876. each$1(coordinateSystemCreators, function (creater, type) {
  16877. var list = creater.create(ecModel, api);
  16878. coordinateSystems = coordinateSystems.concat(list || []);
  16879. });
  16880. this._coordinateSystems = coordinateSystems;
  16881. },
  16882. update: function (ecModel, api) {
  16883. each$1(this._coordinateSystems, function (coordSys) {
  16884. // FIXME MUST have
  16885. coordSys.update && coordSys.update(ecModel, api);
  16886. });
  16887. },
  16888. getCoordinateSystems: function () {
  16889. return this._coordinateSystems.slice();
  16890. }
  16891. };
  16892. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  16893. coordinateSystemCreators[type] = coordinateSystemCreator;
  16894. };
  16895. CoordinateSystemManager.get = function (type) {
  16896. return coordinateSystemCreators[type];
  16897. };
  16898. /**
  16899. * ECharts option manager
  16900. *
  16901. * @module {echarts/model/OptionManager}
  16902. */
  16903. var each$5 = each$1;
  16904. var clone$2 = clone;
  16905. var map$2 = map;
  16906. var merge$1 = merge;
  16907. var QUERY_REG = /^(min|max)?(.+)$/;
  16908. /**
  16909. * TERM EXPLANATIONS:
  16910. *
  16911. * [option]:
  16912. *
  16913. * An object that contains definitions of components. For example:
  16914. * var option = {
  16915. * title: {...},
  16916. * legend: {...},
  16917. * visualMap: {...},
  16918. * series: [
  16919. * {data: [...]},
  16920. * {data: [...]},
  16921. * ...
  16922. * ]
  16923. * };
  16924. *
  16925. * [rawOption]:
  16926. *
  16927. * An object input to echarts.setOption. 'rawOption' may be an
  16928. * 'option', or may be an object contains multi-options. For example:
  16929. * var option = {
  16930. * baseOption: {
  16931. * title: {...},
  16932. * legend: {...},
  16933. * series: [
  16934. * {data: [...]},
  16935. * {data: [...]},
  16936. * ...
  16937. * ]
  16938. * },
  16939. * timeline: {...},
  16940. * options: [
  16941. * {title: {...}, series: {data: [...]}},
  16942. * {title: {...}, series: {data: [...]}},
  16943. * ...
  16944. * ],
  16945. * media: [
  16946. * {
  16947. * query: {maxWidth: 320},
  16948. * option: {series: {x: 20}, visualMap: {show: false}}
  16949. * },
  16950. * {
  16951. * query: {minWidth: 320, maxWidth: 720},
  16952. * option: {series: {x: 500}, visualMap: {show: true}}
  16953. * },
  16954. * {
  16955. * option: {series: {x: 1200}, visualMap: {show: true}}
  16956. * }
  16957. * ]
  16958. * };
  16959. *
  16960. * @alias module:echarts/model/OptionManager
  16961. * @param {module:echarts/ExtensionAPI} api
  16962. */
  16963. function OptionManager(api) {
  16964. /**
  16965. * @private
  16966. * @type {module:echarts/ExtensionAPI}
  16967. */
  16968. this._api = api;
  16969. /**
  16970. * @private
  16971. * @type {Array.<number>}
  16972. */
  16973. this._timelineOptions = [];
  16974. /**
  16975. * @private
  16976. * @type {Array.<Object>}
  16977. */
  16978. this._mediaList = [];
  16979. /**
  16980. * @private
  16981. * @type {Object}
  16982. */
  16983. this._mediaDefault;
  16984. /**
  16985. * -1, means default.
  16986. * empty means no media.
  16987. * @private
  16988. * @type {Array.<number>}
  16989. */
  16990. this._currentMediaIndices = [];
  16991. /**
  16992. * @private
  16993. * @type {Object}
  16994. */
  16995. this._optionBackup;
  16996. /**
  16997. * @private
  16998. * @type {Object}
  16999. */
  17000. this._newBaseOption;
  17001. }
  17002. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17003. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17004. // rawOption cloned and backuped when timeline changed, which does no
  17005. // good to performance. What's more, that both timeline and setOption
  17006. // method supply 'notMerge' brings complex and some problems.
  17007. // Consider this case:
  17008. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17009. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17010. OptionManager.prototype = {
  17011. constructor: OptionManager,
  17012. /**
  17013. * @public
  17014. * @param {Object} rawOption Raw option.
  17015. * @param {module:echarts/model/Global} ecModel
  17016. * @param {Array.<Function>} optionPreprocessorFuncs
  17017. * @return {Object} Init option
  17018. */
  17019. setOption: function (rawOption, optionPreprocessorFuncs) {
  17020. rawOption = clone$2(rawOption, true);
  17021. // FIXME
  17022. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17023. var oldOptionBackup = this._optionBackup;
  17024. var newParsedOption = parseRawOption.call(
  17025. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17026. );
  17027. this._newBaseOption = newParsedOption.baseOption;
  17028. // For setOption at second time (using merge mode);
  17029. if (oldOptionBackup) {
  17030. // Only baseOption can be merged.
  17031. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17032. // For simplicity, timeline options and media options do not support merge,
  17033. // that is, if you `setOption` twice and both has timeline options, the latter
  17034. // timeline opitons will not be merged to the formers, but just substitude them.
  17035. if (newParsedOption.timelineOptions.length) {
  17036. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17037. }
  17038. if (newParsedOption.mediaList.length) {
  17039. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17040. }
  17041. if (newParsedOption.mediaDefault) {
  17042. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17043. }
  17044. }
  17045. else {
  17046. this._optionBackup = newParsedOption;
  17047. }
  17048. },
  17049. /**
  17050. * @param {boolean} isRecreate
  17051. * @return {Object}
  17052. */
  17053. mountOption: function (isRecreate) {
  17054. var optionBackup = this._optionBackup;
  17055. // TODO
  17056. // 如果没有reset功能则不clone。
  17057. this._timelineOptions = map$2(optionBackup.timelineOptions, clone$2);
  17058. this._mediaList = map$2(optionBackup.mediaList, clone$2);
  17059. this._mediaDefault = clone$2(optionBackup.mediaDefault);
  17060. this._currentMediaIndices = [];
  17061. return clone$2(isRecreate
  17062. // this._optionBackup.baseOption, which is created at the first `setOption`
  17063. // called, and is merged into every new option by inner method `mergeOption`
  17064. // each time `setOption` called, can be only used in `isRecreate`, because
  17065. // its reliability is under suspicion. In other cases option merge is
  17066. // performed by `model.mergeOption`.
  17067. ? optionBackup.baseOption : this._newBaseOption
  17068. );
  17069. },
  17070. /**
  17071. * @param {module:echarts/model/Global} ecModel
  17072. * @return {Object}
  17073. */
  17074. getTimelineOption: function (ecModel) {
  17075. var option;
  17076. var timelineOptions = this._timelineOptions;
  17077. if (timelineOptions.length) {
  17078. // getTimelineOption can only be called after ecModel inited,
  17079. // so we can get currentIndex from timelineModel.
  17080. var timelineModel = ecModel.getComponent('timeline');
  17081. if (timelineModel) {
  17082. option = clone$2(
  17083. timelineOptions[timelineModel.getCurrentIndex()],
  17084. true
  17085. );
  17086. }
  17087. }
  17088. return option;
  17089. },
  17090. /**
  17091. * @param {module:echarts/model/Global} ecModel
  17092. * @return {Array.<Object>}
  17093. */
  17094. getMediaOption: function (ecModel) {
  17095. var ecWidth = this._api.getWidth();
  17096. var ecHeight = this._api.getHeight();
  17097. var mediaList = this._mediaList;
  17098. var mediaDefault = this._mediaDefault;
  17099. var indices = [];
  17100. var result = [];
  17101. // No media defined.
  17102. if (!mediaList.length && !mediaDefault) {
  17103. return result;
  17104. }
  17105. // Multi media may be applied, the latter defined media has higher priority.
  17106. for (var i = 0, len = mediaList.length; i < len; i++) {
  17107. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17108. indices.push(i);
  17109. }
  17110. }
  17111. // FIXME
  17112. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17113. if (!indices.length && mediaDefault) {
  17114. indices = [-1];
  17115. }
  17116. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17117. result = map$2(indices, function (index) {
  17118. return clone$2(
  17119. index === -1 ? mediaDefault.option : mediaList[index].option
  17120. );
  17121. });
  17122. }
  17123. // Otherwise return nothing.
  17124. this._currentMediaIndices = indices;
  17125. return result;
  17126. }
  17127. };
  17128. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17129. var timelineOptions = [];
  17130. var mediaList = [];
  17131. var mediaDefault;
  17132. var baseOption;
  17133. // Compatible with ec2.
  17134. var timelineOpt = rawOption.timeline;
  17135. if (rawOption.baseOption) {
  17136. baseOption = rawOption.baseOption;
  17137. }
  17138. // For timeline
  17139. if (timelineOpt || rawOption.options) {
  17140. baseOption = baseOption || {};
  17141. timelineOptions = (rawOption.options || []).slice();
  17142. }
  17143. // For media query
  17144. if (rawOption.media) {
  17145. baseOption = baseOption || {};
  17146. var media = rawOption.media;
  17147. each$5(media, function (singleMedia) {
  17148. if (singleMedia && singleMedia.option) {
  17149. if (singleMedia.query) {
  17150. mediaList.push(singleMedia);
  17151. }
  17152. else if (!mediaDefault) {
  17153. // Use the first media default.
  17154. mediaDefault = singleMedia;
  17155. }
  17156. }
  17157. });
  17158. }
  17159. // For normal option
  17160. if (!baseOption) {
  17161. baseOption = rawOption;
  17162. }
  17163. // Set timelineOpt to baseOption in ec3,
  17164. // which is convenient for merge option.
  17165. if (!baseOption.timeline) {
  17166. baseOption.timeline = timelineOpt;
  17167. }
  17168. // Preprocess.
  17169. each$5([baseOption].concat(timelineOptions)
  17170. .concat(map(mediaList, function (media) {
  17171. return media.option;
  17172. })),
  17173. function (option) {
  17174. each$5(optionPreprocessorFuncs, function (preProcess) {
  17175. preProcess(option, isNew);
  17176. });
  17177. }
  17178. );
  17179. return {
  17180. baseOption: baseOption,
  17181. timelineOptions: timelineOptions,
  17182. mediaDefault: mediaDefault,
  17183. mediaList: mediaList
  17184. };
  17185. }
  17186. /**
  17187. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17188. * Support: width, height, aspectRatio
  17189. * Can use max or min as prefix.
  17190. */
  17191. function applyMediaQuery(query, ecWidth, ecHeight) {
  17192. var realMap = {
  17193. width: ecWidth,
  17194. height: ecHeight,
  17195. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17196. };
  17197. var applicatable = true;
  17198. each$1(query, function (value, attr) {
  17199. var matched = attr.match(QUERY_REG);
  17200. if (!matched || !matched[1] || !matched[2]) {
  17201. return;
  17202. }
  17203. var operator = matched[1];
  17204. var realAttr = matched[2].toLowerCase();
  17205. if (!compare(realMap[realAttr], value, operator)) {
  17206. applicatable = false;
  17207. }
  17208. });
  17209. return applicatable;
  17210. }
  17211. function compare(real, expect, operator) {
  17212. if (operator === 'min') {
  17213. return real >= expect;
  17214. }
  17215. else if (operator === 'max') {
  17216. return real <= expect;
  17217. }
  17218. else { // Equals
  17219. return real === expect;
  17220. }
  17221. }
  17222. function indicesEquals(indices1, indices2) {
  17223. // indices is always order by asc and has only finite number.
  17224. return indices1.join(',') === indices2.join(',');
  17225. }
  17226. /**
  17227. * Consider case:
  17228. * `chart.setOption(opt1);`
  17229. * Then user do some interaction like dataZoom, dataView changing.
  17230. * `chart.setOption(opt2);`
  17231. * Then user press 'reset button' in toolbox.
  17232. *
  17233. * After doing that all of the interaction effects should be reset, the
  17234. * chart should be the same as the result of invoke
  17235. * `chart.setOption(opt1); chart.setOption(opt2);`.
  17236. *
  17237. * Although it is not able ensure that
  17238. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  17239. * `chart.setOption(merge(opt1, opt2));` exactly,
  17240. * this might be the only simple way to implement that feature.
  17241. *
  17242. * MEMO: We've considered some other approaches:
  17243. * 1. Each model handle its self restoration but not uniform treatment.
  17244. * (Too complex in logic and error-prone)
  17245. * 2. Use a shadow ecModel. (Performace expensive)
  17246. */
  17247. function mergeOption(oldOption, newOption) {
  17248. newOption = newOption || {};
  17249. each$5(newOption, function (newCptOpt, mainType) {
  17250. if (newCptOpt == null) {
  17251. return;
  17252. }
  17253. var oldCptOpt = oldOption[mainType];
  17254. if (!ComponentModel.hasClass(mainType)) {
  17255. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  17256. }
  17257. else {
  17258. newCptOpt = normalizeToArray(newCptOpt);
  17259. oldCptOpt = normalizeToArray(oldCptOpt);
  17260. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  17261. oldOption[mainType] = map$2(mapResult, function (item) {
  17262. return (item.option && item.exist)
  17263. ? merge$1(item.exist, item.option, true)
  17264. : (item.exist || item.option);
  17265. });
  17266. }
  17267. });
  17268. }
  17269. var each$6 = each$1;
  17270. var isObject$3 = isObject;
  17271. var POSSIBLE_STYLES = [
  17272. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  17273. 'chordStyle', 'label', 'labelLine'
  17274. ];
  17275. function compatItemStyle(opt) {
  17276. var itemStyleOpt = opt && opt.itemStyle;
  17277. if (!itemStyleOpt) {
  17278. return;
  17279. }
  17280. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17281. var styleName = POSSIBLE_STYLES[i];
  17282. var normalItemStyleOpt = itemStyleOpt.normal;
  17283. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17284. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17285. opt[styleName] = opt[styleName] || {};
  17286. if (!opt[styleName].normal) {
  17287. opt[styleName].normal = normalItemStyleOpt[styleName];
  17288. }
  17289. else {
  17290. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17291. }
  17292. normalItemStyleOpt[styleName] = null;
  17293. }
  17294. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17295. opt[styleName] = opt[styleName] || {};
  17296. if (!opt[styleName].emphasis) {
  17297. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17298. }
  17299. else {
  17300. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17301. }
  17302. emphasisItemStyleOpt[styleName] = null;
  17303. }
  17304. }
  17305. }
  17306. function compatTextStyle(opt, propName) {
  17307. var labelOptSingle = isObject$3(opt) && opt[propName];
  17308. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  17309. if (textStyle) {
  17310. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17311. var propName = TEXT_STYLE_OPTIONS[i];
  17312. if (textStyle.hasOwnProperty(propName)) {
  17313. labelOptSingle[propName] = textStyle[propName];
  17314. }
  17315. }
  17316. }
  17317. }
  17318. function compatLabelTextStyle(labelOpt) {
  17319. if (isObject$3(labelOpt)) {
  17320. compatTextStyle(labelOpt, 'normal');
  17321. compatTextStyle(labelOpt, 'emphasis');
  17322. }
  17323. }
  17324. function processSeries(seriesOpt) {
  17325. if (!isObject$3(seriesOpt)) {
  17326. return;
  17327. }
  17328. compatItemStyle(seriesOpt);
  17329. compatLabelTextStyle(seriesOpt.label);
  17330. // treemap
  17331. compatLabelTextStyle(seriesOpt.upperLabel);
  17332. // graph
  17333. compatLabelTextStyle(seriesOpt.edgeLabel);
  17334. var markPoint = seriesOpt.markPoint;
  17335. compatItemStyle(markPoint);
  17336. compatLabelTextStyle(markPoint && markPoint.label);
  17337. var markLine = seriesOpt.markLine;
  17338. compatItemStyle(seriesOpt.markLine);
  17339. compatLabelTextStyle(markLine && markLine.label);
  17340. var markArea = seriesOpt.markArea;
  17341. compatLabelTextStyle(markArea && markArea.label);
  17342. // For gauge
  17343. compatTextStyle(seriesOpt, 'axisLabel');
  17344. compatTextStyle(seriesOpt, 'title');
  17345. compatTextStyle(seriesOpt, 'detail');
  17346. var data = seriesOpt.data;
  17347. if (data) {
  17348. for (var i = 0; i < data.length; i++) {
  17349. compatItemStyle(data[i]);
  17350. compatLabelTextStyle(data[i] && data[i].label);
  17351. }
  17352. }
  17353. // mark point data
  17354. var markPoint = seriesOpt.markPoint;
  17355. if (markPoint && markPoint.data) {
  17356. var mpData = markPoint.data;
  17357. for (var i = 0; i < mpData.length; i++) {
  17358. compatItemStyle(mpData[i]);
  17359. compatLabelTextStyle(mpData[i] && mpData[i].label);
  17360. }
  17361. }
  17362. // mark line data
  17363. var markLine = seriesOpt.markLine;
  17364. if (markLine && markLine.data) {
  17365. var mlData = markLine.data;
  17366. for (var i = 0; i < mlData.length; i++) {
  17367. if (isArray(mlData[i])) {
  17368. compatItemStyle(mlData[i][0]);
  17369. compatLabelTextStyle(mlData[i][0] && mlData[i][0].label);
  17370. compatItemStyle(mlData[i][1]);
  17371. compatLabelTextStyle(mlData[i][1] && mlData[i][1].label);
  17372. }
  17373. else {
  17374. compatItemStyle(mlData[i]);
  17375. compatLabelTextStyle(mlData[i] && mlData[i].label);
  17376. }
  17377. }
  17378. }
  17379. }
  17380. function toArr(o) {
  17381. return isArray(o) ? o : o ? [o] : [];
  17382. }
  17383. function toObj(o) {
  17384. return (isArray(o) ? o[0] : o) || {};
  17385. }
  17386. var compatStyle = function (option, isTheme) {
  17387. each$6(toArr(option.series), function (seriesOpt) {
  17388. isObject$3(seriesOpt) && processSeries(seriesOpt);
  17389. });
  17390. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17391. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17392. each$6(
  17393. axes,
  17394. function (axisName) {
  17395. each$6(toArr(option[axisName]), function (axisOpt) {
  17396. if (axisOpt) {
  17397. compatTextStyle(axisOpt, 'axisLabel');
  17398. compatTextStyle(axisOpt.axisPointer, 'label');
  17399. }
  17400. });
  17401. }
  17402. );
  17403. each$6(toArr(option.parallel), function (parallelOpt) {
  17404. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17405. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17406. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17407. });
  17408. each$6(toArr(option.calendar), function (calendarOpt) {
  17409. compatTextStyle(calendarOpt, 'dayLabel');
  17410. compatTextStyle(calendarOpt, 'monthLabel');
  17411. compatTextStyle(calendarOpt, 'yearLabel');
  17412. });
  17413. // radar.name.textStyle
  17414. each$6(toArr(option.radar), function (radarOpt) {
  17415. compatTextStyle(radarOpt, 'name');
  17416. });
  17417. each$6(toArr(option.geo), function (geoOpt) {
  17418. if (isObject$3(geoOpt)) {
  17419. compatLabelTextStyle(geoOpt.label);
  17420. each$6(toArr(geoOpt.regions), function (regionObj) {
  17421. compatLabelTextStyle(regionObj.label);
  17422. });
  17423. }
  17424. });
  17425. compatLabelTextStyle(toObj(option.timeline).label);
  17426. compatTextStyle(toObj(option.axisPointer), 'label');
  17427. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  17428. };
  17429. // Compatitable with 2.0
  17430. function get$1(opt, path) {
  17431. path = path.split(',');
  17432. var obj = opt;
  17433. for (var i = 0; i < path.length; i++) {
  17434. obj = obj && obj[path[i]];
  17435. if (obj == null) {
  17436. break;
  17437. }
  17438. }
  17439. return obj;
  17440. }
  17441. function set$2(opt, path, val, overwrite) {
  17442. path = path.split(',');
  17443. var obj = opt;
  17444. var key;
  17445. for (var i = 0; i < path.length - 1; i++) {
  17446. key = path[i];
  17447. if (obj[key] == null) {
  17448. obj[key] = {};
  17449. }
  17450. obj = obj[key];
  17451. }
  17452. if (overwrite || obj[path[i]] == null) {
  17453. obj[path[i]] = val;
  17454. }
  17455. }
  17456. function compatLayoutProperties(option) {
  17457. each$1(LAYOUT_PROPERTIES, function (prop) {
  17458. if (prop[0] in option && !(prop[1] in option)) {
  17459. option[prop[1]] = option[prop[0]];
  17460. }
  17461. });
  17462. }
  17463. var LAYOUT_PROPERTIES = [
  17464. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  17465. ];
  17466. var COMPATITABLE_COMPONENTS = [
  17467. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  17468. ];
  17469. var COMPATITABLE_SERIES = [
  17470. 'bar', 'boxplot', 'candlestick', 'chord', 'effectScatter',
  17471. 'funnel', 'gauge', 'lines', 'graph', 'heatmap', 'line', 'map', 'parallel',
  17472. 'pie', 'radar', 'sankey', 'scatter', 'treemap'
  17473. ];
  17474. var backwardCompat = function (option, isTheme) {
  17475. compatStyle(option, isTheme);
  17476. // Make sure series array for model initialization.
  17477. option.series = normalizeToArray(option.series);
  17478. each$1(option.series, function (seriesOpt) {
  17479. if (!isObject(seriesOpt)) {
  17480. return;
  17481. }
  17482. var seriesType = seriesOpt.type;
  17483. if (seriesType === 'pie' || seriesType === 'gauge') {
  17484. if (seriesOpt.clockWise != null) {
  17485. seriesOpt.clockwise = seriesOpt.clockWise;
  17486. }
  17487. }
  17488. if (seriesType === 'gauge') {
  17489. var pointerColor = get$1(seriesOpt, 'pointer.color');
  17490. pointerColor != null
  17491. && set$2(seriesOpt, 'itemStyle.normal.color', pointerColor);
  17492. }
  17493. for (var i = 0; i < COMPATITABLE_SERIES.length; i++) {
  17494. if (COMPATITABLE_SERIES[i] === seriesOpt.type) {
  17495. compatLayoutProperties(seriesOpt);
  17496. break;
  17497. }
  17498. }
  17499. });
  17500. // dataRange has changed to visualMap
  17501. if (option.dataRange) {
  17502. option.visualMap = option.dataRange;
  17503. }
  17504. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  17505. var options = option[componentName];
  17506. if (options) {
  17507. if (!isArray(options)) {
  17508. options = [options];
  17509. }
  17510. each$1(options, function (option) {
  17511. compatLayoutProperties(option);
  17512. });
  17513. }
  17514. });
  17515. };
  17516. var SeriesModel = ComponentModel.extend({
  17517. type: 'series.__base__',
  17518. /**
  17519. * @readOnly
  17520. */
  17521. seriesIndex: 0,
  17522. // coodinateSystem will be injected in the echarts/CoordinateSystem
  17523. coordinateSystem: null,
  17524. /**
  17525. * @type {Object}
  17526. * @protected
  17527. */
  17528. defaultOption: null,
  17529. /**
  17530. * Data provided for legend
  17531. * @type {Function}
  17532. */
  17533. // PENDING
  17534. legendDataProvider: null,
  17535. /**
  17536. * Access path of color for visual
  17537. */
  17538. visualColorAccessPath: 'itemStyle.normal.color',
  17539. /**
  17540. * Support merge layout params.
  17541. * Only support 'box' now (left/right/top/bottom/width/height).
  17542. * @type {string|Object} Object can be {ignoreSize: true}
  17543. * @readOnly
  17544. */
  17545. layoutMode: null,
  17546. init: function (option, parentModel, ecModel, extraOpt) {
  17547. /**
  17548. * @type {number}
  17549. * @readOnly
  17550. */
  17551. this.seriesIndex = this.componentIndex;
  17552. this.mergeDefaultAndTheme(option, ecModel);
  17553. var data = this.getInitialData(option, ecModel);
  17554. if (__DEV__) {
  17555. assert(data, 'getInitialData returned invalid data.');
  17556. }
  17557. /**
  17558. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  17559. * @private
  17560. */
  17561. set$1(this, 'dataBeforeProcessed', data);
  17562. // If we reverse the order (make data firstly, and then make
  17563. // dataBeforeProcessed by cloneShallow), cloneShallow will
  17564. // cause data.graph.data !== data when using
  17565. // module:echarts/data/Graph or module:echarts/data/Tree.
  17566. // See module:echarts/data/helper/linkList
  17567. this.restoreData();
  17568. },
  17569. /**
  17570. * Util for merge default and theme to option
  17571. * @param {Object} option
  17572. * @param {module:echarts/model/Global} ecModel
  17573. */
  17574. mergeDefaultAndTheme: function (option, ecModel) {
  17575. var layoutMode = this.layoutMode;
  17576. var inputPositionParams = layoutMode
  17577. ? getLayoutParams(option) : {};
  17578. // Backward compat: using subType on theme.
  17579. // But if name duplicate between series subType
  17580. // (for example: parallel) add component mainType,
  17581. // add suffix 'Series'.
  17582. var themeSubType = this.subType;
  17583. if (ComponentModel.hasClass(themeSubType)) {
  17584. themeSubType += 'Series';
  17585. }
  17586. merge(
  17587. option,
  17588. ecModel.getTheme().get(this.subType)
  17589. );
  17590. merge(option, this.getDefaultOption());
  17591. // Default label emphasis `show`
  17592. defaultEmphasis(option.label, ['show']);
  17593. this.fillDataTextStyle(option.data);
  17594. if (layoutMode) {
  17595. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17596. }
  17597. },
  17598. mergeOption: function (newSeriesOption, ecModel) {
  17599. newSeriesOption = merge(this.option, newSeriesOption, true);
  17600. this.fillDataTextStyle(newSeriesOption.data);
  17601. var layoutMode = this.layoutMode;
  17602. if (layoutMode) {
  17603. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  17604. }
  17605. var data = this.getInitialData(newSeriesOption, ecModel);
  17606. // TODO Merge data?
  17607. if (data) {
  17608. set$1(this, 'data', data);
  17609. set$1(this, 'dataBeforeProcessed', data.cloneShallow());
  17610. }
  17611. },
  17612. fillDataTextStyle: function (data) {
  17613. // Default data label emphasis `show`
  17614. // FIXME Tree structure data ?
  17615. // FIXME Performance ?
  17616. if (data) {
  17617. var props = ['show'];
  17618. for (var i = 0; i < data.length; i++) {
  17619. if (data[i] && data[i].label) {
  17620. defaultEmphasis(data[i].label, props);
  17621. }
  17622. }
  17623. }
  17624. },
  17625. /**
  17626. * Init a data structure from data related option in series
  17627. * Must be overwritten
  17628. */
  17629. getInitialData: function () {},
  17630. /**
  17631. * @param {string} [dataType]
  17632. * @return {module:echarts/data/List}
  17633. */
  17634. getData: function (dataType) {
  17635. var data = get(this, 'data');
  17636. return dataType == null ? data : data.getLinkedData(dataType);
  17637. },
  17638. /**
  17639. * @param {module:echarts/data/List} data
  17640. */
  17641. setData: function (data) {
  17642. set$1(this, 'data', data);
  17643. },
  17644. /**
  17645. * Get data before processed
  17646. * @return {module:echarts/data/List}
  17647. */
  17648. getRawData: function () {
  17649. return get(this, 'dataBeforeProcessed');
  17650. },
  17651. /**
  17652. * Coord dimension to data dimension.
  17653. *
  17654. * By default the result is the same as dimensions of series data.
  17655. * But in some series data dimensions are different from coord dimensions (i.e.
  17656. * candlestick and boxplot). Override this method to handle those cases.
  17657. *
  17658. * Coord dimension to data dimension can be one-to-many
  17659. *
  17660. * @param {string} coordDim
  17661. * @return {Array.<string>} dimensions on the axis.
  17662. */
  17663. coordDimToDataDim: function (coordDim) {
  17664. return coordDimToDataDim(this.getData(), coordDim);
  17665. },
  17666. /**
  17667. * Convert data dimension to coord dimension.
  17668. *
  17669. * @param {string|number} dataDim
  17670. * @return {string}
  17671. */
  17672. dataDimToCoordDim: function (dataDim) {
  17673. return dataDimToCoordDim(this.getData(), dataDim);
  17674. },
  17675. /**
  17676. * Get base axis if has coordinate system and has axis.
  17677. * By default use coordSys.getBaseAxis();
  17678. * Can be overrided for some chart.
  17679. * @return {type} description
  17680. */
  17681. getBaseAxis: function () {
  17682. var coordSys = this.coordinateSystem;
  17683. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  17684. },
  17685. // FIXME
  17686. /**
  17687. * Default tooltip formatter
  17688. *
  17689. * @param {number} dataIndex
  17690. * @param {boolean} [multipleSeries=false]
  17691. * @param {number} [dataType]
  17692. */
  17693. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  17694. function formatArrayValue(value) {
  17695. var vertially = reduce(value, function (vertially, val, idx) {
  17696. var dimItem = data.getDimensionInfo(idx);
  17697. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.tooltipName != null;
  17698. }, 0);
  17699. var result = [];
  17700. var tooltipDims = otherDimToDataDim(data, 'tooltip');
  17701. tooltipDims.length
  17702. ? each$1(tooltipDims, function (dimIdx) {
  17703. setEachItem(data.get(dimIdx, dataIndex), dimIdx);
  17704. })
  17705. // By default, all dims is used on tooltip.
  17706. : each$1(value, setEachItem);
  17707. function setEachItem(val, dimIdx) {
  17708. var dimInfo = data.getDimensionInfo(dimIdx);
  17709. // If `dimInfo.tooltip` is not set, show tooltip.
  17710. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  17711. return;
  17712. }
  17713. var dimType = dimInfo.type;
  17714. var valStr = (vertially ? '- ' + (dimInfo.tooltipName || dimInfo.name) + ': ' : '')
  17715. + (dimType === 'ordinal'
  17716. ? val + ''
  17717. : dimType === 'time'
  17718. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  17719. : addCommas(val)
  17720. );
  17721. valStr && result.push(encodeHTML(valStr));
  17722. }
  17723. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  17724. }
  17725. var data = get(this, 'data');
  17726. var value = this.getRawValue(dataIndex);
  17727. var formattedValue = isArray(value)
  17728. ? formatArrayValue(value) : encodeHTML(addCommas(value));
  17729. var name = data.getName(dataIndex);
  17730. var color = data.getItemVisual(dataIndex, 'color');
  17731. if (isObject(color) && color.colorStops) {
  17732. color = (color.colorStops[0] || {}).color;
  17733. }
  17734. color = color || 'transparent';
  17735. var colorEl = getTooltipMarker(color);
  17736. var seriesName = this.name;
  17737. // FIXME
  17738. if (seriesName === '\0-') {
  17739. // Not show '-'
  17740. seriesName = '';
  17741. }
  17742. seriesName = seriesName
  17743. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  17744. : '';
  17745. return !multipleSeries
  17746. ? seriesName + colorEl
  17747. + (name
  17748. ? encodeHTML(name) + ': ' + formattedValue
  17749. : formattedValue
  17750. )
  17751. : colorEl + seriesName + formattedValue;
  17752. },
  17753. /**
  17754. * @return {boolean}
  17755. */
  17756. isAnimationEnabled: function () {
  17757. if (env$1.node) {
  17758. return false;
  17759. }
  17760. var animationEnabled = this.getShallow('animation');
  17761. if (animationEnabled) {
  17762. if (this.getData().count() > this.getShallow('animationThreshold')) {
  17763. animationEnabled = false;
  17764. }
  17765. }
  17766. return animationEnabled;
  17767. },
  17768. restoreData: function () {
  17769. set$1(this, 'data', get(this, 'dataBeforeProcessed').cloneShallow());
  17770. },
  17771. getColorFromPalette: function (name, scope) {
  17772. var ecModel = this.ecModel;
  17773. // PENDING
  17774. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope);
  17775. if (!color) {
  17776. color = ecModel.getColorFromPalette(name, scope);
  17777. }
  17778. return color;
  17779. },
  17780. /**
  17781. * Get data indices for show tooltip content. See tooltip.
  17782. * @abstract
  17783. * @param {Array.<string>|string} dim
  17784. * @param {Array.<number>} value
  17785. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  17786. * @return {Object} {dataIndices, nestestValue}.
  17787. */
  17788. getAxisTooltipData: null,
  17789. /**
  17790. * See tooltip.
  17791. * @abstract
  17792. * @param {number} dataIndex
  17793. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  17794. */
  17795. getTooltipPosition: null
  17796. });
  17797. mixin(SeriesModel, dataFormatMixin);
  17798. mixin(SeriesModel, colorPaletteMixin);
  17799. var Component = function () {
  17800. /**
  17801. * @type {module:zrender/container/Group}
  17802. * @readOnly
  17803. */
  17804. this.group = new Group();
  17805. /**
  17806. * @type {string}
  17807. * @readOnly
  17808. */
  17809. this.uid = getUID('viewComponent');
  17810. };
  17811. Component.prototype = {
  17812. constructor: Component,
  17813. init: function (ecModel, api) {},
  17814. render: function (componentModel, ecModel, api, payload) {},
  17815. dispose: function () {}
  17816. };
  17817. var componentProto = Component.prototype;
  17818. componentProto.updateView
  17819. = componentProto.updateLayout
  17820. = componentProto.updateVisual
  17821. = function (seriesModel, ecModel, api, payload) {
  17822. // Do nothing;
  17823. };
  17824. // Enable Component.extend.
  17825. enableClassExtend(Component);
  17826. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17827. enableClassManagement(Component, {registerWhenExtend: true});
  17828. function Chart() {
  17829. /**
  17830. * @type {module:zrender/container/Group}
  17831. * @readOnly
  17832. */
  17833. this.group = new Group();
  17834. /**
  17835. * @type {string}
  17836. * @readOnly
  17837. */
  17838. this.uid = getUID('viewChart');
  17839. }
  17840. Chart.prototype = {
  17841. type: 'chart',
  17842. /**
  17843. * Init the chart
  17844. * @param {module:echarts/model/Global} ecModel
  17845. * @param {module:echarts/ExtensionAPI} api
  17846. */
  17847. init: function (ecModel, api) {},
  17848. /**
  17849. * Render the chart
  17850. * @param {module:echarts/model/Series} seriesModel
  17851. * @param {module:echarts/model/Global} ecModel
  17852. * @param {module:echarts/ExtensionAPI} api
  17853. * @param {Object} payload
  17854. */
  17855. render: function (seriesModel, ecModel, api, payload) {},
  17856. /**
  17857. * Highlight series or specified data item
  17858. * @param {module:echarts/model/Series} seriesModel
  17859. * @param {module:echarts/model/Global} ecModel
  17860. * @param {module:echarts/ExtensionAPI} api
  17861. * @param {Object} payload
  17862. */
  17863. highlight: function (seriesModel, ecModel, api, payload) {
  17864. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  17865. },
  17866. /**
  17867. * Downplay series or specified data item
  17868. * @param {module:echarts/model/Series} seriesModel
  17869. * @param {module:echarts/model/Global} ecModel
  17870. * @param {module:echarts/ExtensionAPI} api
  17871. * @param {Object} payload
  17872. */
  17873. downplay: function (seriesModel, ecModel, api, payload) {
  17874. toggleHighlight(seriesModel.getData(), payload, 'normal');
  17875. },
  17876. /**
  17877. * Remove self
  17878. * @param {module:echarts/model/Global} ecModel
  17879. * @param {module:echarts/ExtensionAPI} api
  17880. */
  17881. remove: function (ecModel, api) {
  17882. this.group.removeAll();
  17883. },
  17884. /**
  17885. * Dispose self
  17886. * @param {module:echarts/model/Global} ecModel
  17887. * @param {module:echarts/ExtensionAPI} api
  17888. */
  17889. dispose: function () {}
  17890. /**
  17891. * The view contains the given point.
  17892. * @interface
  17893. * @param {Array.<number>} point
  17894. * @return {boolean}
  17895. */
  17896. // containPoint: function () {}
  17897. };
  17898. var chartProto = Chart.prototype;
  17899. chartProto.updateView
  17900. = chartProto.updateLayout
  17901. = chartProto.updateVisual
  17902. = function (seriesModel, ecModel, api, payload) {
  17903. this.render(seriesModel, ecModel, api, payload);
  17904. };
  17905. /**
  17906. * Set state of single element
  17907. * @param {module:zrender/Element} el
  17908. * @param {string} state
  17909. */
  17910. function elSetState(el, state) {
  17911. if (el) {
  17912. el.trigger(state);
  17913. if (el.type === 'group') {
  17914. for (var i = 0; i < el.childCount(); i++) {
  17915. elSetState(el.childAt(i), state);
  17916. }
  17917. }
  17918. }
  17919. }
  17920. /**
  17921. * @param {module:echarts/data/List} data
  17922. * @param {Object} payload
  17923. * @param {string} state 'normal'|'emphasis'
  17924. * @inner
  17925. */
  17926. function toggleHighlight(data, payload, state) {
  17927. var dataIndex = queryDataIndex(data, payload);
  17928. if (dataIndex != null) {
  17929. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  17930. elSetState(data.getItemGraphicEl(dataIdx), state);
  17931. });
  17932. }
  17933. else {
  17934. data.eachItemGraphicEl(function (el) {
  17935. elSetState(el, state);
  17936. });
  17937. }
  17938. }
  17939. // Enable Chart.extend.
  17940. enableClassExtend(Chart, ['dispose']);
  17941. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17942. enableClassManagement(Chart, {registerWhenExtend: true});
  17943. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  17944. var RATE = '\0__throttleRate';
  17945. var THROTTLE_TYPE = '\0__throttleType';
  17946. /**
  17947. * @public
  17948. * @param {(Function)} fn
  17949. * @param {number} [delay=0] Unit: ms.
  17950. * @param {boolean} [debounce=false]
  17951. * true: If call interval less than `delay`, only the last call works.
  17952. * false: If call interval less than `delay, call works on fixed rate.
  17953. * @return {(Function)} throttled fn.
  17954. */
  17955. function throttle(fn, delay, debounce) {
  17956. var currCall;
  17957. var lastCall = 0;
  17958. var lastExec = 0;
  17959. var timer = null;
  17960. var diff;
  17961. var scope;
  17962. var args;
  17963. var debounceNextCall;
  17964. delay = delay || 0;
  17965. function exec() {
  17966. lastExec = (new Date()).getTime();
  17967. timer = null;
  17968. fn.apply(scope, args || []);
  17969. }
  17970. var cb = function () {
  17971. currCall = (new Date()).getTime();
  17972. scope = this;
  17973. args = arguments;
  17974. var thisDelay = debounceNextCall || delay;
  17975. var thisDebounce = debounceNextCall || debounce;
  17976. debounceNextCall = null;
  17977. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  17978. clearTimeout(timer);
  17979. if (thisDebounce) {
  17980. timer = setTimeout(exec, thisDelay);
  17981. }
  17982. else {
  17983. if (diff >= 0) {
  17984. exec();
  17985. }
  17986. else {
  17987. timer = setTimeout(exec, -diff);
  17988. }
  17989. }
  17990. lastCall = currCall;
  17991. };
  17992. /**
  17993. * Clear throttle.
  17994. * @public
  17995. */
  17996. cb.clear = function () {
  17997. if (timer) {
  17998. clearTimeout(timer);
  17999. timer = null;
  18000. }
  18001. };
  18002. /**
  18003. * Enable debounce once.
  18004. */
  18005. cb.debounceNextCall = function (debounceDelay) {
  18006. debounceNextCall = debounceDelay;
  18007. };
  18008. return cb;
  18009. }
  18010. /**
  18011. * Create throttle method or update throttle rate.
  18012. *
  18013. * @example
  18014. * ComponentView.prototype.render = function () {
  18015. * ...
  18016. * throttle.createOrUpdate(
  18017. * this,
  18018. * '_dispatchAction',
  18019. * this.model.get('throttle'),
  18020. * 'fixRate'
  18021. * );
  18022. * };
  18023. * ComponentView.prototype.remove = function () {
  18024. * throttle.clear(this, '_dispatchAction');
  18025. * };
  18026. * ComponentView.prototype.dispose = function () {
  18027. * throttle.clear(this, '_dispatchAction');
  18028. * };
  18029. *
  18030. * @public
  18031. * @param {Object} obj
  18032. * @param {string} fnAttr
  18033. * @param {number} [rate]
  18034. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  18035. * @return {Function} throttled function.
  18036. */
  18037. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  18038. var fn = obj[fnAttr];
  18039. if (!fn) {
  18040. return;
  18041. }
  18042. var originFn = fn[ORIGIN_METHOD] || fn;
  18043. var lastThrottleType = fn[THROTTLE_TYPE];
  18044. var lastRate = fn[RATE];
  18045. if (lastRate !== rate || lastThrottleType !== throttleType) {
  18046. if (rate == null || !throttleType) {
  18047. return (obj[fnAttr] = originFn);
  18048. }
  18049. fn = obj[fnAttr] = throttle(
  18050. originFn, rate, throttleType === 'debounce'
  18051. );
  18052. fn[ORIGIN_METHOD] = originFn;
  18053. fn[THROTTLE_TYPE] = throttleType;
  18054. fn[RATE] = rate;
  18055. }
  18056. return fn;
  18057. }
  18058. /**
  18059. * Clear throttle. Example see throttle.createOrUpdate.
  18060. *
  18061. * @public
  18062. * @param {Object} obj
  18063. * @param {string} fnAttr
  18064. */
  18065. function clear(obj, fnAttr) {
  18066. var fn = obj[fnAttr];
  18067. if (fn && fn[ORIGIN_METHOD]) {
  18068. obj[fnAttr] = fn[ORIGIN_METHOD];
  18069. }
  18070. }
  18071. var seriesColor = function (ecModel) {
  18072. function encodeColor(seriesModel) {
  18073. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.normal.color').split('.');
  18074. var data = seriesModel.getData();
  18075. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  18076. || seriesModel.getColorFromPalette(seriesModel.get('name')); // Default color
  18077. // FIXME Set color function or use the platte color
  18078. data.setVisual('color', color);
  18079. // Only visible series has each data be visual encoded
  18080. if (!ecModel.isSeriesFiltered(seriesModel)) {
  18081. if (typeof color === 'function' && !(color instanceof Gradient)) {
  18082. data.each(function (idx) {
  18083. data.setItemVisual(
  18084. idx, 'color', color(seriesModel.getDataParams(idx))
  18085. );
  18086. });
  18087. }
  18088. // itemStyle in each data item
  18089. data.each(function (idx) {
  18090. var itemModel = data.getItemModel(idx);
  18091. var color = itemModel.get(colorAccessPath, true);
  18092. if (color != null) {
  18093. data.setItemVisual(idx, 'color', color);
  18094. }
  18095. });
  18096. }
  18097. }
  18098. ecModel.eachRawSeries(encodeColor);
  18099. };
  18100. var PI$1 = Math.PI;
  18101. /**
  18102. * @param {module:echarts/ExtensionAPI} api
  18103. * @param {Object} [opts]
  18104. * @param {string} [opts.text]
  18105. * @param {string} [opts.color]
  18106. * @param {string} [opts.textColor]
  18107. * @return {module:zrender/Element}
  18108. */
  18109. var loadingDefault = function (api, opts) {
  18110. opts = opts || {};
  18111. defaults(opts, {
  18112. text: 'loading',
  18113. color: '#c23531',
  18114. textColor: '#000',
  18115. maskColor: 'rgba(255, 255, 255, 0.8)',
  18116. zlevel: 0
  18117. });
  18118. var mask = new Rect({
  18119. style: {
  18120. fill: opts.maskColor
  18121. },
  18122. zlevel: opts.zlevel,
  18123. z: 10000
  18124. });
  18125. var arc = new Arc({
  18126. shape: {
  18127. startAngle: -PI$1 / 2,
  18128. endAngle: -PI$1 / 2 + 0.1,
  18129. r: 10
  18130. },
  18131. style: {
  18132. stroke: opts.color,
  18133. lineCap: 'round',
  18134. lineWidth: 5
  18135. },
  18136. zlevel: opts.zlevel,
  18137. z: 10001
  18138. });
  18139. var labelRect = new Rect({
  18140. style: {
  18141. fill: 'none',
  18142. text: opts.text,
  18143. textPosition: 'right',
  18144. textDistance: 10,
  18145. textFill: opts.textColor
  18146. },
  18147. zlevel: opts.zlevel,
  18148. z: 10001
  18149. });
  18150. arc.animateShape(true)
  18151. .when(1000, {
  18152. endAngle: PI$1 * 3 / 2
  18153. })
  18154. .start('circularInOut');
  18155. arc.animateShape(true)
  18156. .when(1000, {
  18157. startAngle: PI$1 * 3 / 2
  18158. })
  18159. .delay(300)
  18160. .start('circularInOut');
  18161. var group = new Group();
  18162. group.add(arc);
  18163. group.add(labelRect);
  18164. group.add(mask);
  18165. // Inject resize
  18166. group.resize = function () {
  18167. var cx = api.getWidth() / 2;
  18168. var cy = api.getHeight() / 2;
  18169. arc.setShape({
  18170. cx: cx,
  18171. cy: cy
  18172. });
  18173. var r = arc.shape.r;
  18174. labelRect.setShape({
  18175. x: cx - r,
  18176. y: cy - r,
  18177. width: r * 2,
  18178. height: r * 2
  18179. });
  18180. mask.setShape({
  18181. x: 0,
  18182. y: 0,
  18183. width: api.getWidth(),
  18184. height: api.getHeight()
  18185. });
  18186. };
  18187. group.resize();
  18188. return group;
  18189. };
  18190. /*!
  18191. * ECharts, a javascript interactive chart library.
  18192. *
  18193. * Copyright (c) 2015, Baidu Inc.
  18194. * All rights reserved.
  18195. *
  18196. * LICENSE
  18197. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  18198. */
  18199. var each = each$1;
  18200. var parseClassType = ComponentModel.parseClassType;
  18201. var version = '3.8.4';
  18202. var dependencies = {
  18203. zrender: '3.7.3'
  18204. };
  18205. var PRIORITY_PROCESSOR_FILTER = 1000;
  18206. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  18207. var PRIORITY_VISUAL_LAYOUT = 1000;
  18208. var PRIORITY_VISUAL_GLOBAL = 2000;
  18209. var PRIORITY_VISUAL_CHART = 3000;
  18210. var PRIORITY_VISUAL_COMPONENT = 4000;
  18211. // FIXME
  18212. // necessary?
  18213. var PRIORITY_VISUAL_BRUSH = 5000;
  18214. var PRIORITY = {
  18215. PROCESSOR: {
  18216. FILTER: PRIORITY_PROCESSOR_FILTER,
  18217. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  18218. },
  18219. VISUAL: {
  18220. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  18221. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  18222. CHART: PRIORITY_VISUAL_CHART,
  18223. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  18224. BRUSH: PRIORITY_VISUAL_BRUSH
  18225. }
  18226. };
  18227. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  18228. // where they must not be invoked nestedly, except the only case: invoke
  18229. // dispatchAction with updateMethod "none" in main process.
  18230. // This flag is used to carry out this rule.
  18231. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  18232. var IN_MAIN_PROCESS = '__flagInMainProcess';
  18233. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  18234. var OPTION_UPDATED = '__optionUpdated';
  18235. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  18236. function createRegisterEventWithLowercaseName(method) {
  18237. return function (eventName, handler, context) {
  18238. // Event name is all lowercase
  18239. eventName = eventName && eventName.toLowerCase();
  18240. Eventful.prototype[method].call(this, eventName, handler, context);
  18241. };
  18242. }
  18243. /**
  18244. * @module echarts~MessageCenter
  18245. */
  18246. function MessageCenter() {
  18247. Eventful.call(this);
  18248. }
  18249. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  18250. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  18251. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  18252. mixin(MessageCenter, Eventful);
  18253. /**
  18254. * @module echarts~ECharts
  18255. */
  18256. function ECharts(dom, theme, opts) {
  18257. opts = opts || {};
  18258. // Get theme by name
  18259. if (typeof theme === 'string') {
  18260. theme = themeStorage[theme];
  18261. }
  18262. /**
  18263. * @type {string}
  18264. */
  18265. this.id;
  18266. /**
  18267. * Group id
  18268. * @type {string}
  18269. */
  18270. this.group;
  18271. /**
  18272. * @type {HTMLElement}
  18273. * @private
  18274. */
  18275. this._dom = dom;
  18276. var defaultRenderer = 'canvas';
  18277. if (__DEV__) {
  18278. defaultRenderer = (
  18279. typeof window === 'undefined' ? global : window
  18280. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  18281. }
  18282. /**
  18283. * @type {module:zrender/ZRender}
  18284. * @private
  18285. */
  18286. var zr = this._zr = init$1(dom, {
  18287. renderer: opts.renderer || defaultRenderer,
  18288. devicePixelRatio: opts.devicePixelRatio,
  18289. width: opts.width,
  18290. height: opts.height
  18291. });
  18292. /**
  18293. * Expect 60 pfs.
  18294. * @type {Function}
  18295. * @private
  18296. */
  18297. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  18298. var theme = clone(theme);
  18299. theme && backwardCompat(theme, true);
  18300. /**
  18301. * @type {Object}
  18302. * @private
  18303. */
  18304. this._theme = theme;
  18305. /**
  18306. * @type {Array.<module:echarts/view/Chart>}
  18307. * @private
  18308. */
  18309. this._chartsViews = [];
  18310. /**
  18311. * @type {Object.<string, module:echarts/view/Chart>}
  18312. * @private
  18313. */
  18314. this._chartsMap = {};
  18315. /**
  18316. * @type {Array.<module:echarts/view/Component>}
  18317. * @private
  18318. */
  18319. this._componentsViews = [];
  18320. /**
  18321. * @type {Object.<string, module:echarts/view/Component>}
  18322. * @private
  18323. */
  18324. this._componentsMap = {};
  18325. /**
  18326. * @type {module:echarts/CoordinateSystem}
  18327. * @private
  18328. */
  18329. this._coordSysMgr = new CoordinateSystemManager();
  18330. /**
  18331. * @type {module:echarts/ExtensionAPI}
  18332. * @private
  18333. */
  18334. this._api = createExtensionAPI(this);
  18335. Eventful.call(this);
  18336. /**
  18337. * @type {module:echarts~MessageCenter}
  18338. * @private
  18339. */
  18340. this._messageCenter = new MessageCenter();
  18341. // Init mouse events
  18342. this._initEvents();
  18343. // In case some people write `window.onresize = chart.resize`
  18344. this.resize = bind(this.resize, this);
  18345. // Can't dispatch action during rendering procedure
  18346. this._pendingActions = [];
  18347. // Sort on demand
  18348. function prioritySortFunc(a, b) {
  18349. return a.prio - b.prio;
  18350. }
  18351. sort(visualFuncs, prioritySortFunc);
  18352. sort(dataProcessorFuncs, prioritySortFunc);
  18353. zr.animation.on('frame', this._onframe, this);
  18354. // ECharts instance can be used as value.
  18355. setAsPrimitive(this);
  18356. }
  18357. var echartsProto = ECharts.prototype;
  18358. echartsProto._onframe = function () {
  18359. // Lazy update
  18360. if (this[OPTION_UPDATED]) {
  18361. var silent = this[OPTION_UPDATED].silent;
  18362. this[IN_MAIN_PROCESS] = true;
  18363. updateMethods.prepareAndUpdate.call(this);
  18364. this[IN_MAIN_PROCESS] = false;
  18365. this[OPTION_UPDATED] = false;
  18366. flushPendingActions.call(this, silent);
  18367. triggerUpdatedEvent.call(this, silent);
  18368. }
  18369. };
  18370. /**
  18371. * @return {HTMLElement}
  18372. */
  18373. echartsProto.getDom = function () {
  18374. return this._dom;
  18375. };
  18376. /**
  18377. * @return {module:zrender~ZRender}
  18378. */
  18379. echartsProto.getZr = function () {
  18380. return this._zr;
  18381. };
  18382. /**
  18383. * Usage:
  18384. * chart.setOption(option, notMerge, lazyUpdate);
  18385. * chart.setOption(option, {
  18386. * notMerge: ...,
  18387. * lazyUpdate: ...,
  18388. * silent: ...
  18389. * });
  18390. *
  18391. * @param {Object} option
  18392. * @param {Object|boolean} [opts] opts or notMerge.
  18393. * @param {boolean} [opts.notMerge=false]
  18394. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  18395. */
  18396. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  18397. if (__DEV__) {
  18398. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  18399. }
  18400. var silent;
  18401. if (isObject(notMerge)) {
  18402. lazyUpdate = notMerge.lazyUpdate;
  18403. silent = notMerge.silent;
  18404. notMerge = notMerge.notMerge;
  18405. }
  18406. this[IN_MAIN_PROCESS] = true;
  18407. if (!this._model || notMerge) {
  18408. var optionManager = new OptionManager(this._api);
  18409. var theme = this._theme;
  18410. var ecModel = this._model = new GlobalModel(null, null, theme, optionManager);
  18411. ecModel.init(null, null, theme, optionManager);
  18412. }
  18413. this._model.setOption(option, optionPreprocessorFuncs);
  18414. if (lazyUpdate) {
  18415. this[OPTION_UPDATED] = {silent: silent};
  18416. this[IN_MAIN_PROCESS] = false;
  18417. }
  18418. else {
  18419. updateMethods.prepareAndUpdate.call(this);
  18420. // Ensure zr refresh sychronously, and then pixel in canvas can be
  18421. // fetched after `setOption`.
  18422. this._zr.flush();
  18423. this[OPTION_UPDATED] = false;
  18424. this[IN_MAIN_PROCESS] = false;
  18425. flushPendingActions.call(this, silent);
  18426. triggerUpdatedEvent.call(this, silent);
  18427. }
  18428. };
  18429. /**
  18430. * @DEPRECATED
  18431. */
  18432. echartsProto.setTheme = function () {
  18433. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  18434. };
  18435. /**
  18436. * @return {module:echarts/model/Global}
  18437. */
  18438. echartsProto.getModel = function () {
  18439. return this._model;
  18440. };
  18441. /**
  18442. * @return {Object}
  18443. */
  18444. echartsProto.getOption = function () {
  18445. return this._model && this._model.getOption();
  18446. };
  18447. /**
  18448. * @return {number}
  18449. */
  18450. echartsProto.getWidth = function () {
  18451. return this._zr.getWidth();
  18452. };
  18453. /**
  18454. * @return {number}
  18455. */
  18456. echartsProto.getHeight = function () {
  18457. return this._zr.getHeight();
  18458. };
  18459. /**
  18460. * @return {number}
  18461. */
  18462. echartsProto.getDevicePixelRatio = function () {
  18463. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  18464. };
  18465. /**
  18466. * Get canvas which has all thing rendered
  18467. * @param {Object} opts
  18468. * @param {string} [opts.backgroundColor]
  18469. * @return {string}
  18470. */
  18471. echartsProto.getRenderedCanvas = function (opts) {
  18472. if (!env$1.canvasSupported) {
  18473. return;
  18474. }
  18475. opts = opts || {};
  18476. opts.pixelRatio = opts.pixelRatio || 1;
  18477. opts.backgroundColor = opts.backgroundColor
  18478. || this._model.get('backgroundColor');
  18479. var zr = this._zr;
  18480. var list = zr.storage.getDisplayList();
  18481. // Stop animations
  18482. each$1(list, function (el) {
  18483. el.stopAnimation(true);
  18484. });
  18485. return zr.painter.getRenderedCanvas(opts);
  18486. };
  18487. /**
  18488. * Get svg data url
  18489. * @return {string}
  18490. */
  18491. echartsProto.getSvgDataUrl = function () {
  18492. if (!env$1.svgSupported) {
  18493. return;
  18494. }
  18495. var zr = this._zr;
  18496. var list = zr.storage.getDisplayList();
  18497. // Stop animations
  18498. each$1(list, function (el) {
  18499. el.stopAnimation(true);
  18500. });
  18501. return zr.painter.pathToSvg();
  18502. };
  18503. /**
  18504. * @return {string}
  18505. * @param {Object} opts
  18506. * @param {string} [opts.type='png']
  18507. * @param {string} [opts.pixelRatio=1]
  18508. * @param {string} [opts.backgroundColor]
  18509. * @param {string} [opts.excludeComponents]
  18510. */
  18511. echartsProto.getDataURL = function (opts) {
  18512. opts = opts || {};
  18513. var excludeComponents = opts.excludeComponents;
  18514. var ecModel = this._model;
  18515. var excludesComponentViews = [];
  18516. var self = this;
  18517. each(excludeComponents, function (componentType) {
  18518. ecModel.eachComponent({
  18519. mainType: componentType
  18520. }, function (component) {
  18521. var view = self._componentsMap[component.__viewId];
  18522. if (!view.group.ignore) {
  18523. excludesComponentViews.push(view);
  18524. view.group.ignore = true;
  18525. }
  18526. });
  18527. });
  18528. var url = this._zr.painter.getType() === 'svg'
  18529. ? this.getSvgDataUrl()
  18530. : this.getRenderedCanvas(opts).toDataURL(
  18531. 'image/' + (opts && opts.type || 'png')
  18532. );
  18533. each(excludesComponentViews, function (view) {
  18534. view.group.ignore = false;
  18535. });
  18536. return url;
  18537. };
  18538. /**
  18539. * @return {string}
  18540. * @param {Object} opts
  18541. * @param {string} [opts.type='png']
  18542. * @param {string} [opts.pixelRatio=1]
  18543. * @param {string} [opts.backgroundColor]
  18544. */
  18545. echartsProto.getConnectedDataURL = function (opts) {
  18546. if (!env$1.canvasSupported) {
  18547. return;
  18548. }
  18549. var groupId = this.group;
  18550. var mathMin = Math.min;
  18551. var mathMax = Math.max;
  18552. var MAX_NUMBER = Infinity;
  18553. if (connectedGroups[groupId]) {
  18554. var left = MAX_NUMBER;
  18555. var top = MAX_NUMBER;
  18556. var right = -MAX_NUMBER;
  18557. var bottom = -MAX_NUMBER;
  18558. var canvasList = [];
  18559. var dpr = (opts && opts.pixelRatio) || 1;
  18560. each$1(instances, function (chart, id) {
  18561. if (chart.group === groupId) {
  18562. var canvas = chart.getRenderedCanvas(
  18563. clone(opts)
  18564. );
  18565. var boundingRect = chart.getDom().getBoundingClientRect();
  18566. left = mathMin(boundingRect.left, left);
  18567. top = mathMin(boundingRect.top, top);
  18568. right = mathMax(boundingRect.right, right);
  18569. bottom = mathMax(boundingRect.bottom, bottom);
  18570. canvasList.push({
  18571. dom: canvas,
  18572. left: boundingRect.left,
  18573. top: boundingRect.top
  18574. });
  18575. }
  18576. });
  18577. left *= dpr;
  18578. top *= dpr;
  18579. right *= dpr;
  18580. bottom *= dpr;
  18581. var width = right - left;
  18582. var height = bottom - top;
  18583. var targetCanvas = createCanvas();
  18584. targetCanvas.width = width;
  18585. targetCanvas.height = height;
  18586. var zr = init$1(targetCanvas);
  18587. each(canvasList, function (item) {
  18588. var img = new ZImage({
  18589. style: {
  18590. x: item.left * dpr - left,
  18591. y: item.top * dpr - top,
  18592. image: item.dom
  18593. }
  18594. });
  18595. zr.add(img);
  18596. });
  18597. zr.refreshImmediately();
  18598. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  18599. }
  18600. else {
  18601. return this.getDataURL(opts);
  18602. }
  18603. };
  18604. /**
  18605. * Convert from logical coordinate system to pixel coordinate system.
  18606. * See CoordinateSystem#convertToPixel.
  18607. * @param {string|Object} finder
  18608. * If string, e.g., 'geo', means {geoIndex: 0}.
  18609. * If Object, could contain some of these properties below:
  18610. * {
  18611. * seriesIndex / seriesId / seriesName,
  18612. * geoIndex / geoId, geoName,
  18613. * bmapIndex / bmapId / bmapName,
  18614. * xAxisIndex / xAxisId / xAxisName,
  18615. * yAxisIndex / yAxisId / yAxisName,
  18616. * gridIndex / gridId / gridName,
  18617. * ... (can be extended)
  18618. * }
  18619. * @param {Array|number} value
  18620. * @return {Array|number} result
  18621. */
  18622. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  18623. /**
  18624. * Convert from pixel coordinate system to logical coordinate system.
  18625. * See CoordinateSystem#convertFromPixel.
  18626. * @param {string|Object} finder
  18627. * If string, e.g., 'geo', means {geoIndex: 0}.
  18628. * If Object, could contain some of these properties below:
  18629. * {
  18630. * seriesIndex / seriesId / seriesName,
  18631. * geoIndex / geoId / geoName,
  18632. * bmapIndex / bmapId / bmapName,
  18633. * xAxisIndex / xAxisId / xAxisName,
  18634. * yAxisIndex / yAxisId / yAxisName
  18635. * gridIndex / gridId / gridName,
  18636. * ... (can be extended)
  18637. * }
  18638. * @param {Array|number} value
  18639. * @return {Array|number} result
  18640. */
  18641. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  18642. function doConvertPixel(methodName, finder, value) {
  18643. var ecModel = this._model;
  18644. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  18645. var result;
  18646. finder = parseFinder(ecModel, finder);
  18647. for (var i = 0; i < coordSysList.length; i++) {
  18648. var coordSys = coordSysList[i];
  18649. if (coordSys[methodName]
  18650. && (result = coordSys[methodName](ecModel, finder, value)) != null
  18651. ) {
  18652. return result;
  18653. }
  18654. }
  18655. if (__DEV__) {
  18656. console.warn(
  18657. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  18658. );
  18659. }
  18660. }
  18661. /**
  18662. * Is the specified coordinate systems or components contain the given pixel point.
  18663. * @param {string|Object} finder
  18664. * If string, e.g., 'geo', means {geoIndex: 0}.
  18665. * If Object, could contain some of these properties below:
  18666. * {
  18667. * seriesIndex / seriesId / seriesName,
  18668. * geoIndex / geoId / geoName,
  18669. * bmapIndex / bmapId / bmapName,
  18670. * xAxisIndex / xAxisId / xAxisName,
  18671. * yAxisIndex / yAxisId / yAxisName,
  18672. * gridIndex / gridId / gridName,
  18673. * ... (can be extended)
  18674. * }
  18675. * @param {Array|number} value
  18676. * @return {boolean} result
  18677. */
  18678. echartsProto.containPixel = function (finder, value) {
  18679. var ecModel = this._model;
  18680. var result;
  18681. finder = parseFinder(ecModel, finder);
  18682. each$1(finder, function (models, key) {
  18683. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  18684. var coordSys = model.coordinateSystem;
  18685. if (coordSys && coordSys.containPoint) {
  18686. result |= !!coordSys.containPoint(value);
  18687. }
  18688. else if (key === 'seriesModels') {
  18689. var view = this._chartsMap[model.__viewId];
  18690. if (view && view.containPoint) {
  18691. result |= view.containPoint(value, model);
  18692. }
  18693. else {
  18694. if (__DEV__) {
  18695. console.warn(key + ': ' + (view
  18696. ? 'The found component do not support containPoint.'
  18697. : 'No view mapping to the found component.'
  18698. ));
  18699. }
  18700. }
  18701. }
  18702. else {
  18703. if (__DEV__) {
  18704. console.warn(key + ': containPoint is not supported');
  18705. }
  18706. }
  18707. }, this);
  18708. }, this);
  18709. return !!result;
  18710. };
  18711. /**
  18712. * Get visual from series or data.
  18713. * @param {string|Object} finder
  18714. * If string, e.g., 'series', means {seriesIndex: 0}.
  18715. * If Object, could contain some of these properties below:
  18716. * {
  18717. * seriesIndex / seriesId / seriesName,
  18718. * dataIndex / dataIndexInside
  18719. * }
  18720. * If dataIndex is not specified, series visual will be fetched,
  18721. * but not data item visual.
  18722. * If all of seriesIndex, seriesId, seriesName are not specified,
  18723. * visual will be fetched from first series.
  18724. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  18725. */
  18726. echartsProto.getVisual = function (finder, visualType) {
  18727. var ecModel = this._model;
  18728. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  18729. var seriesModel = finder.seriesModel;
  18730. if (__DEV__) {
  18731. if (!seriesModel) {
  18732. console.warn('There is no specified seires model');
  18733. }
  18734. }
  18735. var data = seriesModel.getData();
  18736. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  18737. ? finder.dataIndexInside
  18738. : finder.hasOwnProperty('dataIndex')
  18739. ? data.indexOfRawIndex(finder.dataIndex)
  18740. : null;
  18741. return dataIndexInside != null
  18742. ? data.getItemVisual(dataIndexInside, visualType)
  18743. : data.getVisual(visualType);
  18744. };
  18745. /**
  18746. * Get view of corresponding component model
  18747. * @param {module:echarts/model/Component} componentModel
  18748. * @return {module:echarts/view/Component}
  18749. */
  18750. echartsProto.getViewOfComponentModel = function (componentModel) {
  18751. return this._componentsMap[componentModel.__viewId];
  18752. };
  18753. /**
  18754. * Get view of corresponding series model
  18755. * @param {module:echarts/model/Series} seriesModel
  18756. * @return {module:echarts/view/Chart}
  18757. */
  18758. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  18759. return this._chartsMap[seriesModel.__viewId];
  18760. };
  18761. var updateMethods = {
  18762. /**
  18763. * @param {Object} payload
  18764. * @private
  18765. */
  18766. update: function (payload) {
  18767. // console.profile && console.profile('update');
  18768. var ecModel = this._model;
  18769. var api = this._api;
  18770. var coordSysMgr = this._coordSysMgr;
  18771. var zr = this._zr;
  18772. // update before setOption
  18773. if (!ecModel) {
  18774. return;
  18775. }
  18776. // Fixme First time update ?
  18777. ecModel.restoreData();
  18778. // TODO
  18779. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  18780. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  18781. // Create new coordinate system each update
  18782. // In LineView may save the old coordinate system and use it to get the orignal point
  18783. coordSysMgr.create(this._model, this._api);
  18784. processData.call(this, ecModel, api);
  18785. stackSeriesData.call(this, ecModel);
  18786. coordSysMgr.update(ecModel, api);
  18787. doVisualEncoding.call(this, ecModel, payload);
  18788. doRender.call(this, ecModel, payload);
  18789. // Set background
  18790. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  18791. var painter = zr.painter;
  18792. // TODO all use clearColor ?
  18793. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  18794. zr.configLayer(0, {
  18795. clearColor: backgroundColor
  18796. });
  18797. }
  18798. else {
  18799. // In IE8
  18800. if (!env$1.canvasSupported) {
  18801. var colorArr = parse(backgroundColor);
  18802. backgroundColor = stringify(colorArr, 'rgb');
  18803. if (colorArr[3] === 0) {
  18804. backgroundColor = 'transparent';
  18805. }
  18806. }
  18807. if (backgroundColor.colorStops || backgroundColor.image) {
  18808. // Gradient background
  18809. // FIXME Fixed layer?
  18810. zr.configLayer(0, {
  18811. clearColor: backgroundColor
  18812. });
  18813. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  18814. this._dom.style.background = 'transparent';
  18815. }
  18816. else {
  18817. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  18818. zr.configLayer(0, {
  18819. clearColor: null
  18820. });
  18821. }
  18822. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  18823. this._dom.style.background = backgroundColor;
  18824. }
  18825. }
  18826. each(postUpdateFuncs, function (func) {
  18827. func(ecModel, api);
  18828. });
  18829. // console.profile && console.profileEnd('update');
  18830. },
  18831. /**
  18832. * @param {Object} payload
  18833. * @private
  18834. */
  18835. updateView: function (payload) {
  18836. var ecModel = this._model;
  18837. // update before setOption
  18838. if (!ecModel) {
  18839. return;
  18840. }
  18841. ecModel.eachSeries(function (seriesModel) {
  18842. seriesModel.getData().clearAllVisual();
  18843. });
  18844. doVisualEncoding.call(this, ecModel, payload);
  18845. invokeUpdateMethod.call(this, 'updateView', ecModel, payload);
  18846. },
  18847. /**
  18848. * @param {Object} payload
  18849. * @private
  18850. */
  18851. updateVisual: function (payload) {
  18852. var ecModel = this._model;
  18853. // update before setOption
  18854. if (!ecModel) {
  18855. return;
  18856. }
  18857. ecModel.eachSeries(function (seriesModel) {
  18858. seriesModel.getData().clearAllVisual();
  18859. });
  18860. doVisualEncoding.call(this, ecModel, payload, true);
  18861. invokeUpdateMethod.call(this, 'updateVisual', ecModel, payload);
  18862. },
  18863. /**
  18864. * @param {Object} payload
  18865. * @private
  18866. */
  18867. updateLayout: function (payload) {
  18868. var ecModel = this._model;
  18869. // update before setOption
  18870. if (!ecModel) {
  18871. return;
  18872. }
  18873. doLayout.call(this, ecModel, payload);
  18874. invokeUpdateMethod.call(this, 'updateLayout', ecModel, payload);
  18875. },
  18876. /**
  18877. * @param {Object} payload
  18878. * @private
  18879. */
  18880. prepareAndUpdate: function (payload) {
  18881. var ecModel = this._model;
  18882. prepareView.call(this, 'component', ecModel);
  18883. prepareView.call(this, 'chart', ecModel);
  18884. updateMethods.update.call(this, payload);
  18885. }
  18886. };
  18887. /**
  18888. * @private
  18889. */
  18890. function updateDirectly(ecIns, method, payload, mainType, subType) {
  18891. var ecModel = ecIns._model;
  18892. // broadcast
  18893. if (!mainType) {
  18894. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  18895. return;
  18896. }
  18897. var query = {};
  18898. query[mainType + 'Id'] = payload[mainType + 'Id'];
  18899. query[mainType + 'Index'] = payload[mainType + 'Index'];
  18900. query[mainType + 'Name'] = payload[mainType + 'Name'];
  18901. var condition = {mainType: mainType, query: query};
  18902. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  18903. // If dispatchAction before setOption, do nothing.
  18904. ecModel && ecModel.eachComponent(condition, function (model, index) {
  18905. callView(ecIns[
  18906. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  18907. ][model.__viewId]);
  18908. }, ecIns);
  18909. function callView(view) {
  18910. view && view.__alive && view[method] && view[method](
  18911. view.__model, ecModel, ecIns._api, payload
  18912. );
  18913. }
  18914. }
  18915. /**
  18916. * Resize the chart
  18917. * @param {Object} opts
  18918. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  18919. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  18920. * @param {boolean} [opts.silent=false]
  18921. */
  18922. echartsProto.resize = function (opts) {
  18923. if (__DEV__) {
  18924. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  18925. }
  18926. this[IN_MAIN_PROCESS] = true;
  18927. this._zr.resize(opts);
  18928. var optionChanged = this._model && this._model.resetOption('media');
  18929. var updateMethod = optionChanged ? 'prepareAndUpdate' : 'update';
  18930. updateMethods[updateMethod].call(this);
  18931. // Resize loading effect
  18932. this._loadingFX && this._loadingFX.resize();
  18933. this[IN_MAIN_PROCESS] = false;
  18934. var silent = opts && opts.silent;
  18935. flushPendingActions.call(this, silent);
  18936. triggerUpdatedEvent.call(this, silent);
  18937. };
  18938. /**
  18939. * Show loading effect
  18940. * @param {string} [name='default']
  18941. * @param {Object} [cfg]
  18942. */
  18943. echartsProto.showLoading = function (name, cfg) {
  18944. if (isObject(name)) {
  18945. cfg = name;
  18946. name = '';
  18947. }
  18948. name = name || 'default';
  18949. this.hideLoading();
  18950. if (!loadingEffects[name]) {
  18951. if (__DEV__) {
  18952. console.warn('Loading effects ' + name + ' not exists.');
  18953. }
  18954. return;
  18955. }
  18956. var el = loadingEffects[name](this._api, cfg);
  18957. var zr = this._zr;
  18958. this._loadingFX = el;
  18959. zr.add(el);
  18960. };
  18961. /**
  18962. * Hide loading effect
  18963. */
  18964. echartsProto.hideLoading = function () {
  18965. this._loadingFX && this._zr.remove(this._loadingFX);
  18966. this._loadingFX = null;
  18967. };
  18968. /**
  18969. * @param {Object} eventObj
  18970. * @return {Object}
  18971. */
  18972. echartsProto.makeActionFromEvent = function (eventObj) {
  18973. var payload = extend({}, eventObj);
  18974. payload.type = eventActionMap[eventObj.type];
  18975. return payload;
  18976. };
  18977. /**
  18978. * @pubilc
  18979. * @param {Object} payload
  18980. * @param {string} [payload.type] Action type
  18981. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  18982. * @param {boolean} [opt.silent=false] Whether trigger events.
  18983. * @param {boolean} [opt.flush=undefined]
  18984. * true: Flush immediately, and then pixel in canvas can be fetched
  18985. * immediately. Caution: it might affect performance.
  18986. * false: Not not flush.
  18987. * undefined: Auto decide whether perform flush.
  18988. */
  18989. echartsProto.dispatchAction = function (payload, opt) {
  18990. if (!isObject(opt)) {
  18991. opt = {silent: !!opt};
  18992. }
  18993. if (!actions[payload.type]) {
  18994. return;
  18995. }
  18996. // Avoid dispatch action before setOption. Especially in `connect`.
  18997. if (!this._model) {
  18998. return;
  18999. }
  19000. // May dispatchAction in rendering procedure
  19001. if (this[IN_MAIN_PROCESS]) {
  19002. this._pendingActions.push(payload);
  19003. return;
  19004. }
  19005. doDispatchAction.call(this, payload, opt.silent);
  19006. if (opt.flush) {
  19007. this._zr.flush(true);
  19008. }
  19009. else if (opt.flush !== false && env$1.browser.weChat) {
  19010. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  19011. // hang when sliding page (on touch event), which cause that zr does not
  19012. // refresh util user interaction finished, which is not expected.
  19013. // But `dispatchAction` may be called too frequently when pan on touch
  19014. // screen, which impacts performance if do not throttle them.
  19015. this._throttledZrFlush();
  19016. }
  19017. flushPendingActions.call(this, opt.silent);
  19018. triggerUpdatedEvent.call(this, opt.silent);
  19019. };
  19020. function doDispatchAction(payload, silent) {
  19021. var payloadType = payload.type;
  19022. var escapeConnect = payload.escapeConnect;
  19023. var actionWrap = actions[payloadType];
  19024. var actionInfo = actionWrap.actionInfo;
  19025. var cptType = (actionInfo.update || 'update').split(':');
  19026. var updateMethod = cptType.pop();
  19027. cptType = cptType[0] != null && parseClassType(cptType[0]);
  19028. this[IN_MAIN_PROCESS] = true;
  19029. var payloads = [payload];
  19030. var batched = false;
  19031. // Batch action
  19032. if (payload.batch) {
  19033. batched = true;
  19034. payloads = map(payload.batch, function (item) {
  19035. item = defaults(extend({}, item), payload);
  19036. item.batch = null;
  19037. return item;
  19038. });
  19039. }
  19040. var eventObjBatch = [];
  19041. var eventObj;
  19042. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  19043. each(payloads, function (batchItem) {
  19044. // Action can specify the event by return it.
  19045. eventObj = actionWrap.action(batchItem, this._model, this._api);
  19046. // Emit event outside
  19047. eventObj = eventObj || extend({}, batchItem);
  19048. // Convert type to eventType
  19049. eventObj.type = actionInfo.event || eventObj.type;
  19050. eventObjBatch.push(eventObj);
  19051. // light update does not perform data process, layout and visual.
  19052. if (isHighDown) {
  19053. // method, payload, mainType, subType
  19054. updateDirectly(this, updateMethod, batchItem, 'series');
  19055. }
  19056. else if (cptType) {
  19057. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  19058. }
  19059. }, this);
  19060. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  19061. // Still dirty
  19062. if (this[OPTION_UPDATED]) {
  19063. // FIXME Pass payload ?
  19064. updateMethods.prepareAndUpdate.call(this, payload);
  19065. this[OPTION_UPDATED] = false;
  19066. }
  19067. else {
  19068. updateMethods[updateMethod].call(this, payload);
  19069. }
  19070. }
  19071. // Follow the rule of action batch
  19072. if (batched) {
  19073. eventObj = {
  19074. type: actionInfo.event || payloadType,
  19075. escapeConnect: escapeConnect,
  19076. batch: eventObjBatch
  19077. };
  19078. }
  19079. else {
  19080. eventObj = eventObjBatch[0];
  19081. }
  19082. this[IN_MAIN_PROCESS] = false;
  19083. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  19084. }
  19085. function flushPendingActions(silent) {
  19086. var pendingActions = this._pendingActions;
  19087. while (pendingActions.length) {
  19088. var payload = pendingActions.shift();
  19089. doDispatchAction.call(this, payload, silent);
  19090. }
  19091. }
  19092. function triggerUpdatedEvent(silent) {
  19093. !silent && this.trigger('updated');
  19094. }
  19095. /**
  19096. * Register event
  19097. * @method
  19098. */
  19099. echartsProto.on = createRegisterEventWithLowercaseName('on');
  19100. echartsProto.off = createRegisterEventWithLowercaseName('off');
  19101. echartsProto.one = createRegisterEventWithLowercaseName('one');
  19102. /**
  19103. * @param {string} methodName
  19104. * @private
  19105. */
  19106. function invokeUpdateMethod(methodName, ecModel, payload) {
  19107. var api = this._api;
  19108. // Update all components
  19109. each(this._componentsViews, function (component) {
  19110. var componentModel = component.__model;
  19111. component[methodName](componentModel, ecModel, api, payload);
  19112. updateZ(componentModel, component);
  19113. }, this);
  19114. // Upate all charts
  19115. ecModel.eachSeries(function (seriesModel, idx) {
  19116. var chart = this._chartsMap[seriesModel.__viewId];
  19117. chart[methodName](seriesModel, ecModel, api, payload);
  19118. updateZ(seriesModel, chart);
  19119. updateProgressiveAndBlend(seriesModel, chart);
  19120. }, this);
  19121. // If use hover layer
  19122. updateHoverLayerStatus(this._zr, ecModel);
  19123. // Post render
  19124. each(postUpdateFuncs, function (func) {
  19125. func(ecModel, api);
  19126. });
  19127. }
  19128. /**
  19129. * Prepare view instances of charts and components
  19130. * @param {module:echarts/model/Global} ecModel
  19131. * @private
  19132. */
  19133. function prepareView(type, ecModel) {
  19134. var isComponent = type === 'component';
  19135. var viewList = isComponent ? this._componentsViews : this._chartsViews;
  19136. var viewMap = isComponent ? this._componentsMap : this._chartsMap;
  19137. var zr = this._zr;
  19138. for (var i = 0; i < viewList.length; i++) {
  19139. viewList[i].__alive = false;
  19140. }
  19141. ecModel[isComponent ? 'eachComponent' : 'eachSeries'](function (componentType, model) {
  19142. if (isComponent) {
  19143. if (componentType === 'series') {
  19144. return;
  19145. }
  19146. }
  19147. else {
  19148. model = componentType;
  19149. }
  19150. // Consider: id same and type changed.
  19151. var viewId = '_ec_' + model.id + '_' + model.type;
  19152. var view = viewMap[viewId];
  19153. if (!view) {
  19154. var classType = parseClassType(model.type);
  19155. var Clazz = isComponent
  19156. ? Component.getClass(classType.main, classType.sub)
  19157. : Chart.getClass(classType.sub);
  19158. if (Clazz) {
  19159. view = new Clazz();
  19160. view.init(ecModel, this._api);
  19161. viewMap[viewId] = view;
  19162. viewList.push(view);
  19163. zr.add(view.group);
  19164. }
  19165. else {
  19166. // Error
  19167. return;
  19168. }
  19169. }
  19170. model.__viewId = view.__id = viewId;
  19171. view.__alive = true;
  19172. view.__model = model;
  19173. view.group.__ecComponentInfo = {
  19174. mainType: model.mainType,
  19175. index: model.componentIndex
  19176. };
  19177. }, this);
  19178. for (var i = 0; i < viewList.length;) {
  19179. var view = viewList[i];
  19180. if (!view.__alive) {
  19181. zr.remove(view.group);
  19182. view.dispose(ecModel, this._api);
  19183. viewList.splice(i, 1);
  19184. delete viewMap[view.__id];
  19185. view.__id = view.group.__ecComponentInfo = null;
  19186. }
  19187. else {
  19188. i++;
  19189. }
  19190. }
  19191. }
  19192. /**
  19193. * Processor data in each series
  19194. *
  19195. * @param {module:echarts/model/Global} ecModel
  19196. * @private
  19197. */
  19198. function processData(ecModel, api) {
  19199. each(dataProcessorFuncs, function (process) {
  19200. process.func(ecModel, api);
  19201. });
  19202. }
  19203. /**
  19204. * @private
  19205. */
  19206. function stackSeriesData(ecModel) {
  19207. var stackedDataMap = {};
  19208. ecModel.eachSeries(function (series) {
  19209. var stack = series.get('stack');
  19210. var data = series.getData();
  19211. if (stack && data.type === 'list') {
  19212. var previousStack = stackedDataMap[stack];
  19213. // Avoid conflict with Object.prototype
  19214. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  19215. data.stackedOn = previousStack;
  19216. }
  19217. stackedDataMap[stack] = data;
  19218. }
  19219. });
  19220. }
  19221. /**
  19222. * Layout before each chart render there series, special visual encoding stage
  19223. *
  19224. * @param {module:echarts/model/Global} ecModel
  19225. * @private
  19226. */
  19227. function doLayout(ecModel, payload) {
  19228. var api = this._api;
  19229. each(visualFuncs, function (visual) {
  19230. if (visual.isLayout) {
  19231. visual.func(ecModel, api, payload);
  19232. }
  19233. });
  19234. }
  19235. /**
  19236. * Encode visual infomation from data after data processing
  19237. *
  19238. * @param {module:echarts/model/Global} ecModel
  19239. * @param {object} layout
  19240. * @param {boolean} [excludesLayout]
  19241. * @private
  19242. */
  19243. function doVisualEncoding(ecModel, payload, excludesLayout) {
  19244. var api = this._api;
  19245. ecModel.clearColorPalette();
  19246. ecModel.eachSeries(function (seriesModel) {
  19247. seriesModel.clearColorPalette();
  19248. });
  19249. each(visualFuncs, function (visual) {
  19250. (!excludesLayout || !visual.isLayout)
  19251. && visual.func(ecModel, api, payload);
  19252. });
  19253. }
  19254. /**
  19255. * Render each chart and component
  19256. * @private
  19257. */
  19258. function doRender(ecModel, payload) {
  19259. var api = this._api;
  19260. // Render all components
  19261. each(this._componentsViews, function (componentView) {
  19262. var componentModel = componentView.__model;
  19263. componentView.render(componentModel, ecModel, api, payload);
  19264. updateZ(componentModel, componentView);
  19265. }, this);
  19266. each(this._chartsViews, function (chart) {
  19267. chart.__alive = false;
  19268. }, this);
  19269. // Render all charts
  19270. ecModel.eachSeries(function (seriesModel, idx) {
  19271. var chartView = this._chartsMap[seriesModel.__viewId];
  19272. chartView.__alive = true;
  19273. chartView.render(seriesModel, ecModel, api, payload);
  19274. chartView.group.silent = !!seriesModel.get('silent');
  19275. updateZ(seriesModel, chartView);
  19276. updateProgressiveAndBlend(seriesModel, chartView);
  19277. }, this);
  19278. // If use hover layer
  19279. updateHoverLayerStatus(this._zr, ecModel);
  19280. // Remove groups of unrendered charts
  19281. each(this._chartsViews, function (chart) {
  19282. if (!chart.__alive) {
  19283. chart.remove(ecModel, api);
  19284. }
  19285. }, this);
  19286. }
  19287. var MOUSE_EVENT_NAMES = [
  19288. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  19289. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  19290. ];
  19291. /**
  19292. * @private
  19293. */
  19294. echartsProto._initEvents = function () {
  19295. each(MOUSE_EVENT_NAMES, function (eveName) {
  19296. this._zr.on(eveName, function (e) {
  19297. var ecModel = this.getModel();
  19298. var el = e.target;
  19299. var params;
  19300. // no e.target when 'globalout'.
  19301. if (eveName === 'globalout') {
  19302. params = {};
  19303. }
  19304. else if (el && el.dataIndex != null) {
  19305. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  19306. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  19307. }
  19308. // If element has custom eventData of components
  19309. else if (el && el.eventData) {
  19310. params = extend({}, el.eventData);
  19311. }
  19312. if (params) {
  19313. params.event = e;
  19314. params.type = eveName;
  19315. this.trigger(eveName, params);
  19316. }
  19317. }, this);
  19318. }, this);
  19319. each(eventActionMap, function (actionType, eventType) {
  19320. this._messageCenter.on(eventType, function (event) {
  19321. this.trigger(eventType, event);
  19322. }, this);
  19323. }, this);
  19324. };
  19325. /**
  19326. * @return {boolean}
  19327. */
  19328. echartsProto.isDisposed = function () {
  19329. return this._disposed;
  19330. };
  19331. /**
  19332. * Clear
  19333. */
  19334. echartsProto.clear = function () {
  19335. this.setOption({ series: [] }, true);
  19336. };
  19337. /**
  19338. * Dispose instance
  19339. */
  19340. echartsProto.dispose = function () {
  19341. if (this._disposed) {
  19342. if (__DEV__) {
  19343. console.warn('Instance ' + this.id + ' has been disposed');
  19344. }
  19345. return;
  19346. }
  19347. this._disposed = true;
  19348. var api = this._api;
  19349. var ecModel = this._model;
  19350. each(this._componentsViews, function (component) {
  19351. component.dispose(ecModel, api);
  19352. });
  19353. each(this._chartsViews, function (chart) {
  19354. chart.dispose(ecModel, api);
  19355. });
  19356. // Dispose after all views disposed
  19357. this._zr.dispose();
  19358. delete instances[this.id];
  19359. };
  19360. mixin(ECharts, Eventful);
  19361. function updateHoverLayerStatus(zr, ecModel) {
  19362. var storage = zr.storage;
  19363. var elCount = 0;
  19364. storage.traverse(function (el) {
  19365. if (!el.isGroup) {
  19366. elCount++;
  19367. }
  19368. });
  19369. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  19370. storage.traverse(function (el) {
  19371. if (!el.isGroup) {
  19372. el.useHoverLayer = true;
  19373. }
  19374. });
  19375. }
  19376. }
  19377. /**
  19378. * Update chart progressive and blend.
  19379. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  19380. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  19381. */
  19382. function updateProgressiveAndBlend(seriesModel, chartView) {
  19383. // Progressive configuration
  19384. var elCount = 0;
  19385. chartView.group.traverse(function (el) {
  19386. if (el.type !== 'group' && !el.ignore) {
  19387. elCount++;
  19388. }
  19389. });
  19390. var frameDrawNum = +seriesModel.get('progressive');
  19391. var needProgressive = elCount > seriesModel.get('progressiveThreshold') && frameDrawNum && !env$1.node;
  19392. if (needProgressive) {
  19393. chartView.group.traverse(function (el) {
  19394. // FIXME marker and other components
  19395. if (!el.isGroup) {
  19396. el.progressive = needProgressive ?
  19397. Math.floor(elCount++ / frameDrawNum) : -1;
  19398. if (needProgressive) {
  19399. el.stopAnimation(true);
  19400. }
  19401. }
  19402. });
  19403. }
  19404. // Blend configration
  19405. var blendMode = seriesModel.get('blendMode') || null;
  19406. if (__DEV__) {
  19407. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  19408. console.warn('Only canvas support blendMode');
  19409. }
  19410. }
  19411. chartView.group.traverse(function (el) {
  19412. // FIXME marker and other components
  19413. if (!el.isGroup) {
  19414. el.setStyle('blend', blendMode);
  19415. }
  19416. });
  19417. }
  19418. /**
  19419. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  19420. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  19421. */
  19422. function updateZ(model, view) {
  19423. var z = model.get('z');
  19424. var zlevel = model.get('zlevel');
  19425. // Set z and zlevel
  19426. view.group.traverse(function (el) {
  19427. if (el.type !== 'group') {
  19428. z != null && (el.z = z);
  19429. zlevel != null && (el.zlevel = zlevel);
  19430. }
  19431. });
  19432. }
  19433. function createExtensionAPI(ecInstance) {
  19434. var coordSysMgr = ecInstance._coordSysMgr;
  19435. return extend(new ExtensionAPI(ecInstance), {
  19436. // Inject methods
  19437. getCoordinateSystems: bind(
  19438. coordSysMgr.getCoordinateSystems, coordSysMgr
  19439. ),
  19440. getComponentByElement: function (el) {
  19441. while (el) {
  19442. var modelInfo = el.__ecComponentInfo;
  19443. if (modelInfo != null) {
  19444. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  19445. }
  19446. el = el.parent;
  19447. }
  19448. }
  19449. });
  19450. }
  19451. /**
  19452. * @type {Object} key: actionType.
  19453. * @inner
  19454. */
  19455. var actions = {};
  19456. /**
  19457. * Map eventType to actionType
  19458. * @type {Object}
  19459. */
  19460. var eventActionMap = {};
  19461. /**
  19462. * Data processor functions of each stage
  19463. * @type {Array.<Object.<string, Function>>}
  19464. * @inner
  19465. */
  19466. var dataProcessorFuncs = [];
  19467. /**
  19468. * @type {Array.<Function>}
  19469. * @inner
  19470. */
  19471. var optionPreprocessorFuncs = [];
  19472. /**
  19473. * @type {Array.<Function>}
  19474. * @inner
  19475. */
  19476. var postUpdateFuncs = [];
  19477. /**
  19478. * Visual encoding functions of each stage
  19479. * @type {Array.<Object.<string, Function>>}
  19480. * @inner
  19481. */
  19482. var visualFuncs = [];
  19483. /**
  19484. * Theme storage
  19485. * @type {Object.<key, Object>}
  19486. */
  19487. var themeStorage = {};
  19488. /**
  19489. * Loading effects
  19490. */
  19491. var loadingEffects = {};
  19492. var instances = {};
  19493. var connectedGroups = {};
  19494. var idBase = new Date() - 0;
  19495. var groupIdBase = new Date() - 0;
  19496. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  19497. var mapDataStores = {};
  19498. function enableConnect(chart) {
  19499. var STATUS_PENDING = 0;
  19500. var STATUS_UPDATING = 1;
  19501. var STATUS_UPDATED = 2;
  19502. var STATUS_KEY = '__connectUpdateStatus';
  19503. function updateConnectedChartsStatus(charts, status) {
  19504. for (var i = 0; i < charts.length; i++) {
  19505. var otherChart = charts[i];
  19506. otherChart[STATUS_KEY] = status;
  19507. }
  19508. }
  19509. each$1(eventActionMap, function (actionType, eventType) {
  19510. chart._messageCenter.on(eventType, function (event) {
  19511. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  19512. if (event && event.escapeConnect) {
  19513. return;
  19514. }
  19515. var action = chart.makeActionFromEvent(event);
  19516. var otherCharts = [];
  19517. each$1(instances, function (otherChart) {
  19518. if (otherChart !== chart && otherChart.group === chart.group) {
  19519. otherCharts.push(otherChart);
  19520. }
  19521. });
  19522. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  19523. each(otherCharts, function (otherChart) {
  19524. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  19525. otherChart.dispatchAction(action);
  19526. }
  19527. });
  19528. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  19529. }
  19530. });
  19531. });
  19532. }
  19533. /**
  19534. * @param {HTMLElement} dom
  19535. * @param {Object} [theme]
  19536. * @param {Object} opts
  19537. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  19538. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  19539. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  19540. * Can be 'auto' (the same as null/undefined)
  19541. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  19542. * Can be 'auto' (the same as null/undefined)
  19543. */
  19544. function init(dom, theme, opts) {
  19545. if (__DEV__) {
  19546. // Check version
  19547. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  19548. throw new Error(
  19549. 'zrender/src ' + version$1
  19550. + ' is too old for ECharts ' + version
  19551. + '. Current version need ZRender '
  19552. + dependencies.zrender + '+'
  19553. );
  19554. }
  19555. if (!dom) {
  19556. throw new Error('Initialize failed: invalid dom.');
  19557. }
  19558. }
  19559. var existInstance = getInstanceByDom(dom);
  19560. if (existInstance) {
  19561. if (__DEV__) {
  19562. console.warn('There is a chart instance already initialized on the dom.');
  19563. }
  19564. return existInstance;
  19565. }
  19566. if (__DEV__) {
  19567. if (isDom(dom)
  19568. && dom.nodeName.toUpperCase() !== 'CANVAS'
  19569. && (
  19570. (!dom.clientWidth && (!opts || opts.width == null))
  19571. || (!dom.clientHeight && (!opts || opts.height == null))
  19572. )
  19573. ) {
  19574. console.warn('Can\'t get dom width or height');
  19575. }
  19576. }
  19577. var chart = new ECharts(dom, theme, opts);
  19578. chart.id = 'ec_' + idBase++;
  19579. instances[chart.id] = chart;
  19580. if (dom.setAttribute) {
  19581. dom.setAttribute(DOM_ATTRIBUTE_KEY, chart.id);
  19582. }
  19583. else {
  19584. dom[DOM_ATTRIBUTE_KEY] = chart.id;
  19585. }
  19586. enableConnect(chart);
  19587. return chart;
  19588. }
  19589. /**
  19590. * @return {string|Array.<module:echarts~ECharts>} groupId
  19591. */
  19592. function connect(groupId) {
  19593. // Is array of charts
  19594. if (isArray(groupId)) {
  19595. var charts = groupId;
  19596. groupId = null;
  19597. // If any chart has group
  19598. each$1(charts, function (chart) {
  19599. if (chart.group != null) {
  19600. groupId = chart.group;
  19601. }
  19602. });
  19603. groupId = groupId || ('g_' + groupIdBase++);
  19604. each$1(charts, function (chart) {
  19605. chart.group = groupId;
  19606. });
  19607. }
  19608. connectedGroups[groupId] = true;
  19609. return groupId;
  19610. }
  19611. /**
  19612. * @DEPRECATED
  19613. * @return {string} groupId
  19614. */
  19615. function disConnect(groupId) {
  19616. connectedGroups[groupId] = false;
  19617. }
  19618. /**
  19619. * @return {string} groupId
  19620. */
  19621. var disconnect = disConnect;
  19622. /**
  19623. * Dispose a chart instance
  19624. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  19625. */
  19626. function dispose(chart) {
  19627. if (typeof chart === 'string') {
  19628. chart = instances[chart];
  19629. }
  19630. else if (!(chart instanceof ECharts)){
  19631. // Try to treat as dom
  19632. chart = getInstanceByDom(chart);
  19633. }
  19634. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  19635. chart.dispose();
  19636. }
  19637. }
  19638. /**
  19639. * @param {HTMLElement} dom
  19640. * @return {echarts~ECharts}
  19641. */
  19642. function getInstanceByDom(dom) {
  19643. var key;
  19644. if (dom.getAttribute) {
  19645. key = dom.getAttribute(DOM_ATTRIBUTE_KEY);
  19646. }
  19647. else {
  19648. key = dom[DOM_ATTRIBUTE_KEY];
  19649. }
  19650. return instances[key];
  19651. }
  19652. /**
  19653. * @param {string} key
  19654. * @return {echarts~ECharts}
  19655. */
  19656. function getInstanceById(key) {
  19657. return instances[key];
  19658. }
  19659. /**
  19660. * Register theme
  19661. */
  19662. function registerTheme(name, theme) {
  19663. themeStorage[name] = theme;
  19664. }
  19665. /**
  19666. * Register option preprocessor
  19667. * @param {Function} preprocessorFunc
  19668. */
  19669. function registerPreprocessor(preprocessorFunc) {
  19670. optionPreprocessorFuncs.push(preprocessorFunc);
  19671. }
  19672. /**
  19673. * @param {number} [priority=1000]
  19674. * @param {Function} processorFunc
  19675. */
  19676. function registerProcessor(priority, processorFunc) {
  19677. if (typeof priority === 'function') {
  19678. processorFunc = priority;
  19679. priority = PRIORITY_PROCESSOR_FILTER;
  19680. }
  19681. if (__DEV__) {
  19682. if (isNaN(priority)) {
  19683. throw new Error('Unkown processor priority');
  19684. }
  19685. }
  19686. dataProcessorFuncs.push({
  19687. prio: priority,
  19688. func: processorFunc
  19689. });
  19690. }
  19691. /**
  19692. * Register postUpdater
  19693. * @param {Function} postUpdateFunc
  19694. */
  19695. function registerPostUpdate(postUpdateFunc) {
  19696. postUpdateFuncs.push(postUpdateFunc);
  19697. }
  19698. /**
  19699. * Usage:
  19700. * registerAction('someAction', 'someEvent', function () { ... });
  19701. * registerAction('someAction', function () { ... });
  19702. * registerAction(
  19703. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  19704. * function () { ... }
  19705. * );
  19706. *
  19707. * @param {(string|Object)} actionInfo
  19708. * @param {string} actionInfo.type
  19709. * @param {string} [actionInfo.event]
  19710. * @param {string} [actionInfo.update]
  19711. * @param {string} [eventName]
  19712. * @param {Function} action
  19713. */
  19714. function registerAction(actionInfo, eventName, action) {
  19715. if (typeof eventName === 'function') {
  19716. action = eventName;
  19717. eventName = '';
  19718. }
  19719. var actionType = isObject(actionInfo)
  19720. ? actionInfo.type
  19721. : ([actionInfo, actionInfo = {
  19722. event: eventName
  19723. }][0]);
  19724. // Event name is all lowercase
  19725. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  19726. eventName = actionInfo.event;
  19727. // Validate action type and event name.
  19728. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  19729. if (!actions[actionType]) {
  19730. actions[actionType] = {action: action, actionInfo: actionInfo};
  19731. }
  19732. eventActionMap[eventName] = actionType;
  19733. }
  19734. /**
  19735. * @param {string} type
  19736. * @param {*} CoordinateSystem
  19737. */
  19738. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  19739. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  19740. }
  19741. /**
  19742. * Get dimensions of specified coordinate system.
  19743. * @param {string} type
  19744. * @return {Array.<string|Object>}
  19745. */
  19746. function getCoordinateSystemDimensions(type) {
  19747. var coordSysCreator = CoordinateSystemManager.get(type);
  19748. if (coordSysCreator) {
  19749. return coordSysCreator.getDimensionsInfo
  19750. ? coordSysCreator.getDimensionsInfo()
  19751. : coordSysCreator.dimensions.slice();
  19752. }
  19753. }
  19754. /**
  19755. * Layout is a special stage of visual encoding
  19756. * Most visual encoding like color are common for different chart
  19757. * But each chart has it's own layout algorithm
  19758. *
  19759. * @param {number} [priority=1000]
  19760. * @param {Function} layoutFunc
  19761. */
  19762. function registerLayout(priority, layoutFunc) {
  19763. if (typeof priority === 'function') {
  19764. layoutFunc = priority;
  19765. priority = PRIORITY_VISUAL_LAYOUT;
  19766. }
  19767. if (__DEV__) {
  19768. if (isNaN(priority)) {
  19769. throw new Error('Unkown layout priority');
  19770. }
  19771. }
  19772. visualFuncs.push({
  19773. prio: priority,
  19774. func: layoutFunc,
  19775. isLayout: true
  19776. });
  19777. }
  19778. /**
  19779. * @param {number} [priority=3000]
  19780. * @param {Function} visualFunc
  19781. */
  19782. function registerVisual(priority, visualFunc) {
  19783. if (typeof priority === 'function') {
  19784. visualFunc = priority;
  19785. priority = PRIORITY_VISUAL_CHART;
  19786. }
  19787. if (__DEV__) {
  19788. if (isNaN(priority)) {
  19789. throw new Error('Unkown visual priority');
  19790. }
  19791. }
  19792. visualFuncs.push({
  19793. prio: priority,
  19794. func: visualFunc
  19795. });
  19796. }
  19797. /**
  19798. * @param {string} name
  19799. */
  19800. function registerLoading(name, loadingFx) {
  19801. loadingEffects[name] = loadingFx;
  19802. }
  19803. /**
  19804. * @param {Object} opts
  19805. * @param {string} [superClass]
  19806. */
  19807. function extendComponentModel(opts/*, superClass*/) {
  19808. // var Clazz = ComponentModel;
  19809. // if (superClass) {
  19810. // var classType = parseClassType(superClass);
  19811. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  19812. // }
  19813. return ComponentModel.extend(opts);
  19814. }
  19815. /**
  19816. * @param {Object} opts
  19817. * @param {string} [superClass]
  19818. */
  19819. function extendComponentView(opts/*, superClass*/) {
  19820. // var Clazz = ComponentView;
  19821. // if (superClass) {
  19822. // var classType = parseClassType(superClass);
  19823. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  19824. // }
  19825. return Component.extend(opts);
  19826. }
  19827. /**
  19828. * @param {Object} opts
  19829. * @param {string} [superClass]
  19830. */
  19831. function extendSeriesModel(opts/*, superClass*/) {
  19832. // var Clazz = SeriesModel;
  19833. // if (superClass) {
  19834. // superClass = 'series.' + superClass.replace('series.', '');
  19835. // var classType = parseClassType(superClass);
  19836. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  19837. // }
  19838. return SeriesModel.extend(opts);
  19839. }
  19840. /**
  19841. * @param {Object} opts
  19842. * @param {string} [superClass]
  19843. */
  19844. function extendChartView(opts/*, superClass*/) {
  19845. // var Clazz = ChartView;
  19846. // if (superClass) {
  19847. // superClass = superClass.replace('series.', '');
  19848. // var classType = parseClassType(superClass);
  19849. // Clazz = ChartView.getClass(classType.main, true);
  19850. // }
  19851. return Chart.extend(opts);
  19852. }
  19853. /**
  19854. * ZRender need a canvas context to do measureText.
  19855. * But in node environment canvas may be created by node-canvas.
  19856. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  19857. *
  19858. * Be careful of using it in the browser.
  19859. *
  19860. * @param {Function} creator
  19861. * @example
  19862. * var Canvas = require('canvas');
  19863. * var echarts = require('echarts');
  19864. * echarts.setCanvasCreator(function () {
  19865. * // Small size is enough.
  19866. * return new Canvas(32, 32);
  19867. * });
  19868. */
  19869. function setCanvasCreator(creator) {
  19870. $override('createCanvas', creator);
  19871. }
  19872. /**
  19873. * @param {string} mapName
  19874. * @param {Object|string} geoJson
  19875. * @param {Object} [specialAreas]
  19876. *
  19877. * @example
  19878. * $.get('USA.json', function (geoJson) {
  19879. * echarts.registerMap('USA', geoJson);
  19880. * // Or
  19881. * echarts.registerMap('USA', {
  19882. * geoJson: geoJson,
  19883. * specialAreas: {}
  19884. * })
  19885. * });
  19886. */
  19887. function registerMap(mapName, geoJson, specialAreas) {
  19888. if (geoJson.geoJson && !geoJson.features) {
  19889. specialAreas = geoJson.specialAreas;
  19890. geoJson = geoJson.geoJson;
  19891. }
  19892. if (typeof geoJson === 'string') {
  19893. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  19894. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  19895. }
  19896. mapDataStores[mapName] = {
  19897. geoJson: geoJson,
  19898. specialAreas: specialAreas
  19899. };
  19900. }
  19901. /**
  19902. * @param {string} mapName
  19903. * @return {Object}
  19904. */
  19905. function getMap(mapName) {
  19906. return mapDataStores[mapName];
  19907. }
  19908. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  19909. registerPreprocessor(backwardCompat);
  19910. registerLoading('default', loadingDefault);
  19911. // Default actions
  19912. registerAction({
  19913. type: 'highlight',
  19914. event: 'highlight',
  19915. update: 'highlight'
  19916. }, noop);
  19917. registerAction({
  19918. type: 'downplay',
  19919. event: 'downplay',
  19920. update: 'downplay'
  19921. }, noop);
  19922. // For backward compatibility, where the namespace `dataTool` will
  19923. // be mounted on `echarts` is the extension `dataTool` is imported.
  19924. var dataTool = {};
  19925. function defaultKeyGetter(item) {
  19926. return item;
  19927. }
  19928. /**
  19929. * @param {Array} oldArr
  19930. * @param {Array} newArr
  19931. * @param {Function} oldKeyGetter
  19932. * @param {Function} newKeyGetter
  19933. * @param {Object} [context] Can be visited by this.context in callback.
  19934. */
  19935. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  19936. this._old = oldArr;
  19937. this._new = newArr;
  19938. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  19939. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  19940. this.context = context;
  19941. }
  19942. DataDiffer.prototype = {
  19943. constructor: DataDiffer,
  19944. /**
  19945. * Callback function when add a data
  19946. */
  19947. add: function (func) {
  19948. this._add = func;
  19949. return this;
  19950. },
  19951. /**
  19952. * Callback function when update a data
  19953. */
  19954. update: function (func) {
  19955. this._update = func;
  19956. return this;
  19957. },
  19958. /**
  19959. * Callback function when remove a data
  19960. */
  19961. remove: function (func) {
  19962. this._remove = func;
  19963. return this;
  19964. },
  19965. execute: function () {
  19966. var oldArr = this._old;
  19967. var newArr = this._new;
  19968. var oldDataIndexMap = {};
  19969. var newDataIndexMap = {};
  19970. var oldDataKeyArr = [];
  19971. var newDataKeyArr = [];
  19972. var i;
  19973. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  19974. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  19975. // Travel by inverted order to make sure order consistency
  19976. // when duplicate keys exists (consider newDataIndex.pop() below).
  19977. // For performance consideration, these code below do not look neat.
  19978. for (i = 0; i < oldArr.length; i++) {
  19979. var key = oldDataKeyArr[i];
  19980. var idx = newDataIndexMap[key];
  19981. // idx can never be empty array here. see 'set null' logic below.
  19982. if (idx != null) {
  19983. // Consider there is duplicate key (for example, use dataItem.name as key).
  19984. // We should make sure every item in newArr and oldArr can be visited.
  19985. var len = idx.length;
  19986. if (len) {
  19987. len === 1 && (newDataIndexMap[key] = null);
  19988. idx = idx.unshift();
  19989. }
  19990. else {
  19991. newDataIndexMap[key] = null;
  19992. }
  19993. this._update && this._update(idx, i);
  19994. }
  19995. else {
  19996. this._remove && this._remove(i);
  19997. }
  19998. }
  19999. for (var i = 0; i < newDataKeyArr.length; i++) {
  20000. var key = newDataKeyArr[i];
  20001. if (newDataIndexMap.hasOwnProperty(key)) {
  20002. var idx = newDataIndexMap[key];
  20003. if (idx == null) {
  20004. continue;
  20005. }
  20006. // idx can never be empty array here. see 'set null' logic above.
  20007. if (!idx.length) {
  20008. this._add && this._add(idx);
  20009. }
  20010. else {
  20011. for (var j = 0, len = idx.length; j < len; j++) {
  20012. this._add && this._add(idx[j]);
  20013. }
  20014. }
  20015. }
  20016. }
  20017. }
  20018. };
  20019. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  20020. for (var i = 0; i < arr.length; i++) {
  20021. // Add prefix to avoid conflict with Object.prototype.
  20022. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  20023. var existence = map[key];
  20024. if (existence == null) {
  20025. keyArr.push(key);
  20026. map[key] = i;
  20027. }
  20028. else {
  20029. if (!existence.length) {
  20030. map[key] = existence = [existence];
  20031. }
  20032. existence.push(i);
  20033. }
  20034. }
  20035. }
  20036. /**
  20037. * List for data storage
  20038. * @module echarts/data/List
  20039. */
  20040. var isObject$4 = isObject;
  20041. var UNDEFINED = 'undefined';
  20042. var globalObj = typeof window === UNDEFINED ? global : window;
  20043. var dataCtors = {
  20044. 'float': typeof globalObj.Float64Array === UNDEFINED
  20045. ? Array : globalObj.Float64Array,
  20046. 'int': typeof globalObj.Int32Array === UNDEFINED
  20047. ? Array : globalObj.Int32Array,
  20048. // Ordinal data type can be string or int
  20049. 'ordinal': Array,
  20050. 'number': Array,
  20051. 'time': Array
  20052. };
  20053. var TRANSFERABLE_PROPERTIES = [
  20054. 'stackedOn', 'hasItemOption', '_nameList', '_idList', '_rawData'
  20055. ];
  20056. function transferProperties(a, b) {
  20057. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  20058. if (b.hasOwnProperty(propName)) {
  20059. a[propName] = b[propName];
  20060. }
  20061. });
  20062. a.__wrappedMethods = b.__wrappedMethods;
  20063. }
  20064. function DefaultDataProvider(dataArray) {
  20065. this._array = dataArray || [];
  20066. }
  20067. DefaultDataProvider.prototype.pure = false;
  20068. DefaultDataProvider.prototype.count = function () {
  20069. return this._array.length;
  20070. };
  20071. DefaultDataProvider.prototype.getItem = function (idx) {
  20072. return this._array[idx];
  20073. };
  20074. /**
  20075. * @constructor
  20076. * @alias module:echarts/data/List
  20077. *
  20078. * @param {Array.<string|Object>} dimensions
  20079. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  20080. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  20081. * @param {module:echarts/model/Model} hostModel
  20082. */
  20083. var List = function (dimensions, hostModel) {
  20084. dimensions = dimensions || ['x', 'y'];
  20085. var dimensionInfos = {};
  20086. var dimensionNames = [];
  20087. for (var i = 0; i < dimensions.length; i++) {
  20088. var dimensionName;
  20089. var dimensionInfo = {};
  20090. if (typeof dimensions[i] === 'string') {
  20091. dimensionName = dimensions[i];
  20092. dimensionInfo = {
  20093. name: dimensionName,
  20094. coordDim: dimensionName,
  20095. coordDimIndex: 0,
  20096. stackable: false,
  20097. // Type can be 'float', 'int', 'number'
  20098. // Default is number, Precision of float may not enough
  20099. type: 'number'
  20100. };
  20101. }
  20102. else {
  20103. dimensionInfo = dimensions[i];
  20104. dimensionName = dimensionInfo.name;
  20105. dimensionInfo.type = dimensionInfo.type || 'number';
  20106. if (!dimensionInfo.coordDim) {
  20107. dimensionInfo.coordDim = dimensionName;
  20108. dimensionInfo.coordDimIndex = 0;
  20109. }
  20110. }
  20111. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  20112. dimensionNames.push(dimensionName);
  20113. dimensionInfos[dimensionName] = dimensionInfo;
  20114. }
  20115. /**
  20116. * @readOnly
  20117. * @type {Array.<string>}
  20118. */
  20119. this.dimensions = dimensionNames;
  20120. /**
  20121. * Infomation of each data dimension, like data type.
  20122. * @type {Object}
  20123. */
  20124. this._dimensionInfos = dimensionInfos;
  20125. /**
  20126. * @type {module:echarts/model/Model}
  20127. */
  20128. this.hostModel = hostModel;
  20129. /**
  20130. * @type {module:echarts/model/Model}
  20131. */
  20132. this.dataType;
  20133. /**
  20134. * Indices stores the indices of data subset after filtered.
  20135. * This data subset will be used in chart.
  20136. * @type {Array.<number>}
  20137. * @readOnly
  20138. */
  20139. this.indices = [];
  20140. /**
  20141. * Data storage
  20142. * @type {Object.<key, TypedArray|Array>}
  20143. * @private
  20144. */
  20145. this._storage = {};
  20146. /**
  20147. * @type {Array.<string>}
  20148. */
  20149. this._nameList = [];
  20150. /**
  20151. * @type {Array.<string>}
  20152. */
  20153. this._idList = [];
  20154. /**
  20155. * Models of data option is stored sparse for optimizing memory cost
  20156. * @type {Array.<module:echarts/model/Model>}
  20157. * @private
  20158. */
  20159. this._optionModels = [];
  20160. /**
  20161. * @param {module:echarts/data/List}
  20162. */
  20163. this.stackedOn = null;
  20164. /**
  20165. * Global visual properties after visual coding
  20166. * @type {Object}
  20167. * @private
  20168. */
  20169. this._visual = {};
  20170. /**
  20171. * Globel layout properties.
  20172. * @type {Object}
  20173. * @private
  20174. */
  20175. this._layout = {};
  20176. /**
  20177. * Item visual properties after visual coding
  20178. * @type {Array.<Object>}
  20179. * @private
  20180. */
  20181. this._itemVisuals = [];
  20182. /**
  20183. * Item layout properties after layout
  20184. * @type {Array.<Object>}
  20185. * @private
  20186. */
  20187. this._itemLayouts = [];
  20188. /**
  20189. * Graphic elemnents
  20190. * @type {Array.<module:zrender/Element>}
  20191. * @private
  20192. */
  20193. this._graphicEls = [];
  20194. /**
  20195. * @type {Array.<Array|Object>}
  20196. * @private
  20197. */
  20198. this._rawData;
  20199. /**
  20200. * @type {Object}
  20201. * @private
  20202. */
  20203. this._extent;
  20204. };
  20205. var listProto = List.prototype;
  20206. listProto.type = 'list';
  20207. /**
  20208. * If each data item has it's own option
  20209. * @type {boolean}
  20210. */
  20211. listProto.hasItemOption = true;
  20212. /**
  20213. * Get dimension name
  20214. * @param {string|number} dim
  20215. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  20216. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  20217. * @return {string} Concrete dim name.
  20218. */
  20219. listProto.getDimension = function (dim) {
  20220. if (!isNaN(dim)) {
  20221. dim = this.dimensions[dim] || dim;
  20222. }
  20223. return dim;
  20224. };
  20225. /**
  20226. * Get type and stackable info of particular dimension
  20227. * @param {string|number} dim
  20228. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  20229. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  20230. */
  20231. listProto.getDimensionInfo = function (dim) {
  20232. return clone(this._dimensionInfos[this.getDimension(dim)]);
  20233. };
  20234. /**
  20235. * Initialize from data
  20236. * @param {Array.<Object|number|Array>} data
  20237. * @param {Array.<string>} [nameList]
  20238. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  20239. */
  20240. listProto.initData = function (data, nameList, dimValueGetter) {
  20241. data = data || [];
  20242. var isDataArray = isArray(data);
  20243. if (isDataArray) {
  20244. data = new DefaultDataProvider(data);
  20245. }
  20246. if (__DEV__) {
  20247. if (!isDataArray && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  20248. throw new Error('Inavlid data provider.');
  20249. }
  20250. }
  20251. this._rawData = data;
  20252. // Clear
  20253. var storage = this._storage = {};
  20254. var indices = this.indices = [];
  20255. var dimensions = this.dimensions;
  20256. var dimensionInfoMap = this._dimensionInfos;
  20257. var size = data.count();
  20258. var idList = [];
  20259. var nameRepeatCount = {};
  20260. var nameDimIdx;
  20261. nameList = nameList || [];
  20262. // Init storage
  20263. for (var i = 0; i < dimensions.length; i++) {
  20264. var dimInfo = dimensionInfoMap[dimensions[i]];
  20265. dimInfo.otherDims.itemName === 0 && (nameDimIdx = i);
  20266. var DataCtor = dataCtors[dimInfo.type];
  20267. storage[dimensions[i]] = new DataCtor(size);
  20268. }
  20269. var self = this;
  20270. if (!dimValueGetter) {
  20271. self.hasItemOption = false;
  20272. }
  20273. // Default dim value getter
  20274. dimValueGetter = dimValueGetter || function (dataItem, dimName, dataIndex, dimIndex) {
  20275. var value = getDataItemValue(dataItem);
  20276. // If any dataItem is like { value: 10 }
  20277. if (isDataItemOption(dataItem)) {
  20278. self.hasItemOption = true;
  20279. }
  20280. return converDataValue(
  20281. (value instanceof Array)
  20282. ? value[dimIndex]
  20283. // If value is a single number or something else not array.
  20284. : value,
  20285. dimensionInfoMap[dimName]
  20286. );
  20287. };
  20288. for (var i = 0; i < size; i++) {
  20289. // NOTICE: Try not to write things into dataItem
  20290. var dataItem = data.getItem(i);
  20291. // Each data item is value
  20292. // [1, 2]
  20293. // 2
  20294. // Bar chart, line chart which uses category axis
  20295. // only gives the 'y' value. 'x' value is the indices of cateogry
  20296. // Use a tempValue to normalize the value to be a (x, y) value
  20297. // Store the data by dimensions
  20298. for (var k = 0; k < dimensions.length; k++) {
  20299. var dim = dimensions[k];
  20300. var dimStorage = storage[dim];
  20301. // PENDING NULL is empty or zero
  20302. dimStorage[i] = dimValueGetter(dataItem, dim, i, k);
  20303. }
  20304. indices.push(i);
  20305. }
  20306. // Use the name in option and create id
  20307. for (var i = 0; i < size; i++) {
  20308. var dataItem = data.getItem(i);
  20309. if (!nameList[i] && dataItem) {
  20310. if (dataItem.name != null) {
  20311. nameList[i] = dataItem.name;
  20312. }
  20313. else if (nameDimIdx != null) {
  20314. nameList[i] = storage[dimensions[nameDimIdx]][i];
  20315. }
  20316. }
  20317. var name = nameList[i] || '';
  20318. // Try using the id in option
  20319. var id = dataItem && dataItem.id;
  20320. if (!id && name) {
  20321. // Use name as id and add counter to avoid same name
  20322. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  20323. id = name;
  20324. if (nameRepeatCount[name] > 0) {
  20325. id += '__ec__' + nameRepeatCount[name];
  20326. }
  20327. nameRepeatCount[name]++;
  20328. }
  20329. id && (idList[i] = id);
  20330. }
  20331. this._nameList = nameList;
  20332. this._idList = idList;
  20333. };
  20334. /**
  20335. * @return {number}
  20336. */
  20337. listProto.count = function () {
  20338. return this.indices.length;
  20339. };
  20340. /**
  20341. * Get value. Return NaN if idx is out of range.
  20342. * @param {string} dim Dim must be concrete name.
  20343. * @param {number} idx
  20344. * @param {boolean} stack
  20345. * @return {number}
  20346. */
  20347. listProto.get = function (dim, idx, stack) {
  20348. var storage = this._storage;
  20349. var dataIndex = this.indices[idx];
  20350. // If value not exists
  20351. if (dataIndex == null || !storage[dim]) {
  20352. return NaN;
  20353. }
  20354. var value = storage[dim][dataIndex];
  20355. // FIXME ordinal data type is not stackable
  20356. if (stack) {
  20357. var dimensionInfo = this._dimensionInfos[dim];
  20358. if (dimensionInfo && dimensionInfo.stackable) {
  20359. var stackedOn = this.stackedOn;
  20360. while (stackedOn) {
  20361. // Get no stacked data of stacked on
  20362. var stackedValue = stackedOn.get(dim, idx);
  20363. // Considering positive stack, negative stack and empty data
  20364. if ((value >= 0 && stackedValue > 0) // Positive stack
  20365. || (value <= 0 && stackedValue < 0) // Negative stack
  20366. ) {
  20367. value += stackedValue;
  20368. }
  20369. stackedOn = stackedOn.stackedOn;
  20370. }
  20371. }
  20372. }
  20373. return value;
  20374. };
  20375. /**
  20376. * Get value for multi dimensions.
  20377. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  20378. * @param {number} idx
  20379. * @param {boolean} stack
  20380. * @return {number}
  20381. */
  20382. listProto.getValues = function (dimensions, idx, stack) {
  20383. var values = [];
  20384. if (!isArray(dimensions)) {
  20385. stack = idx;
  20386. idx = dimensions;
  20387. dimensions = this.dimensions;
  20388. }
  20389. for (var i = 0, len = dimensions.length; i < len; i++) {
  20390. values.push(this.get(dimensions[i], idx, stack));
  20391. }
  20392. return values;
  20393. };
  20394. /**
  20395. * If value is NaN. Inlcuding '-'
  20396. * @param {string} dim
  20397. * @param {number} idx
  20398. * @return {number}
  20399. */
  20400. listProto.hasValue = function (idx) {
  20401. var dimensions = this.dimensions;
  20402. var dimensionInfos = this._dimensionInfos;
  20403. for (var i = 0, len = dimensions.length; i < len; i++) {
  20404. if (
  20405. // Ordinal type can be string or number
  20406. dimensionInfos[dimensions[i]].type !== 'ordinal'
  20407. && isNaN(this.get(dimensions[i], idx))
  20408. ) {
  20409. return false;
  20410. }
  20411. }
  20412. return true;
  20413. };
  20414. /**
  20415. * Get extent of data in one dimension
  20416. * @param {string} dim
  20417. * @param {boolean} stack
  20418. * @param {Function} filter
  20419. */
  20420. listProto.getDataExtent = function (dim, stack, filter$$1) {
  20421. dim = this.getDimension(dim);
  20422. var dimData = this._storage[dim];
  20423. var dimInfo = this.getDimensionInfo(dim);
  20424. stack = (dimInfo && dimInfo.stackable) && stack;
  20425. var dimExtent = (this._extent || (this._extent = {}))[dim + (!!stack)];
  20426. var value;
  20427. if (dimExtent) {
  20428. return dimExtent;
  20429. }
  20430. // var dimInfo = this._dimensionInfos[dim];
  20431. if (dimData) {
  20432. var min = Infinity;
  20433. var max = -Infinity;
  20434. // var isOrdinal = dimInfo.type === 'ordinal';
  20435. for (var i = 0, len = this.count(); i < len; i++) {
  20436. value = this.get(dim, i, stack);
  20437. // FIXME
  20438. // if (isOrdinal && typeof value === 'string') {
  20439. // value = zrUtil.indexOf(dimData, value);
  20440. // }
  20441. if (!filter$$1 || filter$$1(value, dim, i)) {
  20442. value < min && (min = value);
  20443. value > max && (max = value);
  20444. }
  20445. }
  20446. return (this._extent[dim + !!stack] = [min, max]);
  20447. }
  20448. else {
  20449. return [Infinity, -Infinity];
  20450. }
  20451. };
  20452. /**
  20453. * Get sum of data in one dimension
  20454. * @param {string} dim
  20455. * @param {boolean} stack
  20456. */
  20457. listProto.getSum = function (dim, stack) {
  20458. var dimData = this._storage[dim];
  20459. var sum = 0;
  20460. if (dimData) {
  20461. for (var i = 0, len = this.count(); i < len; i++) {
  20462. var value = this.get(dim, i, stack);
  20463. if (!isNaN(value)) {
  20464. sum += value;
  20465. }
  20466. }
  20467. }
  20468. return sum;
  20469. };
  20470. /**
  20471. * Retreive the index with given value
  20472. * @param {number} idx
  20473. * @param {number} value
  20474. * @return {number}
  20475. */
  20476. // FIXME Precision of float value
  20477. listProto.indexOf = function (dim, value) {
  20478. var storage = this._storage;
  20479. var dimData = storage[dim];
  20480. var indices = this.indices;
  20481. if (dimData) {
  20482. for (var i = 0, len = indices.length; i < len; i++) {
  20483. var rawIndex = indices[i];
  20484. if (dimData[rawIndex] === value) {
  20485. return i;
  20486. }
  20487. }
  20488. }
  20489. return -1;
  20490. };
  20491. /**
  20492. * Retreive the index with given name
  20493. * @param {number} idx
  20494. * @param {number} name
  20495. * @return {number}
  20496. */
  20497. listProto.indexOfName = function (name) {
  20498. var indices = this.indices;
  20499. var nameList = this._nameList;
  20500. for (var i = 0, len = indices.length; i < len; i++) {
  20501. var rawIndex = indices[i];
  20502. if (nameList[rawIndex] === name) {
  20503. return i;
  20504. }
  20505. }
  20506. return -1;
  20507. };
  20508. /**
  20509. * Retreive the index with given raw data index
  20510. * @param {number} idx
  20511. * @param {number} name
  20512. * @return {number}
  20513. */
  20514. listProto.indexOfRawIndex = function (rawIndex) {
  20515. // Indices are ascending
  20516. var indices = this.indices;
  20517. // If rawIndex === dataIndex
  20518. var rawDataIndex = indices[rawIndex];
  20519. if (rawDataIndex != null && rawDataIndex === rawIndex) {
  20520. return rawIndex;
  20521. }
  20522. var left = 0;
  20523. var right = indices.length - 1;
  20524. while (left <= right) {
  20525. var mid = (left + right) / 2 | 0;
  20526. if (indices[mid] < rawIndex) {
  20527. left = mid + 1;
  20528. }
  20529. else if (indices[mid] > rawIndex) {
  20530. right = mid - 1;
  20531. }
  20532. else {
  20533. return mid;
  20534. }
  20535. }
  20536. return -1;
  20537. };
  20538. /**
  20539. * Retreive the index of nearest value
  20540. * @param {string} dim
  20541. * @param {number} value
  20542. * @param {boolean} stack If given value is after stacked
  20543. * @param {number} [maxDistance=Infinity]
  20544. * @return {Array.<number>} Considere multiple points has the same value.
  20545. */
  20546. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  20547. var storage = this._storage;
  20548. var dimData = storage[dim];
  20549. var nearestIndices = [];
  20550. if (!dimData) {
  20551. return nearestIndices;
  20552. }
  20553. if (maxDistance == null) {
  20554. maxDistance = Infinity;
  20555. }
  20556. var minDist = Number.MAX_VALUE;
  20557. var minDiff = -1;
  20558. for (var i = 0, len = this.count(); i < len; i++) {
  20559. var diff = value - this.get(dim, i, stack);
  20560. var dist = Math.abs(diff);
  20561. if (diff <= maxDistance && dist <= minDist) {
  20562. // For the case of two data are same on xAxis, which has sequence data.
  20563. // Show the nearest index
  20564. // https://github.com/ecomfe/echarts/issues/2869
  20565. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  20566. minDist = dist;
  20567. minDiff = diff;
  20568. nearestIndices.length = 0;
  20569. }
  20570. nearestIndices.push(i);
  20571. }
  20572. }
  20573. return nearestIndices;
  20574. };
  20575. /**
  20576. * Get raw data index
  20577. * @param {number} idx
  20578. * @return {number}
  20579. */
  20580. listProto.getRawIndex = function (idx) {
  20581. var rawIdx = this.indices[idx];
  20582. return rawIdx == null ? -1 : rawIdx;
  20583. };
  20584. /**
  20585. * Get raw data item
  20586. * @param {number} idx
  20587. * @return {number}
  20588. */
  20589. listProto.getRawDataItem = function (idx) {
  20590. return this._rawData.getItem(this.getRawIndex(idx));
  20591. };
  20592. /**
  20593. * @param {number} idx
  20594. * @param {boolean} [notDefaultIdx=false]
  20595. * @return {string}
  20596. */
  20597. listProto.getName = function (idx) {
  20598. return this._nameList[this.indices[idx]] || '';
  20599. };
  20600. /**
  20601. * @param {number} idx
  20602. * @param {boolean} [notDefaultIdx=false]
  20603. * @return {string}
  20604. */
  20605. listProto.getId = function (idx) {
  20606. return this._idList[this.indices[idx]] || (this.getRawIndex(idx) + '');
  20607. };
  20608. function normalizeDimensions(dimensions) {
  20609. if (!isArray(dimensions)) {
  20610. dimensions = [dimensions];
  20611. }
  20612. return dimensions;
  20613. }
  20614. /**
  20615. * Data iteration
  20616. * @param {string|Array.<string>}
  20617. * @param {Function} cb
  20618. * @param {boolean} [stack=false]
  20619. * @param {*} [context=this]
  20620. *
  20621. * @example
  20622. * list.each('x', function (x, idx) {});
  20623. * list.each(['x', 'y'], function (x, y, idx) {});
  20624. * list.each(function (idx) {})
  20625. */
  20626. listProto.each = function (dims, cb, stack, context) {
  20627. if (typeof dims === 'function') {
  20628. context = stack;
  20629. stack = cb;
  20630. cb = dims;
  20631. dims = [];
  20632. }
  20633. dims = map(normalizeDimensions(dims), this.getDimension, this);
  20634. var value = [];
  20635. var dimSize = dims.length;
  20636. var indices = this.indices;
  20637. context = context || this;
  20638. for (var i = 0; i < indices.length; i++) {
  20639. // Simple optimization
  20640. switch (dimSize) {
  20641. case 0:
  20642. cb.call(context, i);
  20643. break;
  20644. case 1:
  20645. cb.call(context, this.get(dims[0], i, stack), i);
  20646. break;
  20647. case 2:
  20648. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  20649. break;
  20650. default:
  20651. for (var k = 0; k < dimSize; k++) {
  20652. value[k] = this.get(dims[k], i, stack);
  20653. }
  20654. // Index
  20655. value[k] = i;
  20656. cb.apply(context, value);
  20657. }
  20658. }
  20659. };
  20660. /**
  20661. * Data filter
  20662. * @param {string|Array.<string>}
  20663. * @param {Function} cb
  20664. * @param {boolean} [stack=false]
  20665. * @param {*} [context=this]
  20666. */
  20667. listProto.filterSelf = function (dimensions, cb, stack, context) {
  20668. if (typeof dimensions === 'function') {
  20669. context = stack;
  20670. stack = cb;
  20671. cb = dimensions;
  20672. dimensions = [];
  20673. }
  20674. dimensions = map(
  20675. normalizeDimensions(dimensions), this.getDimension, this
  20676. );
  20677. var newIndices = [];
  20678. var value = [];
  20679. var dimSize = dimensions.length;
  20680. var indices = this.indices;
  20681. context = context || this;
  20682. for (var i = 0; i < indices.length; i++) {
  20683. var keep;
  20684. // Simple optimization
  20685. if (!dimSize) {
  20686. keep = cb.call(context, i);
  20687. }
  20688. else if (dimSize === 1) {
  20689. keep = cb.call(
  20690. context, this.get(dimensions[0], i, stack), i
  20691. );
  20692. }
  20693. else {
  20694. for (var k = 0; k < dimSize; k++) {
  20695. value[k] = this.get(dimensions[k], i, stack);
  20696. }
  20697. value[k] = i;
  20698. keep = cb.apply(context, value);
  20699. }
  20700. if (keep) {
  20701. newIndices.push(indices[i]);
  20702. }
  20703. }
  20704. this.indices = newIndices;
  20705. // Reset data extent
  20706. this._extent = {};
  20707. return this;
  20708. };
  20709. /**
  20710. * Data mapping to a plain array
  20711. * @param {string|Array.<string>} [dimensions]
  20712. * @param {Function} cb
  20713. * @param {boolean} [stack=false]
  20714. * @param {*} [context=this]
  20715. * @return {Array}
  20716. */
  20717. listProto.mapArray = function (dimensions, cb, stack, context) {
  20718. if (typeof dimensions === 'function') {
  20719. context = stack;
  20720. stack = cb;
  20721. cb = dimensions;
  20722. dimensions = [];
  20723. }
  20724. var result = [];
  20725. this.each(dimensions, function () {
  20726. result.push(cb && cb.apply(this, arguments));
  20727. }, stack, context);
  20728. return result;
  20729. };
  20730. function cloneListForMapAndSample(original, excludeDimensions) {
  20731. var allDimensions = original.dimensions;
  20732. var list = new List(
  20733. map(allDimensions, original.getDimensionInfo, original),
  20734. original.hostModel
  20735. );
  20736. // FIXME If needs stackedOn, value may already been stacked
  20737. transferProperties(list, original);
  20738. var storage = list._storage = {};
  20739. var originalStorage = original._storage;
  20740. // Init storage
  20741. for (var i = 0; i < allDimensions.length; i++) {
  20742. var dim = allDimensions[i];
  20743. var dimStore = originalStorage[dim];
  20744. if (indexOf(excludeDimensions, dim) >= 0) {
  20745. storage[dim] = new dimStore.constructor(
  20746. originalStorage[dim].length
  20747. );
  20748. }
  20749. else {
  20750. // Direct reference for other dimensions
  20751. storage[dim] = originalStorage[dim];
  20752. }
  20753. }
  20754. return list;
  20755. }
  20756. /**
  20757. * Data mapping to a new List with given dimensions
  20758. * @param {string|Array.<string>} dimensions
  20759. * @param {Function} cb
  20760. * @param {boolean} [stack=false]
  20761. * @param {*} [context=this]
  20762. * @return {Array}
  20763. */
  20764. listProto.map = function (dimensions, cb, stack, context) {
  20765. dimensions = map(
  20766. normalizeDimensions(dimensions), this.getDimension, this
  20767. );
  20768. var list = cloneListForMapAndSample(this, dimensions);
  20769. // Following properties are all immutable.
  20770. // So we can reference to the same value
  20771. var indices = list.indices = this.indices;
  20772. var storage = list._storage;
  20773. var tmpRetValue = [];
  20774. this.each(dimensions, function () {
  20775. var idx = arguments[arguments.length - 1];
  20776. var retValue = cb && cb.apply(this, arguments);
  20777. if (retValue != null) {
  20778. // a number
  20779. if (typeof retValue === 'number') {
  20780. tmpRetValue[0] = retValue;
  20781. retValue = tmpRetValue;
  20782. }
  20783. for (var i = 0; i < retValue.length; i++) {
  20784. var dim = dimensions[i];
  20785. var dimStore = storage[dim];
  20786. var rawIdx = indices[idx];
  20787. if (dimStore) {
  20788. dimStore[rawIdx] = retValue[i];
  20789. }
  20790. }
  20791. }
  20792. }, stack, context);
  20793. return list;
  20794. };
  20795. /**
  20796. * Large data down sampling on given dimension
  20797. * @param {string} dimension
  20798. * @param {number} rate
  20799. * @param {Function} sampleValue
  20800. * @param {Function} sampleIndex Sample index for name and id
  20801. */
  20802. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20803. var list = cloneListForMapAndSample(this, [dimension]);
  20804. var storage = this._storage;
  20805. var targetStorage = list._storage;
  20806. var originalIndices = this.indices;
  20807. var indices = list.indices = [];
  20808. var frameValues = [];
  20809. var frameIndices = [];
  20810. var frameSize = Math.floor(1 / rate);
  20811. var dimStore = targetStorage[dimension];
  20812. var len = this.count();
  20813. // Copy data from original data
  20814. for (var i = 0; i < storage[dimension].length; i++) {
  20815. targetStorage[dimension][i] = storage[dimension][i];
  20816. }
  20817. for (var i = 0; i < len; i += frameSize) {
  20818. // Last frame
  20819. if (frameSize > len - i) {
  20820. frameSize = len - i;
  20821. frameValues.length = frameSize;
  20822. }
  20823. for (var k = 0; k < frameSize; k++) {
  20824. var idx = originalIndices[i + k];
  20825. frameValues[k] = dimStore[idx];
  20826. frameIndices[k] = idx;
  20827. }
  20828. var value = sampleValue(frameValues);
  20829. var idx = frameIndices[sampleIndex(frameValues, value) || 0];
  20830. // Only write value on the filtered data
  20831. dimStore[idx] = value;
  20832. indices.push(idx);
  20833. }
  20834. return list;
  20835. };
  20836. /**
  20837. * Get model of one data item.
  20838. *
  20839. * @param {number} idx
  20840. */
  20841. // FIXME Model proxy ?
  20842. listProto.getItemModel = function (idx) {
  20843. var hostModel = this.hostModel;
  20844. idx = this.indices[idx];
  20845. return new Model(this._rawData.getItem(idx), hostModel, hostModel && hostModel.ecModel);
  20846. };
  20847. /**
  20848. * Create a data differ
  20849. * @param {module:echarts/data/List} otherList
  20850. * @return {module:echarts/data/DataDiffer}
  20851. */
  20852. listProto.diff = function (otherList) {
  20853. var idList = this._idList;
  20854. var otherIdList = otherList && otherList._idList;
  20855. var val;
  20856. // Use prefix to avoid index to be the same as otherIdList[idx],
  20857. // which will cause weird udpate animation.
  20858. var prefix = 'e\0\0';
  20859. return new DataDiffer(
  20860. otherList ? otherList.indices : [],
  20861. this.indices,
  20862. function (idx) {
  20863. return (val = otherIdList[idx]) != null ? val : prefix + idx;
  20864. },
  20865. function (idx) {
  20866. return (val = idList[idx]) != null ? val : prefix + idx;
  20867. }
  20868. );
  20869. };
  20870. /**
  20871. * Get visual property.
  20872. * @param {string} key
  20873. */
  20874. listProto.getVisual = function (key) {
  20875. var visual = this._visual;
  20876. return visual && visual[key];
  20877. };
  20878. /**
  20879. * Set visual property
  20880. * @param {string|Object} key
  20881. * @param {*} [value]
  20882. *
  20883. * @example
  20884. * setVisual('color', color);
  20885. * setVisual({
  20886. * 'color': color
  20887. * });
  20888. */
  20889. listProto.setVisual = function (key, val) {
  20890. if (isObject$4(key)) {
  20891. for (var name in key) {
  20892. if (key.hasOwnProperty(name)) {
  20893. this.setVisual(name, key[name]);
  20894. }
  20895. }
  20896. return;
  20897. }
  20898. this._visual = this._visual || {};
  20899. this._visual[key] = val;
  20900. };
  20901. /**
  20902. * Set layout property.
  20903. * @param {string|Object} key
  20904. * @param {*} [val]
  20905. */
  20906. listProto.setLayout = function (key, val) {
  20907. if (isObject$4(key)) {
  20908. for (var name in key) {
  20909. if (key.hasOwnProperty(name)) {
  20910. this.setLayout(name, key[name]);
  20911. }
  20912. }
  20913. return;
  20914. }
  20915. this._layout[key] = val;
  20916. };
  20917. /**
  20918. * Get layout property.
  20919. * @param {string} key.
  20920. * @return {*}
  20921. */
  20922. listProto.getLayout = function (key) {
  20923. return this._layout[key];
  20924. };
  20925. /**
  20926. * Get layout of single data item
  20927. * @param {number} idx
  20928. */
  20929. listProto.getItemLayout = function (idx) {
  20930. return this._itemLayouts[idx];
  20931. };
  20932. /**
  20933. * Set layout of single data item
  20934. * @param {number} idx
  20935. * @param {Object} layout
  20936. * @param {boolean=} [merge=false]
  20937. */
  20938. listProto.setItemLayout = function (idx, layout, merge$$1) {
  20939. this._itemLayouts[idx] = merge$$1
  20940. ? extend(this._itemLayouts[idx] || {}, layout)
  20941. : layout;
  20942. };
  20943. /**
  20944. * Clear all layout of single data item
  20945. */
  20946. listProto.clearItemLayouts = function () {
  20947. this._itemLayouts.length = 0;
  20948. };
  20949. /**
  20950. * Get visual property of single data item
  20951. * @param {number} idx
  20952. * @param {string} key
  20953. * @param {boolean} [ignoreParent=false]
  20954. */
  20955. listProto.getItemVisual = function (idx, key, ignoreParent) {
  20956. var itemVisual = this._itemVisuals[idx];
  20957. var val = itemVisual && itemVisual[key];
  20958. if (val == null && !ignoreParent) {
  20959. // Use global visual property
  20960. return this.getVisual(key);
  20961. }
  20962. return val;
  20963. };
  20964. /**
  20965. * Set visual property of single data item
  20966. *
  20967. * @param {number} idx
  20968. * @param {string|Object} key
  20969. * @param {*} [value]
  20970. *
  20971. * @example
  20972. * setItemVisual(0, 'color', color);
  20973. * setItemVisual(0, {
  20974. * 'color': color
  20975. * });
  20976. */
  20977. listProto.setItemVisual = function (idx, key, value) {
  20978. var itemVisual = this._itemVisuals[idx] || {};
  20979. this._itemVisuals[idx] = itemVisual;
  20980. if (isObject$4(key)) {
  20981. for (var name in key) {
  20982. if (key.hasOwnProperty(name)) {
  20983. itemVisual[name] = key[name];
  20984. }
  20985. }
  20986. return;
  20987. }
  20988. itemVisual[key] = value;
  20989. };
  20990. /**
  20991. * Clear itemVisuals and list visual.
  20992. */
  20993. listProto.clearAllVisual = function () {
  20994. this._visual = {};
  20995. this._itemVisuals = [];
  20996. };
  20997. var setItemDataAndSeriesIndex = function (child) {
  20998. child.seriesIndex = this.seriesIndex;
  20999. child.dataIndex = this.dataIndex;
  21000. child.dataType = this.dataType;
  21001. };
  21002. /**
  21003. * Set graphic element relative to data. It can be set as null
  21004. * @param {number} idx
  21005. * @param {module:zrender/Element} [el]
  21006. */
  21007. listProto.setItemGraphicEl = function (idx, el) {
  21008. var hostModel = this.hostModel;
  21009. if (el) {
  21010. // Add data index and series index for indexing the data by element
  21011. // Useful in tooltip
  21012. el.dataIndex = idx;
  21013. el.dataType = this.dataType;
  21014. el.seriesIndex = hostModel && hostModel.seriesIndex;
  21015. if (el.type === 'group') {
  21016. el.traverse(setItemDataAndSeriesIndex, el);
  21017. }
  21018. }
  21019. this._graphicEls[idx] = el;
  21020. };
  21021. /**
  21022. * @param {number} idx
  21023. * @return {module:zrender/Element}
  21024. */
  21025. listProto.getItemGraphicEl = function (idx) {
  21026. return this._graphicEls[idx];
  21027. };
  21028. /**
  21029. * @param {Function} cb
  21030. * @param {*} context
  21031. */
  21032. listProto.eachItemGraphicEl = function (cb, context) {
  21033. each$1(this._graphicEls, function (el, idx) {
  21034. if (el) {
  21035. cb && cb.call(context, el, idx);
  21036. }
  21037. });
  21038. };
  21039. /**
  21040. * Shallow clone a new list except visual and layout properties, and graph elements.
  21041. * New list only change the indices.
  21042. */
  21043. listProto.cloneShallow = function () {
  21044. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  21045. var list = new List(dimensionInfoList, this.hostModel);
  21046. // FIXME
  21047. list._storage = this._storage;
  21048. transferProperties(list, this);
  21049. // Clone will not change the data extent and indices
  21050. list.indices = this.indices.slice();
  21051. if (this._extent) {
  21052. list._extent = extend({}, this._extent);
  21053. }
  21054. return list;
  21055. };
  21056. /**
  21057. * Wrap some method to add more feature
  21058. * @param {string} methodName
  21059. * @param {Function} injectFunction
  21060. */
  21061. listProto.wrapMethod = function (methodName, injectFunction) {
  21062. var originalMethod = this[methodName];
  21063. if (typeof originalMethod !== 'function') {
  21064. return;
  21065. }
  21066. this.__wrappedMethods = this.__wrappedMethods || [];
  21067. this.__wrappedMethods.push(methodName);
  21068. this[methodName] = function () {
  21069. var res = originalMethod.apply(this, arguments);
  21070. return injectFunction.apply(this, [res].concat(slice(arguments)));
  21071. };
  21072. };
  21073. // Methods that create a new list based on this list should be listed here.
  21074. // Notice that those method should `RETURN` the new list.
  21075. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  21076. // Methods that change indices of this list should be listed here.
  21077. listProto.CHANGABLE_METHODS = ['filterSelf'];
  21078. /**
  21079. * Complete dimensions by data (guess dimension).
  21080. */
  21081. var each$7 = each$1;
  21082. var isString$1 = isString;
  21083. var defaults$1 = defaults;
  21084. var OTHER_DIMS = {tooltip: 1, label: 1, itemName: 1};
  21085. /**
  21086. * Complete the dimensions array, by user defined `dimension` and `encode`,
  21087. * and guessing from the data structure.
  21088. * If no 'value' dimension specified, the first no-named dimension will be
  21089. * named as 'value'.
  21090. *
  21091. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  21092. * provides not only dim template, but also default order.
  21093. * `name` of each item provides default coord name.
  21094. * [{dimsDef: []}, ...] can be specified to give names.
  21095. * @param {Array} data Data list. [[1, 2, 3], [2, 3, 4]].
  21096. * @param {Object} [opt]
  21097. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  21098. * For example: ['asdf', {name, type}, ...].
  21099. * @param {Object} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  21100. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  21101. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  21102. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  21103. * If not specified, extra dim names will be:
  21104. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  21105. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  21106. * @return {Array.<Object>} [{
  21107. * name: string mandatory,
  21108. * coordDim: string mandatory,
  21109. * coordDimIndex: number mandatory,
  21110. * type: string optional,
  21111. * tooltipName: string optional,
  21112. * otherDims: {
  21113. * tooltip: number optional,
  21114. * label: number optional
  21115. * },
  21116. * isExtraCoord: boolean true or undefined.
  21117. * other props ...
  21118. * }]
  21119. */
  21120. function completeDimensions(sysDims, data, opt) {
  21121. data = data || [];
  21122. opt = opt || {};
  21123. sysDims = (sysDims || []).slice();
  21124. var dimsDef = (opt.dimsDef || []).slice();
  21125. var encodeDef = createHashMap(opt.encodeDef);
  21126. var dataDimNameMap = createHashMap();
  21127. var coordDimNameMap = createHashMap();
  21128. // var valueCandidate;
  21129. var result = [];
  21130. var dimCount = opt.dimCount;
  21131. if (dimCount == null) {
  21132. var value0 = retrieveValue(data[0]);
  21133. dimCount = Math.max(
  21134. isArray(value0) && value0.length || 1,
  21135. sysDims.length,
  21136. dimsDef.length
  21137. );
  21138. each$7(sysDims, function (sysDimItem) {
  21139. var sysDimItemDimsDef = sysDimItem.dimsDef;
  21140. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  21141. });
  21142. }
  21143. // Apply user defined dims (`name` and `type`) and init result.
  21144. for (var i = 0; i < dimCount; i++) {
  21145. var dimDefItem = isString$1(dimsDef[i]) ? {name: dimsDef[i]} : (dimsDef[i] || {});
  21146. var userDimName = dimDefItem.name;
  21147. var resultItem = result[i] = {otherDims: {}};
  21148. // Name will be applied later for avoiding duplication.
  21149. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  21150. // Only if `series.dimensions` is defined in option, tooltipName
  21151. // will be set, and dimension will be diplayed vertically in
  21152. // tooltip by default.
  21153. resultItem.name = resultItem.tooltipName = userDimName;
  21154. dataDimNameMap.set(userDimName, i);
  21155. }
  21156. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  21157. }
  21158. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  21159. encodeDef.each(function (dataDims, coordDim) {
  21160. dataDims = encodeDef.set(coordDim, normalizeToArray(dataDims).slice());
  21161. each$7(dataDims, function (resultDimIdx, coordDimIndex) {
  21162. // The input resultDimIdx can be dim name or index.
  21163. isString$1(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  21164. if (resultDimIdx != null && resultDimIdx < dimCount) {
  21165. dataDims[coordDimIndex] = resultDimIdx;
  21166. applyDim(result[resultDimIdx], coordDim, coordDimIndex);
  21167. }
  21168. });
  21169. });
  21170. // Apply templetes and default order from `sysDims`.
  21171. var availDimIdx = 0;
  21172. each$7(sysDims, function (sysDimItem, sysDimIndex) {
  21173. var coordDim;
  21174. var sysDimItem;
  21175. var sysDimItemDimsDef;
  21176. var sysDimItemOtherDims;
  21177. if (isString$1(sysDimItem)) {
  21178. coordDim = sysDimItem;
  21179. sysDimItem = {};
  21180. }
  21181. else {
  21182. coordDim = sysDimItem.name;
  21183. sysDimItem = clone(sysDimItem);
  21184. // `coordDimIndex` should not be set directly.
  21185. sysDimItemDimsDef = sysDimItem.dimsDef;
  21186. sysDimItemOtherDims = sysDimItem.otherDims;
  21187. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  21188. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  21189. }
  21190. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  21191. // dimensions provides default dim sequences.
  21192. if (!dataDims.length) {
  21193. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  21194. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  21195. availDimIdx++;
  21196. }
  21197. availDimIdx < result.length && dataDims.push(availDimIdx++);
  21198. }
  21199. }
  21200. // Apply templates.
  21201. each$7(dataDims, function (resultDimIdx, coordDimIndex) {
  21202. var resultItem = result[resultDimIdx];
  21203. applyDim(defaults$1(resultItem, sysDimItem), coordDim, coordDimIndex);
  21204. if (resultItem.name == null && sysDimItemDimsDef) {
  21205. resultItem.name = resultItem.tooltipName = sysDimItemDimsDef[coordDimIndex];
  21206. }
  21207. sysDimItemOtherDims && defaults$1(resultItem.otherDims, sysDimItemOtherDims);
  21208. });
  21209. });
  21210. // Make sure the first extra dim is 'value'.
  21211. var extra = opt.extraPrefix || 'value';
  21212. // Set dim `name` and other `coordDim` and other props.
  21213. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  21214. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  21215. var coordDim = resultItem.coordDim;
  21216. coordDim == null && (
  21217. resultItem.coordDim = genName(extra, coordDimNameMap, opt.extraFromZero),
  21218. resultItem.coordDimIndex = 0,
  21219. resultItem.isExtraCoord = true
  21220. );
  21221. resultItem.name == null && (resultItem.name = genName(
  21222. resultItem.coordDim,
  21223. dataDimNameMap
  21224. ));
  21225. resultItem.type == null && guessOrdinal(data, resultDimIdx)
  21226. && (resultItem.type = 'ordinal');
  21227. }
  21228. return result;
  21229. function applyDim(resultItem, coordDim, coordDimIndex) {
  21230. if (OTHER_DIMS[coordDim]) {
  21231. resultItem.otherDims[coordDim] = coordDimIndex;
  21232. }
  21233. else {
  21234. resultItem.coordDim = coordDim;
  21235. resultItem.coordDimIndex = coordDimIndex;
  21236. coordDimNameMap.set(coordDim, true);
  21237. }
  21238. }
  21239. function genName(name, map$$1, fromZero) {
  21240. if (fromZero || map$$1.get(name) != null) {
  21241. var i = 0;
  21242. while (map$$1.get(name + i) != null) {
  21243. i++;
  21244. }
  21245. name += i;
  21246. }
  21247. map$$1.set(name, true);
  21248. return name;
  21249. }
  21250. }
  21251. // The rule should not be complex, otherwise user might not
  21252. // be able to known where the data is wrong.
  21253. var guessOrdinal = completeDimensions.guessOrdinal = function (data, dimIndex) {
  21254. for (var i = 0, len = data.length; i < len; i++) {
  21255. var value = retrieveValue(data[i]);
  21256. if (!isArray(value)) {
  21257. return false;
  21258. }
  21259. var value = value[dimIndex];
  21260. // Consider usage convenience, '1', '2' will be treated as "number".
  21261. // `isFinit('')` get `true`.
  21262. if (value != null && isFinite(value) && value !== '') {
  21263. return false;
  21264. }
  21265. else if (isString$1(value) && value !== '-') {
  21266. return true;
  21267. }
  21268. }
  21269. return false;
  21270. };
  21271. function retrieveValue(o) {
  21272. return isArray(o) ? o : isObject(o) ? o.value: o;
  21273. }
  21274. function firstDataNotNull(data) {
  21275. var i = 0;
  21276. while (i < data.length && data[i] == null) {
  21277. i++;
  21278. }
  21279. return data[i];
  21280. }
  21281. function ifNeedCompleteOrdinalData(data) {
  21282. var sampleItem = firstDataNotNull(data);
  21283. return sampleItem != null
  21284. && !isArray(getDataItemValue(sampleItem));
  21285. }
  21286. /**
  21287. * Helper function to create a list from option data
  21288. */
  21289. function createListFromArray(data, seriesModel, ecModel) {
  21290. // If data is undefined
  21291. data = data || [];
  21292. if (__DEV__) {
  21293. if (!isArray(data)) {
  21294. throw new Error('Invalid data.');
  21295. }
  21296. }
  21297. var coordSysName = seriesModel.get('coordinateSystem');
  21298. var creator = creators[coordSysName];
  21299. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  21300. var completeDimOpt = {
  21301. encodeDef: seriesModel.get('encode'),
  21302. dimsDef: seriesModel.get('dimensions')
  21303. };
  21304. // FIXME
  21305. var axesInfo = creator && creator(data, seriesModel, ecModel, completeDimOpt);
  21306. var dimensions = axesInfo && axesInfo.dimensions;
  21307. if (!dimensions) {
  21308. // Get dimensions from registered coordinate system
  21309. dimensions = (registeredCoordSys && (
  21310. registeredCoordSys.getDimensionsInfo
  21311. ? registeredCoordSys.getDimensionsInfo()
  21312. : registeredCoordSys.dimensions.slice()
  21313. )) || ['x', 'y'];
  21314. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21315. }
  21316. var categoryIndex = axesInfo ? axesInfo.categoryIndex : -1;
  21317. var list = new List(dimensions, seriesModel);
  21318. var nameList = createNameList(axesInfo, data);
  21319. var categories = {};
  21320. var dimValueGetter = (categoryIndex >= 0 && ifNeedCompleteOrdinalData(data))
  21321. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  21322. // If any dataItem is like { value: 10 }
  21323. if (isDataItemOption(itemOpt)) {
  21324. list.hasItemOption = true;
  21325. }
  21326. // Use dataIndex as ordinal value in categoryAxis
  21327. return dimIndex === categoryIndex
  21328. ? dataIndex
  21329. : converDataValue(getDataItemValue(itemOpt), dimensions[dimIndex]);
  21330. }
  21331. : function (itemOpt, dimName, dataIndex, dimIndex) {
  21332. var value = getDataItemValue(itemOpt);
  21333. var val = converDataValue(value && value[dimIndex], dimensions[dimIndex]);
  21334. // If any dataItem is like { value: 10 }
  21335. if (isDataItemOption(itemOpt)) {
  21336. list.hasItemOption = true;
  21337. }
  21338. var categoryAxesModels = axesInfo && axesInfo.categoryAxesModels;
  21339. if (categoryAxesModels && categoryAxesModels[dimName]) {
  21340. // If given value is a category string
  21341. if (typeof val === 'string') {
  21342. // Lazy get categories
  21343. categories[dimName] = categories[dimName]
  21344. || categoryAxesModels[dimName].getCategories();
  21345. val = indexOf(categories[dimName], val);
  21346. if (val < 0 && !isNaN(val)) {
  21347. // In case some one write '1', '2' istead of 1, 2
  21348. val = +val;
  21349. }
  21350. }
  21351. }
  21352. return val;
  21353. };
  21354. list.hasItemOption = false;
  21355. list.initData(data, nameList, dimValueGetter);
  21356. return list;
  21357. }
  21358. function isStackable(axisType) {
  21359. return axisType !== 'category' && axisType !== 'time';
  21360. }
  21361. function getDimTypeByAxis(axisType) {
  21362. return axisType === 'category'
  21363. ? 'ordinal'
  21364. : axisType === 'time'
  21365. ? 'time'
  21366. : 'float';
  21367. }
  21368. /**
  21369. * Creaters for each coord system.
  21370. */
  21371. var creators = {
  21372. cartesian2d: function (data, seriesModel, ecModel, completeDimOpt) {
  21373. var axesModels = map(['xAxis', 'yAxis'], function (name) {
  21374. return ecModel.queryComponents({
  21375. mainType: name,
  21376. index: seriesModel.get(name + 'Index'),
  21377. id: seriesModel.get(name + 'Id')
  21378. })[0];
  21379. });
  21380. var xAxisModel = axesModels[0];
  21381. var yAxisModel = axesModels[1];
  21382. if (__DEV__) {
  21383. if (!xAxisModel) {
  21384. throw new Error('xAxis "' + retrieve(
  21385. seriesModel.get('xAxisIndex'),
  21386. seriesModel.get('xAxisId'),
  21387. 0
  21388. ) + '" not found');
  21389. }
  21390. if (!yAxisModel) {
  21391. throw new Error('yAxis "' + retrieve(
  21392. seriesModel.get('xAxisIndex'),
  21393. seriesModel.get('yAxisId'),
  21394. 0
  21395. ) + '" not found');
  21396. }
  21397. }
  21398. var xAxisType = xAxisModel.get('type');
  21399. var yAxisType = yAxisModel.get('type');
  21400. var dimensions = [
  21401. {
  21402. name: 'x',
  21403. type: getDimTypeByAxis(xAxisType),
  21404. stackable: isStackable(xAxisType)
  21405. },
  21406. {
  21407. name: 'y',
  21408. // If two category axes
  21409. type: getDimTypeByAxis(yAxisType),
  21410. stackable: isStackable(yAxisType)
  21411. }
  21412. ];
  21413. var isXAxisCateogry = xAxisType === 'category';
  21414. var isYAxisCategory = yAxisType === 'category';
  21415. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21416. var categoryAxesModels = {};
  21417. if (isXAxisCateogry) {
  21418. categoryAxesModels.x = xAxisModel;
  21419. }
  21420. if (isYAxisCategory) {
  21421. categoryAxesModels.y = yAxisModel;
  21422. }
  21423. return {
  21424. dimensions: dimensions,
  21425. categoryIndex: isXAxisCateogry ? 0 : (isYAxisCategory ? 1 : -1),
  21426. categoryAxesModels: categoryAxesModels
  21427. };
  21428. },
  21429. singleAxis: function (data, seriesModel, ecModel, completeDimOpt) {
  21430. var singleAxisModel = ecModel.queryComponents({
  21431. mainType: 'singleAxis',
  21432. index: seriesModel.get('singleAxisIndex'),
  21433. id: seriesModel.get('singleAxisId')
  21434. })[0];
  21435. if (__DEV__) {
  21436. if (!singleAxisModel) {
  21437. throw new Error('singleAxis should be specified.');
  21438. }
  21439. }
  21440. var singleAxisType = singleAxisModel.get('type');
  21441. var isCategory = singleAxisType === 'category';
  21442. var dimensions = [{
  21443. name: 'single',
  21444. type: getDimTypeByAxis(singleAxisType),
  21445. stackable: isStackable(singleAxisType)
  21446. }];
  21447. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21448. var categoryAxesModels = {};
  21449. if (isCategory) {
  21450. categoryAxesModels.single = singleAxisModel;
  21451. }
  21452. return {
  21453. dimensions: dimensions,
  21454. categoryIndex: isCategory ? 0 : -1,
  21455. categoryAxesModels: categoryAxesModels
  21456. };
  21457. },
  21458. polar: function (data, seriesModel, ecModel, completeDimOpt) {
  21459. var polarModel = ecModel.queryComponents({
  21460. mainType: 'polar',
  21461. index: seriesModel.get('polarIndex'),
  21462. id: seriesModel.get('polarId')
  21463. })[0];
  21464. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  21465. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  21466. if (__DEV__) {
  21467. if (!angleAxisModel) {
  21468. throw new Error('angleAxis option not found');
  21469. }
  21470. if (!radiusAxisModel) {
  21471. throw new Error('radiusAxis option not found');
  21472. }
  21473. }
  21474. var radiusAxisType = radiusAxisModel.get('type');
  21475. var angleAxisType = angleAxisModel.get('type');
  21476. var dimensions = [
  21477. {
  21478. name: 'radius',
  21479. type: getDimTypeByAxis(radiusAxisType),
  21480. stackable: isStackable(radiusAxisType)
  21481. },
  21482. {
  21483. name: 'angle',
  21484. type: getDimTypeByAxis(angleAxisType),
  21485. stackable: isStackable(angleAxisType)
  21486. }
  21487. ];
  21488. var isAngleAxisCateogry = angleAxisType === 'category';
  21489. var isRadiusAxisCateogry = radiusAxisType === 'category';
  21490. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21491. var categoryAxesModels = {};
  21492. if (isRadiusAxisCateogry) {
  21493. categoryAxesModels.radius = radiusAxisModel;
  21494. }
  21495. if (isAngleAxisCateogry) {
  21496. categoryAxesModels.angle = angleAxisModel;
  21497. }
  21498. return {
  21499. dimensions: dimensions,
  21500. categoryIndex: isAngleAxisCateogry ? 1 : (isRadiusAxisCateogry ? 0 : -1),
  21501. categoryAxesModels: categoryAxesModels
  21502. };
  21503. },
  21504. geo: function (data, seriesModel, ecModel, completeDimOpt) {
  21505. // TODO Region
  21506. // 多个散点图系列在同一个地区的时候
  21507. return {
  21508. dimensions: completeDimensions([
  21509. {name: 'lng'},
  21510. {name: 'lat'}
  21511. ], data, completeDimOpt)
  21512. };
  21513. }
  21514. };
  21515. function createNameList(result, data) {
  21516. var nameList = [];
  21517. var categoryDim = result && result.dimensions[result.categoryIndex];
  21518. var categoryAxisModel;
  21519. if (categoryDim) {
  21520. categoryAxisModel = result.categoryAxesModels[categoryDim.name];
  21521. }
  21522. if (categoryAxisModel) {
  21523. // FIXME Two category axis
  21524. var categories = categoryAxisModel.getCategories();
  21525. if (categories) {
  21526. var dataLen = data.length;
  21527. // Ordered data is given explicitly like
  21528. // [[3, 0.2], [1, 0.3], [2, 0.15]]
  21529. // or given scatter data,
  21530. // pick the category
  21531. if (isArray(data[0]) && data[0].length > 1) {
  21532. nameList = [];
  21533. for (var i = 0; i < dataLen; i++) {
  21534. nameList[i] = categories[data[i][result.categoryIndex || 0]];
  21535. }
  21536. }
  21537. else {
  21538. nameList = categories.slice(0);
  21539. }
  21540. }
  21541. }
  21542. return nameList;
  21543. }
  21544. /**
  21545. * // Scale class management
  21546. * @module echarts/scale/Scale
  21547. */
  21548. /**
  21549. * @param {Object} [setting]
  21550. */
  21551. function Scale(setting) {
  21552. this._setting = setting || {};
  21553. /**
  21554. * Extent
  21555. * @type {Array.<number>}
  21556. * @protected
  21557. */
  21558. this._extent = [Infinity, -Infinity];
  21559. /**
  21560. * Step is calculated in adjustExtent
  21561. * @type {Array.<number>}
  21562. * @protected
  21563. */
  21564. this._interval = 0;
  21565. this.init && this.init.apply(this, arguments);
  21566. }
  21567. /**
  21568. * Parse input val to valid inner number.
  21569. * @param {*} val
  21570. * @return {number}
  21571. */
  21572. Scale.prototype.parse = function (val) {
  21573. // Notice: This would be a trap here, If the implementation
  21574. // of this method depends on extent, and this method is used
  21575. // before extent set (like in dataZoom), it would be wrong.
  21576. // Nevertheless, parse does not depend on extent generally.
  21577. return val;
  21578. };
  21579. Scale.prototype.getSetting = function (name) {
  21580. return this._setting[name];
  21581. };
  21582. Scale.prototype.contain = function (val) {
  21583. var extent = this._extent;
  21584. return val >= extent[0] && val <= extent[1];
  21585. };
  21586. /**
  21587. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  21588. * @param {number} val
  21589. * @return {number}
  21590. */
  21591. Scale.prototype.normalize = function (val) {
  21592. var extent = this._extent;
  21593. if (extent[1] === extent[0]) {
  21594. return 0.5;
  21595. }
  21596. return (val - extent[0]) / (extent[1] - extent[0]);
  21597. };
  21598. /**
  21599. * Scale normalized value
  21600. * @param {number} val
  21601. * @return {number}
  21602. */
  21603. Scale.prototype.scale = function (val) {
  21604. var extent = this._extent;
  21605. return val * (extent[1] - extent[0]) + extent[0];
  21606. };
  21607. /**
  21608. * Set extent from data
  21609. * @param {Array.<number>} other
  21610. */
  21611. Scale.prototype.unionExtent = function (other) {
  21612. var extent = this._extent;
  21613. other[0] < extent[0] && (extent[0] = other[0]);
  21614. other[1] > extent[1] && (extent[1] = other[1]);
  21615. // not setExtent because in log axis it may transformed to power
  21616. // this.setExtent(extent[0], extent[1]);
  21617. };
  21618. /**
  21619. * Set extent from data
  21620. * @param {module:echarts/data/List} data
  21621. * @param {string} dim
  21622. */
  21623. Scale.prototype.unionExtentFromData = function (data, dim) {
  21624. this.unionExtent(data.getDataExtent(dim, true));
  21625. };
  21626. /**
  21627. * Get extent
  21628. * @return {Array.<number>}
  21629. */
  21630. Scale.prototype.getExtent = function () {
  21631. return this._extent.slice();
  21632. };
  21633. /**
  21634. * Set extent
  21635. * @param {number} start
  21636. * @param {number} end
  21637. */
  21638. Scale.prototype.setExtent = function (start, end) {
  21639. var thisExtent = this._extent;
  21640. if (!isNaN(start)) {
  21641. thisExtent[0] = start;
  21642. }
  21643. if (!isNaN(end)) {
  21644. thisExtent[1] = end;
  21645. }
  21646. };
  21647. /**
  21648. * @return {Array.<string>}
  21649. */
  21650. Scale.prototype.getTicksLabels = function () {
  21651. var labels = [];
  21652. var ticks = this.getTicks();
  21653. for (var i = 0; i < ticks.length; i++) {
  21654. labels.push(this.getLabel(ticks[i]));
  21655. }
  21656. return labels;
  21657. };
  21658. /**
  21659. * When axis extent depends on data and no data exists,
  21660. * axis ticks should not be drawn, which is named 'blank'.
  21661. */
  21662. Scale.prototype.isBlank = function () {
  21663. return this._isBlank;
  21664. },
  21665. /**
  21666. * When axis extent depends on data and no data exists,
  21667. * axis ticks should not be drawn, which is named 'blank'.
  21668. */
  21669. Scale.prototype.setBlank = function (isBlank) {
  21670. this._isBlank = isBlank;
  21671. };
  21672. enableClassExtend(Scale);
  21673. enableClassManagement(Scale, {
  21674. registerWhenExtend: true
  21675. });
  21676. /**
  21677. * Linear continuous scale
  21678. * @module echarts/coord/scale/Ordinal
  21679. *
  21680. * http://en.wikipedia.org/wiki/Level_of_measurement
  21681. */
  21682. // FIXME only one data
  21683. var scaleProto = Scale.prototype;
  21684. var OrdinalScale = Scale.extend({
  21685. type: 'ordinal',
  21686. init: function (data, extent) {
  21687. this._data = data;
  21688. this._extent = extent || [0, data.length - 1];
  21689. },
  21690. parse: function (val) {
  21691. return typeof val === 'string'
  21692. ? indexOf(this._data, val)
  21693. // val might be float.
  21694. : Math.round(val);
  21695. },
  21696. contain: function (rank) {
  21697. rank = this.parse(rank);
  21698. return scaleProto.contain.call(this, rank)
  21699. && this._data[rank] != null;
  21700. },
  21701. /**
  21702. * Normalize given rank or name to linear [0, 1]
  21703. * @param {number|string} [val]
  21704. * @return {number}
  21705. */
  21706. normalize: function (val) {
  21707. return scaleProto.normalize.call(this, this.parse(val));
  21708. },
  21709. scale: function (val) {
  21710. return Math.round(scaleProto.scale.call(this, val));
  21711. },
  21712. /**
  21713. * @return {Array}
  21714. */
  21715. getTicks: function () {
  21716. var ticks = [];
  21717. var extent = this._extent;
  21718. var rank = extent[0];
  21719. while (rank <= extent[1]) {
  21720. ticks.push(rank);
  21721. rank++;
  21722. }
  21723. return ticks;
  21724. },
  21725. /**
  21726. * Get item on rank n
  21727. * @param {number} n
  21728. * @return {string}
  21729. */
  21730. getLabel: function (n) {
  21731. return this._data[n];
  21732. },
  21733. /**
  21734. * @return {number}
  21735. */
  21736. count: function () {
  21737. return this._extent[1] - this._extent[0] + 1;
  21738. },
  21739. /**
  21740. * @override
  21741. */
  21742. unionExtentFromData: function (data, dim) {
  21743. this.unionExtent(data.getDataExtent(dim, false));
  21744. },
  21745. niceTicks: noop,
  21746. niceExtent: noop
  21747. });
  21748. /**
  21749. * @return {module:echarts/scale/Time}
  21750. */
  21751. OrdinalScale.create = function () {
  21752. return new OrdinalScale();
  21753. };
  21754. /**
  21755. * For testable.
  21756. */
  21757. var roundNumber$1 = round;
  21758. /**
  21759. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  21760. * Should be extent[0] < extent[1].
  21761. * @param {number} splitNumber splitNumber should be >= 1.
  21762. * @param {number} [minInterval]
  21763. * @param {number} [maxInterval]
  21764. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  21765. */
  21766. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  21767. var result = {};
  21768. var span = extent[1] - extent[0];
  21769. var interval = result.interval = nice(span / splitNumber, true);
  21770. if (minInterval != null && interval < minInterval) {
  21771. interval = result.interval = minInterval;
  21772. }
  21773. if (maxInterval != null && interval > maxInterval) {
  21774. interval = result.interval = maxInterval;
  21775. }
  21776. // Tow more digital for tick.
  21777. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  21778. // Niced extent inside original extent
  21779. var niceTickExtent = result.niceTickExtent = [
  21780. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  21781. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  21782. ];
  21783. fixExtent(niceTickExtent, extent);
  21784. return result;
  21785. }
  21786. /**
  21787. * @param {number} interval
  21788. * @return {number} interval precision
  21789. */
  21790. function getIntervalPrecision(interval) {
  21791. // Tow more digital for tick.
  21792. return getPrecisionSafe(interval) + 2;
  21793. }
  21794. function clamp(niceTickExtent, idx, extent) {
  21795. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  21796. }
  21797. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  21798. function fixExtent(niceTickExtent, extent) {
  21799. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  21800. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  21801. clamp(niceTickExtent, 0, extent);
  21802. clamp(niceTickExtent, 1, extent);
  21803. if (niceTickExtent[0] > niceTickExtent[1]) {
  21804. niceTickExtent[0] = niceTickExtent[1];
  21805. }
  21806. }
  21807. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  21808. var ticks = [];
  21809. // If interval is 0, return [];
  21810. if (!interval) {
  21811. return ticks;
  21812. }
  21813. // Consider this case: using dataZoom toolbox, zoom and zoom.
  21814. var safeLimit = 10000;
  21815. if (extent[0] < niceTickExtent[0]) {
  21816. ticks.push(extent[0]);
  21817. }
  21818. var tick = niceTickExtent[0];
  21819. while (tick <= niceTickExtent[1]) {
  21820. ticks.push(tick);
  21821. // Avoid rounding error
  21822. tick = roundNumber$1(tick + interval, intervalPrecision);
  21823. if (tick === ticks[ticks.length - 1]) {
  21824. // Consider out of safe float point, e.g.,
  21825. // -3711126.9907707 + 2e-10 === -3711126.9907707
  21826. break;
  21827. }
  21828. if (ticks.length > safeLimit) {
  21829. return [];
  21830. }
  21831. }
  21832. // Consider this case: the last item of ticks is smaller
  21833. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  21834. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  21835. ticks.push(extent[1]);
  21836. }
  21837. return ticks;
  21838. }
  21839. /**
  21840. * Interval scale
  21841. * @module echarts/scale/Interval
  21842. */
  21843. var roundNumber = round;
  21844. /**
  21845. * @alias module:echarts/coord/scale/Interval
  21846. * @constructor
  21847. */
  21848. var IntervalScale = Scale.extend({
  21849. type: 'interval',
  21850. _interval: 0,
  21851. _intervalPrecision: 2,
  21852. setExtent: function (start, end) {
  21853. var thisExtent = this._extent;
  21854. //start,end may be a Number like '25',so...
  21855. if (!isNaN(start)) {
  21856. thisExtent[0] = parseFloat(start);
  21857. }
  21858. if (!isNaN(end)) {
  21859. thisExtent[1] = parseFloat(end);
  21860. }
  21861. },
  21862. unionExtent: function (other) {
  21863. var extent = this._extent;
  21864. other[0] < extent[0] && (extent[0] = other[0]);
  21865. other[1] > extent[1] && (extent[1] = other[1]);
  21866. // unionExtent may called by it's sub classes
  21867. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  21868. },
  21869. /**
  21870. * Get interval
  21871. */
  21872. getInterval: function () {
  21873. return this._interval;
  21874. },
  21875. /**
  21876. * Set interval
  21877. */
  21878. setInterval: function (interval) {
  21879. this._interval = interval;
  21880. // Dropped auto calculated niceExtent and use user setted extent
  21881. // We assume user wan't to set both interval, min, max to get a better result
  21882. this._niceExtent = this._extent.slice();
  21883. this._intervalPrecision = getIntervalPrecision(interval);
  21884. },
  21885. /**
  21886. * @return {Array.<number>}
  21887. */
  21888. getTicks: function () {
  21889. return intervalScaleGetTicks(
  21890. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  21891. );
  21892. },
  21893. /**
  21894. * @return {Array.<string>}
  21895. */
  21896. getTicksLabels: function () {
  21897. var labels = [];
  21898. var ticks = this.getTicks();
  21899. for (var i = 0; i < ticks.length; i++) {
  21900. labels.push(this.getLabel(ticks[i]));
  21901. }
  21902. return labels;
  21903. },
  21904. /**
  21905. * @param {number} data
  21906. * @param {Object} [opt]
  21907. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  21908. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  21909. * @return {string}
  21910. */
  21911. getLabel: function (data, opt) {
  21912. if (data == null) {
  21913. return '';
  21914. }
  21915. var precision = opt && opt.precision;
  21916. if (precision == null) {
  21917. precision = getPrecisionSafe(data) || 0;
  21918. }
  21919. else if (precision === 'auto') {
  21920. // Should be more precise then tick.
  21921. precision = this._intervalPrecision;
  21922. }
  21923. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  21924. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  21925. data = roundNumber(data, precision, true);
  21926. return addCommas(data);
  21927. },
  21928. /**
  21929. * Update interval and extent of intervals for nice ticks
  21930. *
  21931. * @param {number} [splitNumber = 5] Desired number of ticks
  21932. * @param {number} [minInterval]
  21933. * @param {number} [maxInterval]
  21934. */
  21935. niceTicks: function (splitNumber, minInterval, maxInterval) {
  21936. splitNumber = splitNumber || 5;
  21937. var extent = this._extent;
  21938. var span = extent[1] - extent[0];
  21939. if (!isFinite(span)) {
  21940. return;
  21941. }
  21942. // User may set axis min 0 and data are all negative
  21943. // FIXME If it needs to reverse ?
  21944. if (span < 0) {
  21945. span = -span;
  21946. extent.reverse();
  21947. }
  21948. var result = intervalScaleNiceTicks(
  21949. extent, splitNumber, minInterval, maxInterval
  21950. );
  21951. this._intervalPrecision = result.intervalPrecision;
  21952. this._interval = result.interval;
  21953. this._niceExtent = result.niceTickExtent;
  21954. },
  21955. /**
  21956. * Nice extent.
  21957. * @param {Object} opt
  21958. * @param {number} [opt.splitNumber = 5] Given approx tick number
  21959. * @param {boolean} [opt.fixMin=false]
  21960. * @param {boolean} [opt.fixMax=false]
  21961. * @param {boolean} [opt.minInterval]
  21962. * @param {boolean} [opt.maxInterval]
  21963. */
  21964. niceExtent: function (opt) {
  21965. var extent = this._extent;
  21966. // If extent start and end are same, expand them
  21967. if (extent[0] === extent[1]) {
  21968. if (extent[0] !== 0) {
  21969. // Expand extent
  21970. var expandSize = extent[0];
  21971. // In the fowllowing case
  21972. // Axis has been fixed max 100
  21973. // Plus data are all 100 and axis extent are [100, 100].
  21974. // Extend to the both side will cause expanded max is larger than fixed max.
  21975. // So only expand to the smaller side.
  21976. if (!opt.fixMax) {
  21977. extent[1] += expandSize / 2;
  21978. extent[0] -= expandSize / 2;
  21979. }
  21980. else {
  21981. extent[0] -= expandSize / 2;
  21982. }
  21983. }
  21984. else {
  21985. extent[1] = 1;
  21986. }
  21987. }
  21988. var span = extent[1] - extent[0];
  21989. // If there are no data and extent are [Infinity, -Infinity]
  21990. if (!isFinite(span)) {
  21991. extent[0] = 0;
  21992. extent[1] = 1;
  21993. }
  21994. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  21995. // var extent = this._extent;
  21996. var interval = this._interval;
  21997. if (!opt.fixMin) {
  21998. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  21999. }
  22000. if (!opt.fixMax) {
  22001. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  22002. }
  22003. }
  22004. });
  22005. /**
  22006. * @return {module:echarts/scale/Time}
  22007. */
  22008. IntervalScale.create = function () {
  22009. return new IntervalScale();
  22010. };
  22011. // [About UTC and local time zone]:
  22012. // In most cases, `number.parseDate` will treat input data string as local time
  22013. // (except time zone is specified in time string). And `format.formateTime` returns
  22014. // local time by default. option.useUTC is false by default. This design have
  22015. // concidered these common case:
  22016. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  22017. // in local time by default.
  22018. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  22019. // as its original time, without any time difference.
  22020. var intervalScaleProto = IntervalScale.prototype;
  22021. var mathCeil = Math.ceil;
  22022. var mathFloor = Math.floor;
  22023. var ONE_SECOND = 1000;
  22024. var ONE_MINUTE = ONE_SECOND * 60;
  22025. var ONE_HOUR = ONE_MINUTE * 60;
  22026. var ONE_DAY = ONE_HOUR * 24;
  22027. // FIXME 公用?
  22028. var bisect = function (a, x, lo, hi) {
  22029. while (lo < hi) {
  22030. var mid = lo + hi >>> 1;
  22031. if (a[mid][1] < x) {
  22032. lo = mid + 1;
  22033. }
  22034. else {
  22035. hi = mid;
  22036. }
  22037. }
  22038. return lo;
  22039. };
  22040. /**
  22041. * @alias module:echarts/coord/scale/Time
  22042. * @constructor
  22043. */
  22044. var TimeScale = IntervalScale.extend({
  22045. type: 'time',
  22046. /**
  22047. * @override
  22048. */
  22049. getLabel: function (val) {
  22050. var stepLvl = this._stepLvl;
  22051. var date = new Date(val);
  22052. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  22053. },
  22054. /**
  22055. * @override
  22056. */
  22057. niceExtent: function (opt) {
  22058. var extent = this._extent;
  22059. // If extent start and end are same, expand them
  22060. if (extent[0] === extent[1]) {
  22061. // Expand extent
  22062. extent[0] -= ONE_DAY;
  22063. extent[1] += ONE_DAY;
  22064. }
  22065. // If there are no data and extent are [Infinity, -Infinity]
  22066. if (extent[1] === -Infinity && extent[0] === Infinity) {
  22067. var d = new Date();
  22068. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  22069. extent[0] = extent[1] - ONE_DAY;
  22070. }
  22071. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  22072. // var extent = this._extent;
  22073. var interval = this._interval;
  22074. if (!opt.fixMin) {
  22075. extent[0] = round(mathFloor(extent[0] / interval) * interval);
  22076. }
  22077. if (!opt.fixMax) {
  22078. extent[1] = round(mathCeil(extent[1] / interval) * interval);
  22079. }
  22080. },
  22081. /**
  22082. * @override
  22083. */
  22084. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  22085. approxTickNum = approxTickNum || 10;
  22086. var extent = this._extent;
  22087. var span = extent[1] - extent[0];
  22088. var approxInterval = span / approxTickNum;
  22089. if (minInterval != null && approxInterval < minInterval) {
  22090. approxInterval = minInterval;
  22091. }
  22092. if (maxInterval != null && approxInterval > maxInterval) {
  22093. approxInterval = maxInterval;
  22094. }
  22095. var scaleLevelsLen = scaleLevels.length;
  22096. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  22097. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  22098. var interval = level[1];
  22099. // Same with interval scale if span is much larger than 1 year
  22100. if (level[0] === 'year') {
  22101. var yearSpan = span / interval;
  22102. // From "Nice Numbers for Graph Labels" of Graphic Gems
  22103. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  22104. var yearStep = nice(yearSpan / approxTickNum, true);
  22105. interval *= yearStep;
  22106. }
  22107. var timezoneOffset = this.getSetting('useUTC')
  22108. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  22109. var niceExtent = [
  22110. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  22111. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  22112. ];
  22113. fixExtent(niceExtent, extent);
  22114. this._stepLvl = level;
  22115. // Interval will be used in getTicks
  22116. this._interval = interval;
  22117. this._niceExtent = niceExtent;
  22118. },
  22119. parse: function (val) {
  22120. // val might be float.
  22121. return +parseDate(val);
  22122. }
  22123. });
  22124. each$1(['contain', 'normalize'], function (methodName) {
  22125. TimeScale.prototype[methodName] = function (val) {
  22126. return intervalScaleProto[methodName].call(this, this.parse(val));
  22127. };
  22128. });
  22129. // Steps from d3
  22130. var scaleLevels = [
  22131. // Format interval
  22132. ['hh:mm:ss', ONE_SECOND], // 1s
  22133. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  22134. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  22135. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  22136. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  22137. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  22138. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  22139. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  22140. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  22141. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  22142. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  22143. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  22144. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  22145. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  22146. ['MM-dd\nyyyy', ONE_DAY], // 1d
  22147. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  22148. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  22149. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  22150. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  22151. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  22152. ['week', ONE_DAY * 7], // 7d
  22153. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  22154. ['week', ONE_DAY * 14], // 2w
  22155. ['week', ONE_DAY * 21], // 3w
  22156. ['month', ONE_DAY * 31], // 1M
  22157. ['week', ONE_DAY * 42], // 6w
  22158. ['month', ONE_DAY * 62], // 2M
  22159. ['week', ONE_DAY * 42], // 10w
  22160. ['quarter', ONE_DAY * 380 / 4], // 3M
  22161. ['month', ONE_DAY * 31 * 4], // 4M
  22162. ['month', ONE_DAY * 31 * 5], // 5M
  22163. ['half-year', ONE_DAY * 380 / 2], // 6M
  22164. ['month', ONE_DAY * 31 * 8], // 8M
  22165. ['month', ONE_DAY * 31 * 10], // 10M
  22166. ['year', ONE_DAY * 380] // 1Y
  22167. ];
  22168. /**
  22169. * @param {module:echarts/model/Model}
  22170. * @return {module:echarts/scale/Time}
  22171. */
  22172. TimeScale.create = function (model) {
  22173. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  22174. };
  22175. /**
  22176. * Log scale
  22177. * @module echarts/scale/Log
  22178. */
  22179. // Use some method of IntervalScale
  22180. var scaleProto$1 = Scale.prototype;
  22181. var intervalScaleProto$1 = IntervalScale.prototype;
  22182. var getPrecisionSafe$1 = getPrecisionSafe;
  22183. var roundingErrorFix = round;
  22184. var mathFloor$1 = Math.floor;
  22185. var mathCeil$1 = Math.ceil;
  22186. var mathPow$1 = Math.pow;
  22187. var mathLog = Math.log;
  22188. var LogScale = Scale.extend({
  22189. type: 'log',
  22190. base: 10,
  22191. $constructor: function () {
  22192. Scale.apply(this, arguments);
  22193. this._originalScale = new IntervalScale();
  22194. },
  22195. /**
  22196. * @return {Array.<number>}
  22197. */
  22198. getTicks: function () {
  22199. var originalScale = this._originalScale;
  22200. var extent = this._extent;
  22201. var originalExtent = originalScale.getExtent();
  22202. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  22203. var powVal = round(mathPow$1(this.base, val));
  22204. // Fix #4158
  22205. powVal = (val === extent[0] && originalScale.__fixMin)
  22206. ? fixRoundingError(powVal, originalExtent[0])
  22207. : powVal;
  22208. powVal = (val === extent[1] && originalScale.__fixMax)
  22209. ? fixRoundingError(powVal, originalExtent[1])
  22210. : powVal;
  22211. return powVal;
  22212. }, this);
  22213. },
  22214. /**
  22215. * @param {number} val
  22216. * @return {string}
  22217. */
  22218. getLabel: intervalScaleProto$1.getLabel,
  22219. /**
  22220. * @param {number} val
  22221. * @return {number}
  22222. */
  22223. scale: function (val) {
  22224. val = scaleProto$1.scale.call(this, val);
  22225. return mathPow$1(this.base, val);
  22226. },
  22227. /**
  22228. * @param {number} start
  22229. * @param {number} end
  22230. */
  22231. setExtent: function (start, end) {
  22232. var base = this.base;
  22233. start = mathLog(start) / mathLog(base);
  22234. end = mathLog(end) / mathLog(base);
  22235. intervalScaleProto$1.setExtent.call(this, start, end);
  22236. },
  22237. /**
  22238. * @return {number} end
  22239. */
  22240. getExtent: function () {
  22241. var base = this.base;
  22242. var extent = scaleProto$1.getExtent.call(this);
  22243. extent[0] = mathPow$1(base, extent[0]);
  22244. extent[1] = mathPow$1(base, extent[1]);
  22245. // Fix #4158
  22246. var originalScale = this._originalScale;
  22247. var originalExtent = originalScale.getExtent();
  22248. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  22249. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  22250. return extent;
  22251. },
  22252. /**
  22253. * @param {Array.<number>} extent
  22254. */
  22255. unionExtent: function (extent) {
  22256. this._originalScale.unionExtent(extent);
  22257. var base = this.base;
  22258. extent[0] = mathLog(extent[0]) / mathLog(base);
  22259. extent[1] = mathLog(extent[1]) / mathLog(base);
  22260. scaleProto$1.unionExtent.call(this, extent);
  22261. },
  22262. /**
  22263. * @override
  22264. */
  22265. unionExtentFromData: function (data, dim) {
  22266. this.unionExtent(data.getDataExtent(dim, true, function (val) {
  22267. return val > 0;
  22268. }));
  22269. },
  22270. /**
  22271. * Update interval and extent of intervals for nice ticks
  22272. * @param {number} [approxTickNum = 10] Given approx tick number
  22273. */
  22274. niceTicks: function (approxTickNum) {
  22275. approxTickNum = approxTickNum || 10;
  22276. var extent = this._extent;
  22277. var span = extent[1] - extent[0];
  22278. if (span === Infinity || span <= 0) {
  22279. return;
  22280. }
  22281. var interval = quantity(span);
  22282. var err = approxTickNum / span * interval;
  22283. // Filter ticks to get closer to the desired count.
  22284. if (err <= 0.5) {
  22285. interval *= 10;
  22286. }
  22287. // Interval should be integer
  22288. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  22289. interval *= 10;
  22290. }
  22291. var niceExtent = [
  22292. round(mathCeil$1(extent[0] / interval) * interval),
  22293. round(mathFloor$1(extent[1] / interval) * interval)
  22294. ];
  22295. this._interval = interval;
  22296. this._niceExtent = niceExtent;
  22297. },
  22298. /**
  22299. * Nice extent.
  22300. * @override
  22301. */
  22302. niceExtent: function (opt) {
  22303. intervalScaleProto$1.niceExtent.call(this, opt);
  22304. var originalScale = this._originalScale;
  22305. originalScale.__fixMin = opt.fixMin;
  22306. originalScale.__fixMax = opt.fixMax;
  22307. }
  22308. });
  22309. each$1(['contain', 'normalize'], function (methodName) {
  22310. LogScale.prototype[methodName] = function (val) {
  22311. val = mathLog(val) / mathLog(this.base);
  22312. return scaleProto$1[methodName].call(this, val);
  22313. };
  22314. });
  22315. LogScale.create = function () {
  22316. return new LogScale();
  22317. };
  22318. function fixRoundingError(val, originalVal) {
  22319. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  22320. }
  22321. /**
  22322. * Get axis scale extent before niced.
  22323. * Item of returned array can only be number (including Infinity and NaN).
  22324. */
  22325. function getScaleExtent(scale, model) {
  22326. var scaleType = scale.type;
  22327. var min = model.getMin();
  22328. var max = model.getMax();
  22329. var fixMin = min != null;
  22330. var fixMax = max != null;
  22331. var originalExtent = scale.getExtent();
  22332. var axisDataLen;
  22333. var boundaryGap;
  22334. var span;
  22335. if (scaleType === 'ordinal') {
  22336. axisDataLen = (model.get('data') || []).length;
  22337. }
  22338. else {
  22339. boundaryGap = model.get('boundaryGap');
  22340. if (!isArray(boundaryGap)) {
  22341. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  22342. }
  22343. if (typeof boundaryGap[0] === 'boolean') {
  22344. if (__DEV__) {
  22345. console.warn('Boolean type for boundaryGap is only '
  22346. + 'allowed for ordinal axis. Please use string in '
  22347. + 'percentage instead, e.g., "20%". Currently, '
  22348. + 'boundaryGap is set to be 0.');
  22349. }
  22350. boundaryGap = [0, 0];
  22351. }
  22352. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  22353. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  22354. span = (originalExtent[1] - originalExtent[0])
  22355. || Math.abs(originalExtent[0]);
  22356. }
  22357. // Notice: When min/max is not set (that is, when there are null/undefined,
  22358. // which is the most common case), these cases should be ensured:
  22359. // (1) For 'ordinal', show all axis.data.
  22360. // (2) For others:
  22361. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  22362. // disabled).
  22363. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  22364. // be the result that originalExtent enlarged by boundaryGap.
  22365. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  22366. // FIXME
  22367. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  22368. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  22369. // that the results processed by boundaryGap are positive/negative?
  22370. if (min == null) {
  22371. min = scaleType === 'ordinal'
  22372. ? (axisDataLen ? 0 : NaN)
  22373. : originalExtent[0] - boundaryGap[0] * span;
  22374. }
  22375. if (max == null) {
  22376. max = scaleType === 'ordinal'
  22377. ? (axisDataLen ? axisDataLen - 1 : NaN)
  22378. : originalExtent[1] + boundaryGap[1] * span;
  22379. }
  22380. if (min === 'dataMin') {
  22381. min = originalExtent[0];
  22382. }
  22383. else if (typeof min === 'function') {
  22384. min = min({
  22385. min: originalExtent[0],
  22386. max: originalExtent[1]
  22387. });
  22388. }
  22389. if (max === 'dataMax') {
  22390. max = originalExtent[1];
  22391. }
  22392. else if (typeof max === 'function') {
  22393. max = max({
  22394. min: originalExtent[0],
  22395. max: originalExtent[1]
  22396. });
  22397. }
  22398. (min == null || !isFinite(min)) && (min = NaN);
  22399. (max == null || !isFinite(max)) && (max = NaN);
  22400. scale.setBlank(eqNaN(min) || eqNaN(max));
  22401. // Evaluate if axis needs cross zero
  22402. if (model.getNeedCrossZero()) {
  22403. // Axis is over zero and min is not set
  22404. if (min > 0 && max > 0 && !fixMin) {
  22405. min = 0;
  22406. }
  22407. // Axis is under zero and max is not set
  22408. if (min < 0 && max < 0 && !fixMax) {
  22409. max = 0;
  22410. }
  22411. }
  22412. return [min, max];
  22413. }
  22414. function niceScaleExtent(scale, model) {
  22415. var extent = getScaleExtent(scale, model);
  22416. var fixMin = model.getMin() != null;
  22417. var fixMax = model.getMax() != null;
  22418. var splitNumber = model.get('splitNumber');
  22419. if (scale.type === 'log') {
  22420. scale.base = model.get('logBase');
  22421. }
  22422. var scaleType = scale.type;
  22423. scale.setExtent(extent[0], extent[1]);
  22424. scale.niceExtent({
  22425. splitNumber: splitNumber,
  22426. fixMin: fixMin,
  22427. fixMax: fixMax,
  22428. minInterval: (scaleType === 'interval' || scaleType === 'time')
  22429. ? model.get('minInterval') : null,
  22430. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  22431. ? model.get('maxInterval') : null
  22432. });
  22433. // If some one specified the min, max. And the default calculated interval
  22434. // is not good enough. He can specify the interval. It is often appeared
  22435. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  22436. // to be 60.
  22437. // FIXME
  22438. var interval = model.get('interval');
  22439. if (interval != null) {
  22440. scale.setInterval && scale.setInterval(interval);
  22441. }
  22442. }
  22443. /**
  22444. * @param {module:echarts/model/Model} model
  22445. * @param {string} [axisType] Default retrieve from model.type
  22446. * @return {module:echarts/scale/*}
  22447. */
  22448. function createScaleByModel(model, axisType) {
  22449. axisType = axisType || model.get('type');
  22450. if (axisType) {
  22451. switch (axisType) {
  22452. // Buildin scale
  22453. case 'category':
  22454. return new OrdinalScale(
  22455. model.getCategories(), [Infinity, -Infinity]
  22456. );
  22457. case 'value':
  22458. return new IntervalScale();
  22459. // Extended scale, like time and log
  22460. default:
  22461. return (Scale.getClass(axisType) || IntervalScale).create(model);
  22462. }
  22463. }
  22464. }
  22465. /**
  22466. * Check if the axis corss 0
  22467. */
  22468. function ifAxisCrossZero(axis) {
  22469. var dataExtent = axis.scale.getExtent();
  22470. var min = dataExtent[0];
  22471. var max = dataExtent[1];
  22472. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  22473. }
  22474. /**
  22475. * @param {Array.<number>} tickCoords In axis self coordinate.
  22476. * @param {Array.<string>} labels
  22477. * @param {string} font
  22478. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  22479. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  22480. * @return {number}
  22481. */
  22482. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  22483. var textSpaceTakenRect;
  22484. var autoLabelInterval = 0;
  22485. var accumulatedLabelInterval = 0;
  22486. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  22487. var step = 1;
  22488. if (labels.length > 40) {
  22489. // Simple optimization for large amount of labels
  22490. step = Math.floor(labels.length / 40);
  22491. }
  22492. for (var i = 0; i < tickCoords.length; i += step) {
  22493. var tickCoord = tickCoords[i];
  22494. // Not precise, do not consider align and vertical align
  22495. // and each distance from axis line yet.
  22496. var rect = getBoundingRect(
  22497. labels[i], font, 'center', 'top'
  22498. );
  22499. rect.x += tickCoord * Math.cos(rotation);
  22500. rect.y += tickCoord * Math.sin(rotation);
  22501. // Magic number
  22502. rect.width *= 1.3;
  22503. rect.height *= 1.3;
  22504. if (!textSpaceTakenRect) {
  22505. textSpaceTakenRect = rect.clone();
  22506. }
  22507. // There is no space for current label;
  22508. else if (textSpaceTakenRect.intersect(rect)) {
  22509. accumulatedLabelInterval++;
  22510. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  22511. }
  22512. else {
  22513. textSpaceTakenRect.union(rect);
  22514. // Reset
  22515. accumulatedLabelInterval = 0;
  22516. }
  22517. }
  22518. if (autoLabelInterval === 0 && step > 1) {
  22519. return step;
  22520. }
  22521. return (autoLabelInterval + 1) * step - 1;
  22522. }
  22523. /**
  22524. * @param {Object} axis
  22525. * @param {Function} labelFormatter
  22526. * @return {Array.<string>}
  22527. */
  22528. function getFormattedLabels(axis, labelFormatter) {
  22529. var scale = axis.scale;
  22530. var labels = scale.getTicksLabels();
  22531. var ticks = scale.getTicks();
  22532. if (typeof labelFormatter === 'string') {
  22533. labelFormatter = (function (tpl) {
  22534. return function (val) {
  22535. return tpl.replace('{value}', val != null ? val : '');
  22536. };
  22537. })(labelFormatter);
  22538. // Consider empty array
  22539. return map(labels, labelFormatter);
  22540. }
  22541. else if (typeof labelFormatter === 'function') {
  22542. return map(ticks, function (tick, idx) {
  22543. return labelFormatter(
  22544. getAxisRawValue(axis, tick),
  22545. idx
  22546. );
  22547. }, this);
  22548. }
  22549. else {
  22550. return labels;
  22551. }
  22552. }
  22553. function getAxisRawValue(axis, value) {
  22554. // In category axis with data zoom, tick is not the original
  22555. // index of axis.data. So tick should not be exposed to user
  22556. // in category axis.
  22557. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  22558. }
  22559. function getName(obj) {
  22560. if (isObject(obj) && obj.value != null) {
  22561. return obj.value;
  22562. }
  22563. else {
  22564. return obj + '';
  22565. }
  22566. }
  22567. var axisModelCommonMixin = {
  22568. /**
  22569. * Format labels
  22570. * @return {Array.<string>}
  22571. */
  22572. getFormattedLabels: function () {
  22573. return getFormattedLabels(
  22574. this.axis,
  22575. this.get('axisLabel.formatter')
  22576. );
  22577. },
  22578. /**
  22579. * Get categories
  22580. */
  22581. getCategories: function () {
  22582. return this.get('type') === 'category'
  22583. && map(this.get('data'), getName);
  22584. },
  22585. /**
  22586. * @param {boolean} origin
  22587. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  22588. */
  22589. getMin: function (origin) {
  22590. var option = this.option;
  22591. var min = (!origin && option.rangeStart != null)
  22592. ? option.rangeStart : option.min;
  22593. if (this.axis
  22594. && min != null
  22595. && min !== 'dataMin'
  22596. && typeof min !== 'function'
  22597. && !eqNaN(min)
  22598. ) {
  22599. min = this.axis.scale.parse(min);
  22600. }
  22601. return min;
  22602. },
  22603. /**
  22604. * @param {boolean} origin
  22605. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  22606. */
  22607. getMax: function (origin) {
  22608. var option = this.option;
  22609. var max = (!origin && option.rangeEnd != null)
  22610. ? option.rangeEnd : option.max;
  22611. if (this.axis
  22612. && max != null
  22613. && max !== 'dataMax'
  22614. && typeof max !== 'function'
  22615. && !eqNaN(max)
  22616. ) {
  22617. max = this.axis.scale.parse(max);
  22618. }
  22619. return max;
  22620. },
  22621. /**
  22622. * @return {boolean}
  22623. */
  22624. getNeedCrossZero: function () {
  22625. var option = this.option;
  22626. return (option.rangeStart != null || option.rangeEnd != null)
  22627. ? false : !option.scale;
  22628. },
  22629. /**
  22630. * Should be implemented by each axis model if necessary.
  22631. * @return {module:echarts/model/Component} coordinate system model
  22632. */
  22633. getCoordSysModel: noop,
  22634. /**
  22635. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  22636. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  22637. */
  22638. setRange: function (rangeStart, rangeEnd) {
  22639. this.option.rangeStart = rangeStart;
  22640. this.option.rangeEnd = rangeEnd;
  22641. },
  22642. /**
  22643. * Reset range
  22644. */
  22645. resetRange: function () {
  22646. // rangeStart and rangeEnd is readonly.
  22647. this.option.rangeStart = this.option.rangeEnd = null;
  22648. }
  22649. };
  22650. // Symbol factory
  22651. /**
  22652. * Triangle shape
  22653. * @inner
  22654. */
  22655. var Triangle = extendShape({
  22656. type: 'triangle',
  22657. shape: {
  22658. cx: 0,
  22659. cy: 0,
  22660. width: 0,
  22661. height: 0
  22662. },
  22663. buildPath: function (path, shape) {
  22664. var cx = shape.cx;
  22665. var cy = shape.cy;
  22666. var width = shape.width / 2;
  22667. var height = shape.height / 2;
  22668. path.moveTo(cx, cy - height);
  22669. path.lineTo(cx + width, cy + height);
  22670. path.lineTo(cx - width, cy + height);
  22671. path.closePath();
  22672. }
  22673. });
  22674. /**
  22675. * Diamond shape
  22676. * @inner
  22677. */
  22678. var Diamond = extendShape({
  22679. type: 'diamond',
  22680. shape: {
  22681. cx: 0,
  22682. cy: 0,
  22683. width: 0,
  22684. height: 0
  22685. },
  22686. buildPath: function (path, shape) {
  22687. var cx = shape.cx;
  22688. var cy = shape.cy;
  22689. var width = shape.width / 2;
  22690. var height = shape.height / 2;
  22691. path.moveTo(cx, cy - height);
  22692. path.lineTo(cx + width, cy);
  22693. path.lineTo(cx, cy + height);
  22694. path.lineTo(cx - width, cy);
  22695. path.closePath();
  22696. }
  22697. });
  22698. /**
  22699. * Pin shape
  22700. * @inner
  22701. */
  22702. var Pin = extendShape({
  22703. type: 'pin',
  22704. shape: {
  22705. // x, y on the cusp
  22706. x: 0,
  22707. y: 0,
  22708. width: 0,
  22709. height: 0
  22710. },
  22711. buildPath: function (path, shape) {
  22712. var x = shape.x;
  22713. var y = shape.y;
  22714. var w = shape.width / 5 * 3;
  22715. // Height must be larger than width
  22716. var h = Math.max(w, shape.height);
  22717. var r = w / 2;
  22718. // Dist on y with tangent point and circle center
  22719. var dy = r * r / (h - r);
  22720. var cy = y - h + r + dy;
  22721. var angle = Math.asin(dy / r);
  22722. // Dist on x with tangent point and circle center
  22723. var dx = Math.cos(angle) * r;
  22724. var tanX = Math.sin(angle);
  22725. var tanY = Math.cos(angle);
  22726. var cpLen = r * 0.6;
  22727. var cpLen2 = r * 0.7;
  22728. path.moveTo(x - dx, cy + dy);
  22729. path.arc(
  22730. x, cy, r,
  22731. Math.PI - angle,
  22732. Math.PI * 2 + angle
  22733. );
  22734. path.bezierCurveTo(
  22735. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  22736. x, y - cpLen2,
  22737. x, y
  22738. );
  22739. path.bezierCurveTo(
  22740. x, y - cpLen2,
  22741. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  22742. x - dx, cy + dy
  22743. );
  22744. path.closePath();
  22745. }
  22746. });
  22747. /**
  22748. * Arrow shape
  22749. * @inner
  22750. */
  22751. var Arrow = extendShape({
  22752. type: 'arrow',
  22753. shape: {
  22754. x: 0,
  22755. y: 0,
  22756. width: 0,
  22757. height: 0
  22758. },
  22759. buildPath: function (ctx, shape) {
  22760. var height = shape.height;
  22761. var width = shape.width;
  22762. var x = shape.x;
  22763. var y = shape.y;
  22764. var dx = width / 3 * 2;
  22765. ctx.moveTo(x, y);
  22766. ctx.lineTo(x + dx, y + height);
  22767. ctx.lineTo(x, y + height / 4 * 3);
  22768. ctx.lineTo(x - dx, y + height);
  22769. ctx.lineTo(x, y);
  22770. ctx.closePath();
  22771. }
  22772. });
  22773. /**
  22774. * Map of path contructors
  22775. * @type {Object.<string, module:zrender/graphic/Path>}
  22776. */
  22777. var symbolCtors = {
  22778. line: Line,
  22779. rect: Rect,
  22780. roundRect: Rect,
  22781. square: Rect,
  22782. circle: Circle,
  22783. diamond: Diamond,
  22784. pin: Pin,
  22785. arrow: Arrow,
  22786. triangle: Triangle
  22787. };
  22788. var symbolShapeMakers = {
  22789. line: function (x, y, w, h, shape) {
  22790. // FIXME
  22791. shape.x1 = x;
  22792. shape.y1 = y + h / 2;
  22793. shape.x2 = x + w;
  22794. shape.y2 = y + h / 2;
  22795. },
  22796. rect: function (x, y, w, h, shape) {
  22797. shape.x = x;
  22798. shape.y = y;
  22799. shape.width = w;
  22800. shape.height = h;
  22801. },
  22802. roundRect: function (x, y, w, h, shape) {
  22803. shape.x = x;
  22804. shape.y = y;
  22805. shape.width = w;
  22806. shape.height = h;
  22807. shape.r = Math.min(w, h) / 4;
  22808. },
  22809. square: function (x, y, w, h, shape) {
  22810. var size = Math.min(w, h);
  22811. shape.x = x;
  22812. shape.y = y;
  22813. shape.width = size;
  22814. shape.height = size;
  22815. },
  22816. circle: function (x, y, w, h, shape) {
  22817. // Put circle in the center of square
  22818. shape.cx = x + w / 2;
  22819. shape.cy = y + h / 2;
  22820. shape.r = Math.min(w, h) / 2;
  22821. },
  22822. diamond: function (x, y, w, h, shape) {
  22823. shape.cx = x + w / 2;
  22824. shape.cy = y + h / 2;
  22825. shape.width = w;
  22826. shape.height = h;
  22827. },
  22828. pin: function (x, y, w, h, shape) {
  22829. shape.x = x + w / 2;
  22830. shape.y = y + h / 2;
  22831. shape.width = w;
  22832. shape.height = h;
  22833. },
  22834. arrow: function (x, y, w, h, shape) {
  22835. shape.x = x + w / 2;
  22836. shape.y = y + h / 2;
  22837. shape.width = w;
  22838. shape.height = h;
  22839. },
  22840. triangle: function (x, y, w, h, shape) {
  22841. shape.cx = x + w / 2;
  22842. shape.cy = y + h / 2;
  22843. shape.width = w;
  22844. shape.height = h;
  22845. }
  22846. };
  22847. var symbolBuildProxies = {};
  22848. each$1(symbolCtors, function (Ctor, name) {
  22849. symbolBuildProxies[name] = new Ctor();
  22850. });
  22851. var SymbolClz = extendShape({
  22852. type: 'symbol',
  22853. shape: {
  22854. symbolType: '',
  22855. x: 0,
  22856. y: 0,
  22857. width: 0,
  22858. height: 0
  22859. },
  22860. beforeBrush: function () {
  22861. var style = this.style;
  22862. var shape = this.shape;
  22863. // FIXME
  22864. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  22865. style.textPosition = ['50%', '40%'];
  22866. style.textAlign = 'center';
  22867. style.textVerticalAlign = 'middle';
  22868. }
  22869. },
  22870. buildPath: function (ctx, shape, inBundle) {
  22871. var symbolType = shape.symbolType;
  22872. var proxySymbol = symbolBuildProxies[symbolType];
  22873. if (shape.symbolType !== 'none') {
  22874. if (!proxySymbol) {
  22875. // Default rect
  22876. symbolType = 'rect';
  22877. proxySymbol = symbolBuildProxies[symbolType];
  22878. }
  22879. symbolShapeMakers[symbolType](
  22880. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  22881. );
  22882. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  22883. }
  22884. }
  22885. });
  22886. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  22887. function symbolPathSetColor(color, innerColor) {
  22888. if (this.type !== 'image') {
  22889. var symbolStyle = this.style;
  22890. var symbolShape = this.shape;
  22891. if (symbolShape && symbolShape.symbolType === 'line') {
  22892. symbolStyle.stroke = color;
  22893. }
  22894. else if (this.__isEmptyBrush) {
  22895. symbolStyle.stroke = color;
  22896. symbolStyle.fill = innerColor || '#fff';
  22897. }
  22898. else {
  22899. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  22900. symbolStyle.fill && (symbolStyle.fill = color);
  22901. symbolStyle.stroke && (symbolStyle.stroke = color);
  22902. }
  22903. this.dirty(false);
  22904. }
  22905. }
  22906. /**
  22907. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  22908. * @param {string} symbolType
  22909. * @param {number} x
  22910. * @param {number} y
  22911. * @param {number} w
  22912. * @param {number} h
  22913. * @param {string} color
  22914. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  22915. * for path and image only.
  22916. */
  22917. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  22918. // TODO Support image object, DynamicImage.
  22919. var isEmpty = symbolType.indexOf('empty') === 0;
  22920. if (isEmpty) {
  22921. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  22922. }
  22923. var symbolPath;
  22924. if (symbolType.indexOf('image://') === 0) {
  22925. symbolPath = makeImage(
  22926. symbolType.slice(8),
  22927. new BoundingRect(x, y, w, h),
  22928. keepAspect ? 'center' : 'cover'
  22929. );
  22930. }
  22931. else if (symbolType.indexOf('path://') === 0) {
  22932. symbolPath = makePath(
  22933. symbolType.slice(7),
  22934. {},
  22935. new BoundingRect(x, y, w, h),
  22936. keepAspect ? 'center' : 'cover'
  22937. );
  22938. }
  22939. else {
  22940. symbolPath = new SymbolClz({
  22941. shape: {
  22942. symbolType: symbolType,
  22943. x: x,
  22944. y: y,
  22945. width: w,
  22946. height: h
  22947. }
  22948. });
  22949. }
  22950. symbolPath.__isEmptyBrush = isEmpty;
  22951. symbolPath.setColor = symbolPathSetColor;
  22952. symbolPath.setColor(color);
  22953. return symbolPath;
  22954. }
  22955. /**
  22956. * Create a muti dimension List structure from seriesModel.
  22957. * @param {module:echarts/model/Model} seriesModel
  22958. * @return {module:echarts/data/List} list
  22959. */
  22960. function createList(seriesModel) {
  22961. var data = seriesModel.get('data');
  22962. return createListFromArray(data, seriesModel, seriesModel.ecModel);
  22963. }
  22964. /**
  22965. * Create scale
  22966. * @param {Array.<number>} dataExtent
  22967. * @param {Object|module:echarts/Model} option
  22968. */
  22969. function createScale(dataExtent, option) {
  22970. var axisModel = option;
  22971. if (!(option instanceof Model)) {
  22972. axisModel = new Model(option);
  22973. mixin(axisModel, axisModelCommonMixin);
  22974. }
  22975. var scale = createScaleByModel(axisModel);
  22976. scale.setExtent(dataExtent[0], dataExtent[1]);
  22977. niceScaleExtent(scale, axisModel);
  22978. return scale;
  22979. }
  22980. /**
  22981. * Mixin common methods to axis model,
  22982. *
  22983. * Inlcude methods
  22984. * `getFormattedLabels() => Array.<string>`
  22985. * `getCategories() => Array.<string>`
  22986. * `getMin(origin: boolean) => number`
  22987. * `getMax(origin: boolean) => number`
  22988. * `getNeedCrossZero() => boolean`
  22989. * `setRange(start: number, end: number)`
  22990. * `resetRange()`
  22991. */
  22992. function mixinAxisModelCommonMethods(Model$$1) {
  22993. mixin(Model$$1, axisModelCommonMixin);
  22994. }
  22995. var helper = (Object.freeze || Object)({
  22996. createList: createList,
  22997. createScale: createScale,
  22998. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  22999. completeDimensions: completeDimensions,
  23000. createSymbol: createSymbol
  23001. });
  23002. var linearMap$1 = linearMap;
  23003. function fixExtentWithBands(extent, nTick) {
  23004. var size = extent[1] - extent[0];
  23005. var len = nTick;
  23006. var margin = size / len / 2;
  23007. extent[0] += margin;
  23008. extent[1] -= margin;
  23009. }
  23010. var normalizedExtent = [0, 1];
  23011. /**
  23012. * @name module:echarts/coord/CartesianAxis
  23013. * @constructor
  23014. */
  23015. var Axis = function (dim, scale, extent) {
  23016. /**
  23017. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  23018. * @type {string}
  23019. */
  23020. this.dim = dim;
  23021. /**
  23022. * Axis scale
  23023. * @type {module:echarts/coord/scale/*}
  23024. */
  23025. this.scale = scale;
  23026. /**
  23027. * @type {Array.<number>}
  23028. * @private
  23029. */
  23030. this._extent = extent || [0, 0];
  23031. /**
  23032. * @type {boolean}
  23033. */
  23034. this.inverse = false;
  23035. /**
  23036. * Usually true when axis has a ordinal scale
  23037. * @type {boolean}
  23038. */
  23039. this.onBand = false;
  23040. /**
  23041. * @private
  23042. * @type {number}
  23043. */
  23044. this._labelInterval;
  23045. };
  23046. Axis.prototype = {
  23047. constructor: Axis,
  23048. /**
  23049. * If axis extent contain given coord
  23050. * @param {number} coord
  23051. * @return {boolean}
  23052. */
  23053. contain: function (coord) {
  23054. var extent = this._extent;
  23055. var min = Math.min(extent[0], extent[1]);
  23056. var max = Math.max(extent[0], extent[1]);
  23057. return coord >= min && coord <= max;
  23058. },
  23059. /**
  23060. * If axis extent contain given data
  23061. * @param {number} data
  23062. * @return {boolean}
  23063. */
  23064. containData: function (data) {
  23065. return this.contain(this.dataToCoord(data));
  23066. },
  23067. /**
  23068. * Get coord extent.
  23069. * @return {Array.<number>}
  23070. */
  23071. getExtent: function () {
  23072. return this._extent.slice();
  23073. },
  23074. /**
  23075. * Get precision used for formatting
  23076. * @param {Array.<number>} [dataExtent]
  23077. * @return {number}
  23078. */
  23079. getPixelPrecision: function (dataExtent) {
  23080. return getPixelPrecision(
  23081. dataExtent || this.scale.getExtent(),
  23082. this._extent
  23083. );
  23084. },
  23085. /**
  23086. * Set coord extent
  23087. * @param {number} start
  23088. * @param {number} end
  23089. */
  23090. setExtent: function (start, end) {
  23091. var extent = this._extent;
  23092. extent[0] = start;
  23093. extent[1] = end;
  23094. },
  23095. /**
  23096. * Convert data to coord. Data is the rank if it has a ordinal scale
  23097. * @param {number} data
  23098. * @param {boolean} clamp
  23099. * @return {number}
  23100. */
  23101. dataToCoord: function (data, clamp) {
  23102. var extent = this._extent;
  23103. var scale = this.scale;
  23104. data = scale.normalize(data);
  23105. if (this.onBand && scale.type === 'ordinal') {
  23106. extent = extent.slice();
  23107. fixExtentWithBands(extent, scale.count());
  23108. }
  23109. return linearMap$1(data, normalizedExtent, extent, clamp);
  23110. },
  23111. /**
  23112. * Convert coord to data. Data is the rank if it has a ordinal scale
  23113. * @param {number} coord
  23114. * @param {boolean} clamp
  23115. * @return {number}
  23116. */
  23117. coordToData: function (coord, clamp) {
  23118. var extent = this._extent;
  23119. var scale = this.scale;
  23120. if (this.onBand && scale.type === 'ordinal') {
  23121. extent = extent.slice();
  23122. fixExtentWithBands(extent, scale.count());
  23123. }
  23124. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  23125. return this.scale.scale(t);
  23126. },
  23127. /**
  23128. * Convert pixel point to data in axis
  23129. * @param {Array.<number>} point
  23130. * @param {boolean} clamp
  23131. * @return {number} data
  23132. */
  23133. pointToData: function (point, clamp) {
  23134. // Should be implemented in derived class if necessary.
  23135. },
  23136. /**
  23137. * @return {Array.<number>}
  23138. */
  23139. getTicksCoords: function (alignWithLabel) {
  23140. if (this.onBand && !alignWithLabel) {
  23141. var bands = this.getBands();
  23142. var coords = [];
  23143. for (var i = 0; i < bands.length; i++) {
  23144. coords.push(bands[i][0]);
  23145. }
  23146. if (bands[i - 1]) {
  23147. coords.push(bands[i - 1][1]);
  23148. }
  23149. return coords;
  23150. }
  23151. else {
  23152. return map(this.scale.getTicks(), this.dataToCoord, this);
  23153. }
  23154. },
  23155. /**
  23156. * Coords of labels are on the ticks or on the middle of bands
  23157. * @return {Array.<number>}
  23158. */
  23159. getLabelsCoords: function () {
  23160. return map(this.scale.getTicks(), this.dataToCoord, this);
  23161. },
  23162. /**
  23163. * Get bands.
  23164. *
  23165. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  23166. * |---1---|---2---|---3---|---4---|.
  23167. *
  23168. * @return {Array}
  23169. */
  23170. // FIXME Situation when labels is on ticks
  23171. getBands: function () {
  23172. var extent = this.getExtent();
  23173. var bands = [];
  23174. var len = this.scale.count();
  23175. var start = extent[0];
  23176. var end = extent[1];
  23177. var span = end - start;
  23178. for (var i = 0; i < len; i++) {
  23179. bands.push([
  23180. span * i / len + start,
  23181. span * (i + 1) / len + start
  23182. ]);
  23183. }
  23184. return bands;
  23185. },
  23186. /**
  23187. * Get width of band
  23188. * @return {number}
  23189. */
  23190. getBandWidth: function () {
  23191. var axisExtent = this._extent;
  23192. var dataExtent = this.scale.getExtent();
  23193. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  23194. // Fix #2728, avoid NaN when only one data.
  23195. len === 0 && (len = 1);
  23196. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  23197. return Math.abs(size) / len;
  23198. },
  23199. /**
  23200. * @abstract
  23201. * @return {boolean} Is horizontal
  23202. */
  23203. isHorizontal: null,
  23204. /**
  23205. * @abstract
  23206. * @return {number} Get axis rotate, by degree.
  23207. */
  23208. getRotate: null,
  23209. /**
  23210. * Get interval of the axis label.
  23211. * To get precise result, at least one of `getRotate` and `isHorizontal`
  23212. * should be implemented.
  23213. * @return {number}
  23214. */
  23215. getLabelInterval: function () {
  23216. var labelInterval = this._labelInterval;
  23217. if (!labelInterval) {
  23218. var axisModel = this.model;
  23219. var labelModel = axisModel.getModel('axisLabel');
  23220. labelInterval = labelModel.get('interval');
  23221. if (this.type === 'category'
  23222. && (labelInterval == null || labelInterval === 'auto')
  23223. ) {
  23224. labelInterval = getAxisLabelInterval(
  23225. map(this.scale.getTicks(), this.dataToCoord, this),
  23226. axisModel.getFormattedLabels(),
  23227. labelModel.getFont(),
  23228. this.getRotate
  23229. ? this.getRotate()
  23230. : (this.isHorizontal && !this.isHorizontal())
  23231. ? 90
  23232. : 0,
  23233. labelModel.get('rotate')
  23234. );
  23235. }
  23236. this._labelInterval = labelInterval;
  23237. }
  23238. return labelInterval;
  23239. }
  23240. };
  23241. var EPSILON$3 = 1e-8;
  23242. function isAroundEqual$1(a, b) {
  23243. return Math.abs(a - b) < EPSILON$3;
  23244. }
  23245. function contain$1(points, x, y) {
  23246. var w = 0;
  23247. var p = points[0];
  23248. if (!p) {
  23249. return false;
  23250. }
  23251. for (var i = 1; i < points.length; i++) {
  23252. var p2 = points[i];
  23253. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  23254. p = p2;
  23255. }
  23256. // Close polygon
  23257. var p0 = points[0];
  23258. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  23259. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  23260. }
  23261. return w !== 0;
  23262. }
  23263. /**
  23264. * @module echarts/coord/geo/Region
  23265. */
  23266. /**
  23267. * @param {string} name
  23268. * @param {Array} geometries
  23269. * @param {Array.<number>} cp
  23270. */
  23271. function Region(name, geometries, cp) {
  23272. /**
  23273. * @type {string}
  23274. * @readOnly
  23275. */
  23276. this.name = name;
  23277. /**
  23278. * @type {Array.<Array>}
  23279. * @readOnly
  23280. */
  23281. this.geometries = geometries;
  23282. if (!cp) {
  23283. var rect = this.getBoundingRect();
  23284. cp = [
  23285. rect.x + rect.width / 2,
  23286. rect.y + rect.height / 2
  23287. ];
  23288. }
  23289. else {
  23290. cp = [cp[0], cp[1]];
  23291. }
  23292. /**
  23293. * @type {Array.<number>}
  23294. */
  23295. this.center = cp;
  23296. }
  23297. Region.prototype = {
  23298. constructor: Region,
  23299. properties: null,
  23300. /**
  23301. * @return {module:zrender/core/BoundingRect}
  23302. */
  23303. getBoundingRect: function () {
  23304. var rect = this._rect;
  23305. if (rect) {
  23306. return rect;
  23307. }
  23308. var MAX_NUMBER = Number.MAX_VALUE;
  23309. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  23310. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  23311. var min2 = [];
  23312. var max2 = [];
  23313. var geometries = this.geometries;
  23314. for (var i = 0; i < geometries.length; i++) {
  23315. // Only support polygon
  23316. if (geometries[i].type !== 'polygon') {
  23317. continue;
  23318. }
  23319. // Doesn't consider hole
  23320. var exterior = geometries[i].exterior;
  23321. fromPoints(exterior, min2, max2);
  23322. min(min$$1, min$$1, min2);
  23323. max(max$$1, max$$1, max2);
  23324. }
  23325. // No data
  23326. if (i === 0) {
  23327. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  23328. }
  23329. return (this._rect = new BoundingRect(
  23330. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  23331. ));
  23332. },
  23333. /**
  23334. * @param {<Array.<number>} coord
  23335. * @return {boolean}
  23336. */
  23337. contain: function (coord) {
  23338. var rect = this.getBoundingRect();
  23339. var geometries = this.geometries;
  23340. if (!rect.contain(coord[0], coord[1])) {
  23341. return false;
  23342. }
  23343. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  23344. // Only support polygon.
  23345. if (geometries[i].type !== 'polygon') {
  23346. continue;
  23347. }
  23348. var exterior = geometries[i].exterior;
  23349. var interiors = geometries[i].interiors;
  23350. if (contain$1(exterior, coord[0], coord[1])) {
  23351. // Not in the region if point is in the hole.
  23352. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  23353. if (contain$1(interiors[k])) {
  23354. continue loopGeo;
  23355. }
  23356. }
  23357. return true;
  23358. }
  23359. }
  23360. return false;
  23361. },
  23362. transformTo: function (x, y, width, height) {
  23363. var rect = this.getBoundingRect();
  23364. var aspect = rect.width / rect.height;
  23365. if (!width) {
  23366. width = aspect * height;
  23367. }
  23368. else if (!height) {
  23369. height = width / aspect ;
  23370. }
  23371. var target = new BoundingRect(x, y, width, height);
  23372. var transform = rect.calculateTransform(target);
  23373. var geometries = this.geometries;
  23374. for (var i = 0; i < geometries.length; i++) {
  23375. // Only support polygon.
  23376. if (geometries[i].type !== 'polygon') {
  23377. continue;
  23378. }
  23379. var exterior = geometries[i].exterior;
  23380. var interiors = geometries[i].interiors;
  23381. for (var p = 0; p < exterior.length; p++) {
  23382. applyTransform(exterior[p], exterior[p], transform);
  23383. }
  23384. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  23385. for (var p = 0; p < interiors[h].length; p++) {
  23386. applyTransform(interiors[h][p], interiors[h][p], transform);
  23387. }
  23388. }
  23389. }
  23390. rect = this._rect;
  23391. rect.copy(target);
  23392. // Update center
  23393. this.center = [
  23394. rect.x + rect.width / 2,
  23395. rect.y + rect.height / 2
  23396. ];
  23397. }
  23398. };
  23399. /**
  23400. * Parse and decode geo json
  23401. * @module echarts/coord/geo/parseGeoJson
  23402. */
  23403. function decode(json) {
  23404. if (!json.UTF8Encoding) {
  23405. return json;
  23406. }
  23407. var encodeScale = json.UTF8Scale;
  23408. if (encodeScale == null) {
  23409. encodeScale = 1024;
  23410. }
  23411. var features = json.features;
  23412. for (var f = 0; f < features.length; f++) {
  23413. var feature = features[f];
  23414. var geometry = feature.geometry;
  23415. var coordinates = geometry.coordinates;
  23416. var encodeOffsets = geometry.encodeOffsets;
  23417. for (var c = 0; c < coordinates.length; c++) {
  23418. var coordinate = coordinates[c];
  23419. if (geometry.type === 'Polygon') {
  23420. coordinates[c] = decodePolygon(
  23421. coordinate,
  23422. encodeOffsets[c],
  23423. encodeScale
  23424. );
  23425. }
  23426. else if (geometry.type === 'MultiPolygon') {
  23427. for (var c2 = 0; c2 < coordinate.length; c2++) {
  23428. var polygon = coordinate[c2];
  23429. coordinate[c2] = decodePolygon(
  23430. polygon,
  23431. encodeOffsets[c][c2],
  23432. encodeScale
  23433. );
  23434. }
  23435. }
  23436. }
  23437. }
  23438. // Has been decoded
  23439. json.UTF8Encoding = false;
  23440. return json;
  23441. }
  23442. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  23443. var result = [];
  23444. var prevX = encodeOffsets[0];
  23445. var prevY = encodeOffsets[1];
  23446. for (var i = 0; i < coordinate.length; i += 2) {
  23447. var x = coordinate.charCodeAt(i) - 64;
  23448. var y = coordinate.charCodeAt(i + 1) - 64;
  23449. // ZigZag decoding
  23450. x = (x >> 1) ^ (-(x & 1));
  23451. y = (y >> 1) ^ (-(y & 1));
  23452. // Delta deocding
  23453. x += prevX;
  23454. y += prevY;
  23455. prevX = x;
  23456. prevY = y;
  23457. // Dequantize
  23458. result.push([x / encodeScale, y / encodeScale]);
  23459. }
  23460. return result;
  23461. }
  23462. /**
  23463. * @alias module:echarts/coord/geo/parseGeoJson
  23464. * @param {Object} geoJson
  23465. * @return {module:zrender/container/Group}
  23466. */
  23467. var parseGeoJson = function (geoJson) {
  23468. decode(geoJson);
  23469. return map(filter(geoJson.features, function (featureObj) {
  23470. // Output of mapshaper may have geometry null
  23471. return featureObj.geometry
  23472. && featureObj.properties
  23473. && featureObj.geometry.coordinates.length > 0;
  23474. }), function (featureObj) {
  23475. var properties = featureObj.properties;
  23476. var geo = featureObj.geometry;
  23477. var coordinates = geo.coordinates;
  23478. var geometries = [];
  23479. if (geo.type === 'Polygon') {
  23480. geometries.push({
  23481. type: 'polygon',
  23482. // According to the GeoJSON specification.
  23483. // First must be exterior, and the rest are all interior(holes).
  23484. exterior: coordinates[0],
  23485. interiors: coordinates.slice(1)
  23486. });
  23487. }
  23488. if (geo.type === 'MultiPolygon') {
  23489. each$1(coordinates, function (item) {
  23490. if (item[0]) {
  23491. geometries.push({
  23492. type: 'polygon',
  23493. exterior: item[0],
  23494. interiors: item.slice(1)
  23495. });
  23496. }
  23497. });
  23498. }
  23499. var region = new Region(
  23500. properties.name,
  23501. geometries,
  23502. properties.cp
  23503. );
  23504. region.properties = properties;
  23505. return region;
  23506. });
  23507. };
  23508. /**
  23509. * Do not mount those modules on 'src/echarts' for better tree shaking.
  23510. */
  23511. var ecUtil = {};
  23512. each$1([
  23513. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  23514. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  23515. 'extend', 'defaults', 'clone', 'merge'
  23516. ],
  23517. function (name) {
  23518. ecUtil[name] = zrUtil[name];
  23519. }
  23520. );
  23521. SeriesModel.extend({
  23522. type: 'series.line',
  23523. dependencies: ['grid', 'polar'],
  23524. getInitialData: function (option, ecModel) {
  23525. if (__DEV__) {
  23526. var coordSys = option.coordinateSystem;
  23527. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  23528. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  23529. }
  23530. }
  23531. return createListFromArray(option.data, this, ecModel);
  23532. },
  23533. defaultOption: {
  23534. zlevel: 0, // 一级层叠
  23535. z: 2, // 二级层叠
  23536. coordinateSystem: 'cartesian2d',
  23537. legendHoverLink: true,
  23538. hoverAnimation: true,
  23539. // stack: null
  23540. // xAxisIndex: 0,
  23541. // yAxisIndex: 0,
  23542. // polarIndex: 0,
  23543. // If clip the overflow value
  23544. clipOverflow: true,
  23545. // cursor: null,
  23546. label: {
  23547. normal: {
  23548. position: 'top'
  23549. }
  23550. },
  23551. // itemStyle: {
  23552. // normal: {},
  23553. // emphasis: {}
  23554. // },
  23555. lineStyle: {
  23556. normal: {
  23557. width: 2,
  23558. type: 'solid'
  23559. }
  23560. },
  23561. // areaStyle: {},
  23562. // false, 'start', 'end', 'middle'
  23563. step: false,
  23564. // Disabled if step is true
  23565. smooth: false,
  23566. smoothMonotone: null,
  23567. // 拐点图形类型
  23568. symbol: 'emptyCircle',
  23569. // 拐点图形大小
  23570. symbolSize: 4,
  23571. // 拐点图形旋转控制
  23572. symbolRotate: null,
  23573. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  23574. showSymbol: true,
  23575. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  23576. showAllSymbol: false,
  23577. // 是否连接断点
  23578. connectNulls: false,
  23579. // 数据过滤,'average', 'max', 'min', 'sum'
  23580. sampling: 'none',
  23581. animationEasing: 'linear',
  23582. // Disable progressive
  23583. progressive: 0,
  23584. hoverLayerThreshold: Infinity
  23585. }
  23586. });
  23587. /**
  23588. * @module echarts/chart/helper/Symbol
  23589. */
  23590. function findLabelValueDim(data) {
  23591. var valueDim;
  23592. var labelDims = otherDimToDataDim(data, 'label');
  23593. if (labelDims.length) {
  23594. valueDim = labelDims[0];
  23595. }
  23596. else {
  23597. // Get last value dim
  23598. var dimensions = data.dimensions.slice();
  23599. var dataType;
  23600. while (dimensions.length && (
  23601. valueDim = dimensions.pop(),
  23602. dataType = data.getDimensionInfo(valueDim).type,
  23603. dataType === 'ordinal' || dataType === 'time'
  23604. )) {} // jshint ignore:line
  23605. }
  23606. return valueDim;
  23607. }
  23608. /**
  23609. * @module echarts/chart/helper/Symbol
  23610. */
  23611. function getSymbolSize(data, idx) {
  23612. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  23613. return symbolSize instanceof Array
  23614. ? symbolSize.slice()
  23615. : [+symbolSize, +symbolSize];
  23616. }
  23617. function getScale(symbolSize) {
  23618. return [symbolSize[0] / 2, symbolSize[1] / 2];
  23619. }
  23620. /**
  23621. * @constructor
  23622. * @alias {module:echarts/chart/helper/Symbol}
  23623. * @param {module:echarts/data/List} data
  23624. * @param {number} idx
  23625. * @extends {module:zrender/graphic/Group}
  23626. */
  23627. function SymbolClz$1(data, idx, seriesScope) {
  23628. Group.call(this);
  23629. this.updateData(data, idx, seriesScope);
  23630. }
  23631. var symbolProto = SymbolClz$1.prototype;
  23632. function driftSymbol(dx, dy) {
  23633. this.parent.drift(dx, dy);
  23634. }
  23635. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  23636. // Remove paths created before
  23637. this.removeAll();
  23638. var color = data.getItemVisual(idx, 'color');
  23639. // var symbolPath = createSymbol(
  23640. // symbolType, -0.5, -0.5, 1, 1, color
  23641. // );
  23642. // If width/height are set too small (e.g., set to 1) on ios10
  23643. // and macOS Sierra, a circle stroke become a rect, no matter what
  23644. // the scale is set. So we set width/height as 2. See #4150.
  23645. var symbolPath = createSymbol(
  23646. symbolType, -1, -1, 2, 2, color
  23647. );
  23648. symbolPath.attr({
  23649. z2: 100,
  23650. culling: true,
  23651. scale: getScale(symbolSize)
  23652. });
  23653. // Rewrite drift method
  23654. symbolPath.drift = driftSymbol;
  23655. this._symbolType = symbolType;
  23656. this.add(symbolPath);
  23657. };
  23658. /**
  23659. * Stop animation
  23660. * @param {boolean} toLastFrame
  23661. */
  23662. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  23663. this.childAt(0).stopAnimation(toLastFrame);
  23664. };
  23665. /**
  23666. * FIXME:
  23667. * Caution: This method breaks the encapsulation of this module,
  23668. * but it indeed brings convenience. So do not use the method
  23669. * unless you detailedly know all the implements of `Symbol`,
  23670. * especially animation.
  23671. *
  23672. * Get symbol path element.
  23673. */
  23674. symbolProto.getSymbolPath = function () {
  23675. return this.childAt(0);
  23676. };
  23677. /**
  23678. * Get scale(aka, current symbol size).
  23679. * Including the change caused by animation
  23680. */
  23681. symbolProto.getScale = function () {
  23682. return this.childAt(0).scale;
  23683. };
  23684. /**
  23685. * Highlight symbol
  23686. */
  23687. symbolProto.highlight = function () {
  23688. this.childAt(0).trigger('emphasis');
  23689. };
  23690. /**
  23691. * Downplay symbol
  23692. */
  23693. symbolProto.downplay = function () {
  23694. this.childAt(0).trigger('normal');
  23695. };
  23696. /**
  23697. * @param {number} zlevel
  23698. * @param {number} z
  23699. */
  23700. symbolProto.setZ = function (zlevel, z) {
  23701. var symbolPath = this.childAt(0);
  23702. symbolPath.zlevel = zlevel;
  23703. symbolPath.z = z;
  23704. };
  23705. symbolProto.setDraggable = function (draggable) {
  23706. var symbolPath = this.childAt(0);
  23707. symbolPath.draggable = draggable;
  23708. symbolPath.cursor = draggable ? 'move' : 'pointer';
  23709. };
  23710. /**
  23711. * Update symbol properties
  23712. * @param {module:echarts/data/List} data
  23713. * @param {number} idx
  23714. * @param {Object} [seriesScope]
  23715. * @param {Object} [seriesScope.itemStyle]
  23716. * @param {Object} [seriesScope.hoverItemStyle]
  23717. * @param {Object} [seriesScope.symbolRotate]
  23718. * @param {Object} [seriesScope.symbolOffset]
  23719. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  23720. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  23721. * @param {boolean} [seriesScope.hoverAnimation]
  23722. * @param {Object} [seriesScope.cursorStyle]
  23723. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  23724. * @param {string} [seriesScope.symbolInnerColor]
  23725. * @param {Object} [seriesScope.fadeIn=false]
  23726. */
  23727. symbolProto.updateData = function (data, idx, seriesScope) {
  23728. this.silent = false;
  23729. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  23730. var seriesModel = data.hostModel;
  23731. var symbolSize = getSymbolSize(data, idx);
  23732. var isInit = symbolType !== this._symbolType;
  23733. if (isInit) {
  23734. this._createSymbol(symbolType, data, idx, symbolSize);
  23735. }
  23736. else {
  23737. var symbolPath = this.childAt(0);
  23738. symbolPath.silent = false;
  23739. updateProps(symbolPath, {
  23740. scale: getScale(symbolSize)
  23741. }, seriesModel, idx);
  23742. }
  23743. this._updateCommon(data, idx, symbolSize, seriesScope);
  23744. if (isInit) {
  23745. var symbolPath = this.childAt(0);
  23746. var fadeIn = seriesScope && seriesScope.fadeIn;
  23747. var target = {scale: symbolPath.scale.slice()};
  23748. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  23749. symbolPath.scale = [0, 0];
  23750. fadeIn && (symbolPath.style.opacity = 0);
  23751. initProps(symbolPath, target, seriesModel, idx);
  23752. }
  23753. this._seriesModel = seriesModel;
  23754. };
  23755. // Update common properties
  23756. var normalStyleAccessPath = ['itemStyle', 'normal'];
  23757. var emphasisStyleAccessPath = ['itemStyle', 'emphasis'];
  23758. var normalLabelAccessPath = ['label', 'normal'];
  23759. var emphasisLabelAccessPath = ['label', 'emphasis'];
  23760. /**
  23761. * @param {module:echarts/data/List} data
  23762. * @param {number} idx
  23763. * @param {Array.<number>} symbolSize
  23764. * @param {Object} [seriesScope]
  23765. */
  23766. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  23767. var symbolPath = this.childAt(0);
  23768. var seriesModel = data.hostModel;
  23769. var color = data.getItemVisual(idx, 'color');
  23770. // Reset style
  23771. if (symbolPath.type !== 'image') {
  23772. symbolPath.useStyle({
  23773. strokeNoScale: true
  23774. });
  23775. }
  23776. var itemStyle = seriesScope && seriesScope.itemStyle;
  23777. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  23778. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  23779. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  23780. var labelModel = seriesScope && seriesScope.labelModel;
  23781. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  23782. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  23783. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  23784. if (!seriesScope || data.hasItemOption) {
  23785. var itemModel = (seriesScope && seriesScope.itemModel)
  23786. ? seriesScope.itemModel : data.getItemModel(idx);
  23787. // Color must be excluded.
  23788. // Because symbol provide setColor individually to set fill and stroke
  23789. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  23790. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  23791. symbolRotate = itemModel.getShallow('symbolRotate');
  23792. symbolOffset = itemModel.getShallow('symbolOffset');
  23793. labelModel = itemModel.getModel(normalLabelAccessPath);
  23794. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  23795. hoverAnimation = itemModel.getShallow('hoverAnimation');
  23796. cursorStyle = itemModel.getShallow('cursor');
  23797. }
  23798. else {
  23799. hoverItemStyle = extend({}, hoverItemStyle);
  23800. }
  23801. var elStyle = symbolPath.style;
  23802. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  23803. if (symbolOffset) {
  23804. symbolPath.attr('position', [
  23805. parsePercent$1(symbolOffset[0], symbolSize[0]),
  23806. parsePercent$1(symbolOffset[1], symbolSize[1])
  23807. ]);
  23808. }
  23809. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  23810. // PENDING setColor before setStyle!!!
  23811. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  23812. symbolPath.setStyle(itemStyle);
  23813. var opacity = data.getItemVisual(idx, 'opacity');
  23814. if (opacity != null) {
  23815. elStyle.opacity = opacity;
  23816. }
  23817. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  23818. var valueDim = !useNameLabel && findLabelValueDim(data);
  23819. if (useNameLabel || valueDim != null) {
  23820. setLabelStyle(
  23821. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  23822. {
  23823. labelFetcher: seriesModel,
  23824. labelDataIndex: idx,
  23825. defaultText: useNameLabel ? data.getName(idx) : data.get(valueDim, idx),
  23826. isRectText: true,
  23827. autoColor: color
  23828. }
  23829. );
  23830. }
  23831. symbolPath.off('mouseover')
  23832. .off('mouseout')
  23833. .off('emphasis')
  23834. .off('normal');
  23835. symbolPath.hoverStyle = hoverItemStyle;
  23836. // FIXME
  23837. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  23838. setHoverStyle(symbolPath);
  23839. var scale = getScale(symbolSize);
  23840. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  23841. var onEmphasis = function() {
  23842. var ratio = scale[1] / scale[0];
  23843. this.animateTo({
  23844. scale: [
  23845. Math.max(scale[0] * 1.1, scale[0] + 3),
  23846. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  23847. ]
  23848. }, 400, 'elasticOut');
  23849. };
  23850. var onNormal = function() {
  23851. this.animateTo({
  23852. scale: scale
  23853. }, 400, 'elasticOut');
  23854. };
  23855. symbolPath.on('mouseover', onEmphasis)
  23856. .on('mouseout', onNormal)
  23857. .on('emphasis', onEmphasis)
  23858. .on('normal', onNormal);
  23859. }
  23860. };
  23861. /**
  23862. * @param {Function} cb
  23863. * @param {Object} [opt]
  23864. * @param {Object} [opt.keepLabel=true]
  23865. */
  23866. symbolProto.fadeOut = function (cb, opt) {
  23867. var symbolPath = this.childAt(0);
  23868. // Avoid mistaken hover when fading out
  23869. this.silent = symbolPath.silent = true;
  23870. // Not show text when animating
  23871. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  23872. updateProps(
  23873. symbolPath,
  23874. {
  23875. style: {opacity: 0},
  23876. scale: [0, 0]
  23877. },
  23878. this._seriesModel,
  23879. this.dataIndex,
  23880. cb
  23881. );
  23882. };
  23883. inherits(SymbolClz$1, Group);
  23884. /**
  23885. * @module echarts/chart/helper/SymbolDraw
  23886. */
  23887. /**
  23888. * @constructor
  23889. * @alias module:echarts/chart/helper/SymbolDraw
  23890. * @param {module:zrender/graphic/Group} [symbolCtor]
  23891. */
  23892. function SymbolDraw(symbolCtor) {
  23893. this.group = new Group();
  23894. this._symbolCtor = symbolCtor || SymbolClz$1;
  23895. }
  23896. var symbolDrawProto = SymbolDraw.prototype;
  23897. function symbolNeedsDraw(data, idx, isIgnore) {
  23898. var point = data.getItemLayout(idx);
  23899. // Is an object
  23900. // if (point && point.hasOwnProperty('point')) {
  23901. // point = point.point;
  23902. // }
  23903. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(isIgnore && isIgnore(idx))
  23904. && data.getItemVisual(idx, 'symbol') !== 'none';
  23905. }
  23906. /**
  23907. * Update symbols draw by new data
  23908. * @param {module:echarts/data/List} data
  23909. * @param {Array.<boolean>} [isIgnore]
  23910. */
  23911. symbolDrawProto.updateData = function (data, isIgnore) {
  23912. var group = this.group;
  23913. var seriesModel = data.hostModel;
  23914. var oldData = this._data;
  23915. var SymbolCtor = this._symbolCtor;
  23916. var seriesScope = {
  23917. itemStyle: seriesModel.getModel('itemStyle.normal').getItemStyle(['color']),
  23918. hoverItemStyle: seriesModel.getModel('itemStyle.emphasis').getItemStyle(),
  23919. symbolRotate: seriesModel.get('symbolRotate'),
  23920. symbolOffset: seriesModel.get('symbolOffset'),
  23921. hoverAnimation: seriesModel.get('hoverAnimation'),
  23922. labelModel: seriesModel.getModel('label.normal'),
  23923. hoverLabelModel: seriesModel.getModel('label.emphasis'),
  23924. cursorStyle: seriesModel.get('cursor')
  23925. };
  23926. data.diff(oldData)
  23927. .add(function (newIdx) {
  23928. var point = data.getItemLayout(newIdx);
  23929. if (symbolNeedsDraw(data, newIdx, isIgnore)) {
  23930. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  23931. symbolEl.attr('position', point);
  23932. data.setItemGraphicEl(newIdx, symbolEl);
  23933. group.add(symbolEl);
  23934. }
  23935. })
  23936. .update(function (newIdx, oldIdx) {
  23937. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  23938. var point = data.getItemLayout(newIdx);
  23939. if (!symbolNeedsDraw(data, newIdx, isIgnore)) {
  23940. group.remove(symbolEl);
  23941. return;
  23942. }
  23943. if (!symbolEl) {
  23944. symbolEl = new SymbolCtor(data, newIdx);
  23945. symbolEl.attr('position', point);
  23946. }
  23947. else {
  23948. symbolEl.updateData(data, newIdx, seriesScope);
  23949. updateProps(symbolEl, {
  23950. position: point
  23951. }, seriesModel);
  23952. }
  23953. // Add back
  23954. group.add(symbolEl);
  23955. data.setItemGraphicEl(newIdx, symbolEl);
  23956. })
  23957. .remove(function (oldIdx) {
  23958. var el = oldData.getItemGraphicEl(oldIdx);
  23959. el && el.fadeOut(function () {
  23960. group.remove(el);
  23961. });
  23962. })
  23963. .execute();
  23964. this._data = data;
  23965. };
  23966. symbolDrawProto.updateLayout = function () {
  23967. var data = this._data;
  23968. if (data) {
  23969. // Not use animation
  23970. data.eachItemGraphicEl(function (el, idx) {
  23971. var point = data.getItemLayout(idx);
  23972. el.attr('position', point);
  23973. });
  23974. }
  23975. };
  23976. symbolDrawProto.remove = function (enableAnimation) {
  23977. var group = this.group;
  23978. var data = this._data;
  23979. if (data) {
  23980. if (enableAnimation) {
  23981. data.eachItemGraphicEl(function (el) {
  23982. el.fadeOut(function () {
  23983. group.remove(el);
  23984. });
  23985. });
  23986. }
  23987. else {
  23988. group.removeAll();
  23989. }
  23990. }
  23991. };
  23992. // var arrayDiff = require('zrender/src/core/arrayDiff');
  23993. // 'zrender/src/core/arrayDiff' has been used before, but it did
  23994. // not do well in performance when roam with fixed dataZoom window.
  23995. function sign$1(val) {
  23996. return val >= 0 ? 1 : -1;
  23997. }
  23998. function getStackedOnPoint(coordSys, data, idx) {
  23999. var baseAxis = coordSys.getBaseAxis();
  24000. var valueAxis = coordSys.getOtherAxis(baseAxis);
  24001. var valueStart = baseAxis.onZero
  24002. ? 0 : valueAxis.scale.getExtent()[0];
  24003. var valueDim = valueAxis.dim;
  24004. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  24005. var stackedOnSameSign;
  24006. var stackedOn = data.stackedOn;
  24007. var val = data.get(valueDim, idx);
  24008. // Find first stacked value with same sign
  24009. while (stackedOn &&
  24010. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  24011. ) {
  24012. stackedOnSameSign = stackedOn;
  24013. break;
  24014. }
  24015. var stackedData = [];
  24016. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  24017. stackedData[1 - baseDataOffset] = stackedOnSameSign
  24018. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  24019. return coordSys.dataToPoint(stackedData);
  24020. }
  24021. // function convertToIntId(newIdList, oldIdList) {
  24022. // // Generate int id instead of string id.
  24023. // // Compare string maybe slow in score function of arrDiff
  24024. // // Assume id in idList are all unique
  24025. // var idIndicesMap = {};
  24026. // var idx = 0;
  24027. // for (var i = 0; i < newIdList.length; i++) {
  24028. // idIndicesMap[newIdList[i]] = idx;
  24029. // newIdList[i] = idx++;
  24030. // }
  24031. // for (var i = 0; i < oldIdList.length; i++) {
  24032. // var oldId = oldIdList[i];
  24033. // // Same with newIdList
  24034. // if (idIndicesMap[oldId]) {
  24035. // oldIdList[i] = idIndicesMap[oldId];
  24036. // }
  24037. // else {
  24038. // oldIdList[i] = idx++;
  24039. // }
  24040. // }
  24041. // }
  24042. function diffData(oldData, newData) {
  24043. var diffResult = [];
  24044. newData.diff(oldData)
  24045. .add(function (idx) {
  24046. diffResult.push({cmd: '+', idx: idx});
  24047. })
  24048. .update(function (newIdx, oldIdx) {
  24049. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  24050. })
  24051. .remove(function (idx) {
  24052. diffResult.push({cmd: '-', idx: idx});
  24053. })
  24054. .execute();
  24055. return diffResult;
  24056. }
  24057. var lineAnimationDiff = function (
  24058. oldData, newData,
  24059. oldStackedOnPoints, newStackedOnPoints,
  24060. oldCoordSys, newCoordSys
  24061. ) {
  24062. var diff = diffData(oldData, newData);
  24063. // var newIdList = newData.mapArray(newData.getId);
  24064. // var oldIdList = oldData.mapArray(oldData.getId);
  24065. // convertToIntId(newIdList, oldIdList);
  24066. // // FIXME One data ?
  24067. // diff = arrayDiff(oldIdList, newIdList);
  24068. var currPoints = [];
  24069. var nextPoints = [];
  24070. // Points for stacking base line
  24071. var currStackedPoints = [];
  24072. var nextStackedPoints = [];
  24073. var status = [];
  24074. var sortedIndices = [];
  24075. var rawIndices = [];
  24076. var dims = newCoordSys.dimensions;
  24077. for (var i = 0; i < diff.length; i++) {
  24078. var diffItem = diff[i];
  24079. var pointAdded = true;
  24080. // FIXME, animation is not so perfect when dataZoom window moves fast
  24081. // Which is in case remvoing or add more than one data in the tail or head
  24082. switch (diffItem.cmd) {
  24083. case '=':
  24084. var currentPt = oldData.getItemLayout(diffItem.idx);
  24085. var nextPt = newData.getItemLayout(diffItem.idx1);
  24086. // If previous data is NaN, use next point directly
  24087. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  24088. currentPt = nextPt.slice();
  24089. }
  24090. currPoints.push(currentPt);
  24091. nextPoints.push(nextPt);
  24092. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  24093. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  24094. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  24095. break;
  24096. case '+':
  24097. var idx = diffItem.idx;
  24098. currPoints.push(
  24099. oldCoordSys.dataToPoint([
  24100. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  24101. ])
  24102. );
  24103. nextPoints.push(newData.getItemLayout(idx).slice());
  24104. currStackedPoints.push(
  24105. getStackedOnPoint(oldCoordSys, newData, idx)
  24106. );
  24107. nextStackedPoints.push(newStackedOnPoints[idx]);
  24108. rawIndices.push(newData.getRawIndex(idx));
  24109. break;
  24110. case '-':
  24111. var idx = diffItem.idx;
  24112. var rawIndex = oldData.getRawIndex(idx);
  24113. // Data is replaced. In the case of dynamic data queue
  24114. // FIXME FIXME FIXME
  24115. if (rawIndex !== idx) {
  24116. currPoints.push(oldData.getItemLayout(idx));
  24117. nextPoints.push(newCoordSys.dataToPoint([
  24118. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  24119. ]));
  24120. currStackedPoints.push(oldStackedOnPoints[idx]);
  24121. nextStackedPoints.push(
  24122. getStackedOnPoint(
  24123. newCoordSys, oldData, idx
  24124. )
  24125. );
  24126. rawIndices.push(rawIndex);
  24127. }
  24128. else {
  24129. pointAdded = false;
  24130. }
  24131. }
  24132. // Original indices
  24133. if (pointAdded) {
  24134. status.push(diffItem);
  24135. sortedIndices.push(sortedIndices.length);
  24136. }
  24137. }
  24138. // Diff result may be crossed if all items are changed
  24139. // Sort by data index
  24140. sortedIndices.sort(function (a, b) {
  24141. return rawIndices[a] - rawIndices[b];
  24142. });
  24143. var sortedCurrPoints = [];
  24144. var sortedNextPoints = [];
  24145. var sortedCurrStackedPoints = [];
  24146. var sortedNextStackedPoints = [];
  24147. var sortedStatus = [];
  24148. for (var i = 0; i < sortedIndices.length; i++) {
  24149. var idx = sortedIndices[i];
  24150. sortedCurrPoints[i] = currPoints[idx];
  24151. sortedNextPoints[i] = nextPoints[idx];
  24152. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  24153. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  24154. sortedStatus[i] = status[idx];
  24155. }
  24156. return {
  24157. current: sortedCurrPoints,
  24158. next: sortedNextPoints,
  24159. stackedOnCurrent: sortedCurrStackedPoints,
  24160. stackedOnNext: sortedNextStackedPoints,
  24161. status: sortedStatus
  24162. };
  24163. };
  24164. // Poly path support NaN point
  24165. var vec2Min = min;
  24166. var vec2Max = max;
  24167. var scaleAndAdd$1 = scaleAndAdd;
  24168. var v2Copy = copy;
  24169. // Temporary variable
  24170. var v = [];
  24171. var cp0 = [];
  24172. var cp1 = [];
  24173. function isPointNull(p) {
  24174. return isNaN(p[0]) || isNaN(p[1]);
  24175. }
  24176. function drawSegment(
  24177. ctx, points, start, segLen, allLen,
  24178. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  24179. ) {
  24180. var prevIdx = 0;
  24181. var idx = start;
  24182. for (var k = 0; k < segLen; k++) {
  24183. var p = points[idx];
  24184. if (idx >= allLen || idx < 0) {
  24185. break;
  24186. }
  24187. if (isPointNull(p)) {
  24188. if (connectNulls) {
  24189. idx += dir;
  24190. continue;
  24191. }
  24192. break;
  24193. }
  24194. if (idx === start) {
  24195. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  24196. v2Copy(cp0, p);
  24197. }
  24198. else {
  24199. if (smooth > 0) {
  24200. var nextIdx = idx + dir;
  24201. var nextP = points[nextIdx];
  24202. if (connectNulls) {
  24203. // Find next point not null
  24204. while (nextP && isPointNull(points[nextIdx])) {
  24205. nextIdx += dir;
  24206. nextP = points[nextIdx];
  24207. }
  24208. }
  24209. var ratioNextSeg = 0.5;
  24210. var prevP = points[prevIdx];
  24211. var nextP = points[nextIdx];
  24212. // Last point
  24213. if (!nextP || isPointNull(nextP)) {
  24214. v2Copy(cp1, p);
  24215. }
  24216. else {
  24217. // If next data is null in not connect case
  24218. if (isPointNull(nextP) && !connectNulls) {
  24219. nextP = p;
  24220. }
  24221. sub(v, nextP, prevP);
  24222. var lenPrevSeg;
  24223. var lenNextSeg;
  24224. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  24225. var dim = smoothMonotone === 'x' ? 0 : 1;
  24226. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  24227. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  24228. }
  24229. else {
  24230. lenPrevSeg = dist(p, prevP);
  24231. lenNextSeg = dist(p, nextP);
  24232. }
  24233. // Use ratio of seg length
  24234. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  24235. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  24236. }
  24237. // Smooth constraint
  24238. vec2Min(cp0, cp0, smoothMax);
  24239. vec2Max(cp0, cp0, smoothMin);
  24240. vec2Min(cp1, cp1, smoothMax);
  24241. vec2Max(cp1, cp1, smoothMin);
  24242. ctx.bezierCurveTo(
  24243. cp0[0], cp0[1],
  24244. cp1[0], cp1[1],
  24245. p[0], p[1]
  24246. );
  24247. // cp0 of next segment
  24248. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  24249. }
  24250. else {
  24251. ctx.lineTo(p[0], p[1]);
  24252. }
  24253. }
  24254. prevIdx = idx;
  24255. idx += dir;
  24256. }
  24257. return k;
  24258. }
  24259. function getBoundingBox(points, smoothConstraint) {
  24260. var ptMin = [Infinity, Infinity];
  24261. var ptMax = [-Infinity, -Infinity];
  24262. if (smoothConstraint) {
  24263. for (var i = 0; i < points.length; i++) {
  24264. var pt = points[i];
  24265. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  24266. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  24267. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  24268. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  24269. }
  24270. }
  24271. return {
  24272. min: smoothConstraint ? ptMin : ptMax,
  24273. max: smoothConstraint ? ptMax : ptMin
  24274. };
  24275. }
  24276. var Polyline$1 = Path.extend({
  24277. type: 'ec-polyline',
  24278. shape: {
  24279. points: [],
  24280. smooth: 0,
  24281. smoothConstraint: true,
  24282. smoothMonotone: null,
  24283. connectNulls: false
  24284. },
  24285. style: {
  24286. fill: null,
  24287. stroke: '#000'
  24288. },
  24289. brush: fixClipWithShadow(Path.prototype.brush),
  24290. buildPath: function (ctx, shape) {
  24291. var points = shape.points;
  24292. var i = 0;
  24293. var len$$1 = points.length;
  24294. var result = getBoundingBox(points, shape.smoothConstraint);
  24295. if (shape.connectNulls) {
  24296. // Must remove first and last null values avoid draw error in polygon
  24297. for (; len$$1 > 0; len$$1--) {
  24298. if (!isPointNull(points[len$$1 - 1])) {
  24299. break;
  24300. }
  24301. }
  24302. for (; i < len$$1; i++) {
  24303. if (!isPointNull(points[i])) {
  24304. break;
  24305. }
  24306. }
  24307. }
  24308. while (i < len$$1) {
  24309. i += drawSegment(
  24310. ctx, points, i, len$$1, len$$1,
  24311. 1, result.min, result.max, shape.smooth,
  24312. shape.smoothMonotone, shape.connectNulls
  24313. ) + 1;
  24314. }
  24315. }
  24316. });
  24317. var Polygon$1 = Path.extend({
  24318. type: 'ec-polygon',
  24319. shape: {
  24320. points: [],
  24321. // Offset between stacked base points and points
  24322. stackedOnPoints: [],
  24323. smooth: 0,
  24324. stackedOnSmooth: 0,
  24325. smoothConstraint: true,
  24326. smoothMonotone: null,
  24327. connectNulls: false
  24328. },
  24329. brush: fixClipWithShadow(Path.prototype.brush),
  24330. buildPath: function (ctx, shape) {
  24331. var points = shape.points;
  24332. var stackedOnPoints = shape.stackedOnPoints;
  24333. var i = 0;
  24334. var len$$1 = points.length;
  24335. var smoothMonotone = shape.smoothMonotone;
  24336. var bbox = getBoundingBox(points, shape.smoothConstraint);
  24337. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  24338. if (shape.connectNulls) {
  24339. // Must remove first and last null values avoid draw error in polygon
  24340. for (; len$$1 > 0; len$$1--) {
  24341. if (!isPointNull(points[len$$1 - 1])) {
  24342. break;
  24343. }
  24344. }
  24345. for (; i < len$$1; i++) {
  24346. if (!isPointNull(points[i])) {
  24347. break;
  24348. }
  24349. }
  24350. }
  24351. while (i < len$$1) {
  24352. var k = drawSegment(
  24353. ctx, points, i, len$$1, len$$1,
  24354. 1, bbox.min, bbox.max, shape.smooth,
  24355. smoothMonotone, shape.connectNulls
  24356. );
  24357. drawSegment(
  24358. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  24359. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  24360. smoothMonotone, shape.connectNulls
  24361. );
  24362. i += k + 1;
  24363. ctx.closePath();
  24364. }
  24365. }
  24366. });
  24367. // FIXME step not support polar
  24368. function isPointsSame(points1, points2) {
  24369. if (points1.length !== points2.length) {
  24370. return;
  24371. }
  24372. for (var i = 0; i < points1.length; i++) {
  24373. var p1 = points1[i];
  24374. var p2 = points2[i];
  24375. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  24376. return;
  24377. }
  24378. }
  24379. return true;
  24380. }
  24381. function getSmooth(smooth) {
  24382. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  24383. }
  24384. function getAxisExtentWithGap(axis) {
  24385. var extent = axis.getGlobalExtent();
  24386. if (axis.onBand) {
  24387. // Remove extra 1px to avoid line miter in clipped edge
  24388. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  24389. var dir = extent[1] > extent[0] ? 1 : -1;
  24390. extent[0] += dir * halfBandWidth;
  24391. extent[1] -= dir * halfBandWidth;
  24392. }
  24393. return extent;
  24394. }
  24395. function sign(val) {
  24396. return val >= 0 ? 1 : -1;
  24397. }
  24398. /**
  24399. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  24400. * @param {module:echarts/data/List} data
  24401. * @param {Array.<Array.<number>>} points
  24402. * @private
  24403. */
  24404. function getStackedOnPoints(coordSys, data) {
  24405. var baseAxis = coordSys.getBaseAxis();
  24406. var valueAxis = coordSys.getOtherAxis(baseAxis);
  24407. var valueStart = 0;
  24408. if (!baseAxis.onZero) {
  24409. var extent = valueAxis.scale.getExtent();
  24410. if (extent[0] > 0) {
  24411. // Both positive
  24412. valueStart = extent[0];
  24413. }
  24414. else if (extent[1] < 0) {
  24415. // Both negative
  24416. valueStart = extent[1];
  24417. }
  24418. // If is one positive, and one negative, onZero shall be true
  24419. }
  24420. var valueDim = valueAxis.dim;
  24421. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  24422. return data.mapArray([valueDim], function (val, idx) {
  24423. var stackedOnSameSign;
  24424. var stackedOn = data.stackedOn;
  24425. // Find first stacked value with same sign
  24426. while (stackedOn &&
  24427. sign(stackedOn.get(valueDim, idx)) === sign(val)
  24428. ) {
  24429. stackedOnSameSign = stackedOn;
  24430. break;
  24431. }
  24432. var stackedData = [];
  24433. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  24434. stackedData[1 - baseDataOffset] = stackedOnSameSign
  24435. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  24436. return coordSys.dataToPoint(stackedData);
  24437. }, true);
  24438. }
  24439. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  24440. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  24441. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  24442. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  24443. var x = Math.min(xExtent[0], xExtent[1]);
  24444. var y = Math.min(yExtent[0], yExtent[1]);
  24445. var width = Math.max(xExtent[0], xExtent[1]) - x;
  24446. var height = Math.max(yExtent[0], yExtent[1]) - y;
  24447. var lineWidth = seriesModel.get('lineStyle.normal.width') || 2;
  24448. // Expand clip shape to avoid clipping when line value exceeds axis
  24449. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  24450. if (isHorizontal) {
  24451. y -= expandSize;
  24452. height += expandSize * 2;
  24453. }
  24454. else {
  24455. x -= expandSize;
  24456. width += expandSize * 2;
  24457. }
  24458. var clipPath = new Rect({
  24459. shape: {
  24460. x: x,
  24461. y: y,
  24462. width: width,
  24463. height: height
  24464. }
  24465. });
  24466. if (hasAnimation) {
  24467. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  24468. initProps(clipPath, {
  24469. shape: {
  24470. width: width,
  24471. height: height
  24472. }
  24473. }, seriesModel);
  24474. }
  24475. return clipPath;
  24476. }
  24477. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  24478. var angleAxis = polar.getAngleAxis();
  24479. var radiusAxis = polar.getRadiusAxis();
  24480. var radiusExtent = radiusAxis.getExtent();
  24481. var angleExtent = angleAxis.getExtent();
  24482. var RADIAN = Math.PI / 180;
  24483. var clipPath = new Sector({
  24484. shape: {
  24485. cx: polar.cx,
  24486. cy: polar.cy,
  24487. r0: radiusExtent[0],
  24488. r: radiusExtent[1],
  24489. startAngle: -angleExtent[0] * RADIAN,
  24490. endAngle: -angleExtent[1] * RADIAN,
  24491. clockwise: angleAxis.inverse
  24492. }
  24493. });
  24494. if (hasAnimation) {
  24495. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  24496. initProps(clipPath, {
  24497. shape: {
  24498. endAngle: -angleExtent[1] * RADIAN
  24499. }
  24500. }, seriesModel);
  24501. }
  24502. return clipPath;
  24503. }
  24504. function createClipShape(coordSys, hasAnimation, seriesModel) {
  24505. return coordSys.type === 'polar'
  24506. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  24507. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  24508. }
  24509. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  24510. var baseAxis = coordSys.getBaseAxis();
  24511. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  24512. var stepPoints = [];
  24513. for (var i = 0; i < points.length - 1; i++) {
  24514. var nextPt = points[i + 1];
  24515. var pt = points[i];
  24516. stepPoints.push(pt);
  24517. var stepPt = [];
  24518. switch (stepTurnAt) {
  24519. case 'end':
  24520. stepPt[baseIndex] = nextPt[baseIndex];
  24521. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  24522. // default is start
  24523. stepPoints.push(stepPt);
  24524. break;
  24525. case 'middle':
  24526. // default is start
  24527. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  24528. var stepPt2 = [];
  24529. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  24530. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  24531. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  24532. stepPoints.push(stepPt);
  24533. stepPoints.push(stepPt2);
  24534. break;
  24535. default:
  24536. stepPt[baseIndex] = pt[baseIndex];
  24537. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  24538. // default is start
  24539. stepPoints.push(stepPt);
  24540. }
  24541. }
  24542. // Last points
  24543. points[i] && stepPoints.push(points[i]);
  24544. return stepPoints;
  24545. }
  24546. function getVisualGradient(data, coordSys) {
  24547. var visualMetaList = data.getVisual('visualMeta');
  24548. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  24549. // When data.count() is 0, gradient range can not be calculated.
  24550. return;
  24551. }
  24552. var visualMeta;
  24553. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  24554. // Can only be x or y
  24555. if (visualMetaList[i].dimension < 2) {
  24556. visualMeta = visualMetaList[i];
  24557. break;
  24558. }
  24559. }
  24560. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  24561. if (__DEV__) {
  24562. console.warn('Visual map on line style only support x or y dimension.');
  24563. }
  24564. return;
  24565. }
  24566. // If the area to be rendered is bigger than area defined by LinearGradient,
  24567. // the canvas spec prescribes that the color of the first stop and the last
  24568. // stop should be used. But if two stops are added at offset 0, in effect
  24569. // browsers use the color of the second stop to render area outside
  24570. // LinearGradient. So we can only infinitesimally extend area defined in
  24571. // LinearGradient to render `outerColors`.
  24572. var dimension = visualMeta.dimension;
  24573. var dimName = data.dimensions[dimension];
  24574. var axis = coordSys.getAxis(dimName);
  24575. // dataToCoor mapping may not be linear, but must be monotonic.
  24576. var colorStops = map(visualMeta.stops, function (stop) {
  24577. return {
  24578. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  24579. color: stop.color
  24580. };
  24581. });
  24582. var stopLen = colorStops.length;
  24583. var outerColors = visualMeta.outerColors.slice();
  24584. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  24585. colorStops.reverse();
  24586. outerColors.reverse();
  24587. }
  24588. var tinyExtent = 10; // Arbitrary value: 10px
  24589. var minCoord = colorStops[0].coord - tinyExtent;
  24590. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  24591. var coordSpan = maxCoord - minCoord;
  24592. if (coordSpan < 1e-3) {
  24593. return 'transparent';
  24594. }
  24595. each$1(colorStops, function (stop) {
  24596. stop.offset = (stop.coord - minCoord) / coordSpan;
  24597. });
  24598. colorStops.push({
  24599. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  24600. color: outerColors[1] || 'transparent'
  24601. });
  24602. colorStops.unshift({ // notice colorStops.length have been changed.
  24603. offset: stopLen ? colorStops[0].offset : 0.5,
  24604. color: outerColors[0] || 'transparent'
  24605. });
  24606. // zrUtil.each(colorStops, function (colorStop) {
  24607. // // Make sure each offset has rounded px to avoid not sharp edge
  24608. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  24609. // });
  24610. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  24611. gradient[dimName] = minCoord;
  24612. gradient[dimName + '2'] = maxCoord;
  24613. return gradient;
  24614. }
  24615. Chart.extend({
  24616. type: 'line',
  24617. init: function () {
  24618. var lineGroup = new Group();
  24619. var symbolDraw = new SymbolDraw();
  24620. this.group.add(symbolDraw.group);
  24621. this._symbolDraw = symbolDraw;
  24622. this._lineGroup = lineGroup;
  24623. },
  24624. render: function (seriesModel, ecModel, api) {
  24625. var coordSys = seriesModel.coordinateSystem;
  24626. var group = this.group;
  24627. var data = seriesModel.getData();
  24628. var lineStyleModel = seriesModel.getModel('lineStyle.normal');
  24629. var areaStyleModel = seriesModel.getModel('areaStyle.normal');
  24630. var points = data.mapArray(data.getItemLayout, true);
  24631. var isCoordSysPolar = coordSys.type === 'polar';
  24632. var prevCoordSys = this._coordSys;
  24633. var symbolDraw = this._symbolDraw;
  24634. var polyline = this._polyline;
  24635. var polygon = this._polygon;
  24636. var lineGroup = this._lineGroup;
  24637. var hasAnimation = seriesModel.get('animation');
  24638. var isAreaChart = !areaStyleModel.isEmpty();
  24639. var stackedOnPoints = getStackedOnPoints(coordSys, data);
  24640. var showSymbol = seriesModel.get('showSymbol');
  24641. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  24642. && this._getSymbolIgnoreFunc(data, coordSys);
  24643. // Remove temporary symbols
  24644. var oldData = this._data;
  24645. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  24646. if (el.__temp) {
  24647. group.remove(el);
  24648. oldData.setItemGraphicEl(idx, null);
  24649. }
  24650. });
  24651. // Remove previous created symbols if showSymbol changed to false
  24652. if (!showSymbol) {
  24653. symbolDraw.remove();
  24654. }
  24655. group.add(lineGroup);
  24656. // FIXME step not support polar
  24657. var step = !isCoordSysPolar && seriesModel.get('step');
  24658. // Initialization animation or coordinate system changed
  24659. if (
  24660. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  24661. ) {
  24662. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  24663. if (step) {
  24664. // TODO If stacked series is not step
  24665. points = turnPointsIntoStep(points, coordSys, step);
  24666. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  24667. }
  24668. polyline = this._newPolyline(points, coordSys, hasAnimation);
  24669. if (isAreaChart) {
  24670. polygon = this._newPolygon(
  24671. points, stackedOnPoints,
  24672. coordSys, hasAnimation
  24673. );
  24674. }
  24675. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  24676. }
  24677. else {
  24678. if (isAreaChart && !polygon) {
  24679. // If areaStyle is added
  24680. polygon = this._newPolygon(
  24681. points, stackedOnPoints,
  24682. coordSys, hasAnimation
  24683. );
  24684. }
  24685. else if (polygon && !isAreaChart) {
  24686. // If areaStyle is removed
  24687. lineGroup.remove(polygon);
  24688. polygon = this._polygon = null;
  24689. }
  24690. // Update clipPath
  24691. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  24692. // Always update, or it is wrong in the case turning on legend
  24693. // because points are not changed
  24694. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  24695. // Stop symbol animation and sync with line points
  24696. // FIXME performance?
  24697. data.eachItemGraphicEl(function (el) {
  24698. el.stopAnimation(true);
  24699. });
  24700. // In the case data zoom triggerred refreshing frequently
  24701. // Data may not change if line has a category axis. So it should animate nothing
  24702. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  24703. || !isPointsSame(this._points, points)
  24704. ) {
  24705. if (hasAnimation) {
  24706. this._updateAnimation(
  24707. data, stackedOnPoints, coordSys, api, step
  24708. );
  24709. }
  24710. else {
  24711. // Not do it in update with animation
  24712. if (step) {
  24713. // TODO If stacked series is not step
  24714. points = turnPointsIntoStep(points, coordSys, step);
  24715. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  24716. }
  24717. polyline.setShape({
  24718. points: points
  24719. });
  24720. polygon && polygon.setShape({
  24721. points: points,
  24722. stackedOnPoints: stackedOnPoints
  24723. });
  24724. }
  24725. }
  24726. }
  24727. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  24728. polyline.useStyle(defaults(
  24729. // Use color in lineStyle first
  24730. lineStyleModel.getLineStyle(),
  24731. {
  24732. fill: 'none',
  24733. stroke: visualColor,
  24734. lineJoin: 'bevel'
  24735. }
  24736. ));
  24737. var smooth = seriesModel.get('smooth');
  24738. smooth = getSmooth(seriesModel.get('smooth'));
  24739. polyline.setShape({
  24740. smooth: smooth,
  24741. smoothMonotone: seriesModel.get('smoothMonotone'),
  24742. connectNulls: seriesModel.get('connectNulls')
  24743. });
  24744. if (polygon) {
  24745. var stackedOn = data.stackedOn;
  24746. var stackedOnSmooth = 0;
  24747. polygon.useStyle(defaults(
  24748. areaStyleModel.getAreaStyle(),
  24749. {
  24750. fill: visualColor,
  24751. opacity: 0.7,
  24752. lineJoin: 'bevel'
  24753. }
  24754. ));
  24755. if (stackedOn) {
  24756. var stackedOnSeries = stackedOn.hostModel;
  24757. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  24758. }
  24759. polygon.setShape({
  24760. smooth: smooth,
  24761. stackedOnSmooth: stackedOnSmooth,
  24762. smoothMonotone: seriesModel.get('smoothMonotone'),
  24763. connectNulls: seriesModel.get('connectNulls')
  24764. });
  24765. }
  24766. this._data = data;
  24767. // Save the coordinate system for transition animation when data changed
  24768. this._coordSys = coordSys;
  24769. this._stackedOnPoints = stackedOnPoints;
  24770. this._points = points;
  24771. this._step = step;
  24772. },
  24773. dispose: function () {},
  24774. highlight: function (seriesModel, ecModel, api, payload) {
  24775. var data = seriesModel.getData();
  24776. var dataIndex = queryDataIndex(data, payload);
  24777. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  24778. var symbol = data.getItemGraphicEl(dataIndex);
  24779. if (!symbol) {
  24780. // Create a temporary symbol if it is not exists
  24781. var pt = data.getItemLayout(dataIndex);
  24782. if (!pt) {
  24783. // Null data
  24784. return;
  24785. }
  24786. symbol = new SymbolClz$1(data, dataIndex);
  24787. symbol.position = pt;
  24788. symbol.setZ(
  24789. seriesModel.get('zlevel'),
  24790. seriesModel.get('z')
  24791. );
  24792. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  24793. symbol.__temp = true;
  24794. data.setItemGraphicEl(dataIndex, symbol);
  24795. // Stop scale animation
  24796. symbol.stopSymbolAnimation(true);
  24797. this.group.add(symbol);
  24798. }
  24799. symbol.highlight();
  24800. }
  24801. else {
  24802. // Highlight whole series
  24803. Chart.prototype.highlight.call(
  24804. this, seriesModel, ecModel, api, payload
  24805. );
  24806. }
  24807. },
  24808. downplay: function (seriesModel, ecModel, api, payload) {
  24809. var data = seriesModel.getData();
  24810. var dataIndex = queryDataIndex(data, payload);
  24811. if (dataIndex != null && dataIndex >= 0) {
  24812. var symbol = data.getItemGraphicEl(dataIndex);
  24813. if (symbol) {
  24814. if (symbol.__temp) {
  24815. data.setItemGraphicEl(dataIndex, null);
  24816. this.group.remove(symbol);
  24817. }
  24818. else {
  24819. symbol.downplay();
  24820. }
  24821. }
  24822. }
  24823. else {
  24824. // FIXME
  24825. // can not downplay completely.
  24826. // Downplay whole series
  24827. Chart.prototype.downplay.call(
  24828. this, seriesModel, ecModel, api, payload
  24829. );
  24830. }
  24831. },
  24832. /**
  24833. * @param {module:zrender/container/Group} group
  24834. * @param {Array.<Array.<number>>} points
  24835. * @private
  24836. */
  24837. _newPolyline: function (points) {
  24838. var polyline = this._polyline;
  24839. // Remove previous created polyline
  24840. if (polyline) {
  24841. this._lineGroup.remove(polyline);
  24842. }
  24843. polyline = new Polyline$1({
  24844. shape: {
  24845. points: points
  24846. },
  24847. silent: true,
  24848. z2: 10
  24849. });
  24850. this._lineGroup.add(polyline);
  24851. this._polyline = polyline;
  24852. return polyline;
  24853. },
  24854. /**
  24855. * @param {module:zrender/container/Group} group
  24856. * @param {Array.<Array.<number>>} stackedOnPoints
  24857. * @param {Array.<Array.<number>>} points
  24858. * @private
  24859. */
  24860. _newPolygon: function (points, stackedOnPoints) {
  24861. var polygon = this._polygon;
  24862. // Remove previous created polygon
  24863. if (polygon) {
  24864. this._lineGroup.remove(polygon);
  24865. }
  24866. polygon = new Polygon$1({
  24867. shape: {
  24868. points: points,
  24869. stackedOnPoints: stackedOnPoints
  24870. },
  24871. silent: true
  24872. });
  24873. this._lineGroup.add(polygon);
  24874. this._polygon = polygon;
  24875. return polygon;
  24876. },
  24877. /**
  24878. * @private
  24879. */
  24880. _getSymbolIgnoreFunc: function (data, coordSys) {
  24881. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  24882. // `getLabelInterval` is provided by echarts/component/axis
  24883. if (categoryAxis && categoryAxis.isLabelIgnored) {
  24884. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  24885. }
  24886. },
  24887. /**
  24888. * @private
  24889. */
  24890. // FIXME Two value axis
  24891. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  24892. var polyline = this._polyline;
  24893. var polygon = this._polygon;
  24894. var seriesModel = data.hostModel;
  24895. var diff = lineAnimationDiff(
  24896. this._data, data,
  24897. this._stackedOnPoints, stackedOnPoints,
  24898. this._coordSys, coordSys
  24899. );
  24900. var current = diff.current;
  24901. var stackedOnCurrent = diff.stackedOnCurrent;
  24902. var next = diff.next;
  24903. var stackedOnNext = diff.stackedOnNext;
  24904. if (step) {
  24905. // TODO If stacked series is not step
  24906. current = turnPointsIntoStep(diff.current, coordSys, step);
  24907. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  24908. next = turnPointsIntoStep(diff.next, coordSys, step);
  24909. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  24910. }
  24911. // `diff.current` is subset of `current` (which should be ensured by
  24912. // turnPointsIntoStep), so points in `__points` can be updated when
  24913. // points in `current` are update during animation.
  24914. polyline.shape.__points = diff.current;
  24915. polyline.shape.points = current;
  24916. updateProps(polyline, {
  24917. shape: {
  24918. points: next
  24919. }
  24920. }, seriesModel);
  24921. if (polygon) {
  24922. polygon.setShape({
  24923. points: current,
  24924. stackedOnPoints: stackedOnCurrent
  24925. });
  24926. updateProps(polygon, {
  24927. shape: {
  24928. points: next,
  24929. stackedOnPoints: stackedOnNext
  24930. }
  24931. }, seriesModel);
  24932. }
  24933. var updatedDataInfo = [];
  24934. var diffStatus = diff.status;
  24935. for (var i = 0; i < diffStatus.length; i++) {
  24936. var cmd = diffStatus[i].cmd;
  24937. if (cmd === '=') {
  24938. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  24939. if (el) {
  24940. updatedDataInfo.push({
  24941. el: el,
  24942. ptIdx: i // Index of points
  24943. });
  24944. }
  24945. }
  24946. }
  24947. if (polyline.animators && polyline.animators.length) {
  24948. polyline.animators[0].during(function () {
  24949. for (var i = 0; i < updatedDataInfo.length; i++) {
  24950. var el = updatedDataInfo[i].el;
  24951. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  24952. }
  24953. });
  24954. }
  24955. },
  24956. remove: function (ecModel) {
  24957. var group = this.group;
  24958. var oldData = this._data;
  24959. this._lineGroup.removeAll();
  24960. this._symbolDraw.remove(true);
  24961. // Remove temporary created elements when highlighting
  24962. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  24963. if (el.__temp) {
  24964. group.remove(el);
  24965. oldData.setItemGraphicEl(idx, null);
  24966. }
  24967. });
  24968. this._polyline =
  24969. this._polygon =
  24970. this._coordSys =
  24971. this._points =
  24972. this._stackedOnPoints =
  24973. this._data = null;
  24974. }
  24975. });
  24976. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol, ecModel, api) {
  24977. // Encoding visual for all series include which is filtered for legend drawing
  24978. ecModel.eachRawSeriesByType(seriesType, function (seriesModel) {
  24979. var data = seriesModel.getData();
  24980. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  24981. var symbolSize = seriesModel.get('symbolSize');
  24982. data.setVisual({
  24983. legendSymbol: legendSymbol || symbolType,
  24984. symbol: symbolType,
  24985. symbolSize: symbolSize
  24986. });
  24987. // Only visible series has each data be visual encoded
  24988. if (!ecModel.isSeriesFiltered(seriesModel)) {
  24989. if (typeof symbolSize === 'function') {
  24990. data.each(function (idx) {
  24991. var rawValue = seriesModel.getRawValue(idx);
  24992. // FIXME
  24993. var params = seriesModel.getDataParams(idx);
  24994. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  24995. });
  24996. }
  24997. data.each(function (idx) {
  24998. var itemModel = data.getItemModel(idx);
  24999. var itemSymbolType = itemModel.getShallow('symbol', true);
  25000. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  25001. // If has item symbol
  25002. if (itemSymbolType != null) {
  25003. data.setItemVisual(idx, 'symbol', itemSymbolType);
  25004. }
  25005. if (itemSymbolSize != null) {
  25006. // PENDING Transform symbolSize ?
  25007. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  25008. }
  25009. });
  25010. }
  25011. });
  25012. };
  25013. var layoutPoints = function (seriesType, ecModel) {
  25014. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25015. var data = seriesModel.getData();
  25016. var coordSys = seriesModel.coordinateSystem;
  25017. if (!coordSys) {
  25018. return;
  25019. }
  25020. var dims = [];
  25021. var coordDims = coordSys.dimensions;
  25022. for (var i = 0; i < coordDims.length; i++) {
  25023. dims.push(seriesModel.coordDimToDataDim(coordSys.dimensions[i])[0]);
  25024. }
  25025. if (dims.length === 1) {
  25026. data.each(dims[0], function (x, idx) {
  25027. // Also {Array.<number>}, not undefined to avoid if...else... statement
  25028. data.setItemLayout(idx, isNaN(x) ? [NaN, NaN] : coordSys.dataToPoint(x));
  25029. });
  25030. }
  25031. else if (dims.length === 2) {
  25032. data.each(dims, function (x, y, idx) {
  25033. // Also {Array.<number>}, not undefined to avoid if...else... statement
  25034. data.setItemLayout(
  25035. idx, (isNaN(x) || isNaN(y)) ? [NaN, NaN] : coordSys.dataToPoint([x, y])
  25036. );
  25037. }, true);
  25038. }
  25039. });
  25040. };
  25041. var samplers = {
  25042. average: function (frame) {
  25043. var sum = 0;
  25044. var count = 0;
  25045. for (var i = 0; i < frame.length; i++) {
  25046. if (!isNaN(frame[i])) {
  25047. sum += frame[i];
  25048. count++;
  25049. }
  25050. }
  25051. // Return NaN if count is 0
  25052. return count === 0 ? NaN : sum / count;
  25053. },
  25054. sum: function (frame) {
  25055. var sum = 0;
  25056. for (var i = 0; i < frame.length; i++) {
  25057. // Ignore NaN
  25058. sum += frame[i] || 0;
  25059. }
  25060. return sum;
  25061. },
  25062. max: function (frame) {
  25063. var max = -Infinity;
  25064. for (var i = 0; i < frame.length; i++) {
  25065. frame[i] > max && (max = frame[i]);
  25066. }
  25067. return max;
  25068. },
  25069. min: function (frame) {
  25070. var min = Infinity;
  25071. for (var i = 0; i < frame.length; i++) {
  25072. frame[i] < min && (min = frame[i]);
  25073. }
  25074. return min;
  25075. },
  25076. // TODO
  25077. // Median
  25078. nearest: function (frame) {
  25079. return frame[0];
  25080. }
  25081. };
  25082. var indexSampler = function (frame, value) {
  25083. return Math.round(frame.length / 2);
  25084. };
  25085. var dataSample = function (seriesType, ecModel, api) {
  25086. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25087. var data = seriesModel.getData();
  25088. var sampling = seriesModel.get('sampling');
  25089. var coordSys = seriesModel.coordinateSystem;
  25090. // Only cartesian2d support down sampling
  25091. if (coordSys.type === 'cartesian2d' && sampling) {
  25092. var baseAxis = coordSys.getBaseAxis();
  25093. var valueAxis = coordSys.getOtherAxis(baseAxis);
  25094. var extent = baseAxis.getExtent();
  25095. // Coordinste system has been resized
  25096. var size = extent[1] - extent[0];
  25097. var rate = Math.round(data.count() / size);
  25098. if (rate > 1) {
  25099. var sampler;
  25100. if (typeof sampling === 'string') {
  25101. sampler = samplers[sampling];
  25102. }
  25103. else if (typeof sampling === 'function') {
  25104. sampler = sampling;
  25105. }
  25106. if (sampler) {
  25107. data = data.downSample(
  25108. valueAxis.dim, 1 / rate, sampler, indexSampler
  25109. );
  25110. seriesModel.setData(data);
  25111. }
  25112. }
  25113. }
  25114. }, this);
  25115. };
  25116. /**
  25117. * Cartesian coordinate system
  25118. * @module echarts/coord/Cartesian
  25119. *
  25120. */
  25121. function dimAxisMapper(dim) {
  25122. return this._axes[dim];
  25123. }
  25124. /**
  25125. * @alias module:echarts/coord/Cartesian
  25126. * @constructor
  25127. */
  25128. var Cartesian = function (name) {
  25129. this._axes = {};
  25130. this._dimList = [];
  25131. /**
  25132. * @type {string}
  25133. */
  25134. this.name = name || '';
  25135. };
  25136. Cartesian.prototype = {
  25137. constructor: Cartesian,
  25138. type: 'cartesian',
  25139. /**
  25140. * Get axis
  25141. * @param {number|string} dim
  25142. * @return {module:echarts/coord/Cartesian~Axis}
  25143. */
  25144. getAxis: function (dim) {
  25145. return this._axes[dim];
  25146. },
  25147. /**
  25148. * Get axes list
  25149. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  25150. */
  25151. getAxes: function () {
  25152. return map(this._dimList, dimAxisMapper, this);
  25153. },
  25154. /**
  25155. * Get axes list by given scale type
  25156. */
  25157. getAxesByScale: function (scaleType) {
  25158. scaleType = scaleType.toLowerCase();
  25159. return filter(
  25160. this.getAxes(),
  25161. function (axis) {
  25162. return axis.scale.type === scaleType;
  25163. }
  25164. );
  25165. },
  25166. /**
  25167. * Add axis
  25168. * @param {module:echarts/coord/Cartesian.Axis}
  25169. */
  25170. addAxis: function (axis) {
  25171. var dim = axis.dim;
  25172. this._axes[dim] = axis;
  25173. this._dimList.push(dim);
  25174. },
  25175. /**
  25176. * Convert data to coord in nd space
  25177. * @param {Array.<number>|Object.<string, number>} val
  25178. * @return {Array.<number>|Object.<string, number>}
  25179. */
  25180. dataToCoord: function (val) {
  25181. return this._dataCoordConvert(val, 'dataToCoord');
  25182. },
  25183. /**
  25184. * Convert coord in nd space to data
  25185. * @param {Array.<number>|Object.<string, number>} val
  25186. * @return {Array.<number>|Object.<string, number>}
  25187. */
  25188. coordToData: function (val) {
  25189. return this._dataCoordConvert(val, 'coordToData');
  25190. },
  25191. _dataCoordConvert: function (input, method) {
  25192. var dimList = this._dimList;
  25193. var output = input instanceof Array ? [] : {};
  25194. for (var i = 0; i < dimList.length; i++) {
  25195. var dim = dimList[i];
  25196. var axis = this._axes[dim];
  25197. output[dim] = axis[method](input[dim]);
  25198. }
  25199. return output;
  25200. }
  25201. };
  25202. function Cartesian2D(name) {
  25203. Cartesian.call(this, name);
  25204. }
  25205. Cartesian2D.prototype = {
  25206. constructor: Cartesian2D,
  25207. type: 'cartesian2d',
  25208. /**
  25209. * @type {Array.<string>}
  25210. * @readOnly
  25211. */
  25212. dimensions: ['x', 'y'],
  25213. /**
  25214. * Base axis will be used on stacking.
  25215. *
  25216. * @return {module:echarts/coord/cartesian/Axis2D}
  25217. */
  25218. getBaseAxis: function () {
  25219. return this.getAxesByScale('ordinal')[0]
  25220. || this.getAxesByScale('time')[0]
  25221. || this.getAxis('x');
  25222. },
  25223. /**
  25224. * If contain point
  25225. * @param {Array.<number>} point
  25226. * @return {boolean}
  25227. */
  25228. containPoint: function (point) {
  25229. var axisX = this.getAxis('x');
  25230. var axisY = this.getAxis('y');
  25231. return axisX.contain(axisX.toLocalCoord(point[0]))
  25232. && axisY.contain(axisY.toLocalCoord(point[1]));
  25233. },
  25234. /**
  25235. * If contain data
  25236. * @param {Array.<number>} data
  25237. * @return {boolean}
  25238. */
  25239. containData: function (data) {
  25240. return this.getAxis('x').containData(data[0])
  25241. && this.getAxis('y').containData(data[1]);
  25242. },
  25243. /**
  25244. * @param {Array.<number>} data
  25245. * @param {boolean} [clamp=false]
  25246. * @return {Array.<number>}
  25247. */
  25248. dataToPoint: function (data, clamp) {
  25249. var xAxis = this.getAxis('x');
  25250. var yAxis = this.getAxis('y');
  25251. return [
  25252. xAxis.toGlobalCoord(xAxis.dataToCoord(data[0], clamp)),
  25253. yAxis.toGlobalCoord(yAxis.dataToCoord(data[1], clamp))
  25254. ];
  25255. },
  25256. /**
  25257. * @param {Array.<number>} point
  25258. * @param {boolean} [clamp=false]
  25259. * @return {Array.<number>}
  25260. */
  25261. pointToData: function (point, clamp) {
  25262. var xAxis = this.getAxis('x');
  25263. var yAxis = this.getAxis('y');
  25264. return [
  25265. xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp),
  25266. yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp)
  25267. ];
  25268. },
  25269. /**
  25270. * Get other axis
  25271. * @param {module:echarts/coord/cartesian/Axis2D} axis
  25272. */
  25273. getOtherAxis: function (axis) {
  25274. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  25275. }
  25276. };
  25277. inherits(Cartesian2D, Cartesian);
  25278. /**
  25279. * Extend axis 2d
  25280. * @constructor module:echarts/coord/cartesian/Axis2D
  25281. * @extends {module:echarts/coord/cartesian/Axis}
  25282. * @param {string} dim
  25283. * @param {*} scale
  25284. * @param {Array.<number>} coordExtent
  25285. * @param {string} axisType
  25286. * @param {string} position
  25287. */
  25288. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  25289. Axis.call(this, dim, scale, coordExtent);
  25290. /**
  25291. * Axis type
  25292. * - 'category'
  25293. * - 'value'
  25294. * - 'time'
  25295. * - 'log'
  25296. * @type {string}
  25297. */
  25298. this.type = axisType || 'value';
  25299. /**
  25300. * Axis position
  25301. * - 'top'
  25302. * - 'bottom'
  25303. * - 'left'
  25304. * - 'right'
  25305. */
  25306. this.position = position || 'bottom';
  25307. };
  25308. Axis2D.prototype = {
  25309. constructor: Axis2D,
  25310. /**
  25311. * Index of axis, can be used as key
  25312. */
  25313. index: 0,
  25314. /**
  25315. * If axis is on the zero position of the other axis
  25316. * @type {boolean}
  25317. */
  25318. onZero: false,
  25319. /**
  25320. * Axis model
  25321. * @param {module:echarts/coord/cartesian/AxisModel}
  25322. */
  25323. model: null,
  25324. isHorizontal: function () {
  25325. var position = this.position;
  25326. return position === 'top' || position === 'bottom';
  25327. },
  25328. /**
  25329. * Each item cooresponds to this.getExtent(), which
  25330. * means globalExtent[0] may greater than globalExtent[1],
  25331. * unless `asc` is input.
  25332. *
  25333. * @param {boolean} [asc]
  25334. * @return {Array.<number>}
  25335. */
  25336. getGlobalExtent: function (asc) {
  25337. var ret = this.getExtent();
  25338. ret[0] = this.toGlobalCoord(ret[0]);
  25339. ret[1] = this.toGlobalCoord(ret[1]);
  25340. asc && ret[0] > ret[1] && ret.reverse();
  25341. return ret;
  25342. },
  25343. getOtherAxis: function () {
  25344. this.grid.getOtherAxis();
  25345. },
  25346. /**
  25347. * If label is ignored.
  25348. * Automatically used when axis is category and label can not be all shown
  25349. * @param {number} idx
  25350. * @return {boolean}
  25351. */
  25352. isLabelIgnored: function (idx) {
  25353. if (this.type === 'category') {
  25354. var labelInterval = this.getLabelInterval();
  25355. return ((typeof labelInterval === 'function')
  25356. && !labelInterval(idx, this.scale.getLabel(idx)))
  25357. || idx % (labelInterval + 1);
  25358. }
  25359. },
  25360. /**
  25361. * @override
  25362. */
  25363. pointToData: function (point, clamp) {
  25364. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  25365. },
  25366. /**
  25367. * Transform global coord to local coord,
  25368. * i.e. var localCoord = axis.toLocalCoord(80);
  25369. * designate by module:echarts/coord/cartesian/Grid.
  25370. * @type {Function}
  25371. */
  25372. toLocalCoord: null,
  25373. /**
  25374. * Transform global coord to local coord,
  25375. * i.e. var globalCoord = axis.toLocalCoord(40);
  25376. * designate by module:echarts/coord/cartesian/Grid.
  25377. * @type {Function}
  25378. */
  25379. toGlobalCoord: null
  25380. };
  25381. inherits(Axis2D, Axis);
  25382. var defaultOption = {
  25383. show: true,
  25384. zlevel: 0, // 一级层叠
  25385. z: 0, // 二级层叠
  25386. // 反向坐标轴
  25387. inverse: false,
  25388. // 坐标轴名字,默认为空
  25389. name: '',
  25390. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  25391. nameLocation: 'end',
  25392. // 坐标轴名字旋转,degree。
  25393. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  25394. nameTruncate: {
  25395. maxWidth: null,
  25396. ellipsis: '...',
  25397. placeholder: '.'
  25398. },
  25399. // 坐标轴文字样式,默认取全局样式
  25400. nameTextStyle: {},
  25401. // 文字与轴线距离
  25402. nameGap: 15,
  25403. silent: false, // Default false to support tooltip.
  25404. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  25405. tooltip: {
  25406. show: false
  25407. },
  25408. axisPointer: {},
  25409. // 坐标轴线
  25410. axisLine: {
  25411. // 默认显示,属性show控制显示与否
  25412. show: true,
  25413. onZero: true,
  25414. onZeroAxisIndex: null,
  25415. // 属性lineStyle控制线条样式
  25416. lineStyle: {
  25417. color: '#333',
  25418. width: 1,
  25419. type: 'solid'
  25420. },
  25421. // 坐标轴两端的箭头
  25422. symbol: ['none', 'none'],
  25423. symbolSize: [10, 15]
  25424. },
  25425. // 坐标轴小标记
  25426. axisTick: {
  25427. // 属性show控制显示与否,默认显示
  25428. show: true,
  25429. // 控制小标记是否在grid里
  25430. inside: false,
  25431. // 属性length控制线长
  25432. length: 5,
  25433. // 属性lineStyle控制线条样式
  25434. lineStyle: {
  25435. width: 1
  25436. }
  25437. },
  25438. // 坐标轴文本标签,详见axis.axisLabel
  25439. axisLabel: {
  25440. show: true,
  25441. // 控制文本标签是否在grid里
  25442. inside: false,
  25443. rotate: 0,
  25444. showMinLabel: null, // true | false | null (auto)
  25445. showMaxLabel: null, // true | false | null (auto)
  25446. margin: 8,
  25447. // formatter: null,
  25448. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  25449. fontSize: 12
  25450. },
  25451. // 分隔线
  25452. splitLine: {
  25453. // 默认显示,属性show控制显示与否
  25454. show: true,
  25455. // 属性lineStyle(详见lineStyle)控制线条样式
  25456. lineStyle: {
  25457. color: ['#ccc'],
  25458. width: 1,
  25459. type: 'solid'
  25460. }
  25461. },
  25462. // 分隔区域
  25463. splitArea: {
  25464. // 默认不显示,属性show控制显示与否
  25465. show: false,
  25466. // 属性areaStyle(详见areaStyle)控制区域样式
  25467. areaStyle: {
  25468. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  25469. }
  25470. }
  25471. };
  25472. var axisDefault = {};
  25473. axisDefault.categoryAxis = merge({
  25474. // 类目起始和结束两端空白策略
  25475. boundaryGap: true,
  25476. // splitArea: {
  25477. // show: false
  25478. // },
  25479. splitLine: {
  25480. show: false
  25481. },
  25482. // 坐标轴小标记
  25483. axisTick: {
  25484. // If tick is align with label when boundaryGap is true
  25485. alignWithLabel: false,
  25486. interval: 'auto'
  25487. },
  25488. // 坐标轴文本标签,详见axis.axisLabel
  25489. axisLabel: {
  25490. interval: 'auto'
  25491. }
  25492. }, defaultOption);
  25493. axisDefault.valueAxis = merge({
  25494. // 数值起始和结束两端空白策略
  25495. boundaryGap: [0, 0],
  25496. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  25497. // min: null,
  25498. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  25499. // max: null,
  25500. // Readonly prop, specifies start value of the range when using data zoom.
  25501. // rangeStart: null
  25502. // Readonly prop, specifies end value of the range when using data zoom.
  25503. // rangeEnd: null
  25504. // 脱离0值比例,放大聚焦到最终_min,_max区间
  25505. // scale: false,
  25506. // 分割段数,默认为5
  25507. splitNumber: 5
  25508. // Minimum interval
  25509. // minInterval: null
  25510. // maxInterval: null
  25511. }, defaultOption);
  25512. // FIXME
  25513. axisDefault.timeAxis = defaults({
  25514. scale: true,
  25515. min: 'dataMin',
  25516. max: 'dataMax'
  25517. }, axisDefault.valueAxis);
  25518. axisDefault.logAxis = defaults({
  25519. scale: true,
  25520. logBase: 10
  25521. }, axisDefault.valueAxis);
  25522. // FIXME axisType is fixed ?
  25523. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  25524. /**
  25525. * Generate sub axis model class
  25526. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  25527. * @param {module:echarts/model/Component} BaseAxisModelClass
  25528. * @param {Function} axisTypeDefaulter
  25529. * @param {Object} [extraDefaultOption]
  25530. */
  25531. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  25532. each$1(AXIS_TYPES, function (axisType) {
  25533. BaseAxisModelClass.extend({
  25534. type: axisName + 'Axis.' + axisType,
  25535. mergeDefaultAndTheme: function (option, ecModel) {
  25536. var layoutMode = this.layoutMode;
  25537. var inputPositionParams = layoutMode
  25538. ? getLayoutParams(option) : {};
  25539. var themeModel = ecModel.getTheme();
  25540. merge(option, themeModel.get(axisType + 'Axis'));
  25541. merge(option, this.getDefaultOption());
  25542. option.type = axisTypeDefaulter(axisName, option);
  25543. if (layoutMode) {
  25544. mergeLayoutParam(option, inputPositionParams, layoutMode);
  25545. }
  25546. },
  25547. defaultOption: mergeAll(
  25548. [
  25549. {},
  25550. axisDefault[axisType + 'Axis'],
  25551. extraDefaultOption
  25552. ],
  25553. true
  25554. )
  25555. });
  25556. });
  25557. ComponentModel.registerSubTypeDefaulter(
  25558. axisName + 'Axis',
  25559. curry(axisTypeDefaulter, axisName)
  25560. );
  25561. };
  25562. var AxisModel = ComponentModel.extend({
  25563. type: 'cartesian2dAxis',
  25564. /**
  25565. * @type {module:echarts/coord/cartesian/Axis2D}
  25566. */
  25567. axis: null,
  25568. /**
  25569. * @override
  25570. */
  25571. init: function () {
  25572. AxisModel.superApply(this, 'init', arguments);
  25573. this.resetRange();
  25574. },
  25575. /**
  25576. * @override
  25577. */
  25578. mergeOption: function () {
  25579. AxisModel.superApply(this, 'mergeOption', arguments);
  25580. this.resetRange();
  25581. },
  25582. /**
  25583. * @override
  25584. */
  25585. restoreData: function () {
  25586. AxisModel.superApply(this, 'restoreData', arguments);
  25587. this.resetRange();
  25588. },
  25589. /**
  25590. * @override
  25591. * @return {module:echarts/model/Component}
  25592. */
  25593. getCoordSysModel: function () {
  25594. return this.ecModel.queryComponents({
  25595. mainType: 'grid',
  25596. index: this.option.gridIndex,
  25597. id: this.option.gridId
  25598. })[0];
  25599. }
  25600. });
  25601. function getAxisType(axisDim, option) {
  25602. // Default axis with data is category axis
  25603. return option.type || (option.data ? 'category' : 'value');
  25604. }
  25605. merge(AxisModel.prototype, axisModelCommonMixin);
  25606. var extraOption = {
  25607. // gridIndex: 0,
  25608. // gridId: '',
  25609. // Offset is for multiple axis on the same position
  25610. offset: 0
  25611. };
  25612. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  25613. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  25614. // Grid 是在有直角坐标系的时候必须要存在的
  25615. // 所以这里也要被 Cartesian2D 依赖
  25616. ComponentModel.extend({
  25617. type: 'grid',
  25618. dependencies: ['xAxis', 'yAxis'],
  25619. layoutMode: 'box',
  25620. /**
  25621. * @type {module:echarts/coord/cartesian/Grid}
  25622. */
  25623. coordinateSystem: null,
  25624. defaultOption: {
  25625. show: false,
  25626. zlevel: 0,
  25627. z: 0,
  25628. left: '10%',
  25629. top: 60,
  25630. right: '10%',
  25631. bottom: 60,
  25632. // If grid size contain label
  25633. containLabel: false,
  25634. // width: {totalWidth} - left - right,
  25635. // height: {totalHeight} - top - bottom,
  25636. backgroundColor: 'rgba(0,0,0,0)',
  25637. borderWidth: 1,
  25638. borderColor: '#ccc'
  25639. }
  25640. });
  25641. /**
  25642. * Grid is a region which contains at most 4 cartesian systems
  25643. *
  25644. * TODO Default cartesian
  25645. */
  25646. // Depends on GridModel, AxisModel, which performs preprocess.
  25647. var each$8 = each$1;
  25648. var ifAxisCrossZero$1 = ifAxisCrossZero;
  25649. var niceScaleExtent$1 = niceScaleExtent;
  25650. /**
  25651. * Check if the axis is used in the specified grid
  25652. * @inner
  25653. */
  25654. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  25655. return axisModel.getCoordSysModel() === gridModel;
  25656. }
  25657. function rotateTextRect(textRect, rotate) {
  25658. var rotateRadians = rotate * Math.PI / 180;
  25659. var boundingBox = textRect.plain();
  25660. var beforeWidth = boundingBox.width;
  25661. var beforeHeight = boundingBox.height;
  25662. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  25663. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  25664. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  25665. return rotatedRect;
  25666. }
  25667. function getLabelUnionRect(axis) {
  25668. var axisModel = axis.model;
  25669. var labels = axisModel.getFormattedLabels();
  25670. var axisLabelModel = axisModel.getModel('axisLabel');
  25671. var rect;
  25672. var step = 1;
  25673. var labelCount = labels.length;
  25674. if (labelCount > 40) {
  25675. // Simple optimization for large amount of labels
  25676. step = Math.ceil(labelCount / 40);
  25677. }
  25678. for (var i = 0; i < labelCount; i += step) {
  25679. if (!axis.isLabelIgnored(i)) {
  25680. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  25681. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  25682. rect ? rect.union(singleRect) : (rect = singleRect);
  25683. }
  25684. }
  25685. return rect;
  25686. }
  25687. function Grid(gridModel, ecModel, api) {
  25688. /**
  25689. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  25690. * @private
  25691. */
  25692. this._coordsMap = {};
  25693. /**
  25694. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  25695. * @private
  25696. */
  25697. this._coordsList = [];
  25698. /**
  25699. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  25700. * @private
  25701. */
  25702. this._axesMap = {};
  25703. /**
  25704. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  25705. * @private
  25706. */
  25707. this._axesList = [];
  25708. this._initCartesian(gridModel, ecModel, api);
  25709. this.model = gridModel;
  25710. }
  25711. var gridProto = Grid.prototype;
  25712. gridProto.type = 'grid';
  25713. gridProto.axisPointerEnabled = true;
  25714. gridProto.getRect = function () {
  25715. return this._rect;
  25716. };
  25717. gridProto.update = function (ecModel, api) {
  25718. var axesMap = this._axesMap;
  25719. this._updateScale(ecModel, this.model);
  25720. each$8(axesMap.x, function (xAxis) {
  25721. niceScaleExtent$1(xAxis.scale, xAxis.model);
  25722. });
  25723. each$8(axesMap.y, function (yAxis) {
  25724. niceScaleExtent$1(yAxis.scale, yAxis.model);
  25725. });
  25726. each$8(axesMap.x, function (xAxis) {
  25727. fixAxisOnZero(axesMap, 'y', xAxis);
  25728. });
  25729. each$8(axesMap.y, function (yAxis) {
  25730. fixAxisOnZero(axesMap, 'x', yAxis);
  25731. });
  25732. // Resize again if containLabel is enabled
  25733. // FIXME It may cause getting wrong grid size in data processing stage
  25734. this.resize(this.model, api);
  25735. };
  25736. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  25737. // onZero can not be enabled in these two situations:
  25738. // 1. When any other axis is a category axis.
  25739. // 2. When no axis is cross 0 point.
  25740. var axes = axesMap[otherAxisDim];
  25741. if (!axis.onZero) {
  25742. return;
  25743. }
  25744. var onZeroAxisIndex = axis.onZeroAxisIndex;
  25745. // If target axis is specified.
  25746. if (onZeroAxisIndex != null) {
  25747. var otherAxis = axes[onZeroAxisIndex];
  25748. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  25749. axis.onZero = false;
  25750. }
  25751. return;
  25752. }
  25753. for (var idx in axes) {
  25754. if (axes.hasOwnProperty(idx)) {
  25755. var otherAxis = axes[idx];
  25756. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  25757. onZeroAxisIndex = +idx;
  25758. break;
  25759. }
  25760. }
  25761. }
  25762. if (onZeroAxisIndex == null) {
  25763. axis.onZero = false;
  25764. }
  25765. axis.onZeroAxisIndex = onZeroAxisIndex;
  25766. }
  25767. function canNotOnZeroToAxis(axis) {
  25768. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  25769. }
  25770. /**
  25771. * Resize the grid
  25772. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  25773. * @param {module:echarts/ExtensionAPI} api
  25774. */
  25775. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  25776. var gridRect = getLayoutRect(
  25777. gridModel.getBoxLayoutParams(), {
  25778. width: api.getWidth(),
  25779. height: api.getHeight()
  25780. });
  25781. this._rect = gridRect;
  25782. var axesList = this._axesList;
  25783. adjustAxes();
  25784. // Minus label size
  25785. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  25786. each$8(axesList, function (axis) {
  25787. if (!axis.model.get('axisLabel.inside')) {
  25788. var labelUnionRect = getLabelUnionRect(axis);
  25789. if (labelUnionRect) {
  25790. var dim = axis.isHorizontal() ? 'height' : 'width';
  25791. var margin = axis.model.get('axisLabel.margin');
  25792. gridRect[dim] -= labelUnionRect[dim] + margin;
  25793. if (axis.position === 'top') {
  25794. gridRect.y += labelUnionRect.height + margin;
  25795. }
  25796. else if (axis.position === 'left') {
  25797. gridRect.x += labelUnionRect.width + margin;
  25798. }
  25799. }
  25800. }
  25801. });
  25802. adjustAxes();
  25803. }
  25804. function adjustAxes() {
  25805. each$8(axesList, function (axis) {
  25806. var isHorizontal = axis.isHorizontal();
  25807. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  25808. var idx = axis.inverse ? 1 : 0;
  25809. axis.setExtent(extent[idx], extent[1 - idx]);
  25810. updateAxisTransfrom(axis, isHorizontal ? gridRect.x : gridRect.y);
  25811. });
  25812. }
  25813. };
  25814. /**
  25815. * @param {string} axisType
  25816. * @param {number} [axisIndex]
  25817. */
  25818. gridProto.getAxis = function (axisType, axisIndex) {
  25819. var axesMapOnDim = this._axesMap[axisType];
  25820. if (axesMapOnDim != null) {
  25821. if (axisIndex == null) {
  25822. // Find first axis
  25823. for (var name in axesMapOnDim) {
  25824. if (axesMapOnDim.hasOwnProperty(name)) {
  25825. return axesMapOnDim[name];
  25826. }
  25827. }
  25828. }
  25829. return axesMapOnDim[axisIndex];
  25830. }
  25831. };
  25832. /**
  25833. * @return {Array.<module:echarts/coord/Axis>}
  25834. */
  25835. gridProto.getAxes = function () {
  25836. return this._axesList.slice();
  25837. };
  25838. /**
  25839. * Usage:
  25840. * grid.getCartesian(xAxisIndex, yAxisIndex);
  25841. * grid.getCartesian(xAxisIndex);
  25842. * grid.getCartesian(null, yAxisIndex);
  25843. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  25844. *
  25845. * @param {number|Object} [xAxisIndex]
  25846. * @param {number} [yAxisIndex]
  25847. */
  25848. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  25849. if (xAxisIndex != null && yAxisIndex != null) {
  25850. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  25851. return this._coordsMap[key];
  25852. }
  25853. if (isObject(xAxisIndex)) {
  25854. yAxisIndex = xAxisIndex.yAxisIndex;
  25855. xAxisIndex = xAxisIndex.xAxisIndex;
  25856. }
  25857. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  25858. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  25859. if (coordList[i].getAxis('x').index === xAxisIndex
  25860. || coordList[i].getAxis('y').index === yAxisIndex
  25861. ) {
  25862. return coordList[i];
  25863. }
  25864. }
  25865. };
  25866. gridProto.getCartesians = function () {
  25867. return this._coordsList.slice();
  25868. };
  25869. /**
  25870. * @implements
  25871. * see {module:echarts/CoodinateSystem}
  25872. */
  25873. gridProto.convertToPixel = function (ecModel, finder, value) {
  25874. var target = this._findConvertTarget(ecModel, finder);
  25875. return target.cartesian
  25876. ? target.cartesian.dataToPoint(value)
  25877. : target.axis
  25878. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  25879. : null;
  25880. };
  25881. /**
  25882. * @implements
  25883. * see {module:echarts/CoodinateSystem}
  25884. */
  25885. gridProto.convertFromPixel = function (ecModel, finder, value) {
  25886. var target = this._findConvertTarget(ecModel, finder);
  25887. return target.cartesian
  25888. ? target.cartesian.pointToData(value)
  25889. : target.axis
  25890. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  25891. : null;
  25892. };
  25893. /**
  25894. * @inner
  25895. */
  25896. gridProto._findConvertTarget = function (ecModel, finder) {
  25897. var seriesModel = finder.seriesModel;
  25898. var xAxisModel = finder.xAxisModel
  25899. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  25900. var yAxisModel = finder.yAxisModel
  25901. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  25902. var gridModel = finder.gridModel;
  25903. var coordsList = this._coordsList;
  25904. var cartesian;
  25905. var axis;
  25906. if (seriesModel) {
  25907. cartesian = seriesModel.coordinateSystem;
  25908. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  25909. }
  25910. else if (xAxisModel && yAxisModel) {
  25911. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  25912. }
  25913. else if (xAxisModel) {
  25914. axis = this.getAxis('x', xAxisModel.componentIndex);
  25915. }
  25916. else if (yAxisModel) {
  25917. axis = this.getAxis('y', yAxisModel.componentIndex);
  25918. }
  25919. // Lowest priority.
  25920. else if (gridModel) {
  25921. var grid = gridModel.coordinateSystem;
  25922. if (grid === this) {
  25923. cartesian = this._coordsList[0];
  25924. }
  25925. }
  25926. return {cartesian: cartesian, axis: axis};
  25927. };
  25928. /**
  25929. * @implements
  25930. * see {module:echarts/CoodinateSystem}
  25931. */
  25932. gridProto.containPoint = function (point) {
  25933. var coord = this._coordsList[0];
  25934. if (coord) {
  25935. return coord.containPoint(point);
  25936. }
  25937. };
  25938. /**
  25939. * Initialize cartesian coordinate systems
  25940. * @private
  25941. */
  25942. gridProto._initCartesian = function (gridModel, ecModel, api) {
  25943. var axisPositionUsed = {
  25944. left: false,
  25945. right: false,
  25946. top: false,
  25947. bottom: false
  25948. };
  25949. var axesMap = {
  25950. x: {},
  25951. y: {}
  25952. };
  25953. var axesCount = {
  25954. x: 0,
  25955. y: 0
  25956. };
  25957. /// Create axis
  25958. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  25959. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  25960. if (!axesCount.x || !axesCount.y) {
  25961. // Roll back when there no either x or y axis
  25962. this._axesMap = {};
  25963. this._axesList = [];
  25964. return;
  25965. }
  25966. this._axesMap = axesMap;
  25967. /// Create cartesian2d
  25968. each$8(axesMap.x, function (xAxis, xAxisIndex) {
  25969. each$8(axesMap.y, function (yAxis, yAxisIndex) {
  25970. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  25971. var cartesian = new Cartesian2D(key);
  25972. cartesian.grid = this;
  25973. cartesian.model = gridModel;
  25974. this._coordsMap[key] = cartesian;
  25975. this._coordsList.push(cartesian);
  25976. cartesian.addAxis(xAxis);
  25977. cartesian.addAxis(yAxis);
  25978. }, this);
  25979. }, this);
  25980. function createAxisCreator(axisType) {
  25981. return function (axisModel, idx) {
  25982. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  25983. return;
  25984. }
  25985. var axisPosition = axisModel.get('position');
  25986. if (axisType === 'x') {
  25987. // Fix position
  25988. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  25989. // Default bottom of X
  25990. axisPosition = 'bottom';
  25991. if (axisPositionUsed[axisPosition]) {
  25992. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  25993. }
  25994. }
  25995. }
  25996. else {
  25997. // Fix position
  25998. if (axisPosition !== 'left' && axisPosition !== 'right') {
  25999. // Default left of Y
  26000. axisPosition = 'left';
  26001. if (axisPositionUsed[axisPosition]) {
  26002. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  26003. }
  26004. }
  26005. }
  26006. axisPositionUsed[axisPosition] = true;
  26007. var axis = new Axis2D(
  26008. axisType, createScaleByModel(axisModel),
  26009. [0, 0],
  26010. axisModel.get('type'),
  26011. axisPosition
  26012. );
  26013. var isCategory = axis.type === 'category';
  26014. axis.onBand = isCategory && axisModel.get('boundaryGap');
  26015. axis.inverse = axisModel.get('inverse');
  26016. axis.onZero = axisModel.get('axisLine.onZero');
  26017. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  26018. // Inject axis into axisModel
  26019. axisModel.axis = axis;
  26020. // Inject axisModel into axis
  26021. axis.model = axisModel;
  26022. // Inject grid info axis
  26023. axis.grid = this;
  26024. // Index of axis, can be used as key
  26025. axis.index = idx;
  26026. this._axesList.push(axis);
  26027. axesMap[axisType][idx] = axis;
  26028. axesCount[axisType]++;
  26029. };
  26030. }
  26031. };
  26032. /**
  26033. * Update cartesian properties from series
  26034. * @param {module:echarts/model/Option} option
  26035. * @private
  26036. */
  26037. gridProto._updateScale = function (ecModel, gridModel) {
  26038. // Reset scale
  26039. each$1(this._axesList, function (axis) {
  26040. axis.scale.setExtent(Infinity, -Infinity);
  26041. });
  26042. ecModel.eachSeries(function (seriesModel) {
  26043. if (isCartesian2D(seriesModel)) {
  26044. var axesModels = findAxesModels(seriesModel, ecModel);
  26045. var xAxisModel = axesModels[0];
  26046. var yAxisModel = axesModels[1];
  26047. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  26048. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  26049. ) {
  26050. return;
  26051. }
  26052. var cartesian = this.getCartesian(
  26053. xAxisModel.componentIndex, yAxisModel.componentIndex
  26054. );
  26055. var data = seriesModel.getData();
  26056. var xAxis = cartesian.getAxis('x');
  26057. var yAxis = cartesian.getAxis('y');
  26058. if (data.type === 'list') {
  26059. unionExtent(data, xAxis, seriesModel);
  26060. unionExtent(data, yAxis, seriesModel);
  26061. }
  26062. }
  26063. }, this);
  26064. function unionExtent(data, axis, seriesModel) {
  26065. each$8(seriesModel.coordDimToDataDim(axis.dim), function (dim) {
  26066. axis.scale.unionExtentFromData(data, dim);
  26067. });
  26068. }
  26069. };
  26070. /**
  26071. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  26072. * @return {Object} {baseAxes: [], otherAxes: []}
  26073. */
  26074. gridProto.getTooltipAxes = function (dim) {
  26075. var baseAxes = [];
  26076. var otherAxes = [];
  26077. each$8(this.getCartesians(), function (cartesian) {
  26078. var baseAxis = (dim != null && dim !== 'auto')
  26079. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  26080. var otherAxis = cartesian.getOtherAxis(baseAxis);
  26081. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  26082. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  26083. });
  26084. return {baseAxes: baseAxes, otherAxes: otherAxes};
  26085. };
  26086. /**
  26087. * @inner
  26088. */
  26089. function updateAxisTransfrom(axis, coordBase) {
  26090. var axisExtent = axis.getExtent();
  26091. var axisExtentSum = axisExtent[0] + axisExtent[1];
  26092. // Fast transform
  26093. axis.toGlobalCoord = axis.dim === 'x'
  26094. ? function (coord) {
  26095. return coord + coordBase;
  26096. }
  26097. : function (coord) {
  26098. return axisExtentSum - coord + coordBase;
  26099. };
  26100. axis.toLocalCoord = axis.dim === 'x'
  26101. ? function (coord) {
  26102. return coord - coordBase;
  26103. }
  26104. : function (coord) {
  26105. return axisExtentSum - coord + coordBase;
  26106. };
  26107. }
  26108. var axesTypes = ['xAxis', 'yAxis'];
  26109. /**
  26110. * @inner
  26111. */
  26112. function findAxesModels(seriesModel, ecModel) {
  26113. return map(axesTypes, function (axisType) {
  26114. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  26115. if (__DEV__) {
  26116. if (!axisModel) {
  26117. throw new Error(axisType + ' "' + retrieve(
  26118. seriesModel.get(axisType + 'Index'),
  26119. seriesModel.get(axisType + 'Id'),
  26120. 0
  26121. ) + '" not found');
  26122. }
  26123. }
  26124. return axisModel;
  26125. });
  26126. }
  26127. /**
  26128. * @inner
  26129. */
  26130. function isCartesian2D(seriesModel) {
  26131. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  26132. }
  26133. Grid.create = function (ecModel, api) {
  26134. var grids = [];
  26135. ecModel.eachComponent('grid', function (gridModel, idx) {
  26136. var grid = new Grid(gridModel, ecModel, api);
  26137. grid.name = 'grid_' + idx;
  26138. // dataSampling requires axis extent, so resize
  26139. // should be performed in create stage.
  26140. grid.resize(gridModel, api, true);
  26141. gridModel.coordinateSystem = grid;
  26142. grids.push(grid);
  26143. });
  26144. // Inject the coordinateSystems into seriesModel
  26145. ecModel.eachSeries(function (seriesModel) {
  26146. if (!isCartesian2D(seriesModel)) {
  26147. return;
  26148. }
  26149. var axesModels = findAxesModels(seriesModel, ecModel);
  26150. var xAxisModel = axesModels[0];
  26151. var yAxisModel = axesModels[1];
  26152. var gridModel = xAxisModel.getCoordSysModel();
  26153. if (__DEV__) {
  26154. if (!gridModel) {
  26155. throw new Error(
  26156. 'Grid "' + retrieve(
  26157. xAxisModel.get('gridIndex'),
  26158. xAxisModel.get('gridId'),
  26159. 0
  26160. ) + '" not found'
  26161. );
  26162. }
  26163. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  26164. throw new Error('xAxis and yAxis must use the same grid');
  26165. }
  26166. }
  26167. var grid = gridModel.coordinateSystem;
  26168. seriesModel.coordinateSystem = grid.getCartesian(
  26169. xAxisModel.componentIndex, yAxisModel.componentIndex
  26170. );
  26171. });
  26172. return grids;
  26173. };
  26174. // For deciding which dimensions to use when creating list data
  26175. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  26176. CoordinateSystemManager.register('cartesian2d', Grid);
  26177. var PI$2 = Math.PI;
  26178. function makeAxisEventDataBase(axisModel) {
  26179. var eventData = {
  26180. componentType: axisModel.mainType
  26181. };
  26182. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  26183. return eventData;
  26184. }
  26185. /**
  26186. * A final axis is translated and rotated from a "standard axis".
  26187. * So opt.position and opt.rotation is required.
  26188. *
  26189. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  26190. * for example: (0, 0) ------------> (0, 50)
  26191. *
  26192. * nameDirection or tickDirection or labelDirection is 1 means tick
  26193. * or label is below the standard axis, whereas is -1 means above
  26194. * the standard axis. labelOffset means offset between label and axis,
  26195. * which is useful when 'onZero', where axisLabel is in the grid and
  26196. * label in outside grid.
  26197. *
  26198. * Tips: like always,
  26199. * positive rotation represents anticlockwise, and negative rotation
  26200. * represents clockwise.
  26201. * The direction of position coordinate is the same as the direction
  26202. * of screen coordinate.
  26203. *
  26204. * Do not need to consider axis 'inverse', which is auto processed by
  26205. * axis extent.
  26206. *
  26207. * @param {module:zrender/container/Group} group
  26208. * @param {Object} axisModel
  26209. * @param {Object} opt Standard axis parameters.
  26210. * @param {Array.<number>} opt.position [x, y]
  26211. * @param {number} opt.rotation by radian
  26212. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  26213. * @param {number} [opt.tickDirection=1] 1 or -1
  26214. * @param {number} [opt.labelDirection=1] 1 or -1
  26215. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  26216. * @param {string} [opt.axisLabelShow] default get from axisModel.
  26217. * @param {string} [opt.axisName] default get from axisModel.
  26218. * @param {number} [opt.axisNameAvailableWidth]
  26219. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  26220. * @param {number} [opt.labelInterval] Default label interval when label
  26221. * interval from model is null or 'auto'.
  26222. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  26223. * @param {number} [opt.nameTruncateMaxWidth]
  26224. */
  26225. var AxisBuilder = function (axisModel, opt) {
  26226. /**
  26227. * @readOnly
  26228. */
  26229. this.opt = opt;
  26230. /**
  26231. * @readOnly
  26232. */
  26233. this.axisModel = axisModel;
  26234. // Default value
  26235. defaults(
  26236. opt,
  26237. {
  26238. labelOffset: 0,
  26239. nameDirection: 1,
  26240. tickDirection: 1,
  26241. labelDirection: 1,
  26242. silent: true
  26243. }
  26244. );
  26245. /**
  26246. * @readOnly
  26247. */
  26248. this.group = new Group();
  26249. // FIXME Not use a seperate text group?
  26250. var dumbGroup = new Group({
  26251. position: opt.position.slice(),
  26252. rotation: opt.rotation
  26253. });
  26254. // this.group.add(dumbGroup);
  26255. // this._dumbGroup = dumbGroup;
  26256. dumbGroup.updateTransform();
  26257. this._transform = dumbGroup.transform;
  26258. this._dumbGroup = dumbGroup;
  26259. };
  26260. AxisBuilder.prototype = {
  26261. constructor: AxisBuilder,
  26262. hasBuilder: function (name) {
  26263. return !!builders[name];
  26264. },
  26265. add: function (name) {
  26266. builders[name].call(this);
  26267. },
  26268. getGroup: function () {
  26269. return this.group;
  26270. }
  26271. };
  26272. var builders = {
  26273. /**
  26274. * @private
  26275. */
  26276. axisLine: function () {
  26277. var opt = this.opt;
  26278. var axisModel = this.axisModel;
  26279. if (!axisModel.get('axisLine.show')) {
  26280. return;
  26281. }
  26282. var extent = this.axisModel.axis.getExtent();
  26283. var matrix = this._transform;
  26284. var pt1 = [extent[0], 0];
  26285. var pt2 = [extent[1], 0];
  26286. if (matrix) {
  26287. applyTransform(pt1, pt1, matrix);
  26288. applyTransform(pt2, pt2, matrix);
  26289. }
  26290. var lineStyle = extend(
  26291. {
  26292. lineCap: 'round'
  26293. },
  26294. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  26295. );
  26296. this.group.add(new Line(subPixelOptimizeLine({
  26297. // Id for animation
  26298. anid: 'line',
  26299. shape: {
  26300. x1: pt1[0],
  26301. y1: pt1[1],
  26302. x2: pt2[0],
  26303. y2: pt2[1]
  26304. },
  26305. style: lineStyle,
  26306. strokeContainThreshold: opt.strokeContainThreshold || 5,
  26307. silent: true,
  26308. z2: 1
  26309. })));
  26310. var arrows = axisModel.get('axisLine.symbol');
  26311. var arrowSize = axisModel.get('axisLine.symbolSize');
  26312. if (arrows != null) {
  26313. if (typeof arrows === 'string') {
  26314. // Use the same arrow for start and end point
  26315. arrows = [arrows, arrows];
  26316. }
  26317. if (typeof arrowSize === 'string'
  26318. || typeof arrowSize === 'number'
  26319. ) {
  26320. // Use the same size for width and height
  26321. arrowSize = [arrowSize, arrowSize];
  26322. }
  26323. var symbolWidth = arrowSize[0];
  26324. var symbolHeight = arrowSize[1];
  26325. each$1([
  26326. [opt.rotation + Math.PI / 2, pt1],
  26327. [opt.rotation - Math.PI / 2, pt2]
  26328. ], function (item, index) {
  26329. if (arrows[index] !== 'none' && arrows[index] != null) {
  26330. var symbol = createSymbol(
  26331. arrows[index],
  26332. -symbolWidth / 2,
  26333. -symbolHeight / 2,
  26334. symbolWidth,
  26335. symbolHeight,
  26336. lineStyle.stroke,
  26337. true
  26338. );
  26339. symbol.attr({
  26340. rotation: item[0],
  26341. position: item[1],
  26342. silent: true
  26343. });
  26344. this.group.add(symbol);
  26345. }
  26346. }, this);
  26347. }
  26348. },
  26349. /**
  26350. * @private
  26351. */
  26352. axisTickLabel: function () {
  26353. var axisModel = this.axisModel;
  26354. var opt = this.opt;
  26355. var tickEls = buildAxisTick(this, axisModel, opt);
  26356. var labelEls = buildAxisLabel(this, axisModel, opt);
  26357. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  26358. },
  26359. /**
  26360. * @private
  26361. */
  26362. axisName: function () {
  26363. var opt = this.opt;
  26364. var axisModel = this.axisModel;
  26365. var name = retrieve(opt.axisName, axisModel.get('name'));
  26366. if (!name) {
  26367. return;
  26368. }
  26369. var nameLocation = axisModel.get('nameLocation');
  26370. var nameDirection = opt.nameDirection;
  26371. var textStyleModel = axisModel.getModel('nameTextStyle');
  26372. var gap = axisModel.get('nameGap') || 0;
  26373. var extent = this.axisModel.axis.getExtent();
  26374. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  26375. var pos = [
  26376. nameLocation === 'start'
  26377. ? extent[0] - gapSignal * gap
  26378. : nameLocation === 'end'
  26379. ? extent[1] + gapSignal * gap
  26380. : (extent[0] + extent[1]) / 2, // 'middle'
  26381. // Reuse labelOffset.
  26382. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  26383. ];
  26384. var labelLayout;
  26385. var nameRotation = axisModel.get('nameRotate');
  26386. if (nameRotation != null) {
  26387. nameRotation = nameRotation * PI$2 / 180; // To radian.
  26388. }
  26389. var axisNameAvailableWidth;
  26390. if (isNameLocationCenter(nameLocation)) {
  26391. labelLayout = innerTextLayout(
  26392. opt.rotation,
  26393. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  26394. nameDirection
  26395. );
  26396. }
  26397. else {
  26398. labelLayout = endTextLayout(
  26399. opt, nameLocation, nameRotation || 0, extent
  26400. );
  26401. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  26402. if (axisNameAvailableWidth != null) {
  26403. axisNameAvailableWidth = Math.abs(
  26404. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  26405. );
  26406. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  26407. }
  26408. }
  26409. var textFont = textStyleModel.getFont();
  26410. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  26411. var ellipsis = truncateOpt.ellipsis;
  26412. var maxWidth = retrieve(
  26413. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  26414. );
  26415. // FIXME
  26416. // truncate rich text? (consider performance)
  26417. var truncatedText = (ellipsis != null && maxWidth != null)
  26418. ? truncateText$1(
  26419. name, maxWidth, textFont, ellipsis,
  26420. {minChar: 2, placeholder: truncateOpt.placeholder}
  26421. )
  26422. : name;
  26423. var tooltipOpt = axisModel.get('tooltip', true);
  26424. var mainType = axisModel.mainType;
  26425. var formatterParams = {
  26426. componentType: mainType,
  26427. name: name,
  26428. $vars: ['name']
  26429. };
  26430. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  26431. var textEl = new Text({
  26432. // Id for animation
  26433. anid: 'name',
  26434. __fullText: name,
  26435. __truncatedText: truncatedText,
  26436. position: pos,
  26437. rotation: labelLayout.rotation,
  26438. silent: isSilent(axisModel),
  26439. z2: 1,
  26440. tooltip: (tooltipOpt && tooltipOpt.show)
  26441. ? extend({
  26442. content: name,
  26443. formatter: function () {
  26444. return name;
  26445. },
  26446. formatterParams: formatterParams
  26447. }, tooltipOpt)
  26448. : null
  26449. });
  26450. setTextStyle(textEl.style, textStyleModel, {
  26451. text: truncatedText,
  26452. textFont: textFont,
  26453. textFill: textStyleModel.getTextColor()
  26454. || axisModel.get('axisLine.lineStyle.color'),
  26455. textAlign: labelLayout.textAlign,
  26456. textVerticalAlign: labelLayout.textVerticalAlign
  26457. });
  26458. if (axisModel.get('triggerEvent')) {
  26459. textEl.eventData = makeAxisEventDataBase(axisModel);
  26460. textEl.eventData.targetType = 'axisName';
  26461. textEl.eventData.name = name;
  26462. }
  26463. // FIXME
  26464. this._dumbGroup.add(textEl);
  26465. textEl.updateTransform();
  26466. this.group.add(textEl);
  26467. textEl.decomposeTransform();
  26468. }
  26469. };
  26470. /**
  26471. * @public
  26472. * @static
  26473. * @param {Object} opt
  26474. * @param {number} axisRotation in radian
  26475. * @param {number} textRotation in radian
  26476. * @param {number} direction
  26477. * @return {Object} {
  26478. * rotation, // according to axis
  26479. * textAlign,
  26480. * textVerticalAlign
  26481. * }
  26482. */
  26483. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  26484. var rotationDiff = remRadian(textRotation - axisRotation);
  26485. var textAlign;
  26486. var textVerticalAlign;
  26487. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  26488. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  26489. textAlign = 'center';
  26490. }
  26491. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  26492. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  26493. textAlign = 'center';
  26494. }
  26495. else {
  26496. textVerticalAlign = 'middle';
  26497. if (rotationDiff > 0 && rotationDiff < PI$2) {
  26498. textAlign = direction > 0 ? 'right' : 'left';
  26499. }
  26500. else {
  26501. textAlign = direction > 0 ? 'left' : 'right';
  26502. }
  26503. }
  26504. return {
  26505. rotation: rotationDiff,
  26506. textAlign: textAlign,
  26507. textVerticalAlign: textVerticalAlign
  26508. };
  26509. };
  26510. function endTextLayout(opt, textPosition, textRotate, extent) {
  26511. var rotationDiff = remRadian(textRotate - opt.rotation);
  26512. var textAlign;
  26513. var textVerticalAlign;
  26514. var inverse = extent[0] > extent[1];
  26515. var onLeft = (textPosition === 'start' && !inverse)
  26516. || (textPosition !== 'start' && inverse);
  26517. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  26518. textVerticalAlign = onLeft ? 'bottom' : 'top';
  26519. textAlign = 'center';
  26520. }
  26521. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  26522. textVerticalAlign = onLeft ? 'top' : 'bottom';
  26523. textAlign = 'center';
  26524. }
  26525. else {
  26526. textVerticalAlign = 'middle';
  26527. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  26528. textAlign = onLeft ? 'left' : 'right';
  26529. }
  26530. else {
  26531. textAlign = onLeft ? 'right' : 'left';
  26532. }
  26533. }
  26534. return {
  26535. rotation: rotationDiff,
  26536. textAlign: textAlign,
  26537. textVerticalAlign: textVerticalAlign
  26538. };
  26539. }
  26540. function isSilent(axisModel) {
  26541. var tooltipOpt = axisModel.get('tooltip');
  26542. return axisModel.get('silent')
  26543. // Consider mouse cursor, add these restrictions.
  26544. || !(
  26545. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  26546. );
  26547. }
  26548. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  26549. // If min or max are user set, we need to check
  26550. // If the tick on min(max) are overlap on their neighbour tick
  26551. // If they are overlapped, we need to hide the min(max) tick label
  26552. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26553. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26554. // FIXME
  26555. // Have not consider onBand yet, where tick els is more than label els.
  26556. labelEls = labelEls || [];
  26557. tickEls = tickEls || [];
  26558. var firstLabel = labelEls[0];
  26559. var nextLabel = labelEls[1];
  26560. var lastLabel = labelEls[labelEls.length - 1];
  26561. var prevLabel = labelEls[labelEls.length - 2];
  26562. var firstTick = tickEls[0];
  26563. var nextTick = tickEls[1];
  26564. var lastTick = tickEls[tickEls.length - 1];
  26565. var prevTick = tickEls[tickEls.length - 2];
  26566. if (showMinLabel === false) {
  26567. ignoreEl(firstLabel);
  26568. ignoreEl(firstTick);
  26569. }
  26570. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  26571. if (showMinLabel) {
  26572. ignoreEl(nextLabel);
  26573. ignoreEl(nextTick);
  26574. }
  26575. else {
  26576. ignoreEl(firstLabel);
  26577. ignoreEl(firstTick);
  26578. }
  26579. }
  26580. if (showMaxLabel === false) {
  26581. ignoreEl(lastLabel);
  26582. ignoreEl(lastTick);
  26583. }
  26584. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  26585. if (showMaxLabel) {
  26586. ignoreEl(prevLabel);
  26587. ignoreEl(prevTick);
  26588. }
  26589. else {
  26590. ignoreEl(lastLabel);
  26591. ignoreEl(lastTick);
  26592. }
  26593. }
  26594. }
  26595. function ignoreEl(el) {
  26596. el && (el.ignore = true);
  26597. }
  26598. function isTwoLabelOverlapped(current, next, labelLayout) {
  26599. // current and next has the same rotation.
  26600. var firstRect = current && current.getBoundingRect().clone();
  26601. var nextRect = next && next.getBoundingRect().clone();
  26602. if (!firstRect || !nextRect) {
  26603. return;
  26604. }
  26605. // When checking intersect of two rotated labels, we use mRotationBack
  26606. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  26607. var mRotationBack = identity([]);
  26608. rotate(mRotationBack, mRotationBack, -current.rotation);
  26609. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  26610. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  26611. return firstRect.intersect(nextRect);
  26612. }
  26613. function isNameLocationCenter(nameLocation) {
  26614. return nameLocation === 'middle' || nameLocation === 'center';
  26615. }
  26616. /**
  26617. * @static
  26618. */
  26619. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  26620. axis,
  26621. i,
  26622. interval,
  26623. ticksCnt,
  26624. showMinLabel,
  26625. showMaxLabel
  26626. ) {
  26627. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  26628. return false;
  26629. }
  26630. // FIXME
  26631. // Have not consider label overlap (if label is too long) yet.
  26632. var rawTick;
  26633. var scale$$1 = axis.scale;
  26634. return scale$$1.type === 'ordinal'
  26635. && (
  26636. typeof interval === 'function'
  26637. ? (
  26638. rawTick = scale$$1.getTicks()[i],
  26639. !interval(rawTick, scale$$1.getLabel(rawTick))
  26640. )
  26641. : i % (interval + 1)
  26642. );
  26643. };
  26644. /**
  26645. * @static
  26646. */
  26647. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  26648. var interval = model.get('interval');
  26649. if (interval == null || interval == 'auto') {
  26650. interval = labelInterval;
  26651. }
  26652. return interval;
  26653. };
  26654. function buildAxisTick(axisBuilder, axisModel, opt) {
  26655. var axis = axisModel.axis;
  26656. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  26657. return;
  26658. }
  26659. var tickModel = axisModel.getModel('axisTick');
  26660. var lineStyleModel = tickModel.getModel('lineStyle');
  26661. var tickLen = tickModel.get('length');
  26662. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  26663. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  26664. // FIXME
  26665. // Corresponds to ticksCoords ?
  26666. var ticks = axis.scale.getTicks();
  26667. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26668. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26669. var pt1 = [];
  26670. var pt2 = [];
  26671. var matrix = axisBuilder._transform;
  26672. var tickEls = [];
  26673. var ticksCnt = ticksCoords.length;
  26674. for (var i = 0; i < ticksCnt; i++) {
  26675. // Only ordinal scale support tick interval
  26676. if (ifIgnoreOnTick$1(
  26677. axis, i, tickInterval, ticksCnt,
  26678. showMinLabel, showMaxLabel
  26679. )) {
  26680. continue;
  26681. }
  26682. var tickCoord = ticksCoords[i];
  26683. pt1[0] = tickCoord;
  26684. pt1[1] = 0;
  26685. pt2[0] = tickCoord;
  26686. pt2[1] = opt.tickDirection * tickLen;
  26687. if (matrix) {
  26688. applyTransform(pt1, pt1, matrix);
  26689. applyTransform(pt2, pt2, matrix);
  26690. }
  26691. // Tick line, Not use group transform to have better line draw
  26692. var tickEl = new Line(subPixelOptimizeLine({
  26693. // Id for animation
  26694. anid: 'tick_' + ticks[i],
  26695. shape: {
  26696. x1: pt1[0],
  26697. y1: pt1[1],
  26698. x2: pt2[0],
  26699. y2: pt2[1]
  26700. },
  26701. style: defaults(
  26702. lineStyleModel.getLineStyle(),
  26703. {
  26704. stroke: axisModel.get('axisLine.lineStyle.color')
  26705. }
  26706. ),
  26707. z2: 2,
  26708. silent: true
  26709. }));
  26710. axisBuilder.group.add(tickEl);
  26711. tickEls.push(tickEl);
  26712. }
  26713. return tickEls;
  26714. }
  26715. function buildAxisLabel(axisBuilder, axisModel, opt) {
  26716. var axis = axisModel.axis;
  26717. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  26718. if (!show || axis.scale.isBlank()) {
  26719. return;
  26720. }
  26721. var labelModel = axisModel.getModel('axisLabel');
  26722. var labelMargin = labelModel.get('margin');
  26723. var ticks = axis.scale.getTicks();
  26724. var labels = axisModel.getFormattedLabels();
  26725. // Special label rotate.
  26726. var labelRotation = (
  26727. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  26728. ) * PI$2 / 180;
  26729. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  26730. var categoryData = axisModel.get('data');
  26731. var labelEls = [];
  26732. var silent = isSilent(axisModel);
  26733. var triggerEvent = axisModel.get('triggerEvent');
  26734. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26735. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26736. each$1(ticks, function (tickVal, index) {
  26737. if (ifIgnoreOnTick$1(
  26738. axis, index, opt.labelInterval, ticks.length,
  26739. showMinLabel, showMaxLabel
  26740. )) {
  26741. return;
  26742. }
  26743. var itemLabelModel = labelModel;
  26744. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  26745. itemLabelModel = new Model(
  26746. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  26747. );
  26748. }
  26749. var textColor = itemLabelModel.getTextColor()
  26750. || axisModel.get('axisLine.lineStyle.color');
  26751. var tickCoord = axis.dataToCoord(tickVal);
  26752. var pos = [
  26753. tickCoord,
  26754. opt.labelOffset + opt.labelDirection * labelMargin
  26755. ];
  26756. var labelStr = axis.scale.getLabel(tickVal);
  26757. var textEl = new Text({
  26758. // Id for animation
  26759. anid: 'label_' + tickVal,
  26760. position: pos,
  26761. rotation: labelLayout.rotation,
  26762. silent: silent,
  26763. z2: 10
  26764. });
  26765. setTextStyle(textEl.style, itemLabelModel, {
  26766. text: labels[index],
  26767. textAlign: itemLabelModel.getShallow('align', true)
  26768. || labelLayout.textAlign,
  26769. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  26770. || itemLabelModel.getShallow('baseline', true)
  26771. || labelLayout.textVerticalAlign,
  26772. textFill: typeof textColor === 'function'
  26773. ? textColor(
  26774. // (1) In category axis with data zoom, tick is not the original
  26775. // index of axis.data. So tick should not be exposed to user
  26776. // in category axis.
  26777. // (2) Compatible with previous version, which always returns labelStr.
  26778. // But in interval scale labelStr is like '223,445', which maked
  26779. // user repalce ','. So we modify it to return original val but remain
  26780. // it as 'string' to avoid error in replacing.
  26781. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  26782. index
  26783. )
  26784. : textColor
  26785. });
  26786. // Pack data for mouse event
  26787. if (triggerEvent) {
  26788. textEl.eventData = makeAxisEventDataBase(axisModel);
  26789. textEl.eventData.targetType = 'axisLabel';
  26790. textEl.eventData.value = labelStr;
  26791. }
  26792. // FIXME
  26793. axisBuilder._dumbGroup.add(textEl);
  26794. textEl.updateTransform();
  26795. labelEls.push(textEl);
  26796. axisBuilder.group.add(textEl);
  26797. textEl.decomposeTransform();
  26798. });
  26799. return labelEls;
  26800. }
  26801. var each$9 = each$1;
  26802. var curry$1 = curry;
  26803. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  26804. // allAxesInfo should be updated when setOption performed.
  26805. function collect(ecModel, api) {
  26806. var result = {
  26807. /**
  26808. * key: makeKey(axis.model)
  26809. * value: {
  26810. * axis,
  26811. * coordSys,
  26812. * axisPointerModel,
  26813. * triggerTooltip,
  26814. * involveSeries,
  26815. * snap,
  26816. * seriesModels,
  26817. * seriesDataCount
  26818. * }
  26819. */
  26820. axesInfo: {},
  26821. seriesInvolved: false,
  26822. /**
  26823. * key: makeKey(coordSys.model)
  26824. * value: Object: key makeKey(axis.model), value: axisInfo
  26825. */
  26826. coordSysAxesInfo: {},
  26827. coordSysMap: {}
  26828. };
  26829. collectAxesInfo(result, ecModel, api);
  26830. // Check seriesInvolved for performance, in case too many series in some chart.
  26831. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  26832. return result;
  26833. }
  26834. function collectAxesInfo(result, ecModel, api) {
  26835. var globalTooltipModel = ecModel.getComponent('tooltip');
  26836. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  26837. // links can only be set on global.
  26838. var linksOption = globalAxisPointerModel.get('link', true) || [];
  26839. var linkGroups = [];
  26840. // Collect axes info.
  26841. each$9(api.getCoordinateSystems(), function (coordSys) {
  26842. // Some coordinate system do not support axes, like geo.
  26843. if (!coordSys.axisPointerEnabled) {
  26844. return;
  26845. }
  26846. var coordSysKey = makeKey(coordSys.model);
  26847. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  26848. result.coordSysMap[coordSysKey] = coordSys;
  26849. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  26850. // for user. So we enable seting tooltip on coordSys model.
  26851. var coordSysModel = coordSys.model;
  26852. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  26853. each$9(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  26854. // If axis tooltip used, choose tooltip axis for each coordSys.
  26855. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  26856. if (coordSys.getTooltipAxes
  26857. && globalTooltipModel
  26858. // If tooltip.showContent is set as false, tooltip will not
  26859. // show but axisPointer will show as normal.
  26860. && baseTooltipModel.get('show')
  26861. ) {
  26862. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  26863. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  26864. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  26865. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  26866. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  26867. if (triggerAxis || cross) {
  26868. each$9(tooltipAxes.baseAxes, curry$1(
  26869. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  26870. ));
  26871. }
  26872. if (cross) {
  26873. each$9(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  26874. }
  26875. }
  26876. // fromTooltip: true | false | 'cross'
  26877. // triggerTooltip: true | false | null
  26878. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  26879. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  26880. var axisPointerShow = axisPointerModel.get('show');
  26881. if (!axisPointerShow || (
  26882. axisPointerShow === 'auto'
  26883. && !fromTooltip
  26884. && !isHandleTrigger(axisPointerModel)
  26885. )) {
  26886. return;
  26887. }
  26888. if (triggerTooltip == null) {
  26889. triggerTooltip = axisPointerModel.get('triggerTooltip');
  26890. }
  26891. axisPointerModel = fromTooltip
  26892. ? makeAxisPointerModel(
  26893. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  26894. fromTooltip, triggerTooltip
  26895. )
  26896. : axisPointerModel;
  26897. var snap = axisPointerModel.get('snap');
  26898. var key = makeKey(axis.model);
  26899. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  26900. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  26901. var axisInfo = result.axesInfo[key] = {
  26902. key: key,
  26903. axis: axis,
  26904. coordSys: coordSys,
  26905. axisPointerModel: axisPointerModel,
  26906. triggerTooltip: triggerTooltip,
  26907. involveSeries: involveSeries,
  26908. snap: snap,
  26909. useHandle: isHandleTrigger(axisPointerModel),
  26910. seriesModels: []
  26911. };
  26912. axesInfoInCoordSys[key] = axisInfo;
  26913. result.seriesInvolved |= involveSeries;
  26914. var groupIndex = getLinkGroupIndex(linksOption, axis);
  26915. if (groupIndex != null) {
  26916. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  26917. linkGroup.axesInfo[key] = axisInfo;
  26918. linkGroup.mapper = linksOption[groupIndex].mapper;
  26919. axisInfo.linkGroup = linkGroup;
  26920. }
  26921. }
  26922. });
  26923. }
  26924. function makeAxisPointerModel(
  26925. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  26926. ) {
  26927. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  26928. var volatileOption = {};
  26929. each$9(
  26930. [
  26931. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  26932. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  26933. ],
  26934. function (field) {
  26935. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  26936. }
  26937. );
  26938. // category axis do not auto snap, otherwise some tick that do not
  26939. // has value can not be hovered. value/time/log axis default snap if
  26940. // triggered from tooltip and trigger tooltip.
  26941. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  26942. // Compatibel with previous behavior, tooltip axis do not show label by default.
  26943. // Only these properties can be overrided from tooltip to axisPointer.
  26944. if (tooltipAxisPointerModel.get('type') === 'cross') {
  26945. volatileOption.type = 'line';
  26946. }
  26947. var labelOption = volatileOption.label || (volatileOption.label = {});
  26948. // Follow the convention, do not show label when triggered by tooltip by default.
  26949. labelOption.show == null && (labelOption.show = false);
  26950. if (fromTooltip === 'cross') {
  26951. // When 'cross', both axes show labels.
  26952. labelOption.show = true;
  26953. // If triggerTooltip, this is a base axis, which should better not use cross style
  26954. // (cross style is dashed by default)
  26955. if (!triggerTooltip) {
  26956. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  26957. crossStyle && defaults(labelOption, crossStyle.textStyle);
  26958. }
  26959. }
  26960. return axis.model.getModel(
  26961. 'axisPointer',
  26962. new Model(volatileOption, globalAxisPointerModel, ecModel)
  26963. );
  26964. }
  26965. function collectSeriesInfo(result, ecModel) {
  26966. // Prepare data for axis trigger
  26967. ecModel.eachSeries(function (seriesModel) {
  26968. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  26969. var coordSys = seriesModel.coordinateSystem;
  26970. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  26971. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  26972. if (!coordSys
  26973. || seriesTooltipTrigger === 'none'
  26974. || seriesTooltipTrigger === false
  26975. || seriesTooltipTrigger === 'item'
  26976. || seriesTooltipShow === false
  26977. || seriesModel.get('axisPointer.show', true) === false
  26978. ) {
  26979. return;
  26980. }
  26981. each$9(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  26982. var axis = axisInfo.axis;
  26983. if (coordSys.getAxis(axis.dim) === axis) {
  26984. axisInfo.seriesModels.push(seriesModel);
  26985. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  26986. axisInfo.seriesDataCount += seriesModel.getData().count();
  26987. }
  26988. });
  26989. }, this);
  26990. }
  26991. /**
  26992. * For example:
  26993. * {
  26994. * axisPointer: {
  26995. * links: [{
  26996. * xAxisIndex: [2, 4],
  26997. * yAxisIndex: 'all'
  26998. * }, {
  26999. * xAxisId: ['a5', 'a7'],
  27000. * xAxisName: 'xxx'
  27001. * }]
  27002. * }
  27003. * }
  27004. */
  27005. function getLinkGroupIndex(linksOption, axis) {
  27006. var axisModel = axis.model;
  27007. var dim = axis.dim;
  27008. for (var i = 0; i < linksOption.length; i++) {
  27009. var linkOption = linksOption[i] || {};
  27010. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  27011. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  27012. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  27013. ) {
  27014. return i;
  27015. }
  27016. }
  27017. }
  27018. function checkPropInLink(linkPropValue, axisPropValue) {
  27019. return linkPropValue === 'all'
  27020. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  27021. || linkPropValue === axisPropValue;
  27022. }
  27023. function fixValue(axisModel) {
  27024. var axisInfo = getAxisInfo(axisModel);
  27025. if (!axisInfo) {
  27026. return;
  27027. }
  27028. var axisPointerModel = axisInfo.axisPointerModel;
  27029. var scale = axisInfo.axis.scale;
  27030. var option = axisPointerModel.option;
  27031. var status = axisPointerModel.get('status');
  27032. var value = axisPointerModel.get('value');
  27033. // Parse init value for category and time axis.
  27034. if (value != null) {
  27035. value = scale.parse(value);
  27036. }
  27037. var useHandle = isHandleTrigger(axisPointerModel);
  27038. // If `handle` used, `axisPointer` will always be displayed, so value
  27039. // and status should be initialized.
  27040. if (status == null) {
  27041. option.status = useHandle ? 'show' : 'hide';
  27042. }
  27043. var extent = scale.getExtent().slice();
  27044. extent[0] > extent[1] && extent.reverse();
  27045. if (// Pick a value on axis when initializing.
  27046. value == null
  27047. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  27048. // where we should re-pick a value to keep `handle` displaying normally.
  27049. || value > extent[1]
  27050. ) {
  27051. // Make handle displayed on the end of the axis when init, which looks better.
  27052. value = extent[1];
  27053. }
  27054. if (value < extent[0]) {
  27055. value = extent[0];
  27056. }
  27057. option.value = value;
  27058. if (useHandle) {
  27059. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  27060. }
  27061. }
  27062. function getAxisInfo(axisModel) {
  27063. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  27064. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  27065. }
  27066. function getAxisPointerModel(axisModel) {
  27067. var axisInfo = getAxisInfo(axisModel);
  27068. return axisInfo && axisInfo.axisPointerModel;
  27069. }
  27070. function isHandleTrigger(axisPointerModel) {
  27071. return !!axisPointerModel.get('handle.show');
  27072. }
  27073. /**
  27074. * @param {module:echarts/model/Model} model
  27075. * @return {string} unique key
  27076. */
  27077. function makeKey(model) {
  27078. return model.type + '||' + model.id;
  27079. }
  27080. /**
  27081. * Base class of AxisView.
  27082. */
  27083. var AxisView = extendComponentView({
  27084. type: 'axis',
  27085. /**
  27086. * @private
  27087. */
  27088. _axisPointer: null,
  27089. /**
  27090. * @protected
  27091. * @type {string}
  27092. */
  27093. axisPointerClass: null,
  27094. /**
  27095. * @override
  27096. */
  27097. render: function (axisModel, ecModel, api, payload) {
  27098. // FIXME
  27099. // This process should proformed after coordinate systems updated
  27100. // (axis scale updated), and should be performed each time update.
  27101. // So put it here temporarily, although it is not appropriate to
  27102. // put a model-writing procedure in `view`.
  27103. this.axisPointerClass && fixValue(axisModel);
  27104. AxisView.superApply(this, 'render', arguments);
  27105. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  27106. },
  27107. /**
  27108. * Action handler.
  27109. * @public
  27110. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27111. * @param {module:echarts/model/Global} ecModel
  27112. * @param {module:echarts/ExtensionAPI} api
  27113. * @param {Object} payload
  27114. */
  27115. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  27116. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  27117. },
  27118. /**
  27119. * @override
  27120. */
  27121. remove: function (ecModel, api) {
  27122. var axisPointer = this._axisPointer;
  27123. axisPointer && axisPointer.remove(api);
  27124. AxisView.superApply(this, 'remove', arguments);
  27125. },
  27126. /**
  27127. * @override
  27128. */
  27129. dispose: function (ecModel, api) {
  27130. disposeAxisPointer(this, api);
  27131. AxisView.superApply(this, 'dispose', arguments);
  27132. }
  27133. });
  27134. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  27135. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  27136. if (!Clazz) {
  27137. return;
  27138. }
  27139. var axisPointerModel = getAxisPointerModel(axisModel);
  27140. axisPointerModel
  27141. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  27142. .render(axisModel, axisPointerModel, api, forceRender)
  27143. : disposeAxisPointer(axisView, api);
  27144. }
  27145. function disposeAxisPointer(axisView, ecModel, api) {
  27146. var axisPointer = axisView._axisPointer;
  27147. axisPointer && axisPointer.dispose(ecModel, api);
  27148. axisView._axisPointer = null;
  27149. }
  27150. var axisPointerClazz = [];
  27151. AxisView.registerAxisPointerClass = function (type, clazz) {
  27152. if (__DEV__) {
  27153. if (axisPointerClazz[type]) {
  27154. throw new Error('axisPointer ' + type + ' exists');
  27155. }
  27156. }
  27157. axisPointerClazz[type] = clazz;
  27158. };
  27159. AxisView.getAxisPointerClass = function (type) {
  27160. return type && axisPointerClazz[type];
  27161. };
  27162. /**
  27163. * @param {Object} opt {labelInside}
  27164. * @return {Object} {
  27165. * position, rotation, labelDirection, labelOffset,
  27166. * tickDirection, labelRotate, labelInterval, z2
  27167. * }
  27168. */
  27169. function layout(gridModel, axisModel, opt) {
  27170. opt = opt || {};
  27171. var grid = gridModel.coordinateSystem;
  27172. var axis = axisModel.axis;
  27173. var layout = {};
  27174. var rawAxisPosition = axis.position;
  27175. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  27176. var axisDim = axis.dim;
  27177. var rect = grid.getRect();
  27178. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  27179. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  27180. var axisOffset = axisModel.get('offset') || 0;
  27181. var posBound = axisDim === 'x'
  27182. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  27183. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  27184. if (axis.onZero) {
  27185. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  27186. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  27187. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  27188. }
  27189. // Axis position
  27190. layout.position = [
  27191. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  27192. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  27193. ];
  27194. // Axis rotation
  27195. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  27196. // Tick and label direction, x y is axisDim
  27197. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  27198. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  27199. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  27200. if (axisModel.get('axisTick.inside')) {
  27201. layout.tickDirection = -layout.tickDirection;
  27202. }
  27203. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  27204. layout.labelDirection = -layout.labelDirection;
  27205. }
  27206. // Special label rotation
  27207. var labelRotate = axisModel.get('axisLabel.rotate');
  27208. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  27209. // label interval when auto mode.
  27210. layout.labelInterval = axis.getLabelInterval();
  27211. // Over splitLine and splitArea
  27212. layout.z2 = 1;
  27213. return layout;
  27214. }
  27215. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  27216. var getInterval = AxisBuilder.getInterval;
  27217. var axisBuilderAttrs = [
  27218. 'axisLine', 'axisTickLabel', 'axisName'
  27219. ];
  27220. var selfBuilderAttrs = [
  27221. 'splitArea', 'splitLine'
  27222. ];
  27223. // function getAlignWithLabel(model, axisModel) {
  27224. // var alignWithLabel = model.get('alignWithLabel');
  27225. // if (alignWithLabel === 'auto') {
  27226. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  27227. // }
  27228. // return alignWithLabel;
  27229. // }
  27230. var CartesianAxisView = AxisView.extend({
  27231. type: 'cartesianAxis',
  27232. axisPointerClass: 'CartesianAxisPointer',
  27233. /**
  27234. * @override
  27235. */
  27236. render: function (axisModel, ecModel, api, payload) {
  27237. this.group.removeAll();
  27238. var oldAxisGroup = this._axisGroup;
  27239. this._axisGroup = new Group();
  27240. this.group.add(this._axisGroup);
  27241. if (!axisModel.get('show')) {
  27242. return;
  27243. }
  27244. var gridModel = axisModel.getCoordSysModel();
  27245. var layout$$1 = layout(gridModel, axisModel);
  27246. var axisBuilder = new AxisBuilder(axisModel, layout$$1);
  27247. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  27248. this._axisGroup.add(axisBuilder.getGroup());
  27249. each$1(selfBuilderAttrs, function (name) {
  27250. if (axisModel.get(name + '.show')) {
  27251. this['_' + name](axisModel, gridModel, layout$$1.labelInterval);
  27252. }
  27253. }, this);
  27254. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  27255. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  27256. },
  27257. /**
  27258. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27259. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  27260. * @param {number|Function} labelInterval
  27261. * @private
  27262. */
  27263. _splitLine: function (axisModel, gridModel, labelInterval) {
  27264. var axis = axisModel.axis;
  27265. if (axis.scale.isBlank()) {
  27266. return;
  27267. }
  27268. var splitLineModel = axisModel.getModel('splitLine');
  27269. var lineStyleModel = splitLineModel.getModel('lineStyle');
  27270. var lineColors = lineStyleModel.get('color');
  27271. var lineInterval = getInterval(splitLineModel, labelInterval);
  27272. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  27273. var gridRect = gridModel.coordinateSystem.getRect();
  27274. var isHorizontal = axis.isHorizontal();
  27275. var lineCount = 0;
  27276. var ticksCoords = axis.getTicksCoords(
  27277. // splitLineModel.get('alignWithLabel')
  27278. );
  27279. var ticks = axis.scale.getTicks();
  27280. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  27281. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  27282. var p1 = [];
  27283. var p2 = [];
  27284. // Simple optimization
  27285. // Batching the lines if color are the same
  27286. var lineStyle = lineStyleModel.getLineStyle();
  27287. for (var i = 0; i < ticksCoords.length; i++) {
  27288. if (ifIgnoreOnTick(
  27289. axis, i, lineInterval, ticksCoords.length,
  27290. showMinLabel, showMaxLabel
  27291. )) {
  27292. continue;
  27293. }
  27294. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  27295. if (isHorizontal) {
  27296. p1[0] = tickCoord;
  27297. p1[1] = gridRect.y;
  27298. p2[0] = tickCoord;
  27299. p2[1] = gridRect.y + gridRect.height;
  27300. }
  27301. else {
  27302. p1[0] = gridRect.x;
  27303. p1[1] = tickCoord;
  27304. p2[0] = gridRect.x + gridRect.width;
  27305. p2[1] = tickCoord;
  27306. }
  27307. var colorIndex = (lineCount++) % lineColors.length;
  27308. this._axisGroup.add(new Line(subPixelOptimizeLine({
  27309. anid: 'line_' + ticks[i],
  27310. shape: {
  27311. x1: p1[0],
  27312. y1: p1[1],
  27313. x2: p2[0],
  27314. y2: p2[1]
  27315. },
  27316. style: defaults({
  27317. stroke: lineColors[colorIndex]
  27318. }, lineStyle),
  27319. silent: true
  27320. })));
  27321. }
  27322. },
  27323. /**
  27324. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27325. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  27326. * @param {number|Function} labelInterval
  27327. * @private
  27328. */
  27329. _splitArea: function (axisModel, gridModel, labelInterval) {
  27330. var axis = axisModel.axis;
  27331. if (axis.scale.isBlank()) {
  27332. return;
  27333. }
  27334. var splitAreaModel = axisModel.getModel('splitArea');
  27335. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  27336. var areaColors = areaStyleModel.get('color');
  27337. var gridRect = gridModel.coordinateSystem.getRect();
  27338. var ticksCoords = axis.getTicksCoords(
  27339. // splitAreaModel.get('alignWithLabel')
  27340. );
  27341. var ticks = axis.scale.getTicks();
  27342. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  27343. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  27344. var count = 0;
  27345. var areaInterval = getInterval(splitAreaModel, labelInterval);
  27346. var areaStyle = areaStyleModel.getAreaStyle();
  27347. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  27348. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  27349. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  27350. for (var i = 1; i < ticksCoords.length; i++) {
  27351. if (ifIgnoreOnTick(
  27352. axis, i, areaInterval, ticksCoords.length,
  27353. showMinLabel, showMaxLabel
  27354. )) {
  27355. continue;
  27356. }
  27357. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  27358. var x;
  27359. var y;
  27360. var width;
  27361. var height;
  27362. if (axis.isHorizontal()) {
  27363. x = prevX;
  27364. y = gridRect.y;
  27365. width = tickCoord - x;
  27366. height = gridRect.height;
  27367. }
  27368. else {
  27369. x = gridRect.x;
  27370. y = prevY;
  27371. width = gridRect.width;
  27372. height = tickCoord - y;
  27373. }
  27374. var colorIndex = (count++) % areaColors.length;
  27375. this._axisGroup.add(new Rect({
  27376. anid: 'area_' + ticks[i],
  27377. shape: {
  27378. x: x,
  27379. y: y,
  27380. width: width,
  27381. height: height
  27382. },
  27383. style: defaults({
  27384. fill: areaColors[colorIndex]
  27385. }, areaStyle),
  27386. silent: true
  27387. }));
  27388. prevX = x + width;
  27389. prevY = y + height;
  27390. }
  27391. }
  27392. });
  27393. CartesianAxisView.extend({
  27394. type: 'xAxis'
  27395. });
  27396. CartesianAxisView.extend({
  27397. type: 'yAxis'
  27398. });
  27399. // Grid view
  27400. extendComponentView({
  27401. type: 'grid',
  27402. render: function (gridModel, ecModel) {
  27403. this.group.removeAll();
  27404. if (gridModel.get('show')) {
  27405. this.group.add(new Rect({
  27406. shape: gridModel.coordinateSystem.getRect(),
  27407. style: defaults({
  27408. fill: gridModel.get('backgroundColor')
  27409. }, gridModel.getItemStyle()),
  27410. silent: true,
  27411. z2: -1
  27412. }));
  27413. }
  27414. }
  27415. });
  27416. registerPreprocessor(function (option) {
  27417. // Only create grid when need
  27418. if (option.xAxis && option.yAxis && !option.grid) {
  27419. option.grid = {};
  27420. }
  27421. });
  27422. // In case developer forget to include grid component
  27423. registerVisual(curry(
  27424. visualSymbol, 'line', 'circle', 'line'
  27425. ));
  27426. registerLayout(curry(
  27427. layoutPoints, 'line'
  27428. ));
  27429. // Down sample after filter
  27430. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, curry(
  27431. dataSample, 'line'
  27432. ));
  27433. var STACK_PREFIX = '__ec_stack_';
  27434. function getSeriesStackId(seriesModel) {
  27435. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  27436. }
  27437. function getAxisKey(axis) {
  27438. return axis.dim + axis.index;
  27439. }
  27440. /**
  27441. * @param {Object} opt
  27442. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  27443. * @param {number} opt.count Positive interger.
  27444. * @param {number} [opt.barWidth]
  27445. * @param {number} [opt.barMaxWidth]
  27446. * @param {number} [opt.barGap]
  27447. * @param {number} [opt.barCategoryGap]
  27448. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  27449. */
  27450. function getLayoutOnAxis(opt, api) {
  27451. var params = [];
  27452. var baseAxis = opt.axis;
  27453. var axisKey = 'axis0';
  27454. if (baseAxis.type !== 'category') {
  27455. return;
  27456. }
  27457. var bandWidth = baseAxis.getBandWidth();
  27458. for (var i = 0; i < opt.count || 0; i++) {
  27459. params.push(defaults({
  27460. bandWidth: bandWidth,
  27461. axisKey: axisKey,
  27462. stackId: STACK_PREFIX + i
  27463. }, opt));
  27464. }
  27465. var widthAndOffsets = doCalBarWidthAndOffset(params, api);
  27466. var result = [];
  27467. for (var i = 0; i < opt.count; i++) {
  27468. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  27469. item.offsetCenter = item.offset + item.width / 2;
  27470. result.push(item);
  27471. }
  27472. return result;
  27473. }
  27474. function calBarWidthAndOffset(barSeries, api) {
  27475. var seriesInfoList = map(barSeries, function (seriesModel) {
  27476. var data = seriesModel.getData();
  27477. var cartesian = seriesModel.coordinateSystem;
  27478. var baseAxis = cartesian.getBaseAxis();
  27479. var axisExtent = baseAxis.getExtent();
  27480. var bandWidth = baseAxis.type === 'category'
  27481. ? baseAxis.getBandWidth()
  27482. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  27483. var barWidth = parsePercent$1(
  27484. seriesModel.get('barWidth'), bandWidth
  27485. );
  27486. var barMaxWidth = parsePercent$1(
  27487. seriesModel.get('barMaxWidth'), bandWidth
  27488. );
  27489. var barGap = seriesModel.get('barGap');
  27490. var barCategoryGap = seriesModel.get('barCategoryGap');
  27491. return {
  27492. bandWidth: bandWidth,
  27493. barWidth: barWidth,
  27494. barMaxWidth: barMaxWidth,
  27495. barGap: barGap,
  27496. barCategoryGap: barCategoryGap,
  27497. axisKey: getAxisKey(baseAxis),
  27498. stackId: getSeriesStackId(seriesModel)
  27499. };
  27500. });
  27501. return doCalBarWidthAndOffset(seriesInfoList, api);
  27502. }
  27503. function doCalBarWidthAndOffset(seriesInfoList, api) {
  27504. // Columns info on each category axis. Key is cartesian name
  27505. var columnsMap = {};
  27506. each$1(seriesInfoList, function (seriesInfo, idx) {
  27507. var axisKey = seriesInfo.axisKey;
  27508. var bandWidth = seriesInfo.bandWidth;
  27509. var columnsOnAxis = columnsMap[axisKey] || {
  27510. bandWidth: bandWidth,
  27511. remainedWidth: bandWidth,
  27512. autoWidthCount: 0,
  27513. categoryGap: '20%',
  27514. gap: '30%',
  27515. stacks: {}
  27516. };
  27517. var stacks = columnsOnAxis.stacks;
  27518. columnsMap[axisKey] = columnsOnAxis;
  27519. var stackId = seriesInfo.stackId;
  27520. if (!stacks[stackId]) {
  27521. columnsOnAxis.autoWidthCount++;
  27522. }
  27523. stacks[stackId] = stacks[stackId] || {
  27524. width: 0,
  27525. maxWidth: 0
  27526. };
  27527. // Caution: In a single coordinate system, these barGrid attributes
  27528. // will be shared by series. Consider that they have default values,
  27529. // only the attributes set on the last series will work.
  27530. // Do not change this fact unless there will be a break change.
  27531. // TODO
  27532. var barWidth = seriesInfo.barWidth;
  27533. if (barWidth && !stacks[stackId].width) {
  27534. // See #6312, do not restrict width.
  27535. stacks[stackId].width = barWidth;
  27536. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  27537. columnsOnAxis.remainedWidth -= barWidth;
  27538. }
  27539. var barMaxWidth = seriesInfo.barMaxWidth;
  27540. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  27541. var barGap = seriesInfo.barGap;
  27542. (barGap != null) && (columnsOnAxis.gap = barGap);
  27543. var barCategoryGap = seriesInfo.barCategoryGap;
  27544. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  27545. });
  27546. var result = {};
  27547. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  27548. result[coordSysName] = {};
  27549. var stacks = columnsOnAxis.stacks;
  27550. var bandWidth = columnsOnAxis.bandWidth;
  27551. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  27552. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  27553. var remainedWidth = columnsOnAxis.remainedWidth;
  27554. var autoWidthCount = columnsOnAxis.autoWidthCount;
  27555. var autoWidth = (remainedWidth - categoryGap)
  27556. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27557. autoWidth = Math.max(autoWidth, 0);
  27558. // Find if any auto calculated bar exceeded maxBarWidth
  27559. each$1(stacks, function (column, stack) {
  27560. var maxWidth = column.maxWidth;
  27561. if (maxWidth && maxWidth < autoWidth) {
  27562. maxWidth = Math.min(maxWidth, remainedWidth);
  27563. if (column.width) {
  27564. maxWidth = Math.min(maxWidth, column.width);
  27565. }
  27566. remainedWidth -= maxWidth;
  27567. column.width = maxWidth;
  27568. autoWidthCount--;
  27569. }
  27570. });
  27571. // Recalculate width again
  27572. autoWidth = (remainedWidth - categoryGap)
  27573. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27574. autoWidth = Math.max(autoWidth, 0);
  27575. var widthSum = 0;
  27576. var lastColumn;
  27577. each$1(stacks, function (column, idx) {
  27578. if (!column.width) {
  27579. column.width = autoWidth;
  27580. }
  27581. lastColumn = column;
  27582. widthSum += column.width * (1 + barGapPercent);
  27583. });
  27584. if (lastColumn) {
  27585. widthSum -= lastColumn.width * barGapPercent;
  27586. }
  27587. var offset = -widthSum / 2;
  27588. each$1(stacks, function (column, stackId) {
  27589. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  27590. offset: offset,
  27591. width: column.width
  27592. };
  27593. offset += column.width * (1 + barGapPercent);
  27594. });
  27595. });
  27596. return result;
  27597. }
  27598. /**
  27599. * @param {string} seriesType
  27600. * @param {module:echarts/model/Global} ecModel
  27601. * @param {module:echarts/ExtensionAPI} api
  27602. */
  27603. function barLayoutGrid(seriesType, ecModel, api) {
  27604. var barWidthAndOffset = calBarWidthAndOffset(
  27605. filter(
  27606. ecModel.getSeriesByType(seriesType),
  27607. function (seriesModel) {
  27608. return !ecModel.isSeriesFiltered(seriesModel)
  27609. && seriesModel.coordinateSystem
  27610. && seriesModel.coordinateSystem.type === 'cartesian2d';
  27611. }
  27612. )
  27613. );
  27614. var lastStackCoords = {};
  27615. var lastStackCoordsOrigin = {};
  27616. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  27617. // Check series coordinate, do layout for cartesian2d only
  27618. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  27619. return;
  27620. }
  27621. var data = seriesModel.getData();
  27622. var cartesian = seriesModel.coordinateSystem;
  27623. var baseAxis = cartesian.getBaseAxis();
  27624. var stackId = getSeriesStackId(seriesModel);
  27625. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27626. var columnOffset = columnLayoutInfo.offset;
  27627. var columnWidth = columnLayoutInfo.width;
  27628. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27629. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27630. var valueAxisStart = baseAxis.onZero
  27631. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  27632. : valueAxis.getGlobalExtent()[0];
  27633. var coordDims = [
  27634. seriesModel.coordDimToDataDim('x')[0],
  27635. seriesModel.coordDimToDataDim('y')[0]
  27636. ];
  27637. var coords = data.mapArray(coordDims, function (x, y) {
  27638. return cartesian.dataToPoint([x, y]);
  27639. }, true);
  27640. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27641. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  27642. data.setLayout({
  27643. offset: columnOffset,
  27644. size: columnWidth
  27645. });
  27646. data.each(seriesModel.coordDimToDataDim(valueAxis.dim)[0], function (value, idx) {
  27647. if (isNaN(value)) {
  27648. return;
  27649. }
  27650. if (!lastStackCoords[stackId][idx]) {
  27651. lastStackCoords[stackId][idx] = {
  27652. p: valueAxisStart, // Positive stack
  27653. n: valueAxisStart // Negative stack
  27654. };
  27655. lastStackCoordsOrigin[stackId][idx] = {
  27656. p: valueAxisStart, // Positive stack
  27657. n: valueAxisStart // Negative stack
  27658. };
  27659. }
  27660. var sign = value >= 0 ? 'p' : 'n';
  27661. var coord = coords[idx];
  27662. var lastCoord = lastStackCoords[stackId][idx][sign];
  27663. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  27664. var x;
  27665. var y;
  27666. var width;
  27667. var height;
  27668. if (valueAxis.isHorizontal()) {
  27669. x = lastCoord;
  27670. y = coord[1] + columnOffset;
  27671. width = coord[0] - lastCoordOrigin;
  27672. height = columnWidth;
  27673. lastStackCoordsOrigin[stackId][idx][sign] += width;
  27674. if (Math.abs(width) < barMinHeight) {
  27675. width = (width < 0 ? -1 : 1) * barMinHeight;
  27676. }
  27677. lastStackCoords[stackId][idx][sign] += width;
  27678. }
  27679. else {
  27680. x = coord[0] + columnOffset;
  27681. y = lastCoord;
  27682. width = columnWidth;
  27683. height = coord[1] - lastCoordOrigin;
  27684. lastStackCoordsOrigin[stackId][idx][sign] += height;
  27685. if (Math.abs(height) < barMinHeight) {
  27686. // Include zero to has a positive bar
  27687. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27688. }
  27689. lastStackCoords[stackId][idx][sign] += height;
  27690. }
  27691. data.setItemLayout(idx, {
  27692. x: x,
  27693. y: y,
  27694. width: width,
  27695. height: height
  27696. });
  27697. }, true);
  27698. }, this);
  27699. }
  27700. barLayoutGrid.getLayoutOnAxis = getLayoutOnAxis;
  27701. var BaseBarSeries = SeriesModel.extend({
  27702. type: 'series.__base_bar__',
  27703. getInitialData: function (option, ecModel) {
  27704. return createListFromArray(option.data, this, ecModel);
  27705. },
  27706. getMarkerPosition: function (value) {
  27707. var coordSys = this.coordinateSystem;
  27708. if (coordSys) {
  27709. // PENDING if clamp ?
  27710. var pt = coordSys.dataToPoint(value, true);
  27711. var data = this.getData();
  27712. var offset = data.getLayout('offset');
  27713. var size = data.getLayout('size');
  27714. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  27715. pt[offsetIndex] += offset + size / 2;
  27716. return pt;
  27717. }
  27718. return [NaN, NaN];
  27719. },
  27720. defaultOption: {
  27721. zlevel: 0, // 一级层叠
  27722. z: 2, // 二级层叠
  27723. coordinateSystem: 'cartesian2d',
  27724. legendHoverLink: true,
  27725. // stack: null
  27726. // Cartesian coordinate system
  27727. // xAxisIndex: 0,
  27728. // yAxisIndex: 0,
  27729. // 最小高度改为0
  27730. barMinHeight: 0,
  27731. // 最小角度为0,仅对极坐标系下的柱状图有效
  27732. barMinAngle: 0,
  27733. // cursor: null,
  27734. // barMaxWidth: null,
  27735. // 默认自适应
  27736. // barWidth: null,
  27737. // 柱间距离,默认为柱形宽度的30%,可设固定值
  27738. // barGap: '30%',
  27739. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  27740. // barCategoryGap: '20%',
  27741. // label: {
  27742. // normal: {
  27743. // show: false
  27744. // }
  27745. // },
  27746. itemStyle: {
  27747. // normal: {
  27748. // color: '各异'
  27749. // },
  27750. // emphasis: {}
  27751. }
  27752. }
  27753. });
  27754. BaseBarSeries.extend({
  27755. type: 'series.bar',
  27756. dependencies: ['grid', 'polar'],
  27757. brushSelector: 'rect'
  27758. });
  27759. function setLabel(
  27760. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  27761. ) {
  27762. var labelModel = itemModel.getModel('label.normal');
  27763. var hoverLabelModel = itemModel.getModel('label.emphasis');
  27764. setLabelStyle(
  27765. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  27766. {
  27767. labelFetcher: seriesModel,
  27768. labelDataIndex: dataIndex,
  27769. defaultText: seriesModel.getRawValue(dataIndex),
  27770. isRectText: true,
  27771. autoColor: color
  27772. }
  27773. );
  27774. fixPosition(normalStyle);
  27775. fixPosition(hoverStyle);
  27776. }
  27777. function fixPosition(style, labelPositionOutside) {
  27778. if (style.textPosition === 'outside') {
  27779. style.textPosition = labelPositionOutside;
  27780. }
  27781. }
  27782. var getBarItemStyle = makeStyleMapper(
  27783. [
  27784. ['fill', 'color'],
  27785. ['stroke', 'borderColor'],
  27786. ['lineWidth', 'borderWidth'],
  27787. // Compatitable with 2
  27788. ['stroke', 'barBorderColor'],
  27789. ['lineWidth', 'barBorderWidth'],
  27790. ['opacity'],
  27791. ['shadowBlur'],
  27792. ['shadowOffsetX'],
  27793. ['shadowOffsetY'],
  27794. ['shadowColor']
  27795. ]
  27796. );
  27797. var barItemStyle = {
  27798. getBarItemStyle: function (excludes) {
  27799. var style = getBarItemStyle(this, excludes);
  27800. if (this.getBorderLineDash) {
  27801. var lineDash = this.getBorderLineDash();
  27802. lineDash && (style.lineDash = lineDash);
  27803. }
  27804. return style;
  27805. }
  27806. };
  27807. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'normal', 'barBorderWidth'];
  27808. // FIXME
  27809. // Just for compatible with ec2.
  27810. extend(Model.prototype, barItemStyle);
  27811. extendChartView({
  27812. type: 'bar',
  27813. render: function (seriesModel, ecModel, api) {
  27814. var coordinateSystemType = seriesModel.get('coordinateSystem');
  27815. if (coordinateSystemType === 'cartesian2d'
  27816. || coordinateSystemType === 'polar'
  27817. ) {
  27818. this._render(seriesModel, ecModel, api);
  27819. }
  27820. else if (__DEV__) {
  27821. console.warn('Only cartesian2d and polar supported for bar.');
  27822. }
  27823. return this.group;
  27824. },
  27825. dispose: noop,
  27826. _render: function (seriesModel, ecModel, api) {
  27827. var group = this.group;
  27828. var data = seriesModel.getData();
  27829. var oldData = this._data;
  27830. var coord = seriesModel.coordinateSystem;
  27831. var baseAxis = coord.getBaseAxis();
  27832. var isHorizontalOrRadial;
  27833. if (coord.type === 'cartesian2d') {
  27834. isHorizontalOrRadial = baseAxis.isHorizontal();
  27835. }
  27836. else if (coord.type === 'polar') {
  27837. isHorizontalOrRadial = baseAxis.dim === 'angle';
  27838. }
  27839. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  27840. data.diff(oldData)
  27841. .add(function (dataIndex) {
  27842. if (!data.hasValue(dataIndex)) {
  27843. return;
  27844. }
  27845. var itemModel = data.getItemModel(dataIndex);
  27846. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  27847. var el = elementCreator[coord.type](
  27848. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  27849. );
  27850. data.setItemGraphicEl(dataIndex, el);
  27851. group.add(el);
  27852. updateStyle(
  27853. el, data, dataIndex, itemModel, layout,
  27854. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  27855. );
  27856. })
  27857. .update(function (newIndex, oldIndex) {
  27858. var el = oldData.getItemGraphicEl(oldIndex);
  27859. if (!data.hasValue(newIndex)) {
  27860. group.remove(el);
  27861. return;
  27862. }
  27863. var itemModel = data.getItemModel(newIndex);
  27864. var layout = getLayout[coord.type](data, newIndex, itemModel);
  27865. if (el) {
  27866. updateProps(el, {shape: layout}, animationModel, newIndex);
  27867. }
  27868. else {
  27869. el = elementCreator[coord.type](
  27870. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  27871. );
  27872. }
  27873. data.setItemGraphicEl(newIndex, el);
  27874. // Add back
  27875. group.add(el);
  27876. updateStyle(
  27877. el, data, newIndex, itemModel, layout,
  27878. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  27879. );
  27880. })
  27881. .remove(function (dataIndex) {
  27882. var el = oldData.getItemGraphicEl(dataIndex);
  27883. if (coord.type === 'cartesian2d') {
  27884. el && removeRect(dataIndex, animationModel, el);
  27885. }
  27886. else {
  27887. el && removeSector(dataIndex, animationModel, el);
  27888. }
  27889. })
  27890. .execute();
  27891. this._data = data;
  27892. },
  27893. remove: function (ecModel, api) {
  27894. var group = this.group;
  27895. var data = this._data;
  27896. if (ecModel.get('animation')) {
  27897. if (data) {
  27898. data.eachItemGraphicEl(function (el) {
  27899. if (el.type === 'sector') {
  27900. removeSector(el.dataIndex, ecModel, el);
  27901. }
  27902. else {
  27903. removeRect(el.dataIndex, ecModel, el);
  27904. }
  27905. });
  27906. }
  27907. }
  27908. else {
  27909. group.removeAll();
  27910. }
  27911. }
  27912. });
  27913. var elementCreator = {
  27914. cartesian2d: function (
  27915. data, dataIndex, itemModel, layout, isHorizontal,
  27916. animationModel, isUpdate
  27917. ) {
  27918. var rect = new Rect({shape: extend({}, layout)});
  27919. // Animation
  27920. if (animationModel) {
  27921. var rectShape = rect.shape;
  27922. var animateProperty = isHorizontal ? 'height' : 'width';
  27923. var animateTarget = {};
  27924. rectShape[animateProperty] = 0;
  27925. animateTarget[animateProperty] = layout[animateProperty];
  27926. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  27927. shape: animateTarget
  27928. }, animationModel, dataIndex);
  27929. }
  27930. return rect;
  27931. },
  27932. polar: function (
  27933. data, dataIndex, itemModel, layout, isRadial,
  27934. animationModel, isUpdate
  27935. ) {
  27936. var sector = new Sector({shape: extend({}, layout)});
  27937. // Animation
  27938. if (animationModel) {
  27939. var sectorShape = sector.shape;
  27940. var animateProperty = isRadial ? 'r' : 'endAngle';
  27941. var animateTarget = {};
  27942. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  27943. animateTarget[animateProperty] = layout[animateProperty];
  27944. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  27945. shape: animateTarget
  27946. }, animationModel, dataIndex);
  27947. }
  27948. return sector;
  27949. }
  27950. };
  27951. function removeRect(dataIndex, animationModel, el) {
  27952. // Not show text when animating
  27953. el.style.text = null;
  27954. updateProps(el, {
  27955. shape: {
  27956. width: 0
  27957. }
  27958. }, animationModel, dataIndex, function () {
  27959. el.parent && el.parent.remove(el);
  27960. });
  27961. }
  27962. function removeSector(dataIndex, animationModel, el) {
  27963. // Not show text when animating
  27964. el.style.text = null;
  27965. updateProps(el, {
  27966. shape: {
  27967. r: el.shape.r0
  27968. }
  27969. }, animationModel, dataIndex, function () {
  27970. el.parent && el.parent.remove(el);
  27971. });
  27972. }
  27973. var getLayout = {
  27974. cartesian2d: function (data, dataIndex, itemModel) {
  27975. var layout = data.getItemLayout(dataIndex);
  27976. var fixedLineWidth = getLineWidth(itemModel, layout);
  27977. // fix layout with lineWidth
  27978. var signX = layout.width > 0 ? 1 : -1;
  27979. var signY = layout.height > 0 ? 1 : -1;
  27980. return {
  27981. x: layout.x + signX * fixedLineWidth / 2,
  27982. y: layout.y + signY * fixedLineWidth / 2,
  27983. width: layout.width - signX * fixedLineWidth,
  27984. height: layout.height - signY * fixedLineWidth
  27985. };
  27986. },
  27987. polar: function (data, dataIndex, itemModel) {
  27988. var layout = data.getItemLayout(dataIndex);
  27989. return {
  27990. cx: layout.cx,
  27991. cy: layout.cy,
  27992. r0: layout.r0,
  27993. r: layout.r,
  27994. startAngle: layout.startAngle,
  27995. endAngle: layout.endAngle
  27996. };
  27997. }
  27998. };
  27999. function updateStyle(
  28000. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  28001. ) {
  28002. var color = data.getItemVisual(dataIndex, 'color');
  28003. var opacity = data.getItemVisual(dataIndex, 'opacity');
  28004. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  28005. var hoverStyle = itemModel.getModel('itemStyle.emphasis').getBarItemStyle();
  28006. if (!isPolar) {
  28007. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  28008. }
  28009. el.useStyle(defaults(
  28010. {
  28011. fill: color,
  28012. opacity: opacity
  28013. },
  28014. itemStyleModel.getBarItemStyle()
  28015. ));
  28016. var cursorStyle = itemModel.getShallow('cursor');
  28017. cursorStyle && el.attr('cursor', cursorStyle);
  28018. var labelPositionOutside = isHorizontal
  28019. ? (layout.height > 0 ? 'bottom' : 'top')
  28020. : (layout.width > 0 ? 'left' : 'right');
  28021. if (!isPolar) {
  28022. setLabel(
  28023. el.style, hoverStyle, itemModel, color,
  28024. seriesModel, dataIndex, labelPositionOutside
  28025. );
  28026. }
  28027. setHoverStyle(el, hoverStyle);
  28028. }
  28029. // In case width or height are too small.
  28030. function getLineWidth(itemModel, rawLayout) {
  28031. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  28032. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  28033. }
  28034. // In case developer forget to include grid component
  28035. registerLayout(curry(barLayoutGrid, 'bar'));
  28036. // Visual coding for legend
  28037. registerVisual(function (ecModel) {
  28038. ecModel.eachSeriesByType('bar', function (seriesModel) {
  28039. var data = seriesModel.getData();
  28040. data.setVisual('legendSymbol', 'roundRect');
  28041. });
  28042. });
  28043. /**
  28044. * Data selectable mixin for chart series.
  28045. * To eanble data select, option of series must have `selectedMode`.
  28046. * And each data item will use `selected` to toggle itself selected status
  28047. */
  28048. var selectableMixin = {
  28049. updateSelectedMap: function (targetList) {
  28050. this._targetList = targetList.slice();
  28051. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  28052. targetMap.set(target.name, target);
  28053. return targetMap;
  28054. }, createHashMap());
  28055. },
  28056. /**
  28057. * Either name or id should be passed as input here.
  28058. * If both of them are defined, id is used.
  28059. *
  28060. * @param {string|undefined} name name of data
  28061. * @param {number|undefined} id dataIndex of data
  28062. */
  28063. // PENGING If selectedMode is null ?
  28064. select: function (name, id) {
  28065. var target = id != null
  28066. ? this._targetList[id]
  28067. : this._selectTargetMap.get(name);
  28068. var selectedMode = this.get('selectedMode');
  28069. if (selectedMode === 'single') {
  28070. this._selectTargetMap.each(function (target) {
  28071. target.selected = false;
  28072. });
  28073. }
  28074. target && (target.selected = true);
  28075. },
  28076. /**
  28077. * Either name or id should be passed as input here.
  28078. * If both of them are defined, id is used.
  28079. *
  28080. * @param {string|undefined} name name of data
  28081. * @param {number|undefined} id dataIndex of data
  28082. */
  28083. unSelect: function (name, id) {
  28084. var target = id != null
  28085. ? this._targetList[id]
  28086. : this._selectTargetMap.get(name);
  28087. // var selectedMode = this.get('selectedMode');
  28088. // selectedMode !== 'single' && target && (target.selected = false);
  28089. target && (target.selected = false);
  28090. },
  28091. /**
  28092. * Either name or id should be passed as input here.
  28093. * If both of them are defined, id is used.
  28094. *
  28095. * @param {string|undefined} name name of data
  28096. * @param {number|undefined} id dataIndex of data
  28097. */
  28098. toggleSelected: function (name, id) {
  28099. var target = id != null
  28100. ? this._targetList[id]
  28101. : this._selectTargetMap.get(name);
  28102. if (target != null) {
  28103. this[target.selected ? 'unSelect' : 'select'](name, id);
  28104. return target.selected;
  28105. }
  28106. },
  28107. /**
  28108. * Either name or id should be passed as input here.
  28109. * If both of them are defined, id is used.
  28110. *
  28111. * @param {string|undefined} name name of data
  28112. * @param {number|undefined} id dataIndex of data
  28113. */
  28114. isSelected: function (name, id) {
  28115. var target = id != null
  28116. ? this._targetList[id]
  28117. : this._selectTargetMap.get(name);
  28118. return target && target.selected;
  28119. }
  28120. };
  28121. var PieSeries = extendSeriesModel({
  28122. type: 'series.pie',
  28123. // Overwrite
  28124. init: function (option) {
  28125. PieSeries.superApply(this, 'init', arguments);
  28126. // Enable legend selection for each data item
  28127. // Use a function instead of direct access because data reference may changed
  28128. this.legendDataProvider = function () {
  28129. return this.getRawData();
  28130. };
  28131. this.updateSelectedMap(option.data);
  28132. this._defaultLabelLine(option);
  28133. },
  28134. // Overwrite
  28135. mergeOption: function (newOption) {
  28136. PieSeries.superCall(this, 'mergeOption', newOption);
  28137. this.updateSelectedMap(this.option.data);
  28138. },
  28139. getInitialData: function (option, ecModel) {
  28140. var dimensions = completeDimensions(['value'], option.data);
  28141. var list = new List(dimensions, this);
  28142. list.initData(option.data);
  28143. return list;
  28144. },
  28145. // Overwrite
  28146. getDataParams: function (dataIndex) {
  28147. var data = this.getData();
  28148. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  28149. // FIXME toFixed?
  28150. var valueList = [];
  28151. data.each('value', function (value) {
  28152. valueList.push(value);
  28153. });
  28154. params.percent = getPercentWithPrecision(
  28155. valueList,
  28156. dataIndex,
  28157. data.hostModel.get('percentPrecision')
  28158. );
  28159. params.$vars.push('percent');
  28160. return params;
  28161. },
  28162. _defaultLabelLine: function (option) {
  28163. // Extend labelLine emphasis
  28164. defaultEmphasis(option.labelLine, ['show']);
  28165. var labelLineNormalOpt = option.labelLine.normal;
  28166. var labelLineEmphasisOpt = option.labelLine.emphasis;
  28167. // Not show label line if `label.normal.show = false`
  28168. labelLineNormalOpt.show = labelLineNormalOpt.show
  28169. && option.label.normal.show;
  28170. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  28171. && option.label.emphasis.show;
  28172. },
  28173. defaultOption: {
  28174. zlevel: 0,
  28175. z: 2,
  28176. legendHoverLink: true,
  28177. hoverAnimation: true,
  28178. // 默认全局居中
  28179. center: ['50%', '50%'],
  28180. radius: [0, '75%'],
  28181. // 默认顺时针
  28182. clockwise: true,
  28183. startAngle: 90,
  28184. // 最小角度改为0
  28185. minAngle: 0,
  28186. // 选中时扇区偏移量
  28187. selectedOffset: 10,
  28188. // 高亮扇区偏移量
  28189. hoverOffset: 10,
  28190. // If use strategy to avoid label overlapping
  28191. avoidLabelOverlap: true,
  28192. // 选择模式,默认关闭,可选single,multiple
  28193. // selectedMode: false,
  28194. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  28195. // roseType: null,
  28196. percentPrecision: 2,
  28197. // If still show when all data zero.
  28198. stillShowZeroSum: true,
  28199. // cursor: null,
  28200. label: {
  28201. normal: {
  28202. // If rotate around circle
  28203. rotate: false,
  28204. show: true,
  28205. // 'outer', 'inside', 'center'
  28206. position: 'outer'
  28207. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  28208. // 默认使用全局文本样式,详见TEXTSTYLE
  28209. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  28210. },
  28211. emphasis: {}
  28212. },
  28213. // Enabled when label.normal.position is 'outer'
  28214. labelLine: {
  28215. normal: {
  28216. show: true,
  28217. // 引导线两段中的第一段长度
  28218. length: 15,
  28219. // 引导线两段中的第二段长度
  28220. length2: 15,
  28221. smooth: false,
  28222. lineStyle: {
  28223. // color: 各异,
  28224. width: 1,
  28225. type: 'solid'
  28226. }
  28227. }
  28228. },
  28229. itemStyle: {
  28230. normal: {
  28231. borderWidth: 1
  28232. },
  28233. emphasis: {}
  28234. },
  28235. // Animation type canbe expansion, scale
  28236. animationType: 'expansion',
  28237. animationEasing: 'cubicOut',
  28238. data: []
  28239. }
  28240. });
  28241. mixin(PieSeries, selectableMixin);
  28242. /**
  28243. * @param {module:echarts/model/Series} seriesModel
  28244. * @param {boolean} hasAnimation
  28245. * @inner
  28246. */
  28247. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  28248. var data = seriesModel.getData();
  28249. var dataIndex = this.dataIndex;
  28250. var name = data.getName(dataIndex);
  28251. var selectedOffset = seriesModel.get('selectedOffset');
  28252. api.dispatchAction({
  28253. type: 'pieToggleSelect',
  28254. from: uid,
  28255. name: name,
  28256. seriesId: seriesModel.id
  28257. });
  28258. data.each(function (idx) {
  28259. toggleItemSelected(
  28260. data.getItemGraphicEl(idx),
  28261. data.getItemLayout(idx),
  28262. seriesModel.isSelected(data.getName(idx)),
  28263. selectedOffset,
  28264. hasAnimation
  28265. );
  28266. });
  28267. }
  28268. /**
  28269. * @param {module:zrender/graphic/Sector} el
  28270. * @param {Object} layout
  28271. * @param {boolean} isSelected
  28272. * @param {number} selectedOffset
  28273. * @param {boolean} hasAnimation
  28274. * @inner
  28275. */
  28276. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  28277. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  28278. var dx = Math.cos(midAngle);
  28279. var dy = Math.sin(midAngle);
  28280. var offset = isSelected ? selectedOffset : 0;
  28281. var position = [dx * offset, dy * offset];
  28282. hasAnimation
  28283. // animateTo will stop revious animation like update transition
  28284. ? el.animate()
  28285. .when(200, {
  28286. position: position
  28287. })
  28288. .start('bounceOut')
  28289. : el.attr('position', position);
  28290. }
  28291. /**
  28292. * Piece of pie including Sector, Label, LabelLine
  28293. * @constructor
  28294. * @extends {module:zrender/graphic/Group}
  28295. */
  28296. function PiePiece(data, idx) {
  28297. Group.call(this);
  28298. var sector = new Sector({
  28299. z2: 2
  28300. });
  28301. var polyline = new Polyline();
  28302. var text = new Text();
  28303. this.add(sector);
  28304. this.add(polyline);
  28305. this.add(text);
  28306. this.updateData(data, idx, true);
  28307. // Hover to change label and labelLine
  28308. function onEmphasis() {
  28309. polyline.ignore = polyline.hoverIgnore;
  28310. text.ignore = text.hoverIgnore;
  28311. }
  28312. function onNormal() {
  28313. polyline.ignore = polyline.normalIgnore;
  28314. text.ignore = text.normalIgnore;
  28315. }
  28316. this.on('emphasis', onEmphasis)
  28317. .on('normal', onNormal)
  28318. .on('mouseover', onEmphasis)
  28319. .on('mouseout', onNormal);
  28320. }
  28321. var piePieceProto = PiePiece.prototype;
  28322. piePieceProto.updateData = function (data, idx, firstCreate) {
  28323. var sector = this.childAt(0);
  28324. var seriesModel = data.hostModel;
  28325. var itemModel = data.getItemModel(idx);
  28326. var layout = data.getItemLayout(idx);
  28327. var sectorShape = extend({}, layout);
  28328. sectorShape.label = null;
  28329. if (firstCreate) {
  28330. sector.setShape(sectorShape);
  28331. var animationType = seriesModel.getShallow('animationType');
  28332. if (animationType === 'scale') {
  28333. sector.shape.r = layout.r0;
  28334. initProps(sector, {
  28335. shape: {
  28336. r: layout.r
  28337. }
  28338. }, seriesModel, idx);
  28339. }
  28340. // Expansion
  28341. else {
  28342. sector.shape.endAngle = layout.startAngle;
  28343. updateProps(sector, {
  28344. shape: {
  28345. endAngle: layout.endAngle
  28346. }
  28347. }, seriesModel, idx);
  28348. }
  28349. }
  28350. else {
  28351. updateProps(sector, {
  28352. shape: sectorShape
  28353. }, seriesModel, idx);
  28354. }
  28355. // Update common style
  28356. var itemStyleModel = itemModel.getModel('itemStyle');
  28357. var visualColor = data.getItemVisual(idx, 'color');
  28358. sector.useStyle(
  28359. defaults(
  28360. {
  28361. lineJoin: 'bevel',
  28362. fill: visualColor
  28363. },
  28364. itemStyleModel.getModel('normal').getItemStyle()
  28365. )
  28366. );
  28367. sector.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  28368. var cursorStyle = itemModel.getShallow('cursor');
  28369. cursorStyle && sector.attr('cursor', cursorStyle);
  28370. // Toggle selected
  28371. toggleItemSelected(
  28372. this,
  28373. data.getItemLayout(idx),
  28374. itemModel.get('selected'),
  28375. seriesModel.get('selectedOffset'),
  28376. seriesModel.get('animation')
  28377. );
  28378. function onEmphasis() {
  28379. // Sector may has animation of updating data. Force to move to the last frame
  28380. // Or it may stopped on the wrong shape
  28381. sector.stopAnimation(true);
  28382. sector.animateTo({
  28383. shape: {
  28384. r: layout.r + seriesModel.get('hoverOffset')
  28385. }
  28386. }, 300, 'elasticOut');
  28387. }
  28388. function onNormal() {
  28389. sector.stopAnimation(true);
  28390. sector.animateTo({
  28391. shape: {
  28392. r: layout.r
  28393. }
  28394. }, 300, 'elasticOut');
  28395. }
  28396. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  28397. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  28398. sector
  28399. .on('mouseover', onEmphasis)
  28400. .on('mouseout', onNormal)
  28401. .on('emphasis', onEmphasis)
  28402. .on('normal', onNormal);
  28403. }
  28404. this._updateLabel(data, idx);
  28405. setHoverStyle(this);
  28406. };
  28407. piePieceProto._updateLabel = function (data, idx) {
  28408. var labelLine = this.childAt(1);
  28409. var labelText = this.childAt(2);
  28410. var seriesModel = data.hostModel;
  28411. var itemModel = data.getItemModel(idx);
  28412. var layout = data.getItemLayout(idx);
  28413. var labelLayout = layout.label;
  28414. var visualColor = data.getItemVisual(idx, 'color');
  28415. updateProps(labelLine, {
  28416. shape: {
  28417. points: labelLayout.linePoints || [
  28418. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  28419. ]
  28420. }
  28421. }, seriesModel, idx);
  28422. updateProps(labelText, {
  28423. style: {
  28424. x: labelLayout.x,
  28425. y: labelLayout.y
  28426. }
  28427. }, seriesModel, idx);
  28428. labelText.attr({
  28429. rotation: labelLayout.rotation,
  28430. origin: [labelLayout.x, labelLayout.y],
  28431. z2: 10
  28432. });
  28433. var labelModel = itemModel.getModel('label.normal');
  28434. var labelHoverModel = itemModel.getModel('label.emphasis');
  28435. var labelLineModel = itemModel.getModel('labelLine.normal');
  28436. var labelLineHoverModel = itemModel.getModel('labelLine.emphasis');
  28437. var visualColor = data.getItemVisual(idx, 'color');
  28438. setLabelStyle(
  28439. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  28440. {
  28441. labelFetcher: data.hostModel,
  28442. labelDataIndex: idx,
  28443. defaultText: data.getName(idx),
  28444. autoColor: visualColor,
  28445. useInsideStyle: !!labelLayout.inside
  28446. },
  28447. {
  28448. textAlign: labelLayout.textAlign,
  28449. textVerticalAlign: labelLayout.verticalAlign,
  28450. opacity: data.getItemVisual(idx, 'opacity')
  28451. }
  28452. );
  28453. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  28454. labelText.hoverIgnore = !labelHoverModel.get('show');
  28455. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  28456. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  28457. // Default use item visual color
  28458. labelLine.setStyle({
  28459. stroke: visualColor,
  28460. opacity: data.getItemVisual(idx, 'opacity')
  28461. });
  28462. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  28463. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  28464. var smooth = labelLineModel.get('smooth');
  28465. if (smooth && smooth === true) {
  28466. smooth = 0.4;
  28467. }
  28468. labelLine.setShape({
  28469. smooth: smooth
  28470. });
  28471. };
  28472. inherits(PiePiece, Group);
  28473. // Pie view
  28474. var PieView = Chart.extend({
  28475. type: 'pie',
  28476. init: function () {
  28477. var sectorGroup = new Group();
  28478. this._sectorGroup = sectorGroup;
  28479. },
  28480. render: function (seriesModel, ecModel, api, payload) {
  28481. if (payload && (payload.from === this.uid)) {
  28482. return;
  28483. }
  28484. var data = seriesModel.getData();
  28485. var oldData = this._data;
  28486. var group = this.group;
  28487. var hasAnimation = ecModel.get('animation');
  28488. var isFirstRender = !oldData;
  28489. var animationType = seriesModel.get('animationType');
  28490. var onSectorClick = curry(
  28491. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  28492. );
  28493. var selectedMode = seriesModel.get('selectedMode');
  28494. data.diff(oldData)
  28495. .add(function (idx) {
  28496. var piePiece = new PiePiece(data, idx);
  28497. // Default expansion animation
  28498. if (isFirstRender && animationType !== 'scale') {
  28499. piePiece.eachChild(function (child) {
  28500. child.stopAnimation(true);
  28501. });
  28502. }
  28503. selectedMode && piePiece.on('click', onSectorClick);
  28504. data.setItemGraphicEl(idx, piePiece);
  28505. group.add(piePiece);
  28506. })
  28507. .update(function (newIdx, oldIdx) {
  28508. var piePiece = oldData.getItemGraphicEl(oldIdx);
  28509. piePiece.updateData(data, newIdx);
  28510. piePiece.off('click');
  28511. selectedMode && piePiece.on('click', onSectorClick);
  28512. group.add(piePiece);
  28513. data.setItemGraphicEl(newIdx, piePiece);
  28514. })
  28515. .remove(function (idx) {
  28516. var piePiece = oldData.getItemGraphicEl(idx);
  28517. group.remove(piePiece);
  28518. })
  28519. .execute();
  28520. if (
  28521. hasAnimation && isFirstRender && data.count() > 0
  28522. // Default expansion animation
  28523. && animationType !== 'scale'
  28524. ) {
  28525. var shape = data.getItemLayout(0);
  28526. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  28527. var removeClipPath = bind(group.removeClipPath, group);
  28528. group.setClipPath(this._createClipPath(
  28529. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  28530. ));
  28531. }
  28532. this._data = data;
  28533. },
  28534. dispose: function () {},
  28535. _createClipPath: function (
  28536. cx, cy, r, startAngle, clockwise, cb, seriesModel
  28537. ) {
  28538. var clipPath = new Sector({
  28539. shape: {
  28540. cx: cx,
  28541. cy: cy,
  28542. r0: 0,
  28543. r: r,
  28544. startAngle: startAngle,
  28545. endAngle: startAngle,
  28546. clockwise: clockwise
  28547. }
  28548. });
  28549. initProps(clipPath, {
  28550. shape: {
  28551. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  28552. }
  28553. }, seriesModel, cb);
  28554. return clipPath;
  28555. },
  28556. /**
  28557. * @implement
  28558. */
  28559. containPoint: function (point, seriesModel) {
  28560. var data = seriesModel.getData();
  28561. var itemLayout = data.getItemLayout(0);
  28562. if (itemLayout) {
  28563. var dx = point[0] - itemLayout.cx;
  28564. var dy = point[1] - itemLayout.cy;
  28565. var radius = Math.sqrt(dx * dx + dy * dy);
  28566. return radius <= itemLayout.r && radius >= itemLayout.r0;
  28567. }
  28568. }
  28569. });
  28570. var createDataSelectAction = function (seriesType, actionInfos) {
  28571. each$1(actionInfos, function (actionInfo) {
  28572. actionInfo.update = 'updateView';
  28573. /**
  28574. * @payload
  28575. * @property {string} seriesName
  28576. * @property {string} name
  28577. */
  28578. registerAction(actionInfo, function (payload, ecModel) {
  28579. var selected = {};
  28580. ecModel.eachComponent(
  28581. {mainType: 'series', subType: seriesType, query: payload},
  28582. function (seriesModel) {
  28583. if (seriesModel[actionInfo.method]) {
  28584. seriesModel[actionInfo.method](
  28585. payload.name,
  28586. payload.dataIndex
  28587. );
  28588. }
  28589. var data = seriesModel.getData();
  28590. // Create selected map
  28591. data.each(function (idx) {
  28592. var name = data.getName(idx);
  28593. selected[name] = seriesModel.isSelected(name)
  28594. || false;
  28595. });
  28596. }
  28597. );
  28598. return {
  28599. name: payload.name,
  28600. selected: selected
  28601. };
  28602. });
  28603. });
  28604. };
  28605. // Pick color from palette for each data item.
  28606. // Applicable for charts that require applying color palette
  28607. // in data level (like pie, funnel, chord).
  28608. var dataColor = function (seriesType, ecModel) {
  28609. // Pie and funnel may use diferrent scope
  28610. var paletteScope = {};
  28611. ecModel.eachRawSeriesByType(seriesType, function (seriesModel) {
  28612. var dataAll = seriesModel.getRawData();
  28613. var idxMap = {};
  28614. if (!ecModel.isSeriesFiltered(seriesModel)) {
  28615. var data = seriesModel.getData();
  28616. data.each(function (idx) {
  28617. var rawIdx = data.getRawIndex(idx);
  28618. idxMap[rawIdx] = idx;
  28619. });
  28620. dataAll.each(function (rawIdx) {
  28621. var filteredIdx = idxMap[rawIdx];
  28622. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  28623. var singleDataColor = filteredIdx != null
  28624. && data.getItemVisual(filteredIdx, 'color', true);
  28625. if (!singleDataColor) {
  28626. // FIXME Performance
  28627. var itemModel = dataAll.getItemModel(rawIdx);
  28628. var color = itemModel.get('itemStyle.normal.color')
  28629. || seriesModel.getColorFromPalette(dataAll.getName(rawIdx), paletteScope);
  28630. // Legend may use the visual info in data before processed
  28631. dataAll.setItemVisual(rawIdx, 'color', color);
  28632. // Data is not filtered
  28633. if (filteredIdx != null) {
  28634. data.setItemVisual(filteredIdx, 'color', color);
  28635. }
  28636. }
  28637. else {
  28638. // Set data all color for legend
  28639. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  28640. }
  28641. });
  28642. }
  28643. });
  28644. };
  28645. // FIXME emphasis label position is not same with normal label position
  28646. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  28647. list.sort(function (a, b) {
  28648. return a.y - b.y;
  28649. });
  28650. // 压
  28651. function shiftDown(start, end, delta, dir) {
  28652. for (var j = start; j < end; j++) {
  28653. list[j].y += delta;
  28654. if (j > start
  28655. && j + 1 < end
  28656. && list[j + 1].y > list[j].y + list[j].height
  28657. ) {
  28658. shiftUp(j, delta / 2);
  28659. return;
  28660. }
  28661. }
  28662. shiftUp(end - 1, delta / 2);
  28663. }
  28664. // 弹
  28665. function shiftUp(end, delta) {
  28666. for (var j = end; j >= 0; j--) {
  28667. list[j].y -= delta;
  28668. if (j > 0
  28669. && list[j].y > list[j - 1].y + list[j - 1].height
  28670. ) {
  28671. break;
  28672. }
  28673. }
  28674. }
  28675. function changeX(list, isDownList, cx, cy, r, dir) {
  28676. var lastDeltaX = dir > 0
  28677. ? isDownList // 右侧
  28678. ? Number.MAX_VALUE // 下
  28679. : 0 // 上
  28680. : isDownList // 左侧
  28681. ? Number.MAX_VALUE // 下
  28682. : 0; // 上
  28683. for (var i = 0, l = list.length; i < l; i++) {
  28684. // Not change x for center label
  28685. if (list[i].position === 'center') {
  28686. continue;
  28687. }
  28688. var deltaY = Math.abs(list[i].y - cy);
  28689. var length = list[i].len;
  28690. var length2 = list[i].len2;
  28691. var deltaX = (deltaY < r + length)
  28692. ? Math.sqrt(
  28693. (r + length + length2) * (r + length + length2)
  28694. - deltaY * deltaY
  28695. )
  28696. : Math.abs(list[i].x - cx);
  28697. if (isDownList && deltaX >= lastDeltaX) {
  28698. // 右下,左下
  28699. deltaX = lastDeltaX - 10;
  28700. }
  28701. if (!isDownList && deltaX <= lastDeltaX) {
  28702. // 右上,左上
  28703. deltaX = lastDeltaX + 10;
  28704. }
  28705. list[i].x = cx + deltaX * dir;
  28706. lastDeltaX = deltaX;
  28707. }
  28708. }
  28709. var lastY = 0;
  28710. var delta;
  28711. var len = list.length;
  28712. var upList = [];
  28713. var downList = [];
  28714. for (var i = 0; i < len; i++) {
  28715. delta = list[i].y - lastY;
  28716. if (delta < 0) {
  28717. shiftDown(i, len, -delta, dir);
  28718. }
  28719. lastY = list[i].y + list[i].height;
  28720. }
  28721. if (viewHeight - lastY < 0) {
  28722. shiftUp(len - 1, lastY - viewHeight);
  28723. }
  28724. for (var i = 0; i < len; i++) {
  28725. if (list[i].y >= cy) {
  28726. downList.push(list[i]);
  28727. }
  28728. else {
  28729. upList.push(list[i]);
  28730. }
  28731. }
  28732. changeX(upList, false, cx, cy, r, dir);
  28733. changeX(downList, true, cx, cy, r, dir);
  28734. }
  28735. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  28736. var leftList = [];
  28737. var rightList = [];
  28738. for (var i = 0; i < labelLayoutList.length; i++) {
  28739. if (labelLayoutList[i].x < cx) {
  28740. leftList.push(labelLayoutList[i]);
  28741. }
  28742. else {
  28743. rightList.push(labelLayoutList[i]);
  28744. }
  28745. }
  28746. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  28747. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  28748. for (var i = 0; i < labelLayoutList.length; i++) {
  28749. var linePoints = labelLayoutList[i].linePoints;
  28750. if (linePoints) {
  28751. var dist = linePoints[1][0] - linePoints[2][0];
  28752. if (labelLayoutList[i].x < cx) {
  28753. linePoints[2][0] = labelLayoutList[i].x + 3;
  28754. }
  28755. else {
  28756. linePoints[2][0] = labelLayoutList[i].x - 3;
  28757. }
  28758. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  28759. linePoints[1][0] = linePoints[2][0] + dist;
  28760. }
  28761. }
  28762. }
  28763. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  28764. var data = seriesModel.getData();
  28765. var labelLayoutList = [];
  28766. var cx;
  28767. var cy;
  28768. var hasLabelRotate = false;
  28769. data.each(function (idx) {
  28770. var layout = data.getItemLayout(idx);
  28771. var itemModel = data.getItemModel(idx);
  28772. var labelModel = itemModel.getModel('label.normal');
  28773. // Use position in normal or emphasis
  28774. var labelPosition = labelModel.get('position') || itemModel.get('label.emphasis.position');
  28775. var labelLineModel = itemModel.getModel('labelLine.normal');
  28776. var labelLineLen = labelLineModel.get('length');
  28777. var labelLineLen2 = labelLineModel.get('length2');
  28778. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  28779. var dx = Math.cos(midAngle);
  28780. var dy = Math.sin(midAngle);
  28781. var textX;
  28782. var textY;
  28783. var linePoints;
  28784. var textAlign;
  28785. cx = layout.cx;
  28786. cy = layout.cy;
  28787. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  28788. if (labelPosition === 'center') {
  28789. textX = layout.cx;
  28790. textY = layout.cy;
  28791. textAlign = 'center';
  28792. }
  28793. else {
  28794. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  28795. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  28796. textX = x1 + dx * 3;
  28797. textY = y1 + dy * 3;
  28798. if (!isLabelInside) {
  28799. // For roseType
  28800. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  28801. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  28802. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  28803. var y3 = y2;
  28804. textX = x3 + (dx < 0 ? -5 : 5);
  28805. textY = y3;
  28806. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  28807. }
  28808. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  28809. }
  28810. var font = labelModel.getFont();
  28811. var labelRotate = labelModel.get('rotate')
  28812. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  28813. var text = seriesModel.getFormattedLabel(idx, 'normal')
  28814. || data.getName(idx);
  28815. var textRect = getBoundingRect(
  28816. text, font, textAlign, 'top'
  28817. );
  28818. hasLabelRotate = !!labelRotate;
  28819. layout.label = {
  28820. x: textX,
  28821. y: textY,
  28822. position: labelPosition,
  28823. height: textRect.height,
  28824. len: labelLineLen,
  28825. len2: labelLineLen2,
  28826. linePoints: linePoints,
  28827. textAlign: textAlign,
  28828. verticalAlign: 'middle',
  28829. rotation: labelRotate,
  28830. inside: isLabelInside
  28831. };
  28832. // Not layout the inside label
  28833. if (!isLabelInside) {
  28834. labelLayoutList.push(layout.label);
  28835. }
  28836. });
  28837. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  28838. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  28839. }
  28840. };
  28841. var PI2$4 = Math.PI * 2;
  28842. var RADIAN = Math.PI / 180;
  28843. var pieLayout = function (seriesType, ecModel, api, payload) {
  28844. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28845. var center = seriesModel.get('center');
  28846. var radius = seriesModel.get('radius');
  28847. if (!isArray(radius)) {
  28848. radius = [0, radius];
  28849. }
  28850. if (!isArray(center)) {
  28851. center = [center, center];
  28852. }
  28853. var width = api.getWidth();
  28854. var height = api.getHeight();
  28855. var size = Math.min(width, height);
  28856. var cx = parsePercent$1(center[0], width);
  28857. var cy = parsePercent$1(center[1], height);
  28858. var r0 = parsePercent$1(radius[0], size / 2);
  28859. var r = parsePercent$1(radius[1], size / 2);
  28860. var data = seriesModel.getData();
  28861. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  28862. var minAngle = seriesModel.get('minAngle') * RADIAN;
  28863. var validDataCount = 0;
  28864. data.each('value', function (value) {
  28865. !isNaN(value) && validDataCount++;
  28866. });
  28867. var sum = data.getSum('value');
  28868. // Sum may be 0
  28869. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  28870. var clockwise = seriesModel.get('clockwise');
  28871. var roseType = seriesModel.get('roseType');
  28872. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  28873. // [0...max]
  28874. var extent = data.getDataExtent('value');
  28875. extent[0] = 0;
  28876. // In the case some sector angle is smaller than minAngle
  28877. var restAngle = PI2$4;
  28878. var valueSumLargerThanMinAngle = 0;
  28879. var currentAngle = startAngle;
  28880. var dir = clockwise ? 1 : -1;
  28881. data.each('value', function (value, idx) {
  28882. var angle;
  28883. if (isNaN(value)) {
  28884. data.setItemLayout(idx, {
  28885. angle: NaN,
  28886. startAngle: NaN,
  28887. endAngle: NaN,
  28888. clockwise: clockwise,
  28889. cx: cx,
  28890. cy: cy,
  28891. r0: r0,
  28892. r: roseType
  28893. ? NaN
  28894. : r
  28895. });
  28896. return;
  28897. }
  28898. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  28899. if (roseType !== 'area') {
  28900. angle = (sum === 0 && stillShowZeroSum)
  28901. ? unitRadian : (value * unitRadian);
  28902. }
  28903. else {
  28904. angle = PI2$4 / validDataCount;
  28905. }
  28906. if (angle < minAngle) {
  28907. angle = minAngle;
  28908. restAngle -= minAngle;
  28909. }
  28910. else {
  28911. valueSumLargerThanMinAngle += value;
  28912. }
  28913. var endAngle = currentAngle + dir * angle;
  28914. data.setItemLayout(idx, {
  28915. angle: angle,
  28916. startAngle: currentAngle,
  28917. endAngle: endAngle,
  28918. clockwise: clockwise,
  28919. cx: cx,
  28920. cy: cy,
  28921. r0: r0,
  28922. r: roseType
  28923. ? linearMap(value, extent, [r0, r])
  28924. : r
  28925. });
  28926. currentAngle = endAngle;
  28927. }, true);
  28928. // Some sector is constrained by minAngle
  28929. // Rest sectors needs recalculate angle
  28930. if (restAngle < PI2$4 && validDataCount) {
  28931. // Average the angle if rest angle is not enough after all angles is
  28932. // Constrained by minAngle
  28933. if (restAngle <= 1e-3) {
  28934. var angle = PI2$4 / validDataCount;
  28935. data.each('value', function (value, idx) {
  28936. if (!isNaN(value)) {
  28937. var layout = data.getItemLayout(idx);
  28938. layout.angle = angle;
  28939. layout.startAngle = startAngle + dir * idx * angle;
  28940. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  28941. }
  28942. });
  28943. }
  28944. else {
  28945. unitRadian = restAngle / valueSumLargerThanMinAngle;
  28946. currentAngle = startAngle;
  28947. data.each('value', function (value, idx) {
  28948. if (!isNaN(value)) {
  28949. var layout = data.getItemLayout(idx);
  28950. var angle = layout.angle === minAngle
  28951. ? minAngle : value * unitRadian;
  28952. layout.startAngle = currentAngle;
  28953. layout.endAngle = currentAngle + dir * angle;
  28954. currentAngle += dir * angle;
  28955. }
  28956. });
  28957. }
  28958. }
  28959. labelLayout(seriesModel, r, width, height);
  28960. });
  28961. };
  28962. var dataFilter = function (seriesType, ecModel) {
  28963. var legendModels = ecModel.findComponents({
  28964. mainType: 'legend'
  28965. });
  28966. if (!legendModels || !legendModels.length) {
  28967. return;
  28968. }
  28969. ecModel.eachSeriesByType(seriesType, function (series) {
  28970. var data = series.getData();
  28971. data.filterSelf(function (idx) {
  28972. var name = data.getName(idx);
  28973. // If in any legend component the status is not selected.
  28974. for (var i = 0; i < legendModels.length; i++) {
  28975. if (!legendModels[i].isSelected(name)) {
  28976. return false;
  28977. }
  28978. }
  28979. return true;
  28980. }, this);
  28981. }, this);
  28982. };
  28983. createDataSelectAction('pie', [{
  28984. type: 'pieToggleSelect',
  28985. event: 'pieselectchanged',
  28986. method: 'toggleSelected'
  28987. }, {
  28988. type: 'pieSelect',
  28989. event: 'pieselected',
  28990. method: 'select'
  28991. }, {
  28992. type: 'pieUnSelect',
  28993. event: 'pieunselected',
  28994. method: 'unSelect'
  28995. }]);
  28996. registerVisual(curry(dataColor, 'pie'));
  28997. registerLayout(curry(pieLayout, 'pie'));
  28998. registerProcessor(curry(dataFilter, 'pie'));
  28999. SeriesModel.extend({
  29000. type: 'series.scatter',
  29001. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  29002. getInitialData: function (option, ecModel) {
  29003. return createListFromArray(option.data, this, ecModel);
  29004. },
  29005. brushSelector: 'point',
  29006. defaultOption: {
  29007. coordinateSystem: 'cartesian2d',
  29008. zlevel: 0,
  29009. z: 2,
  29010. legendHoverLink: true,
  29011. hoverAnimation: true,
  29012. // Cartesian coordinate system
  29013. // xAxisIndex: 0,
  29014. // yAxisIndex: 0,
  29015. // Polar coordinate system
  29016. // polarIndex: 0,
  29017. // Geo coordinate system
  29018. // geoIndex: 0,
  29019. // symbol: null, // 图形类型
  29020. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  29021. // symbolRotate: null, // 图形旋转控制
  29022. large: false,
  29023. // Available when large is true
  29024. largeThreshold: 2000,
  29025. // cursor: null,
  29026. // label: {
  29027. // normal: {
  29028. // show: false
  29029. // distance: 5,
  29030. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  29031. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  29032. // 'inside'|'left'|'right'|'top'|'bottom'
  29033. // 默认使用全局文本样式,详见TEXTSTYLE
  29034. // }
  29035. // },
  29036. itemStyle: {
  29037. normal: {
  29038. opacity: 0.8
  29039. // color: 各异
  29040. }
  29041. }
  29042. }
  29043. });
  29044. // TODO Batch by color
  29045. var LargeSymbolPath = extendShape({
  29046. shape: {
  29047. points: null,
  29048. sizes: null
  29049. },
  29050. symbolProxy: null,
  29051. buildPath: function (path, shape) {
  29052. var points = shape.points;
  29053. var sizes = shape.sizes;
  29054. var symbolProxy = this.symbolProxy;
  29055. var symbolProxyShape = symbolProxy.shape;
  29056. for (var i = 0; i < points.length; i++) {
  29057. var pt = points[i];
  29058. if (isNaN(pt[0]) || isNaN(pt[1])) {
  29059. continue;
  29060. }
  29061. var size = sizes[i];
  29062. if (size[0] < 4) {
  29063. // Optimize for small symbol
  29064. path.rect(
  29065. pt[0] - size[0] / 2, pt[1] - size[1] / 2,
  29066. size[0], size[1]
  29067. );
  29068. }
  29069. else {
  29070. symbolProxyShape.x = pt[0] - size[0] / 2;
  29071. symbolProxyShape.y = pt[1] - size[1] / 2;
  29072. symbolProxyShape.width = size[0];
  29073. symbolProxyShape.height = size[1];
  29074. symbolProxy.buildPath(path, symbolProxyShape, true);
  29075. }
  29076. }
  29077. },
  29078. findDataIndex: function (x, y) {
  29079. var shape = this.shape;
  29080. var points = shape.points;
  29081. var sizes = shape.sizes;
  29082. // Not consider transform
  29083. // Treat each element as a rect
  29084. // top down traverse
  29085. for (var i = points.length - 1; i >= 0; i--) {
  29086. var pt = points[i];
  29087. var size = sizes[i];
  29088. var x0 = pt[0] - size[0] / 2;
  29089. var y0 = pt[1] - size[1] / 2;
  29090. if (x >= x0 && y >= y0 && x <= x0 + size[0] && y <= y0 + size[1]) {
  29091. // i is dataIndex
  29092. return i;
  29093. }
  29094. }
  29095. return -1;
  29096. }
  29097. });
  29098. function LargeSymbolDraw() {
  29099. this.group = new Group();
  29100. this._symbolEl = new LargeSymbolPath({
  29101. // rectHover: true,
  29102. // cursor: 'default'
  29103. });
  29104. }
  29105. var largeSymbolProto = LargeSymbolDraw.prototype;
  29106. /**
  29107. * Update symbols draw by new data
  29108. * @param {module:echarts/data/List} data
  29109. */
  29110. largeSymbolProto.updateData = function (data) {
  29111. this.group.removeAll();
  29112. var symbolEl = this._symbolEl;
  29113. var seriesModel = data.hostModel;
  29114. symbolEl.setShape({
  29115. points: data.mapArray(data.getItemLayout),
  29116. sizes: data.mapArray(
  29117. function (idx) {
  29118. var size = data.getItemVisual(idx, 'symbolSize');
  29119. if (!(size instanceof Array)) {
  29120. size = [size, size];
  29121. }
  29122. return size;
  29123. }
  29124. )
  29125. });
  29126. // Create symbolProxy to build path for each data
  29127. symbolEl.symbolProxy = createSymbol(
  29128. data.getVisual('symbol'), 0, 0, 0, 0
  29129. );
  29130. // Use symbolProxy setColor method
  29131. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  29132. symbolEl.useStyle(
  29133. seriesModel.getModel('itemStyle.normal').getItemStyle(['color'])
  29134. );
  29135. var visualColor = data.getVisual('color');
  29136. if (visualColor) {
  29137. symbolEl.setColor(visualColor);
  29138. }
  29139. // Enable tooltip
  29140. // PENDING May have performance issue when path is extremely large
  29141. symbolEl.seriesIndex = seriesModel.seriesIndex;
  29142. symbolEl.on('mousemove', function (e) {
  29143. symbolEl.dataIndex = null;
  29144. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  29145. if (dataIndex >= 0) {
  29146. // Provide dataIndex for tooltip
  29147. symbolEl.dataIndex = dataIndex;
  29148. }
  29149. });
  29150. // Add back
  29151. this.group.add(symbolEl);
  29152. };
  29153. largeSymbolProto.updateLayout = function (seriesModel) {
  29154. var data = seriesModel.getData();
  29155. this._symbolEl.setShape({
  29156. points: data.mapArray(data.getItemLayout)
  29157. });
  29158. };
  29159. largeSymbolProto.remove = function () {
  29160. this.group.removeAll();
  29161. };
  29162. extendChartView({
  29163. type: 'scatter',
  29164. init: function () {
  29165. this._normalSymbolDraw = new SymbolDraw();
  29166. this._largeSymbolDraw = new LargeSymbolDraw();
  29167. },
  29168. render: function (seriesModel, ecModel, api) {
  29169. var data = seriesModel.getData();
  29170. var largeSymbolDraw = this._largeSymbolDraw;
  29171. var normalSymbolDraw = this._normalSymbolDraw;
  29172. var group = this.group;
  29173. var symbolDraw = seriesModel.get('large') && data.count() > seriesModel.get('largeThreshold')
  29174. ? largeSymbolDraw : normalSymbolDraw;
  29175. this._symbolDraw = symbolDraw;
  29176. symbolDraw.updateData(data);
  29177. group.add(symbolDraw.group);
  29178. group.remove(
  29179. symbolDraw === largeSymbolDraw
  29180. ? normalSymbolDraw.group : largeSymbolDraw.group
  29181. );
  29182. },
  29183. updateLayout: function (seriesModel) {
  29184. this._symbolDraw.updateLayout(seriesModel);
  29185. },
  29186. remove: function (ecModel, api) {
  29187. this._symbolDraw && this._symbolDraw.remove(api, true);
  29188. },
  29189. dispose: function () {}
  29190. });
  29191. // In case developer forget to include grid component
  29192. registerVisual(curry(visualSymbol, 'scatter', 'circle', null));
  29193. registerLayout(curry(layoutPoints, 'scatter'));
  29194. function IndicatorAxis(dim, scale, radiusExtent) {
  29195. Axis.call(this, dim, scale, radiusExtent);
  29196. /**
  29197. * Axis type
  29198. * - 'category'
  29199. * - 'value'
  29200. * - 'time'
  29201. * - 'log'
  29202. * @type {string}
  29203. */
  29204. this.type = 'value';
  29205. this.angle = 0;
  29206. /**
  29207. * Indicator name
  29208. * @type {string}
  29209. */
  29210. this.name = '';
  29211. /**
  29212. * @type {module:echarts/model/Model}
  29213. */
  29214. this.model;
  29215. }
  29216. inherits(IndicatorAxis, Axis);
  29217. // TODO clockwise
  29218. function Radar(radarModel, ecModel, api) {
  29219. this._model = radarModel;
  29220. /**
  29221. * Radar dimensions
  29222. * @type {Array.<string>}
  29223. */
  29224. this.dimensions = [];
  29225. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  29226. var dim = 'indicator_' + idx;
  29227. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  29228. indicatorAxis.name = indicatorModel.get('name');
  29229. // Inject model and axis
  29230. indicatorAxis.model = indicatorModel;
  29231. indicatorModel.axis = indicatorAxis;
  29232. this.dimensions.push(dim);
  29233. return indicatorAxis;
  29234. }, this);
  29235. this.resize(radarModel, api);
  29236. /**
  29237. * @type {number}
  29238. * @readOnly
  29239. */
  29240. this.cx;
  29241. /**
  29242. * @type {number}
  29243. * @readOnly
  29244. */
  29245. this.cy;
  29246. /**
  29247. * @type {number}
  29248. * @readOnly
  29249. */
  29250. this.r;
  29251. /**
  29252. * @type {number}
  29253. * @readOnly
  29254. */
  29255. this.startAngle;
  29256. }
  29257. Radar.prototype.getIndicatorAxes = function () {
  29258. return this._indicatorAxes;
  29259. };
  29260. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  29261. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  29262. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  29263. };
  29264. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  29265. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  29266. var angle = indicatorAxis.angle;
  29267. var x = this.cx + coord * Math.cos(angle);
  29268. var y = this.cy - coord * Math.sin(angle);
  29269. return [x, y];
  29270. };
  29271. Radar.prototype.pointToData = function (pt) {
  29272. var dx = pt[0] - this.cx;
  29273. var dy = pt[1] - this.cy;
  29274. var radius = Math.sqrt(dx * dx + dy * dy);
  29275. dx /= radius;
  29276. dy /= radius;
  29277. var radian = Math.atan2(-dy, dx);
  29278. // Find the closest angle
  29279. // FIXME index can calculated directly
  29280. var minRadianDiff = Infinity;
  29281. var closestAxis;
  29282. var closestAxisIdx = -1;
  29283. for (var i = 0; i < this._indicatorAxes.length; i++) {
  29284. var indicatorAxis = this._indicatorAxes[i];
  29285. var diff = Math.abs(radian - indicatorAxis.angle);
  29286. if (diff < minRadianDiff) {
  29287. closestAxis = indicatorAxis;
  29288. closestAxisIdx = i;
  29289. minRadianDiff = diff;
  29290. }
  29291. }
  29292. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  29293. };
  29294. Radar.prototype.resize = function (radarModel, api) {
  29295. var center = radarModel.get('center');
  29296. var viewWidth = api.getWidth();
  29297. var viewHeight = api.getHeight();
  29298. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  29299. this.cx = parsePercent$1(center[0], viewWidth);
  29300. this.cy = parsePercent$1(center[1], viewHeight);
  29301. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  29302. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  29303. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  29304. indicatorAxis.setExtent(0, this.r);
  29305. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  29306. // Normalize to [-PI, PI]
  29307. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  29308. indicatorAxis.angle = angle;
  29309. }, this);
  29310. };
  29311. Radar.prototype.update = function (ecModel, api) {
  29312. var indicatorAxes = this._indicatorAxes;
  29313. var radarModel = this._model;
  29314. each$1(indicatorAxes, function (indicatorAxis) {
  29315. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  29316. });
  29317. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  29318. if (radarSeries.get('coordinateSystem') !== 'radar'
  29319. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  29320. ) {
  29321. return;
  29322. }
  29323. var data = radarSeries.getData();
  29324. each$1(indicatorAxes, function (indicatorAxis) {
  29325. indicatorAxis.scale.unionExtentFromData(data, indicatorAxis.dim);
  29326. });
  29327. }, this);
  29328. var splitNumber = radarModel.get('splitNumber');
  29329. function increaseInterval(interval) {
  29330. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  29331. // Increase interval
  29332. var f = interval / exp10;
  29333. if (f === 2) {
  29334. f = 5;
  29335. }
  29336. else { // f is 2 or 5
  29337. f *= 2;
  29338. }
  29339. return f * exp10;
  29340. }
  29341. // Force all the axis fixing the maxSplitNumber.
  29342. each$1(indicatorAxes, function (indicatorAxis, idx) {
  29343. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  29344. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  29345. var axisModel = indicatorAxis.model;
  29346. var scale = indicatorAxis.scale;
  29347. var fixedMin = axisModel.getMin();
  29348. var fixedMax = axisModel.getMax();
  29349. var interval = scale.getInterval();
  29350. if (fixedMin != null && fixedMax != null) {
  29351. // User set min, max, divide to get new interval
  29352. scale.setExtent(+fixedMin, +fixedMax);
  29353. scale.setInterval(
  29354. (fixedMax - fixedMin) / splitNumber
  29355. );
  29356. }
  29357. else if (fixedMin != null) {
  29358. var max;
  29359. // User set min, expand extent on the other side
  29360. do {
  29361. max = fixedMin + interval * splitNumber;
  29362. scale.setExtent(+fixedMin, max);
  29363. // Interval must been set after extent
  29364. // FIXME
  29365. scale.setInterval(interval);
  29366. interval = increaseInterval(interval);
  29367. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  29368. }
  29369. else if (fixedMax != null) {
  29370. var min;
  29371. // User set min, expand extent on the other side
  29372. do {
  29373. min = fixedMax - interval * splitNumber;
  29374. scale.setExtent(min, +fixedMax);
  29375. scale.setInterval(interval);
  29376. interval = increaseInterval(interval);
  29377. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  29378. }
  29379. else {
  29380. var nicedSplitNumber = scale.getTicks().length - 1;
  29381. if (nicedSplitNumber > splitNumber) {
  29382. interval = increaseInterval(interval);
  29383. }
  29384. // PENDING
  29385. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  29386. var halfSplitNumber = Math.round(splitNumber / 2);
  29387. scale.setExtent(
  29388. round(center - halfSplitNumber * interval),
  29389. round(center + (splitNumber - halfSplitNumber) * interval)
  29390. );
  29391. scale.setInterval(interval);
  29392. }
  29393. });
  29394. };
  29395. /**
  29396. * Radar dimensions is based on the data
  29397. * @type {Array}
  29398. */
  29399. Radar.dimensions = [];
  29400. Radar.create = function (ecModel, api) {
  29401. var radarList = [];
  29402. ecModel.eachComponent('radar', function (radarModel) {
  29403. var radar = new Radar(radarModel, ecModel, api);
  29404. radarList.push(radar);
  29405. radarModel.coordinateSystem = radar;
  29406. });
  29407. ecModel.eachSeriesByType('radar', function (radarSeries) {
  29408. if (radarSeries.get('coordinateSystem') === 'radar') {
  29409. // Inject coordinate system
  29410. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  29411. }
  29412. });
  29413. return radarList;
  29414. };
  29415. CoordinateSystemManager.register('radar', Radar);
  29416. var valueAxisDefault = axisDefault.valueAxis;
  29417. function defaultsShow(opt, show) {
  29418. return defaults({
  29419. show: show
  29420. }, opt);
  29421. }
  29422. var RadarModel = extendComponentModel({
  29423. type: 'radar',
  29424. optionUpdated: function () {
  29425. var boundaryGap = this.get('boundaryGap');
  29426. var splitNumber = this.get('splitNumber');
  29427. var scale = this.get('scale');
  29428. var axisLine = this.get('axisLine');
  29429. var axisTick = this.get('axisTick');
  29430. var axisLabel = this.get('axisLabel');
  29431. var nameTextStyle = this.get('name');
  29432. var showName = this.get('name.show');
  29433. var nameFormatter = this.get('name.formatter');
  29434. var nameGap = this.get('nameGap');
  29435. var triggerEvent = this.get('triggerEvent');
  29436. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  29437. // PENDING
  29438. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  29439. indicatorOpt.min = 0;
  29440. }
  29441. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  29442. indicatorOpt.max = 0;
  29443. }
  29444. var iNameTextStyle = nameTextStyle;
  29445. if(indicatorOpt.color != null) {
  29446. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  29447. }
  29448. // Use same configuration
  29449. indicatorOpt = merge(clone(indicatorOpt), {
  29450. boundaryGap: boundaryGap,
  29451. splitNumber: splitNumber,
  29452. scale: scale,
  29453. axisLine: axisLine,
  29454. axisTick: axisTick,
  29455. axisLabel: axisLabel,
  29456. // Competitable with 2 and use text
  29457. name: indicatorOpt.text,
  29458. nameLocation: 'end',
  29459. nameGap: nameGap,
  29460. // min: 0,
  29461. nameTextStyle: iNameTextStyle,
  29462. triggerEvent: triggerEvent
  29463. }, false);
  29464. if (!showName) {
  29465. indicatorOpt.name = '';
  29466. }
  29467. if (typeof nameFormatter === 'string') {
  29468. var indName = indicatorOpt.name;
  29469. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  29470. }
  29471. else if (typeof nameFormatter === 'function') {
  29472. indicatorOpt.name = nameFormatter(
  29473. indicatorOpt.name, indicatorOpt
  29474. );
  29475. }
  29476. var model = extend(
  29477. new Model(indicatorOpt, null, this.ecModel),
  29478. axisModelCommonMixin
  29479. );
  29480. // For triggerEvent.
  29481. model.mainType = 'radar';
  29482. model.componentIndex = this.componentIndex;
  29483. return model;
  29484. }, this);
  29485. this.getIndicatorModels = function () {
  29486. return indicatorModels;
  29487. };
  29488. },
  29489. defaultOption: {
  29490. zlevel: 0,
  29491. z: 0,
  29492. center: ['50%', '50%'],
  29493. radius: '75%',
  29494. startAngle: 90,
  29495. name: {
  29496. show: true
  29497. // formatter: null
  29498. // textStyle: {}
  29499. },
  29500. boundaryGap: [0, 0],
  29501. splitNumber: 5,
  29502. nameGap: 15,
  29503. scale: false,
  29504. // Polygon or circle
  29505. shape: 'polygon',
  29506. axisLine: merge(
  29507. {
  29508. lineStyle: {
  29509. color: '#bbb'
  29510. }
  29511. },
  29512. valueAxisDefault.axisLine
  29513. ),
  29514. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  29515. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  29516. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  29517. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  29518. // {text, min, max}
  29519. indicator: []
  29520. }
  29521. });
  29522. var axisBuilderAttrs$1 = [
  29523. 'axisLine', 'axisTickLabel', 'axisName'
  29524. ];
  29525. extendComponentView({
  29526. type: 'radar',
  29527. render: function (radarModel, ecModel, api) {
  29528. var group = this.group;
  29529. group.removeAll();
  29530. this._buildAxes(radarModel);
  29531. this._buildSplitLineAndArea(radarModel);
  29532. },
  29533. _buildAxes: function (radarModel) {
  29534. var radar = radarModel.coordinateSystem;
  29535. var indicatorAxes = radar.getIndicatorAxes();
  29536. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  29537. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  29538. position: [radar.cx, radar.cy],
  29539. rotation: indicatorAxis.angle,
  29540. labelDirection: -1,
  29541. tickDirection: -1,
  29542. nameDirection: 1
  29543. });
  29544. return axisBuilder;
  29545. });
  29546. each$1(axisBuilders, function (axisBuilder) {
  29547. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  29548. this.group.add(axisBuilder.getGroup());
  29549. }, this);
  29550. },
  29551. _buildSplitLineAndArea: function (radarModel) {
  29552. var radar = radarModel.coordinateSystem;
  29553. var indicatorAxes = radar.getIndicatorAxes();
  29554. if (!indicatorAxes.length) {
  29555. return;
  29556. }
  29557. var shape = radarModel.get('shape');
  29558. var splitLineModel = radarModel.getModel('splitLine');
  29559. var splitAreaModel = radarModel.getModel('splitArea');
  29560. var lineStyleModel = splitLineModel.getModel('lineStyle');
  29561. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  29562. var showSplitLine = splitLineModel.get('show');
  29563. var showSplitArea = splitAreaModel.get('show');
  29564. var splitLineColors = lineStyleModel.get('color');
  29565. var splitAreaColors = areaStyleModel.get('color');
  29566. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  29567. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  29568. var splitLines = [];
  29569. var splitAreas = [];
  29570. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  29571. var colorIndex = idx % areaOrLineColorList.length;
  29572. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  29573. return colorIndex;
  29574. }
  29575. if (shape === 'circle') {
  29576. var ticksRadius = indicatorAxes[0].getTicksCoords();
  29577. var cx = radar.cx;
  29578. var cy = radar.cy;
  29579. for (var i = 0; i < ticksRadius.length; i++) {
  29580. if (showSplitLine) {
  29581. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  29582. splitLines[colorIndex].push(new Circle({
  29583. shape: {
  29584. cx: cx,
  29585. cy: cy,
  29586. r: ticksRadius[i]
  29587. }
  29588. }));
  29589. }
  29590. if (showSplitArea && i < ticksRadius.length - 1) {
  29591. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  29592. splitAreas[colorIndex].push(new Ring({
  29593. shape: {
  29594. cx: cx,
  29595. cy: cy,
  29596. r0: ticksRadius[i],
  29597. r: ticksRadius[i + 1]
  29598. }
  29599. }));
  29600. }
  29601. }
  29602. }
  29603. // Polyyon
  29604. else {
  29605. var realSplitNumber;
  29606. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  29607. var ticksCoords = indicatorAxis.getTicksCoords();
  29608. realSplitNumber = realSplitNumber == null
  29609. ? ticksCoords.length - 1
  29610. : Math.min(ticksCoords.length - 1, realSplitNumber);
  29611. return map(ticksCoords, function (tickCoord) {
  29612. return radar.coordToPoint(tickCoord, idx);
  29613. });
  29614. });
  29615. var prevPoints = [];
  29616. for (var i = 0; i <= realSplitNumber; i++) {
  29617. var points = [];
  29618. for (var j = 0; j < indicatorAxes.length; j++) {
  29619. points.push(axesTicksPoints[j][i]);
  29620. }
  29621. // Close
  29622. if (points[0]) {
  29623. points.push(points[0].slice());
  29624. }
  29625. else {
  29626. if (__DEV__) {
  29627. console.error('Can\'t draw value axis ' + i);
  29628. }
  29629. }
  29630. if (showSplitLine) {
  29631. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  29632. splitLines[colorIndex].push(new Polyline({
  29633. shape: {
  29634. points: points
  29635. }
  29636. }));
  29637. }
  29638. if (showSplitArea && prevPoints) {
  29639. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  29640. splitAreas[colorIndex].push(new Polygon({
  29641. shape: {
  29642. points: points.concat(prevPoints)
  29643. }
  29644. }));
  29645. }
  29646. prevPoints = points.slice().reverse();
  29647. }
  29648. }
  29649. var lineStyle = lineStyleModel.getLineStyle();
  29650. var areaStyle = areaStyleModel.getAreaStyle();
  29651. // Add splitArea before splitLine
  29652. each$1(splitAreas, function (splitAreas, idx) {
  29653. this.group.add(mergePath(
  29654. splitAreas, {
  29655. style: defaults({
  29656. stroke: 'none',
  29657. fill: splitAreaColors[idx % splitAreaColors.length]
  29658. }, areaStyle),
  29659. silent: true
  29660. }
  29661. ));
  29662. }, this);
  29663. each$1(splitLines, function (splitLines, idx) {
  29664. this.group.add(mergePath(
  29665. splitLines, {
  29666. style: defaults({
  29667. fill: 'none',
  29668. stroke: splitLineColors[idx % splitLineColors.length]
  29669. }, lineStyle),
  29670. silent: true
  29671. }
  29672. ));
  29673. }, this);
  29674. }
  29675. });
  29676. var RadarSeries = SeriesModel.extend({
  29677. type: 'series.radar',
  29678. dependencies: ['radar'],
  29679. // Overwrite
  29680. init: function (option) {
  29681. RadarSeries.superApply(this, 'init', arguments);
  29682. // Enable legend selection for each data item
  29683. // Use a function instead of direct access because data reference may changed
  29684. this.legendDataProvider = function () {
  29685. return this.getRawData();
  29686. };
  29687. },
  29688. getInitialData: function (option, ecModel) {
  29689. var data = option.data || [];
  29690. var dimensions = completeDimensions(
  29691. [], data, {extraPrefix: 'indicator_', extraFromZero: true}
  29692. );
  29693. var list = new List(dimensions, this);
  29694. list.initData(data);
  29695. return list;
  29696. },
  29697. formatTooltip: function (dataIndex) {
  29698. var value = this.getRawValue(dataIndex);
  29699. var coordSys = this.coordinateSystem;
  29700. var indicatorAxes = coordSys.getIndicatorAxes();
  29701. var name = this.getData().getName(dataIndex);
  29702. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  29703. + map(indicatorAxes, function (axis, idx) {
  29704. return encodeHTML(axis.name + ' : ' + value[idx]);
  29705. }).join('<br />');
  29706. },
  29707. defaultOption: {
  29708. zlevel: 0,
  29709. z: 2,
  29710. coordinateSystem: 'radar',
  29711. legendHoverLink: true,
  29712. radarIndex: 0,
  29713. lineStyle: {
  29714. normal: {
  29715. width: 2,
  29716. type: 'solid'
  29717. }
  29718. },
  29719. label: {
  29720. normal: {
  29721. position: 'top'
  29722. }
  29723. },
  29724. // areaStyle: {
  29725. // },
  29726. // itemStyle: {}
  29727. symbol: 'emptyCircle',
  29728. symbolSize: 4
  29729. // symbolRotate: null
  29730. }
  29731. });
  29732. function normalizeSymbolSize(symbolSize) {
  29733. if (!isArray(symbolSize)) {
  29734. symbolSize = [+symbolSize, +symbolSize];
  29735. }
  29736. return symbolSize;
  29737. }
  29738. extendChartView({
  29739. type: 'radar',
  29740. render: function (seriesModel, ecModel, api) {
  29741. var polar = seriesModel.coordinateSystem;
  29742. var group = this.group;
  29743. var data = seriesModel.getData();
  29744. var oldData = this._data;
  29745. function createSymbol$$1(data, idx) {
  29746. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29747. var color = data.getItemVisual(idx, 'color');
  29748. if (symbolType === 'none') {
  29749. return;
  29750. }
  29751. var symbolSize = normalizeSymbolSize(
  29752. data.getItemVisual(idx, 'symbolSize')
  29753. );
  29754. var symbolPath = createSymbol(
  29755. symbolType, -1, -1, 2, 2, color
  29756. );
  29757. symbolPath.attr({
  29758. style: {
  29759. strokeNoScale: true
  29760. },
  29761. z2: 100,
  29762. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  29763. });
  29764. return symbolPath;
  29765. }
  29766. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  29767. // Simply rerender all
  29768. symbolGroup.removeAll();
  29769. for (var i = 0; i < newPoints.length - 1; i++) {
  29770. var symbolPath = createSymbol$$1(data, idx);
  29771. if (symbolPath) {
  29772. symbolPath.__dimIdx = i;
  29773. if (oldPoints[i]) {
  29774. symbolPath.attr('position', oldPoints[i]);
  29775. graphic[isInit ? 'initProps' : 'updateProps'](
  29776. symbolPath, {
  29777. position: newPoints[i]
  29778. }, seriesModel, idx
  29779. );
  29780. }
  29781. else {
  29782. symbolPath.attr('position', newPoints[i]);
  29783. }
  29784. symbolGroup.add(symbolPath);
  29785. }
  29786. }
  29787. }
  29788. function getInitialPoints(points) {
  29789. return map(points, function (pt) {
  29790. return [polar.cx, polar.cy];
  29791. });
  29792. }
  29793. data.diff(oldData)
  29794. .add(function (idx) {
  29795. var points = data.getItemLayout(idx);
  29796. if (!points) {
  29797. return;
  29798. }
  29799. var polygon = new Polygon();
  29800. var polyline = new Polyline();
  29801. var target = {
  29802. shape: {
  29803. points: points
  29804. }
  29805. };
  29806. polygon.shape.points = getInitialPoints(points);
  29807. polyline.shape.points = getInitialPoints(points);
  29808. initProps(polygon, target, seriesModel, idx);
  29809. initProps(polyline, target, seriesModel, idx);
  29810. var itemGroup = new Group();
  29811. var symbolGroup = new Group();
  29812. itemGroup.add(polyline);
  29813. itemGroup.add(polygon);
  29814. itemGroup.add(symbolGroup);
  29815. updateSymbols(
  29816. polyline.shape.points, points, symbolGroup, data, idx, true
  29817. );
  29818. data.setItemGraphicEl(idx, itemGroup);
  29819. })
  29820. .update(function (newIdx, oldIdx) {
  29821. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  29822. var polyline = itemGroup.childAt(0);
  29823. var polygon = itemGroup.childAt(1);
  29824. var symbolGroup = itemGroup.childAt(2);
  29825. var target = {
  29826. shape: {
  29827. points: data.getItemLayout(newIdx)
  29828. }
  29829. };
  29830. if (!target.shape.points) {
  29831. return;
  29832. }
  29833. updateSymbols(
  29834. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  29835. );
  29836. updateProps(polyline, target, seriesModel);
  29837. updateProps(polygon, target, seriesModel);
  29838. data.setItemGraphicEl(newIdx, itemGroup);
  29839. })
  29840. .remove(function (idx) {
  29841. group.remove(oldData.getItemGraphicEl(idx));
  29842. })
  29843. .execute();
  29844. data.eachItemGraphicEl(function (itemGroup, idx) {
  29845. var itemModel = data.getItemModel(idx);
  29846. var polyline = itemGroup.childAt(0);
  29847. var polygon = itemGroup.childAt(1);
  29848. var symbolGroup = itemGroup.childAt(2);
  29849. var color = data.getItemVisual(idx, 'color');
  29850. group.add(itemGroup);
  29851. polyline.useStyle(
  29852. defaults(
  29853. itemModel.getModel('lineStyle.normal').getLineStyle(),
  29854. {
  29855. fill: 'none',
  29856. stroke: color
  29857. }
  29858. )
  29859. );
  29860. polyline.hoverStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  29861. var areaStyleModel = itemModel.getModel('areaStyle.normal');
  29862. var hoverAreaStyleModel = itemModel.getModel('areaStyle.emphasis');
  29863. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  29864. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  29865. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  29866. polygon.ignore = polygonIgnore;
  29867. polygon.useStyle(
  29868. defaults(
  29869. areaStyleModel.getAreaStyle(),
  29870. {
  29871. fill: color,
  29872. opacity: 0.7
  29873. }
  29874. )
  29875. );
  29876. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  29877. var itemStyle = itemModel.getModel('itemStyle.normal').getItemStyle(['color']);
  29878. var itemHoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  29879. var labelModel = itemModel.getModel('label.normal');
  29880. var labelHoverModel = itemModel.getModel('label.emphasis');
  29881. symbolGroup.eachChild(function (symbolPath) {
  29882. symbolPath.setStyle(itemStyle);
  29883. symbolPath.hoverStyle = clone(itemHoverStyle);
  29884. setLabelStyle(
  29885. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  29886. {
  29887. labelFetcher: data.hostModel,
  29888. labelDataIndex: idx,
  29889. labelDimIndex: symbolPath.__dimIdx,
  29890. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  29891. autoColor: color,
  29892. isRectText: true
  29893. }
  29894. );
  29895. });
  29896. function onEmphasis() {
  29897. polygon.attr('ignore', hoverPolygonIgnore);
  29898. }
  29899. function onNormal() {
  29900. polygon.attr('ignore', polygonIgnore);
  29901. }
  29902. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  29903. itemGroup.on('emphasis', onEmphasis)
  29904. .on('mouseover', onEmphasis)
  29905. .on('normal', onNormal)
  29906. .on('mouseout', onNormal);
  29907. setHoverStyle(itemGroup);
  29908. });
  29909. this._data = data;
  29910. },
  29911. remove: function () {
  29912. this.group.removeAll();
  29913. this._data = null;
  29914. },
  29915. dispose: function () {}
  29916. });
  29917. var radarLayout = function (ecModel) {
  29918. ecModel.eachSeriesByType('radar', function (seriesModel) {
  29919. var data = seriesModel.getData();
  29920. var points = [];
  29921. var coordSys = seriesModel.coordinateSystem;
  29922. if (!coordSys) {
  29923. return;
  29924. }
  29925. function pointsConverter(val, idx) {
  29926. points[idx] = points[idx] || [];
  29927. points[idx][i] = coordSys.dataToPoint(val, i);
  29928. }
  29929. for (var i = 0; i < coordSys.getIndicatorAxes().length; i++) {
  29930. var dim = data.dimensions[i];
  29931. data.each(dim, pointsConverter);
  29932. }
  29933. data.each(function (idx) {
  29934. // Close polygon
  29935. points[idx][0] && points[idx].push(points[idx][0].slice());
  29936. data.setItemLayout(idx, points[idx]);
  29937. });
  29938. });
  29939. };
  29940. // Backward compat for radar chart in 2
  29941. var backwardCompat$1 = function (option) {
  29942. var polarOptArr = option.polar;
  29943. if (polarOptArr) {
  29944. if (!isArray(polarOptArr)) {
  29945. polarOptArr = [polarOptArr];
  29946. }
  29947. var polarNotRadar = [];
  29948. each$1(polarOptArr, function (polarOpt, idx) {
  29949. if (polarOpt.indicator) {
  29950. if (polarOpt.type && !polarOpt.shape) {
  29951. polarOpt.shape = polarOpt.type;
  29952. }
  29953. option.radar = option.radar || [];
  29954. if (!isArray(option.radar)) {
  29955. option.radar = [option.radar];
  29956. }
  29957. option.radar.push(polarOpt);
  29958. }
  29959. else {
  29960. polarNotRadar.push(polarOpt);
  29961. }
  29962. });
  29963. option.polar = polarNotRadar;
  29964. }
  29965. each$1(option.series, function (seriesOpt) {
  29966. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  29967. seriesOpt.radarIndex = seriesOpt.polarIndex;
  29968. }
  29969. });
  29970. };
  29971. // Must use radar component
  29972. registerVisual(curry(dataColor, 'radar'));
  29973. registerVisual(curry(visualSymbol, 'radar', 'circle', null));
  29974. registerLayout(radarLayout);
  29975. registerProcessor(curry(dataFilter, 'radar'));
  29976. registerPreprocessor(backwardCompat$1);
  29977. /**
  29978. * Simple view coordinate system
  29979. * Mapping given x, y to transformd view x, y
  29980. */
  29981. var v2ApplyTransform$1 = applyTransform;
  29982. // Dummy transform node
  29983. function TransformDummy() {
  29984. Transformable.call(this);
  29985. }
  29986. mixin(TransformDummy, Transformable);
  29987. function View(name) {
  29988. /**
  29989. * @type {string}
  29990. */
  29991. this.name = name;
  29992. /**
  29993. * @type {Object}
  29994. */
  29995. this.zoomLimit;
  29996. Transformable.call(this);
  29997. this._roamTransform = new TransformDummy();
  29998. this._viewTransform = new TransformDummy();
  29999. this._center;
  30000. this._zoom;
  30001. }
  30002. View.prototype = {
  30003. constructor: View,
  30004. type: 'view',
  30005. /**
  30006. * @param {Array.<string>}
  30007. * @readOnly
  30008. */
  30009. dimensions: ['x', 'y'],
  30010. /**
  30011. * Set bounding rect
  30012. * @param {number} x
  30013. * @param {number} y
  30014. * @param {number} width
  30015. * @param {number} height
  30016. */
  30017. // PENDING to getRect
  30018. setBoundingRect: function (x, y, width, height) {
  30019. this._rect = new BoundingRect(x, y, width, height);
  30020. return this._rect;
  30021. },
  30022. /**
  30023. * @return {module:zrender/core/BoundingRect}
  30024. */
  30025. // PENDING to getRect
  30026. getBoundingRect: function () {
  30027. return this._rect;
  30028. },
  30029. /**
  30030. * @param {number} x
  30031. * @param {number} y
  30032. * @param {number} width
  30033. * @param {number} height
  30034. */
  30035. setViewRect: function (x, y, width, height) {
  30036. this.transformTo(x, y, width, height);
  30037. this._viewRect = new BoundingRect(x, y, width, height);
  30038. },
  30039. /**
  30040. * Transformed to particular position and size
  30041. * @param {number} x
  30042. * @param {number} y
  30043. * @param {number} width
  30044. * @param {number} height
  30045. */
  30046. transformTo: function (x, y, width, height) {
  30047. var rect = this.getBoundingRect();
  30048. var viewTransform = this._viewTransform;
  30049. viewTransform.transform = rect.calculateTransform(
  30050. new BoundingRect(x, y, width, height)
  30051. );
  30052. viewTransform.decomposeTransform();
  30053. this._updateTransform();
  30054. },
  30055. /**
  30056. * Set center of view
  30057. * @param {Array.<number>} [centerCoord]
  30058. */
  30059. setCenter: function (centerCoord) {
  30060. if (!centerCoord) {
  30061. return;
  30062. }
  30063. this._center = centerCoord;
  30064. this._updateCenterAndZoom();
  30065. },
  30066. /**
  30067. * @param {number} zoom
  30068. */
  30069. setZoom: function (zoom) {
  30070. zoom = zoom || 1;
  30071. var zoomLimit = this.zoomLimit;
  30072. if (zoomLimit) {
  30073. if (zoomLimit.max != null) {
  30074. zoom = Math.min(zoomLimit.max, zoom);
  30075. }
  30076. if (zoomLimit.min != null) {
  30077. zoom = Math.max(zoomLimit.min, zoom);
  30078. }
  30079. }
  30080. this._zoom = zoom;
  30081. this._updateCenterAndZoom();
  30082. },
  30083. /**
  30084. * Get default center without roam
  30085. */
  30086. getDefaultCenter: function () {
  30087. // Rect before any transform
  30088. var rawRect = this.getBoundingRect();
  30089. var cx = rawRect.x + rawRect.width / 2;
  30090. var cy = rawRect.y + rawRect.height / 2;
  30091. return [cx, cy];
  30092. },
  30093. getCenter: function () {
  30094. return this._center || this.getDefaultCenter();
  30095. },
  30096. getZoom: function () {
  30097. return this._zoom || 1;
  30098. },
  30099. /**
  30100. * @return {Array.<number}
  30101. */
  30102. getRoamTransform: function () {
  30103. return this._roamTransform;
  30104. },
  30105. _updateCenterAndZoom: function () {
  30106. // Must update after view transform updated
  30107. var viewTransformMatrix = this._viewTransform.getLocalTransform();
  30108. var roamTransform = this._roamTransform;
  30109. var defaultCenter = this.getDefaultCenter();
  30110. var center = this.getCenter();
  30111. var zoom = this.getZoom();
  30112. center = applyTransform([], center, viewTransformMatrix);
  30113. defaultCenter = applyTransform([], defaultCenter, viewTransformMatrix);
  30114. roamTransform.origin = center;
  30115. roamTransform.position = [
  30116. defaultCenter[0] - center[0],
  30117. defaultCenter[1] - center[1]
  30118. ];
  30119. roamTransform.scale = [zoom, zoom];
  30120. this._updateTransform();
  30121. },
  30122. /**
  30123. * Update transform from roam and mapLocation
  30124. * @private
  30125. */
  30126. _updateTransform: function () {
  30127. var roamTransform = this._roamTransform;
  30128. var viewTransform = this._viewTransform;
  30129. viewTransform.parent = roamTransform;
  30130. roamTransform.updateTransform();
  30131. viewTransform.updateTransform();
  30132. viewTransform.transform
  30133. && copy$1(this.transform || (this.transform = []), viewTransform.transform);
  30134. if (this.transform) {
  30135. this.invTransform = this.invTransform || [];
  30136. invert(this.invTransform, this.transform);
  30137. }
  30138. else {
  30139. this.invTransform = null;
  30140. }
  30141. this.decomposeTransform();
  30142. },
  30143. /**
  30144. * @return {module:zrender/core/BoundingRect}
  30145. */
  30146. getViewRect: function () {
  30147. return this._viewRect;
  30148. },
  30149. /**
  30150. * Get view rect after roam transform
  30151. * @return {module:zrender/core/BoundingRect}
  30152. */
  30153. getViewRectAfterRoam: function () {
  30154. var rect = this.getBoundingRect().clone();
  30155. rect.applyTransform(this.transform);
  30156. return rect;
  30157. },
  30158. /**
  30159. * Convert a single (lon, lat) data item to (x, y) point.
  30160. * @param {Array.<number>} data
  30161. * @return {Array.<number>}
  30162. */
  30163. dataToPoint: function (data) {
  30164. var transform = this.transform;
  30165. return transform
  30166. ? v2ApplyTransform$1([], data, transform)
  30167. : [data[0], data[1]];
  30168. },
  30169. /**
  30170. * Convert a (x, y) point to (lon, lat) data
  30171. * @param {Array.<number>} point
  30172. * @return {Array.<number>}
  30173. */
  30174. pointToData: function (point) {
  30175. var invTransform = this.invTransform;
  30176. return invTransform
  30177. ? v2ApplyTransform$1([], point, invTransform)
  30178. : [point[0], point[1]];
  30179. },
  30180. /**
  30181. * @implements
  30182. * see {module:echarts/CoodinateSystem}
  30183. */
  30184. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  30185. /**
  30186. * @implements
  30187. * see {module:echarts/CoodinateSystem}
  30188. */
  30189. convertFromPixel: curry(doConvert$1, 'pointToData'),
  30190. /**
  30191. * @implements
  30192. * see {module:echarts/CoodinateSystem}
  30193. */
  30194. containPoint: function (point) {
  30195. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  30196. }
  30197. /**
  30198. * @return {number}
  30199. */
  30200. // getScalarScale: function () {
  30201. // // Use determinant square root of transform to mutiply scalar
  30202. // var m = this.transform;
  30203. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  30204. // return det;
  30205. // }
  30206. };
  30207. mixin(View, Transformable);
  30208. function doConvert$1(methodName, ecModel, finder, value) {
  30209. var seriesModel = finder.seriesModel;
  30210. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  30211. return coordSys === this ? coordSys[methodName](value) : null;
  30212. }
  30213. // Fix for 南海诸岛
  30214. var geoCoord = [126, 25];
  30215. var points$1 = [
  30216. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  30217. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  30218. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  30219. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  30220. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  30221. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  30222. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  30223. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  30224. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  30225. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  30226. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  30227. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  30228. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  30229. [1,92.4],[1,3.5],[0,3.5]]
  30230. ];
  30231. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  30232. for (var k = 0; k < points$1[i$1].length; k++) {
  30233. points$1[i$1][k][0] /= 10.5;
  30234. points$1[i$1][k][1] /= -10.5 / 0.75;
  30235. points$1[i$1][k][0] += geoCoord[0];
  30236. points$1[i$1][k][1] += geoCoord[1];
  30237. }
  30238. }
  30239. var fixNanhai = function (geo) {
  30240. if (geo.map === 'china') {
  30241. geo.regions.push(new Region(
  30242. '南海诸岛',
  30243. map(points$1, function (exterior) {
  30244. return {
  30245. type: 'polygon',
  30246. exterior: exterior
  30247. };
  30248. }), geoCoord
  30249. ));
  30250. }
  30251. };
  30252. var coordsOffsetMap = {
  30253. '南海诸岛' : [32, 80],
  30254. // 全国
  30255. '广东': [0, -10],
  30256. '香港': [10, 5],
  30257. '澳门': [-10, 10],
  30258. //'北京': [-10, 0],
  30259. '天津': [5, 5]
  30260. };
  30261. var fixTextCoord = function (geo) {
  30262. each$1(geo.regions, function (region) {
  30263. var coordFix = coordsOffsetMap[region.name];
  30264. if (coordFix) {
  30265. var cp = region.center;
  30266. cp[0] += coordFix[0] / 10.5;
  30267. cp[1] += -coordFix[1] / (10.5 / 0.75);
  30268. }
  30269. });
  30270. };
  30271. var geoCoordMap = {
  30272. 'Russia': [100, 60],
  30273. 'United States': [-99, 38],
  30274. 'United States of America': [-99, 38]
  30275. };
  30276. var fixGeoCoord = function (geo) {
  30277. each$1(geo.regions, function (region) {
  30278. var geoCoord = geoCoordMap[region.name];
  30279. if (geoCoord) {
  30280. var cp = region.center;
  30281. cp[0] = geoCoord[0];
  30282. cp[1] = geoCoord[1];
  30283. }
  30284. });
  30285. };
  30286. // Fix for 钓鱼岛
  30287. // var Region = require('../Region');
  30288. // var zrUtil = require('zrender/src/core/util');
  30289. // var geoCoord = [126, 25];
  30290. var points$2 = [
  30291. [
  30292. [123.45165252685547, 25.73527164402261],
  30293. [123.49731445312499, 25.73527164402261],
  30294. [123.49731445312499, 25.750734064600884],
  30295. [123.45165252685547, 25.750734064600884],
  30296. [123.45165252685547, 25.73527164402261]
  30297. ]
  30298. ];
  30299. var fixDiaoyuIsland = function (geo) {
  30300. if (geo.map === 'china') {
  30301. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  30302. if (geo.regions[i].name === '台湾') {
  30303. geo.regions[i].geometries.push({
  30304. type: 'polygon',
  30305. exterior: points$2[0]
  30306. });
  30307. }
  30308. }
  30309. }
  30310. };
  30311. // Geo fix functions
  30312. var geoFixFuncs = [
  30313. fixNanhai,
  30314. fixTextCoord,
  30315. fixGeoCoord,
  30316. fixDiaoyuIsland
  30317. ];
  30318. /**
  30319. * [Geo description]
  30320. * @param {string} name Geo name
  30321. * @param {string} map Map type
  30322. * @param {Object} geoJson
  30323. * @param {Object} [specialAreas]
  30324. * Specify the positioned areas by left, top, width, height
  30325. * @param {Object.<string, string>} [nameMap]
  30326. * Specify name alias
  30327. */
  30328. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  30329. View.call(this, name);
  30330. /**
  30331. * Map type
  30332. * @type {string}
  30333. */
  30334. this.map = map$$1;
  30335. this._nameCoordMap = createHashMap();
  30336. this.loadGeoJson(geoJson, specialAreas, nameMap);
  30337. }
  30338. Geo.prototype = {
  30339. constructor: Geo,
  30340. type: 'geo',
  30341. /**
  30342. * @param {Array.<string>}
  30343. * @readOnly
  30344. */
  30345. dimensions: ['lng', 'lat'],
  30346. /**
  30347. * If contain given lng,lat coord
  30348. * @param {Array.<number>}
  30349. * @readOnly
  30350. */
  30351. containCoord: function (coord) {
  30352. var regions = this.regions;
  30353. for (var i = 0; i < regions.length; i++) {
  30354. if (regions[i].contain(coord)) {
  30355. return true;
  30356. }
  30357. }
  30358. return false;
  30359. },
  30360. /**
  30361. * @param {Object} geoJson
  30362. * @param {Object} [specialAreas]
  30363. * Specify the positioned areas by left, top, width, height
  30364. * @param {Object.<string, string>} [nameMap]
  30365. * Specify name alias
  30366. */
  30367. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  30368. // https://jsperf.com/try-catch-performance-overhead
  30369. try {
  30370. this.regions = geoJson ? parseGeoJson(geoJson) : [];
  30371. }
  30372. catch (e) {
  30373. throw 'Invalid geoJson format\n' + e.message;
  30374. }
  30375. specialAreas = specialAreas || {};
  30376. nameMap = nameMap || {};
  30377. var regions = this.regions;
  30378. var regionsMap = createHashMap();
  30379. for (var i = 0; i < regions.length; i++) {
  30380. var regionName = regions[i].name;
  30381. // Try use the alias in nameMap
  30382. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  30383. regions[i].name = regionName;
  30384. regionsMap.set(regionName, regions[i]);
  30385. // Add geoJson
  30386. this.addGeoCoord(regionName, regions[i].center);
  30387. // Some area like Alaska in USA map needs to be tansformed
  30388. // to look better
  30389. var specialArea = specialAreas[regionName];
  30390. if (specialArea) {
  30391. regions[i].transformTo(
  30392. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  30393. );
  30394. }
  30395. }
  30396. this._regionsMap = regionsMap;
  30397. this._rect = null;
  30398. each$1(geoFixFuncs, function (fixFunc) {
  30399. fixFunc(this);
  30400. }, this);
  30401. },
  30402. // Overwrite
  30403. transformTo: function (x, y, width, height) {
  30404. var rect = this.getBoundingRect();
  30405. rect = rect.clone();
  30406. // Longitute is inverted
  30407. rect.y = -rect.y - rect.height;
  30408. var viewTransform = this._viewTransform;
  30409. viewTransform.transform = rect.calculateTransform(
  30410. new BoundingRect(x, y, width, height)
  30411. );
  30412. viewTransform.decomposeTransform();
  30413. var scale = viewTransform.scale;
  30414. scale[1] = -scale[1];
  30415. viewTransform.updateTransform();
  30416. this._updateTransform();
  30417. },
  30418. /**
  30419. * @param {string} name
  30420. * @return {module:echarts/coord/geo/Region}
  30421. */
  30422. getRegion: function (name) {
  30423. return this._regionsMap.get(name);
  30424. },
  30425. getRegionByCoord: function (coord) {
  30426. var regions = this.regions;
  30427. for (var i = 0; i < regions.length; i++) {
  30428. if (regions[i].contain(coord)) {
  30429. return regions[i];
  30430. }
  30431. }
  30432. },
  30433. /**
  30434. * Add geoCoord for indexing by name
  30435. * @param {string} name
  30436. * @param {Array.<number>} geoCoord
  30437. */
  30438. addGeoCoord: function (name, geoCoord) {
  30439. this._nameCoordMap.set(name, geoCoord);
  30440. },
  30441. /**
  30442. * Get geoCoord by name
  30443. * @param {string} name
  30444. * @return {Array.<number>}
  30445. */
  30446. getGeoCoord: function (name) {
  30447. return this._nameCoordMap.get(name);
  30448. },
  30449. // Overwrite
  30450. getBoundingRect: function () {
  30451. if (this._rect) {
  30452. return this._rect;
  30453. }
  30454. var rect;
  30455. var regions = this.regions;
  30456. for (var i = 0; i < regions.length; i++) {
  30457. var regionRect = regions[i].getBoundingRect();
  30458. rect = rect || regionRect.clone();
  30459. rect.union(regionRect);
  30460. }
  30461. // FIXME Always return new ?
  30462. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  30463. },
  30464. /**
  30465. * @param {string|Array.<number>} data
  30466. * @return {Array.<number>}
  30467. */
  30468. dataToPoint: function (data) {
  30469. if (typeof data === 'string') {
  30470. // Map area name to geoCoord
  30471. data = this.getGeoCoord(data);
  30472. }
  30473. if (data) {
  30474. return View.prototype.dataToPoint.call(this, data);
  30475. }
  30476. },
  30477. /**
  30478. * @inheritDoc
  30479. */
  30480. convertToPixel: curry(doConvert, 'dataToPoint'),
  30481. /**
  30482. * @inheritDoc
  30483. */
  30484. convertFromPixel: curry(doConvert, 'pointToData')
  30485. };
  30486. mixin(Geo, View);
  30487. function doConvert(methodName, ecModel, finder, value) {
  30488. var geoModel = finder.geoModel;
  30489. var seriesModel = finder.seriesModel;
  30490. var coordSys = geoModel
  30491. ? geoModel.coordinateSystem
  30492. : seriesModel
  30493. ? (
  30494. seriesModel.coordinateSystem // For map.
  30495. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  30496. )
  30497. : null;
  30498. return coordSys === this ? coordSys[methodName](value) : null;
  30499. }
  30500. /**
  30501. * Resize method bound to the geo
  30502. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  30503. * @param {module:echarts/ExtensionAPI} api
  30504. */
  30505. function resizeGeo(geoModel, api) {
  30506. var boundingCoords = geoModel.get('boundingCoords');
  30507. if (boundingCoords != null) {
  30508. var leftTop = boundingCoords[0];
  30509. var rightBottom = boundingCoords[1];
  30510. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  30511. if (__DEV__) {
  30512. console.error('Invalid boundingCoords');
  30513. }
  30514. }
  30515. else {
  30516. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  30517. }
  30518. }
  30519. var rect = this.getBoundingRect();
  30520. var boxLayoutOption;
  30521. var center = geoModel.get('layoutCenter');
  30522. var size = geoModel.get('layoutSize');
  30523. var viewWidth = api.getWidth();
  30524. var viewHeight = api.getHeight();
  30525. var aspectScale = geoModel.get('aspectScale') || 0.75;
  30526. var aspect = rect.width / rect.height * aspectScale;
  30527. var useCenterAndSize = false;
  30528. if (center && size) {
  30529. center = [
  30530. parsePercent$1(center[0], viewWidth),
  30531. parsePercent$1(center[1], viewHeight)
  30532. ];
  30533. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  30534. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  30535. useCenterAndSize = true;
  30536. }
  30537. else {
  30538. if (__DEV__) {
  30539. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  30540. }
  30541. }
  30542. }
  30543. var viewRect;
  30544. if (useCenterAndSize) {
  30545. var viewRect = {};
  30546. if (aspect > 1) {
  30547. // Width is same with size
  30548. viewRect.width = size;
  30549. viewRect.height = size / aspect;
  30550. }
  30551. else {
  30552. viewRect.height = size;
  30553. viewRect.width = size * aspect;
  30554. }
  30555. viewRect.y = center[1] - viewRect.height / 2;
  30556. viewRect.x = center[0] - viewRect.width / 2;
  30557. }
  30558. else {
  30559. // Use left/top/width/height
  30560. boxLayoutOption = geoModel.getBoxLayoutParams();
  30561. // 0.75 rate
  30562. boxLayoutOption.aspect = aspect;
  30563. viewRect = getLayoutRect(boxLayoutOption, {
  30564. width: viewWidth,
  30565. height: viewHeight
  30566. });
  30567. }
  30568. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  30569. this.setCenter(geoModel.get('center'));
  30570. this.setZoom(geoModel.get('zoom'));
  30571. }
  30572. /**
  30573. * @param {module:echarts/coord/Geo} geo
  30574. * @param {module:echarts/model/Model} model
  30575. * @inner
  30576. */
  30577. function setGeoCoords(geo, model) {
  30578. each$1(model.get('geoCoord'), function (geoCoord, name) {
  30579. geo.addGeoCoord(name, geoCoord);
  30580. });
  30581. }
  30582. if (__DEV__) {
  30583. var mapNotExistsError = function (name) {
  30584. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  30585. };
  30586. }
  30587. var geoCreator = {
  30588. // For deciding which dimensions to use when creating list data
  30589. dimensions: Geo.prototype.dimensions,
  30590. create: function (ecModel, api) {
  30591. var geoList = [];
  30592. // FIXME Create each time may be slow
  30593. ecModel.eachComponent('geo', function (geoModel, idx) {
  30594. var name = geoModel.get('map');
  30595. var mapData = getMap(name);
  30596. if (__DEV__) {
  30597. if (!mapData) {
  30598. mapNotExistsError(name);
  30599. }
  30600. }
  30601. var geo = new Geo(
  30602. name + idx, name,
  30603. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  30604. geoModel.get('nameMap')
  30605. );
  30606. geo.zoomLimit = geoModel.get('scaleLimit');
  30607. geoList.push(geo);
  30608. setGeoCoords(geo, geoModel);
  30609. geoModel.coordinateSystem = geo;
  30610. geo.model = geoModel;
  30611. // Inject resize method
  30612. geo.resize = resizeGeo;
  30613. geo.resize(geoModel, api);
  30614. });
  30615. ecModel.eachSeries(function (seriesModel) {
  30616. var coordSys = seriesModel.get('coordinateSystem');
  30617. if (coordSys === 'geo') {
  30618. var geoIndex = seriesModel.get('geoIndex') || 0;
  30619. seriesModel.coordinateSystem = geoList[geoIndex];
  30620. }
  30621. });
  30622. // If has map series
  30623. var mapModelGroupBySeries = {};
  30624. ecModel.eachSeriesByType('map', function (seriesModel) {
  30625. if (!seriesModel.getHostGeoModel()) {
  30626. var mapType = seriesModel.getMapType();
  30627. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  30628. mapModelGroupBySeries[mapType].push(seriesModel);
  30629. }
  30630. });
  30631. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  30632. var mapData = getMap(mapType);
  30633. if (__DEV__) {
  30634. if (!mapData) {
  30635. mapNotExistsError(mapSeries[0].get('map'));
  30636. }
  30637. }
  30638. var nameMapList = map(mapSeries, function (singleMapSeries) {
  30639. return singleMapSeries.get('nameMap');
  30640. });
  30641. var geo = new Geo(
  30642. mapType, mapType,
  30643. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  30644. mergeAll(nameMapList)
  30645. );
  30646. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  30647. return singleMapSeries.get('scaleLimit');
  30648. }));
  30649. geoList.push(geo);
  30650. // Inject resize method
  30651. geo.resize = resizeGeo;
  30652. geo.resize(mapSeries[0], api);
  30653. each$1(mapSeries, function (singleMapSeries) {
  30654. singleMapSeries.coordinateSystem = geo;
  30655. setGeoCoords(geo, singleMapSeries);
  30656. });
  30657. });
  30658. return geoList;
  30659. },
  30660. /**
  30661. * Fill given regions array
  30662. * @param {Array.<Object>} originRegionArr
  30663. * @param {string} mapName
  30664. * @param {Object} [nameMap]
  30665. * @return {Array}
  30666. */
  30667. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  30668. // Not use the original
  30669. var regionsArr = (originRegionArr || []).slice();
  30670. nameMap = nameMap || {};
  30671. var map$$1 = getMap(mapName);
  30672. var geoJson = map$$1 && map$$1.geoJson;
  30673. if (!geoJson) {
  30674. if (__DEV__) {
  30675. mapNotExistsError(mapName);
  30676. }
  30677. return originRegionArr;
  30678. }
  30679. var dataNameMap = createHashMap();
  30680. var features = geoJson.features;
  30681. for (var i = 0; i < regionsArr.length; i++) {
  30682. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  30683. }
  30684. for (var i = 0; i < features.length; i++) {
  30685. var name = features[i].properties.name;
  30686. if (!dataNameMap.get(name)) {
  30687. if (nameMap.hasOwnProperty(name)) {
  30688. name = nameMap[name];
  30689. }
  30690. regionsArr.push({
  30691. name: name
  30692. });
  30693. }
  30694. }
  30695. return regionsArr;
  30696. }
  30697. };
  30698. registerCoordinateSystem('geo', geoCreator);
  30699. var MapSeries = SeriesModel.extend({
  30700. type: 'series.map',
  30701. dependencies: ['geo'],
  30702. layoutMode: 'box',
  30703. /**
  30704. * Only first map series of same mapType will drawMap
  30705. * @type {boolean}
  30706. */
  30707. needsDrawMap: false,
  30708. /**
  30709. * Group of all map series with same mapType
  30710. * @type {boolean}
  30711. */
  30712. seriesGroup: [],
  30713. init: function (option) {
  30714. this._fillOption(option, this.getMapType());
  30715. // this.option = option;
  30716. MapSeries.superApply(this, 'init', arguments);
  30717. this.updateSelectedMap(option.data);
  30718. },
  30719. getInitialData: function (option) {
  30720. var dimensions = completeDimensions(['value'], option.data || []);
  30721. var list = new List(dimensions, this);
  30722. list.initData(option.data);
  30723. return list;
  30724. },
  30725. mergeOption: function (newOption) {
  30726. this._fillOption(newOption, this.getMapType());
  30727. MapSeries.superApply(this, 'mergeOption', arguments);
  30728. this.updateSelectedMap(this.option.data);
  30729. },
  30730. /**
  30731. * If no host geo model, return null, which means using a
  30732. * inner exclusive geo model.
  30733. */
  30734. getHostGeoModel: function () {
  30735. var geoIndex = this.option.geoIndex;
  30736. return geoIndex != null
  30737. ? this.dependentModels.geo[geoIndex]
  30738. : null;
  30739. },
  30740. getMapType: function () {
  30741. return (this.getHostGeoModel() || this).option.map;
  30742. },
  30743. _fillOption: function (option, mapName) {
  30744. // Shallow clone
  30745. // option = zrUtil.extend({}, option);
  30746. option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  30747. // return option;
  30748. },
  30749. getRawValue: function (dataIndex) {
  30750. // Use value stored in data instead because it is calculated from multiple series
  30751. // FIXME Provide all value of multiple series ?
  30752. return this.getData().get('value', dataIndex);
  30753. },
  30754. /**
  30755. * Get model of region
  30756. * @param {string} name
  30757. * @return {module:echarts/model/Model}
  30758. */
  30759. getRegionModel: function (regionName) {
  30760. var data = this.getData();
  30761. return data.getItemModel(data.indexOfName(regionName));
  30762. },
  30763. /**
  30764. * Map tooltip formatter
  30765. *
  30766. * @param {number} dataIndex
  30767. */
  30768. formatTooltip: function (dataIndex) {
  30769. // FIXME orignalData and data is a bit confusing
  30770. var data = this.getData();
  30771. var formattedValue = addCommas(this.getRawValue(dataIndex));
  30772. var name = data.getName(dataIndex);
  30773. var seriesGroup = this.seriesGroup;
  30774. var seriesNames = [];
  30775. for (var i = 0; i < seriesGroup.length; i++) {
  30776. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  30777. if (!isNaN(seriesGroup[i].originalData.get('value', otherIndex))) {
  30778. seriesNames.push(
  30779. encodeHTML(seriesGroup[i].name)
  30780. );
  30781. }
  30782. }
  30783. return seriesNames.join(', ') + '<br />'
  30784. + encodeHTML(name + ' : ' + formattedValue);
  30785. },
  30786. /**
  30787. * @implement
  30788. */
  30789. getTooltipPosition: function (dataIndex) {
  30790. if (dataIndex != null) {
  30791. var name = this.getData().getName(dataIndex);
  30792. var geo = this.coordinateSystem;
  30793. var region = geo.getRegion(name);
  30794. return region && geo.dataToPoint(region.center);
  30795. }
  30796. },
  30797. setZoom: function (zoom) {
  30798. this.option.zoom = zoom;
  30799. },
  30800. setCenter: function (center) {
  30801. this.option.center = center;
  30802. },
  30803. defaultOption: {
  30804. // 一级层叠
  30805. zlevel: 0,
  30806. // 二级层叠
  30807. z: 2,
  30808. coordinateSystem: 'geo',
  30809. // map should be explicitly specified since ec3.
  30810. map: '',
  30811. // If `geoIndex` is not specified, a exclusive geo will be
  30812. // created. Otherwise use the specified geo component, and
  30813. // `map` and `mapType` are ignored.
  30814. // geoIndex: 0,
  30815. // 'center' | 'left' | 'right' | 'x%' | {number}
  30816. left: 'center',
  30817. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  30818. top: 'center',
  30819. // right
  30820. // bottom
  30821. // width:
  30822. // height
  30823. // Aspect is width / height. Inited to be geoJson bbox aspect
  30824. // This parameter is used for scale this aspect
  30825. aspectScale: 0.75,
  30826. ///// Layout with center and size
  30827. // If you wan't to put map in a fixed size box with right aspect ratio
  30828. // This two properties may more conveninet
  30829. // layoutCenter: [50%, 50%]
  30830. // layoutSize: 100
  30831. // 数值合并方式,默认加和,可选为:
  30832. // 'sum' | 'average' | 'max' | 'min'
  30833. // mapValueCalculation: 'sum',
  30834. // 地图数值计算结果小数精度
  30835. // mapValuePrecision: 0,
  30836. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  30837. showLegendSymbol: true,
  30838. // 选择模式,默认关闭,可选single,multiple
  30839. // selectedMode: false,
  30840. dataRangeHoverLink: true,
  30841. // 是否开启缩放及漫游模式
  30842. // roam: false,
  30843. // Define left-top, right-bottom coords to control view
  30844. // For example, [ [180, 90], [-180, -90] ],
  30845. // higher priority than center and zoom
  30846. boundingCoords: null,
  30847. // Default on center of map
  30848. center: null,
  30849. zoom: 1,
  30850. scaleLimit: null,
  30851. label: {
  30852. normal: {
  30853. show: false,
  30854. color: '#000'
  30855. },
  30856. emphasis: {
  30857. show: true,
  30858. color: 'rgb(100,0,0)'
  30859. }
  30860. },
  30861. // scaleLimit: null,
  30862. itemStyle: {
  30863. normal: {
  30864. // color: 各异,
  30865. borderWidth: 0.5,
  30866. borderColor: '#444',
  30867. areaColor: '#eee'
  30868. },
  30869. // 也是选中样式
  30870. emphasis: {
  30871. areaColor: 'rgba(255,215,0,0.8)'
  30872. }
  30873. }
  30874. }
  30875. });
  30876. mixin(MapSeries, selectableMixin);
  30877. var ATTR = '\0_ec_interaction_mutex';
  30878. function take(zr, resourceKey, userKey) {
  30879. var store = getStore(zr);
  30880. store[resourceKey] = userKey;
  30881. }
  30882. function release(zr, resourceKey, userKey) {
  30883. var store = getStore(zr);
  30884. var uKey = store[resourceKey];
  30885. if (uKey === userKey) {
  30886. store[resourceKey] = null;
  30887. }
  30888. }
  30889. function isTaken(zr, resourceKey) {
  30890. return !!getStore(zr)[resourceKey];
  30891. }
  30892. function getStore(zr) {
  30893. return zr[ATTR] || (zr[ATTR] = {});
  30894. }
  30895. /**
  30896. * payload: {
  30897. * type: 'takeGlobalCursor',
  30898. * key: 'dataZoomSelect', or 'brush', or ...,
  30899. * If no userKey, release global cursor.
  30900. * }
  30901. */
  30902. registerAction(
  30903. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  30904. function () {}
  30905. );
  30906. /**
  30907. * @alias module:echarts/component/helper/RoamController
  30908. * @constructor
  30909. * @mixin {module:zrender/mixin/Eventful}
  30910. *
  30911. * @param {module:zrender/zrender~ZRender} zr
  30912. */
  30913. function RoamController(zr) {
  30914. /**
  30915. * @type {Function}
  30916. */
  30917. this.pointerChecker;
  30918. /**
  30919. * @type {module:zrender}
  30920. */
  30921. this._zr = zr;
  30922. /**
  30923. * @type {Object}
  30924. */
  30925. this._opt = {};
  30926. // Avoid two roamController bind the same handler
  30927. var bind$$1 = bind;
  30928. var mousedownHandler = bind$$1(mousedown, this);
  30929. var mousemoveHandler = bind$$1(mousemove, this);
  30930. var mouseupHandler = bind$$1(mouseup, this);
  30931. var mousewheelHandler = bind$$1(mousewheel, this);
  30932. var pinchHandler = bind$$1(pinch, this);
  30933. Eventful.call(this);
  30934. /**
  30935. * @param {Function} pointerChecker
  30936. * input: x, y
  30937. * output: boolean
  30938. */
  30939. this.setPointerChecker = function (pointerChecker) {
  30940. this.pointerChecker = pointerChecker;
  30941. };
  30942. /**
  30943. * Notice: only enable needed types. For example, if 'zoom'
  30944. * is not needed, 'zoom' should not be enabled, otherwise
  30945. * default mousewheel behaviour (scroll page) will be disabled.
  30946. *
  30947. * @param {boolean|string} [controlType=true] Specify the control type,
  30948. * which can be null/undefined or true/false
  30949. * or 'pan/move' or 'zoom'/'scale'
  30950. * @param {Object} [opt]
  30951. * @param {Object} [opt.zoomOnMouseWheel=true]
  30952. * @param {Object} [opt.moveOnMouseMove=true]
  30953. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  30954. */
  30955. this.enable = function (controlType, opt) {
  30956. // Disable previous first
  30957. this.disable();
  30958. this._opt = defaults(clone(opt) || {}, {
  30959. zoomOnMouseWheel: true,
  30960. moveOnMouseMove: true,
  30961. preventDefaultMouseMove: true
  30962. });
  30963. if (controlType == null) {
  30964. controlType = true;
  30965. }
  30966. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  30967. zr.on('mousedown', mousedownHandler);
  30968. zr.on('mousemove', mousemoveHandler);
  30969. zr.on('mouseup', mouseupHandler);
  30970. }
  30971. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  30972. zr.on('mousewheel', mousewheelHandler);
  30973. zr.on('pinch', pinchHandler);
  30974. }
  30975. };
  30976. this.disable = function () {
  30977. zr.off('mousedown', mousedownHandler);
  30978. zr.off('mousemove', mousemoveHandler);
  30979. zr.off('mouseup', mouseupHandler);
  30980. zr.off('mousewheel', mousewheelHandler);
  30981. zr.off('pinch', pinchHandler);
  30982. };
  30983. this.dispose = this.disable;
  30984. this.isDragging = function () {
  30985. return this._dragging;
  30986. };
  30987. this.isPinching = function () {
  30988. return this._pinching;
  30989. };
  30990. }
  30991. mixin(RoamController, Eventful);
  30992. function mousedown(e) {
  30993. if (notLeftMouse(e)
  30994. || (e.target && e.target.draggable)
  30995. ) {
  30996. return;
  30997. }
  30998. var x = e.offsetX;
  30999. var y = e.offsetY;
  31000. // Only check on mosedown, but not mousemove.
  31001. // Mouse can be out of target when mouse moving.
  31002. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  31003. this._x = x;
  31004. this._y = y;
  31005. this._dragging = true;
  31006. }
  31007. }
  31008. function mousemove(e) {
  31009. if (notLeftMouse(e)
  31010. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  31011. || !this._dragging
  31012. || e.gestureEvent === 'pinch'
  31013. || isTaken(this._zr, 'globalPan')
  31014. ) {
  31015. return;
  31016. }
  31017. var x = e.offsetX;
  31018. var y = e.offsetY;
  31019. var oldX = this._x;
  31020. var oldY = this._y;
  31021. var dx = x - oldX;
  31022. var dy = y - oldY;
  31023. this._x = x;
  31024. this._y = y;
  31025. this._opt.preventDefaultMouseMove && stop(e.event);
  31026. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  31027. }
  31028. function mouseup(e) {
  31029. if (!notLeftMouse(e)) {
  31030. this._dragging = false;
  31031. }
  31032. }
  31033. function mousewheel(e) {
  31034. // wheelDelta maybe -0 in chrome mac.
  31035. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  31036. return;
  31037. }
  31038. // Convenience:
  31039. // Mac and VM Windows on Mac: scroll up: zoom out.
  31040. // Windows: scroll up: zoom in.
  31041. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  31042. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  31043. }
  31044. function pinch(e) {
  31045. if (isTaken(this._zr, 'globalPan')) {
  31046. return;
  31047. }
  31048. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  31049. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  31050. }
  31051. function zoom(e, zoomDelta, zoomX, zoomY) {
  31052. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  31053. // When mouse is out of roamController rect,
  31054. // default befavoius should not be be disabled, otherwise
  31055. // page sliding is disabled, contrary to expectation.
  31056. stop(e.event);
  31057. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  31058. }
  31059. }
  31060. function checkKeyBinding(roamController, prop, e) {
  31061. var setting = roamController._opt[prop];
  31062. return setting
  31063. && (!isString(setting) || e.event[setting + 'Key']);
  31064. }
  31065. /**
  31066. * For geo and graph.
  31067. *
  31068. * @param {Object} controllerHost
  31069. * @param {module:zrender/Element} controllerHost.target
  31070. */
  31071. function updateViewOnPan(controllerHost, dx, dy) {
  31072. var target = controllerHost.target;
  31073. var pos = target.position;
  31074. pos[0] += dx;
  31075. pos[1] += dy;
  31076. target.dirty();
  31077. }
  31078. /**
  31079. * For geo and graph.
  31080. *
  31081. * @param {Object} controllerHost
  31082. * @param {module:zrender/Element} controllerHost.target
  31083. * @param {number} controllerHost.zoom
  31084. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  31085. */
  31086. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  31087. var target = controllerHost.target;
  31088. var zoomLimit = controllerHost.zoomLimit;
  31089. var pos = target.position;
  31090. var scale = target.scale;
  31091. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  31092. newZoom *= zoomDelta;
  31093. if (zoomLimit) {
  31094. var zoomMin = zoomLimit.min || 0;
  31095. var zoomMax = zoomLimit.max || Infinity;
  31096. newZoom = Math.max(
  31097. Math.min(zoomMax, newZoom),
  31098. zoomMin
  31099. );
  31100. }
  31101. var zoomScale = newZoom / controllerHost.zoom;
  31102. controllerHost.zoom = newZoom;
  31103. // Keep the mouse center when scaling
  31104. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  31105. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  31106. scale[0] *= zoomScale;
  31107. scale[1] *= zoomScale;
  31108. target.dirty();
  31109. }
  31110. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  31111. /**
  31112. * Avoid that: mouse click on a elements that is over geo or graph,
  31113. * but roam is triggered.
  31114. */
  31115. function onIrrelevantElement(e, api, targetCoordSysModel) {
  31116. var model = api.getComponentByElement(e.topTarget);
  31117. // If model is axisModel, it works only if it is injected with coordinateSystem.
  31118. var coordSys = model && model.coordinateSystem;
  31119. return model
  31120. && model !== targetCoordSysModel
  31121. && !IRRELEVANT_EXCLUDES[model.mainType]
  31122. && (coordSys && coordSys.model !== targetCoordSysModel);
  31123. }
  31124. function getFixedItemStyle(model, scale) {
  31125. var itemStyle = model.getItemStyle();
  31126. var areaColor = model.get('areaColor');
  31127. // If user want the color not to be changed when hover,
  31128. // they should both set areaColor and color to be null.
  31129. if (areaColor != null) {
  31130. itemStyle.fill = areaColor;
  31131. }
  31132. return itemStyle;
  31133. }
  31134. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  31135. group.off('click');
  31136. group.off('mousedown');
  31137. if (mapOrGeoModel.get('selectedMode')) {
  31138. group.on('mousedown', function () {
  31139. mapDraw._mouseDownFlag = true;
  31140. });
  31141. group.on('click', function (e) {
  31142. if (!mapDraw._mouseDownFlag) {
  31143. return;
  31144. }
  31145. mapDraw._mouseDownFlag = false;
  31146. var el = e.target;
  31147. while (!el.__regions) {
  31148. el = el.parent;
  31149. }
  31150. if (!el) {
  31151. return;
  31152. }
  31153. var action = {
  31154. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  31155. batch: map(el.__regions, function (region) {
  31156. return {
  31157. name: region.name,
  31158. from: fromView.uid
  31159. };
  31160. })
  31161. };
  31162. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  31163. api.dispatchAction(action);
  31164. updateMapSelected(mapOrGeoModel, group);
  31165. });
  31166. }
  31167. }
  31168. function updateMapSelected(mapOrGeoModel, group) {
  31169. // FIXME
  31170. group.eachChild(function (otherRegionEl) {
  31171. each$1(otherRegionEl.__regions, function (region) {
  31172. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  31173. });
  31174. });
  31175. }
  31176. /**
  31177. * @alias module:echarts/component/helper/MapDraw
  31178. * @param {module:echarts/ExtensionAPI} api
  31179. * @param {boolean} updateGroup
  31180. */
  31181. function MapDraw(api, updateGroup) {
  31182. var group = new Group();
  31183. /**
  31184. * @type {module:echarts/component/helper/RoamController}
  31185. * @private
  31186. */
  31187. this._controller = new RoamController(api.getZr());
  31188. /**
  31189. * @type {Object} {target, zoom, zoomLimit}
  31190. * @private
  31191. */
  31192. this._controllerHost = {target: updateGroup ? group : null};
  31193. /**
  31194. * @type {module:zrender/container/Group}
  31195. * @readOnly
  31196. */
  31197. this.group = group;
  31198. /**
  31199. * @type {boolean}
  31200. * @private
  31201. */
  31202. this._updateGroup = updateGroup;
  31203. /**
  31204. * This flag is used to make sure that only one among
  31205. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  31206. * action may be triggered when `pan`, which is unexpected.
  31207. * @type {booelan}
  31208. */
  31209. this._mouseDownFlag;
  31210. }
  31211. MapDraw.prototype = {
  31212. constructor: MapDraw,
  31213. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  31214. var isGeo = mapOrGeoModel.mainType === 'geo';
  31215. // Map series has data. GEO model that controlled by map series
  31216. // will be assigned with map data. Other GEO model has no data.
  31217. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  31218. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  31219. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  31220. data = mapSeries.getData();
  31221. }
  31222. });
  31223. var geo = mapOrGeoModel.coordinateSystem;
  31224. var group = this.group;
  31225. var scale = geo.scale;
  31226. var groupNewProp = {
  31227. position: geo.position,
  31228. scale: scale
  31229. };
  31230. // No animation when first draw or in action
  31231. if (!group.childAt(0) || payload) {
  31232. group.attr(groupNewProp);
  31233. }
  31234. else {
  31235. updateProps(group, groupNewProp, mapOrGeoModel);
  31236. }
  31237. group.removeAll();
  31238. var itemStyleAccessPath = ['itemStyle', 'normal'];
  31239. var hoverItemStyleAccessPath = ['itemStyle', 'emphasis'];
  31240. var labelAccessPath = ['label', 'normal'];
  31241. var hoverLabelAccessPath = ['label', 'emphasis'];
  31242. var nameMap = createHashMap();
  31243. each$1(geo.regions, function (region) {
  31244. // Consider in GeoJson properties.name may be duplicated, for example,
  31245. // there is multiple region named "United Kindom" or "France" (so many
  31246. // colonies). And it is not appropriate to merge them in geo, which
  31247. // will make them share the same label and bring trouble in label
  31248. // location calculation.
  31249. var regionGroup = nameMap.get(region.name)
  31250. || nameMap.set(region.name, new Group());
  31251. var compoundPath = new CompoundPath({
  31252. shape: {
  31253. paths: []
  31254. }
  31255. });
  31256. regionGroup.add(compoundPath);
  31257. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  31258. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  31259. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  31260. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  31261. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  31262. var labelModel = regionModel.getModel(labelAccessPath);
  31263. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  31264. var dataIdx;
  31265. // Use the itemStyle in data if has data
  31266. if (data) {
  31267. dataIdx = data.indexOfName(region.name);
  31268. // Only visual color of each item will be used. It can be encoded by dataRange
  31269. // But visual color of series is used in symbol drawing
  31270. //
  31271. // Visual color for each series is for the symbol draw
  31272. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  31273. if (visualColor) {
  31274. itemStyle.fill = visualColor;
  31275. }
  31276. }
  31277. each$1(region.geometries, function (geometry) {
  31278. if (geometry.type !== 'polygon') {
  31279. return;
  31280. }
  31281. compoundPath.shape.paths.push(new Polygon({
  31282. shape: {
  31283. points: geometry.exterior
  31284. }
  31285. }));
  31286. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  31287. compoundPath.shape.paths.push(new Polygon({
  31288. shape: {
  31289. points: geometry.interiors[i]
  31290. }
  31291. }));
  31292. }
  31293. });
  31294. compoundPath.setStyle(itemStyle);
  31295. compoundPath.style.strokeNoScale = true;
  31296. compoundPath.culling = true;
  31297. // Label
  31298. var showLabel = labelModel.get('show');
  31299. var hoverShowLabel = hoverLabelModel.get('show');
  31300. var isDataNaN = data && isNaN(data.get('value', dataIdx));
  31301. var itemLayout = data && data.getItemLayout(dataIdx);
  31302. // In the following cases label will be drawn
  31303. // 1. In map series and data value is NaN
  31304. // 2. In geo component
  31305. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  31306. if (
  31307. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  31308. || (itemLayout && itemLayout.showLabel)
  31309. ) {
  31310. var query = !isGeo ? dataIdx : region.name;
  31311. var labelFetcher;
  31312. // Consider dataIdx not found.
  31313. if (!data || dataIdx >= 0) {
  31314. labelFetcher = mapOrGeoModel;
  31315. }
  31316. var textEl = new Text({
  31317. position: region.center.slice(),
  31318. scale: [1 / scale[0], 1 / scale[1]],
  31319. z2: 10,
  31320. silent: true
  31321. });
  31322. setLabelStyle(
  31323. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  31324. {
  31325. labelFetcher: labelFetcher,
  31326. labelDataIndex: query,
  31327. defaultText: region.name,
  31328. useInsideStyle: false
  31329. },
  31330. {
  31331. textAlign: 'center',
  31332. textVerticalAlign: 'middle'
  31333. }
  31334. );
  31335. regionGroup.add(textEl);
  31336. }
  31337. // setItemGraphicEl, setHoverStyle after all polygons and labels
  31338. // are added to the rigionGroup
  31339. if (data) {
  31340. data.setItemGraphicEl(dataIdx, regionGroup);
  31341. }
  31342. else {
  31343. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  31344. // Package custom mouse event for geo component
  31345. compoundPath.eventData = {
  31346. componentType: 'geo',
  31347. geoIndex: mapOrGeoModel.componentIndex,
  31348. name: region.name,
  31349. region: (regionModel && regionModel.option) || {}
  31350. };
  31351. }
  31352. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  31353. groupRegions.push(region);
  31354. setHoverStyle(
  31355. regionGroup,
  31356. hoverItemStyle,
  31357. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  31358. );
  31359. group.add(regionGroup);
  31360. });
  31361. this._updateController(mapOrGeoModel, ecModel, api);
  31362. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  31363. updateMapSelected(mapOrGeoModel, group);
  31364. },
  31365. remove: function () {
  31366. this.group.removeAll();
  31367. this._controller.dispose();
  31368. this._controllerHost = {};
  31369. },
  31370. _updateController: function (mapOrGeoModel, ecModel, api) {
  31371. var geo = mapOrGeoModel.coordinateSystem;
  31372. var controller = this._controller;
  31373. var controllerHost = this._controllerHost;
  31374. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  31375. controllerHost.zoom = geo.getZoom();
  31376. // roamType is will be set default true if it is null
  31377. controller.enable(mapOrGeoModel.get('roam') || false);
  31378. var mainType = mapOrGeoModel.mainType;
  31379. function makeActionBase() {
  31380. var action = {
  31381. type: 'geoRoam',
  31382. componentType: mainType
  31383. };
  31384. action[mainType + 'Id'] = mapOrGeoModel.id;
  31385. return action;
  31386. }
  31387. controller.off('pan').on('pan', function (dx, dy) {
  31388. this._mouseDownFlag = false;
  31389. updateViewOnPan(controllerHost, dx, dy);
  31390. api.dispatchAction(extend(makeActionBase(), {
  31391. dx: dx,
  31392. dy: dy
  31393. }));
  31394. }, this);
  31395. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  31396. this._mouseDownFlag = false;
  31397. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  31398. api.dispatchAction(extend(makeActionBase(), {
  31399. zoom: zoom,
  31400. originX: mouseX,
  31401. originY: mouseY
  31402. }));
  31403. if (this._updateGroup) {
  31404. var group = this.group;
  31405. var scale = group.scale;
  31406. group.traverse(function (el) {
  31407. if (el.type === 'text') {
  31408. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  31409. }
  31410. });
  31411. }
  31412. }, this);
  31413. controller.setPointerChecker(function (e, x, y) {
  31414. return geo.getViewRectAfterRoam().contain(x, y)
  31415. && !onIrrelevantElement(e, api, mapOrGeoModel);
  31416. });
  31417. }
  31418. };
  31419. extendChartView({
  31420. type: 'map',
  31421. render: function (mapModel, ecModel, api, payload) {
  31422. // Not render if it is an toggleSelect action from self
  31423. if (payload && payload.type === 'mapToggleSelect'
  31424. && payload.from === this.uid
  31425. ) {
  31426. return;
  31427. }
  31428. var group = this.group;
  31429. group.removeAll();
  31430. if (mapModel.getHostGeoModel()) {
  31431. return;
  31432. }
  31433. // Not update map if it is an roam action from self
  31434. if (!(payload && payload.type === 'geoRoam'
  31435. && payload.componentType === 'series'
  31436. && payload.seriesId === mapModel.id
  31437. )
  31438. ) {
  31439. if (mapModel.needsDrawMap) {
  31440. var mapDraw = this._mapDraw || new MapDraw(api, true);
  31441. group.add(mapDraw.group);
  31442. mapDraw.draw(mapModel, ecModel, api, this, payload);
  31443. this._mapDraw = mapDraw;
  31444. }
  31445. else {
  31446. // Remove drawed map
  31447. this._mapDraw && this._mapDraw.remove();
  31448. this._mapDraw = null;
  31449. }
  31450. }
  31451. else {
  31452. var mapDraw = this._mapDraw;
  31453. mapDraw && group.add(mapDraw.group);
  31454. }
  31455. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  31456. && this._renderSymbols(mapModel, ecModel, api);
  31457. },
  31458. remove: function () {
  31459. this._mapDraw && this._mapDraw.remove();
  31460. this._mapDraw = null;
  31461. this.group.removeAll();
  31462. },
  31463. dispose: function () {
  31464. this._mapDraw && this._mapDraw.remove();
  31465. this._mapDraw = null;
  31466. },
  31467. _renderSymbols: function (mapModel, ecModel, api) {
  31468. var originalData = mapModel.originalData;
  31469. var group = this.group;
  31470. originalData.each('value', function (value, idx) {
  31471. if (isNaN(value)) {
  31472. return;
  31473. }
  31474. var layout = originalData.getItemLayout(idx);
  31475. if (!layout || !layout.point) {
  31476. // Not exists in map
  31477. return;
  31478. }
  31479. var point = layout.point;
  31480. var offset = layout.offset;
  31481. var circle = new Circle({
  31482. style: {
  31483. // Because the special of map draw.
  31484. // Which needs statistic of multiple series and draw on one map.
  31485. // And each series also need a symbol with legend color
  31486. //
  31487. // Layout and visual are put one the different data
  31488. fill: mapModel.getData().getVisual('color')
  31489. },
  31490. shape: {
  31491. cx: point[0] + offset * 9,
  31492. cy: point[1],
  31493. r: 3
  31494. },
  31495. silent: true,
  31496. // Do not overlap the first series, on which labels are displayed.
  31497. z2: !offset ? 10 : 8
  31498. });
  31499. // First data on the same region
  31500. if (!offset) {
  31501. var fullData = mapModel.mainSeries.getData();
  31502. var name = originalData.getName(idx);
  31503. var fullIndex = fullData.indexOfName(name);
  31504. var itemModel = originalData.getItemModel(idx);
  31505. var labelModel = itemModel.getModel('label.normal');
  31506. var hoverLabelModel = itemModel.getModel('label.emphasis');
  31507. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  31508. var normalText = retrieve2(
  31509. mapModel.getFormattedLabel(idx, 'normal'),
  31510. name
  31511. );
  31512. var emphasisText = retrieve2(
  31513. mapModel.getFormattedLabel(idx, 'emphasis'),
  31514. normalText
  31515. );
  31516. var onEmphasis = function () {
  31517. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  31518. text: hoverLabelModel.get('show') ? emphasisText : null
  31519. }, {isRectText: true, useInsideStyle: false}, true);
  31520. circle.style.extendFrom(hoverStyle);
  31521. // Make label upper than others if overlaps.
  31522. circle.__mapOriginalZ2 = circle.z2;
  31523. circle.z2 += 1;
  31524. };
  31525. var onNormal = function () {
  31526. setTextStyle(circle.style, labelModel, {
  31527. text: labelModel.get('show') ? normalText : null,
  31528. textPosition: labelModel.getShallow('position') || 'bottom'
  31529. }, {isRectText: true, useInsideStyle: false});
  31530. if (circle.__mapOriginalZ2 != null) {
  31531. circle.z2 = circle.__mapOriginalZ2;
  31532. circle.__mapOriginalZ2 = null;
  31533. }
  31534. };
  31535. polygonGroups.on('mouseover', onEmphasis)
  31536. .on('mouseout', onNormal)
  31537. .on('emphasis', onEmphasis)
  31538. .on('normal', onNormal);
  31539. onNormal();
  31540. }
  31541. group.add(circle);
  31542. });
  31543. }
  31544. });
  31545. /**
  31546. * @param {module:echarts/coord/View} view
  31547. * @param {Object} payload
  31548. * @param {Object} [zoomLimit]
  31549. */
  31550. function updateCenterAndZoom(
  31551. view, payload, zoomLimit
  31552. ) {
  31553. var previousZoom = view.getZoom();
  31554. var center = view.getCenter();
  31555. var zoom = payload.zoom;
  31556. var point = view.dataToPoint(center);
  31557. if (payload.dx != null && payload.dy != null) {
  31558. point[0] -= payload.dx;
  31559. point[1] -= payload.dy;
  31560. var center = view.pointToData(point);
  31561. view.setCenter(center);
  31562. }
  31563. if (zoom != null) {
  31564. if (zoomLimit) {
  31565. var zoomMin = zoomLimit.min || 0;
  31566. var zoomMax = zoomLimit.max || Infinity;
  31567. zoom = Math.max(
  31568. Math.min(previousZoom * zoom, zoomMax),
  31569. zoomMin
  31570. ) / previousZoom;
  31571. }
  31572. // Zoom on given point(originX, originY)
  31573. view.scale[0] *= zoom;
  31574. view.scale[1] *= zoom;
  31575. var position = view.position;
  31576. var fixX = (payload.originX - position[0]) * (zoom - 1);
  31577. var fixY = (payload.originY - position[1]) * (zoom - 1);
  31578. position[0] -= fixX;
  31579. position[1] -= fixY;
  31580. view.updateTransform();
  31581. // Get the new center
  31582. var center = view.pointToData(point);
  31583. view.setCenter(center);
  31584. view.setZoom(zoom * previousZoom);
  31585. }
  31586. return {
  31587. center: view.getCenter(),
  31588. zoom: view.getZoom()
  31589. };
  31590. }
  31591. /**
  31592. * @payload
  31593. * @property {string} [componentType=series]
  31594. * @property {number} [dx]
  31595. * @property {number} [dy]
  31596. * @property {number} [zoom]
  31597. * @property {number} [originX]
  31598. * @property {number} [originY]
  31599. */
  31600. registerAction({
  31601. type: 'geoRoam',
  31602. event: 'geoRoam',
  31603. update: 'updateLayout'
  31604. }, function (payload, ecModel) {
  31605. var componentType = payload.componentType || 'series';
  31606. ecModel.eachComponent(
  31607. { mainType: componentType, query: payload },
  31608. function (componentModel) {
  31609. var geo = componentModel.coordinateSystem;
  31610. if (geo.type !== 'geo') {
  31611. return;
  31612. }
  31613. var res = updateCenterAndZoom(
  31614. geo, payload, componentModel.get('scaleLimit')
  31615. );
  31616. componentModel.setCenter
  31617. && componentModel.setCenter(res.center);
  31618. componentModel.setZoom
  31619. && componentModel.setZoom(res.zoom);
  31620. // All map series with same `map` use the same geo coordinate system
  31621. // So the center and zoom must be in sync. Include the series not selected by legend
  31622. if (componentType === 'series') {
  31623. each$1(componentModel.seriesGroup, function (seriesModel) {
  31624. seriesModel.setCenter(res.center);
  31625. seriesModel.setZoom(res.zoom);
  31626. });
  31627. }
  31628. }
  31629. );
  31630. });
  31631. var mapSymbolLayout = function (ecModel) {
  31632. var processedMapType = {};
  31633. ecModel.eachSeriesByType('map', function (mapSeries) {
  31634. var mapType = mapSeries.getMapType();
  31635. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  31636. return;
  31637. }
  31638. var mapSymbolOffsets = {};
  31639. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  31640. var geo = subMapSeries.coordinateSystem;
  31641. var data = subMapSeries.originalData;
  31642. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  31643. data.each('value', function (value, idx) {
  31644. var name = data.getName(idx);
  31645. var region = geo.getRegion(name);
  31646. // If input series.data is [11, 22, '-'/null/undefined, 44],
  31647. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  31648. // not be drawn. So here must validate if value is NaN.
  31649. if (!region || isNaN(value)) {
  31650. return;
  31651. }
  31652. var offset = mapSymbolOffsets[name] || 0;
  31653. var point = geo.dataToPoint(region.center);
  31654. mapSymbolOffsets[name] = offset + 1;
  31655. data.setItemLayout(idx, {
  31656. point: point,
  31657. offset: offset
  31658. });
  31659. });
  31660. }
  31661. });
  31662. // Show label of those region not has legendSymbol(which is offset 0)
  31663. var data = mapSeries.getData();
  31664. data.each(function (idx) {
  31665. var name = data.getName(idx);
  31666. var layout = data.getItemLayout(idx) || {};
  31667. layout.showLabel = !mapSymbolOffsets[name];
  31668. data.setItemLayout(idx, layout);
  31669. });
  31670. processedMapType[mapType] = true;
  31671. });
  31672. };
  31673. var mapVisual = function (ecModel) {
  31674. ecModel.eachSeriesByType('map', function (seriesModel) {
  31675. var colorList = seriesModel.get('color');
  31676. var itemStyleModel = seriesModel.getModel('itemStyle.normal');
  31677. var areaColor = itemStyleModel.get('areaColor');
  31678. var color = itemStyleModel.get('color')
  31679. || colorList[seriesModel.seriesIndex % colorList.length];
  31680. seriesModel.getData().setVisual({
  31681. 'areaColor': areaColor,
  31682. 'color': color
  31683. });
  31684. });
  31685. };
  31686. // FIXME 公用?
  31687. /**
  31688. * @param {Array.<module:echarts/data/List>} datas
  31689. * @param {string} statisticType 'average' 'sum'
  31690. * @inner
  31691. */
  31692. function dataStatistics(datas, statisticType) {
  31693. var dataNameMap = {};
  31694. var dims = ['value'];
  31695. each$1(datas, function (data) {
  31696. data.each(dims, function (value, idx) {
  31697. // Add prefix to avoid conflict with Object.prototype.
  31698. var mapKey = 'ec-' + data.getName(idx);
  31699. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  31700. if (!isNaN(value)) {
  31701. dataNameMap[mapKey].push(value);
  31702. }
  31703. });
  31704. });
  31705. return datas[0].map(dims, function (value, idx) {
  31706. var mapKey = 'ec-' + datas[0].getName(idx);
  31707. var sum = 0;
  31708. var min = Infinity;
  31709. var max = -Infinity;
  31710. var len = dataNameMap[mapKey].length;
  31711. for (var i = 0; i < len; i++) {
  31712. min = Math.min(min, dataNameMap[mapKey][i]);
  31713. max = Math.max(max, dataNameMap[mapKey][i]);
  31714. sum += dataNameMap[mapKey][i];
  31715. }
  31716. var result;
  31717. if (statisticType === 'min') {
  31718. result = min;
  31719. }
  31720. else if (statisticType === 'max') {
  31721. result = max;
  31722. }
  31723. else if (statisticType === 'average') {
  31724. result = sum / len;
  31725. }
  31726. else {
  31727. result = sum;
  31728. }
  31729. return len === 0 ? NaN : result;
  31730. });
  31731. }
  31732. var mapDataStatistic = function (ecModel) {
  31733. var seriesGroups = {};
  31734. ecModel.eachSeriesByType('map', function (seriesModel) {
  31735. var hostGeoModel = seriesModel.getHostGeoModel();
  31736. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  31737. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  31738. });
  31739. each$1(seriesGroups, function (seriesList, key) {
  31740. var data = dataStatistics(
  31741. map(seriesList, function (seriesModel) {
  31742. return seriesModel.getData();
  31743. }),
  31744. seriesList[0].get('mapValueCalculation')
  31745. );
  31746. for (var i = 0; i < seriesList.length; i++) {
  31747. seriesList[i].originalData = seriesList[i].getData();
  31748. }
  31749. // FIXME Put where?
  31750. for (var i = 0; i < seriesList.length; i++) {
  31751. seriesList[i].seriesGroup = seriesList;
  31752. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  31753. seriesList[i].setData(data.cloneShallow());
  31754. seriesList[i].mainSeries = seriesList[0];
  31755. }
  31756. });
  31757. };
  31758. var backwardCompat$2 = function (option) {
  31759. // Save geoCoord
  31760. var mapSeries = [];
  31761. each$1(option.series, function (seriesOpt) {
  31762. if (seriesOpt && seriesOpt.type === 'map') {
  31763. mapSeries.push(seriesOpt);
  31764. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  31765. // Put x, y, width, height, x2, y2 in the top level
  31766. defaults(seriesOpt, seriesOpt.mapLocation);
  31767. }
  31768. });
  31769. };
  31770. registerLayout(mapSymbolLayout);
  31771. registerVisual(mapVisual);
  31772. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  31773. registerPreprocessor(backwardCompat$2);
  31774. createDataSelectAction('map', [{
  31775. type: 'mapToggleSelect',
  31776. event: 'mapselectchanged',
  31777. method: 'toggleSelected'
  31778. }, {
  31779. type: 'mapSelect',
  31780. event: 'mapselected',
  31781. method: 'select'
  31782. }, {
  31783. type: 'mapUnSelect',
  31784. event: 'mapunselected',
  31785. method: 'unSelect'
  31786. }]);
  31787. /**
  31788. * Link lists and struct (graph or tree)
  31789. */
  31790. var each$10 = each$1;
  31791. var DATAS = '\0__link_datas';
  31792. var MAIN_DATA = '\0__link_mainData';
  31793. // Caution:
  31794. // In most case, either list or its shallow clones (see list.cloneShallow)
  31795. // is active in echarts process. So considering heap memory consumption,
  31796. // we do not clone tree or graph, but share them among list and its shallow clones.
  31797. // But in some rare case, we have to keep old list (like do animation in chart). So
  31798. // please take care that both the old list and the new list share the same tree/graph.
  31799. /**
  31800. * @param {Object} opt
  31801. * @param {module:echarts/data/List} opt.mainData
  31802. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  31803. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  31804. * @param {Object} [opt.datas] {dataType: data},
  31805. * like: {node: nodeList, edge: edgeList}.
  31806. * Should contain mainData.
  31807. * @param {Object} [opt.datasAttr] {dataType: attr},
  31808. * designation: struct[datasAttr[dataType]] = list;
  31809. */
  31810. function linkList(opt) {
  31811. var mainData = opt.mainData;
  31812. var datas = opt.datas;
  31813. if (!datas) {
  31814. datas = {main: mainData};
  31815. opt.datasAttr = {main: 'data'};
  31816. }
  31817. opt.datas = opt.mainData = null;
  31818. linkAll(mainData, datas, opt);
  31819. // Porxy data original methods.
  31820. each$10(datas, function (data) {
  31821. each$10(mainData.TRANSFERABLE_METHODS, function (methodName) {
  31822. data.wrapMethod(methodName, curry(transferInjection, opt));
  31823. });
  31824. });
  31825. // Beyond transfer, additional features should be added to `cloneShallow`.
  31826. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  31827. // Only mainData trigger change, because struct.update may trigger
  31828. // another changable methods, which may bring about dead lock.
  31829. each$10(mainData.CHANGABLE_METHODS, function (methodName) {
  31830. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  31831. });
  31832. // Make sure datas contains mainData.
  31833. assert(datas[mainData.dataType] === mainData);
  31834. }
  31835. function transferInjection(opt, res) {
  31836. if (isMainData(this)) {
  31837. // Transfer datas to new main data.
  31838. var datas = extend({}, this[DATAS]);
  31839. datas[this.dataType] = res;
  31840. linkAll(res, datas, opt);
  31841. }
  31842. else {
  31843. // Modify the reference in main data to point newData.
  31844. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  31845. }
  31846. return res;
  31847. }
  31848. function changeInjection(opt, res) {
  31849. opt.struct && opt.struct.update(this);
  31850. return res;
  31851. }
  31852. function cloneShallowInjection(opt, res) {
  31853. // cloneShallow, which brings about some fragilities, may be inappropriate
  31854. // to be exposed as an API. So for implementation simplicity we can make
  31855. // the restriction that cloneShallow of not-mainData should not be invoked
  31856. // outside, but only be invoked here.
  31857. each$10(res[DATAS], function (data, dataType) {
  31858. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  31859. });
  31860. return res;
  31861. }
  31862. /**
  31863. * Supplement method to List.
  31864. *
  31865. * @public
  31866. * @param {string} [dataType] If not specified, return mainData.
  31867. * @return {module:echarts/data/List}
  31868. */
  31869. function getLinkedData(dataType) {
  31870. var mainData = this[MAIN_DATA];
  31871. return (dataType == null || mainData == null)
  31872. ? mainData
  31873. : mainData[DATAS][dataType];
  31874. }
  31875. function isMainData(data) {
  31876. return data[MAIN_DATA] === data;
  31877. }
  31878. function linkAll(mainData, datas, opt) {
  31879. mainData[DATAS] = {};
  31880. each$10(datas, function (data, dataType) {
  31881. linkSingle(data, dataType, mainData, opt);
  31882. });
  31883. }
  31884. function linkSingle(data, dataType, mainData, opt) {
  31885. mainData[DATAS][dataType] = data;
  31886. data[MAIN_DATA] = mainData;
  31887. data.dataType = dataType;
  31888. if (opt.struct) {
  31889. data[opt.structAttr] = opt.struct;
  31890. opt.struct[opt.datasAttr[dataType]] = data;
  31891. }
  31892. // Supplement method.
  31893. data.getLinkedData = getLinkedData;
  31894. }
  31895. /**
  31896. * Tree data structure
  31897. *
  31898. * @module echarts/data/Tree
  31899. */
  31900. /**
  31901. * @constructor module:echarts/data/Tree~TreeNode
  31902. * @param {string} name
  31903. * @param {module:echarts/data/Tree} hostTree
  31904. */
  31905. var TreeNode = function (name, hostTree) {
  31906. /**
  31907. * @type {string}
  31908. */
  31909. this.name = name || '';
  31910. /**
  31911. * Depth of node
  31912. *
  31913. * @type {number}
  31914. * @readOnly
  31915. */
  31916. this.depth = 0;
  31917. /**
  31918. * Height of the subtree rooted at this node.
  31919. * @type {number}
  31920. * @readOnly
  31921. */
  31922. this.height = 0;
  31923. /**
  31924. * @type {module:echarts/data/Tree~TreeNode}
  31925. * @readOnly
  31926. */
  31927. this.parentNode = null;
  31928. /**
  31929. * Reference to list item.
  31930. * Do not persistent dataIndex outside,
  31931. * besause it may be changed by list.
  31932. * If dataIndex -1,
  31933. * this node is logical deleted (filtered) in list.
  31934. *
  31935. * @type {Object}
  31936. * @readOnly
  31937. */
  31938. this.dataIndex = -1;
  31939. /**
  31940. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  31941. * @readOnly
  31942. */
  31943. this.children = [];
  31944. /**
  31945. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  31946. * @pubilc
  31947. */
  31948. this.viewChildren = [];
  31949. /**
  31950. * @type {moduel:echarts/data/Tree}
  31951. * @readOnly
  31952. */
  31953. this.hostTree = hostTree;
  31954. };
  31955. TreeNode.prototype = {
  31956. constructor: TreeNode,
  31957. /**
  31958. * The node is removed.
  31959. * @return {boolean} is removed.
  31960. */
  31961. isRemoved: function () {
  31962. return this.dataIndex < 0;
  31963. },
  31964. /**
  31965. * Travel this subtree (include this node).
  31966. * Usage:
  31967. * node.eachNode(function () { ... }); // preorder
  31968. * node.eachNode('preorder', function () { ... }); // preorder
  31969. * node.eachNode('postorder', function () { ... }); // postorder
  31970. * node.eachNode(
  31971. * {order: 'postorder', attr: 'viewChildren'},
  31972. * function () { ... }
  31973. * ); // postorder
  31974. *
  31975. * @param {(Object|string)} options If string, means order.
  31976. * @param {string=} options.order 'preorder' or 'postorder'
  31977. * @param {string=} options.attr 'children' or 'viewChildren'
  31978. * @param {Function} cb If in preorder and return false,
  31979. * its subtree will not be visited.
  31980. * @param {Object} [context]
  31981. */
  31982. eachNode: function (options, cb, context) {
  31983. if (typeof options === 'function') {
  31984. context = cb;
  31985. cb = options;
  31986. options = null;
  31987. }
  31988. options = options || {};
  31989. if (isString(options)) {
  31990. options = {order: options};
  31991. }
  31992. var order = options.order || 'preorder';
  31993. var children = this[options.attr || 'children'];
  31994. var suppressVisitSub;
  31995. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  31996. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  31997. children[i].eachNode(options, cb, context);
  31998. }
  31999. order === 'postorder' && cb.call(context, this);
  32000. },
  32001. /**
  32002. * Update depth and height of this subtree.
  32003. *
  32004. * @param {number} depth
  32005. */
  32006. updateDepthAndHeight: function (depth) {
  32007. var height = 0;
  32008. this.depth = depth;
  32009. for (var i = 0; i < this.children.length; i++) {
  32010. var child = this.children[i];
  32011. child.updateDepthAndHeight(depth + 1);
  32012. if (child.height > height) {
  32013. height = child.height;
  32014. }
  32015. }
  32016. this.height = height + 1;
  32017. },
  32018. /**
  32019. * @param {string} id
  32020. * @return {module:echarts/data/Tree~TreeNode}
  32021. */
  32022. getNodeById: function (id) {
  32023. if (this.getId() === id) {
  32024. return this;
  32025. }
  32026. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  32027. var res = children[i].getNodeById(id);
  32028. if (res) {
  32029. return res;
  32030. }
  32031. }
  32032. },
  32033. /**
  32034. * @param {module:echarts/data/Tree~TreeNode} node
  32035. * @return {boolean}
  32036. */
  32037. contains: function (node) {
  32038. if (node === this) {
  32039. return true;
  32040. }
  32041. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  32042. var res = children[i].contains(node);
  32043. if (res) {
  32044. return res;
  32045. }
  32046. }
  32047. },
  32048. /**
  32049. * @param {boolean} includeSelf Default false.
  32050. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  32051. */
  32052. getAncestors: function (includeSelf) {
  32053. var ancestors = [];
  32054. var node = includeSelf ? this : this.parentNode;
  32055. while (node) {
  32056. ancestors.push(node);
  32057. node = node.parentNode;
  32058. }
  32059. ancestors.reverse();
  32060. return ancestors;
  32061. },
  32062. /**
  32063. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  32064. * @return {number} Value.
  32065. */
  32066. getValue: function (dimension) {
  32067. var data = this.hostTree.data;
  32068. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  32069. },
  32070. /**
  32071. * @param {Object} layout
  32072. * @param {boolean=} [merge=false]
  32073. */
  32074. setLayout: function (layout, merge$$1) {
  32075. this.dataIndex >= 0
  32076. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  32077. },
  32078. /**
  32079. * @return {Object} layout
  32080. */
  32081. getLayout: function () {
  32082. return this.hostTree.data.getItemLayout(this.dataIndex);
  32083. },
  32084. /**
  32085. * @param {string} [path]
  32086. * @return {module:echarts/model/Model}
  32087. */
  32088. getModel: function (path) {
  32089. if (this.dataIndex < 0) {
  32090. return;
  32091. }
  32092. var hostTree = this.hostTree;
  32093. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  32094. var levelModel = this.getLevelModel();
  32095. var leavesModel;
  32096. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  32097. leavesModel = this.getLeavesModel();
  32098. }
  32099. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  32100. },
  32101. /**
  32102. * @return {module:echarts/model/Model}
  32103. */
  32104. getLevelModel: function () {
  32105. return (this.hostTree.levelModels || [])[this.depth];
  32106. },
  32107. /**
  32108. * @return {module:echarts/model/Model}
  32109. */
  32110. getLeavesModel: function () {
  32111. return this.hostTree.leavesModel;
  32112. },
  32113. /**
  32114. * @example
  32115. * setItemVisual('color', color);
  32116. * setItemVisual({
  32117. * 'color': color
  32118. * });
  32119. */
  32120. setVisual: function (key, value) {
  32121. this.dataIndex >= 0
  32122. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  32123. },
  32124. /**
  32125. * Get item visual
  32126. */
  32127. getVisual: function (key, ignoreParent) {
  32128. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  32129. },
  32130. /**
  32131. * @public
  32132. * @return {number}
  32133. */
  32134. getRawIndex: function () {
  32135. return this.hostTree.data.getRawIndex(this.dataIndex);
  32136. },
  32137. /**
  32138. * @public
  32139. * @return {string}
  32140. */
  32141. getId: function () {
  32142. return this.hostTree.data.getId(this.dataIndex);
  32143. }
  32144. };
  32145. /**
  32146. * @constructor
  32147. * @alias module:echarts/data/Tree
  32148. * @param {module:echarts/model/Model} hostModel
  32149. * @param {Array.<Object>} levelOptions
  32150. * @param {Object} leavesOption
  32151. */
  32152. function Tree(hostModel, levelOptions, leavesOption) {
  32153. /**
  32154. * @type {module:echarts/data/Tree~TreeNode}
  32155. * @readOnly
  32156. */
  32157. this.root;
  32158. /**
  32159. * @type {module:echarts/data/List}
  32160. * @readOnly
  32161. */
  32162. this.data;
  32163. /**
  32164. * Index of each item is the same as the raw index of coresponding list item.
  32165. * @private
  32166. * @type {Array.<module:echarts/data/Tree~TreeNode}
  32167. */
  32168. this._nodes = [];
  32169. /**
  32170. * @private
  32171. * @readOnly
  32172. * @type {module:echarts/model/Model}
  32173. */
  32174. this.hostModel = hostModel;
  32175. /**
  32176. * @private
  32177. * @readOnly
  32178. * @type {Array.<module:echarts/model/Model}
  32179. */
  32180. this.levelModels = map(levelOptions || [], function (levelDefine) {
  32181. return new Model(levelDefine, hostModel, hostModel.ecModel);
  32182. });
  32183. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  32184. }
  32185. Tree.prototype = {
  32186. constructor: Tree,
  32187. type: 'tree',
  32188. /**
  32189. * Travel this subtree (include this node).
  32190. * Usage:
  32191. * node.eachNode(function () { ... }); // preorder
  32192. * node.eachNode('preorder', function () { ... }); // preorder
  32193. * node.eachNode('postorder', function () { ... }); // postorder
  32194. * node.eachNode(
  32195. * {order: 'postorder', attr: 'viewChildren'},
  32196. * function () { ... }
  32197. * ); // postorder
  32198. *
  32199. * @param {(Object|string)} options If string, means order.
  32200. * @param {string=} options.order 'preorder' or 'postorder'
  32201. * @param {string=} options.attr 'children' or 'viewChildren'
  32202. * @param {Function} cb
  32203. * @param {Object} [context]
  32204. */
  32205. eachNode: function(options, cb, context) {
  32206. this.root.eachNode(options, cb, context);
  32207. },
  32208. /**
  32209. * @param {number} dataIndex
  32210. * @return {module:echarts/data/Tree~TreeNode}
  32211. */
  32212. getNodeByDataIndex: function (dataIndex) {
  32213. var rawIndex = this.data.getRawIndex(dataIndex);
  32214. return this._nodes[rawIndex];
  32215. },
  32216. /**
  32217. * @param {string} name
  32218. * @return {module:echarts/data/Tree~TreeNode}
  32219. */
  32220. getNodeByName: function (name) {
  32221. return this.root.getNodeByName(name);
  32222. },
  32223. /**
  32224. * Update item available by list,
  32225. * when list has been performed options like 'filterSelf' or 'map'.
  32226. */
  32227. update: function () {
  32228. var data = this.data;
  32229. var nodes = this._nodes;
  32230. for (var i = 0, len = nodes.length; i < len; i++) {
  32231. nodes[i].dataIndex = -1;
  32232. }
  32233. for (var i = 0, len = data.count(); i < len; i++) {
  32234. nodes[data.getRawIndex(i)].dataIndex = i;
  32235. }
  32236. },
  32237. /**
  32238. * Clear all layouts
  32239. */
  32240. clearLayouts: function () {
  32241. this.data.clearItemLayouts();
  32242. }
  32243. };
  32244. /**
  32245. * data node format:
  32246. * {
  32247. * name: ...
  32248. * value: ...
  32249. * children: [
  32250. * {
  32251. * name: ...
  32252. * value: ...
  32253. * children: ...
  32254. * },
  32255. * ...
  32256. * ]
  32257. * }
  32258. *
  32259. * @static
  32260. * @param {Object} dataRoot Root node.
  32261. * @param {module:echarts/model/Model} hostModel
  32262. * @param {Object} treeOptions
  32263. * @param {Array.<Object>} treeOptions.levels
  32264. * @param {Array.<Object>} treeOptions.leaves
  32265. * @return module:echarts/data/Tree
  32266. */
  32267. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  32268. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  32269. var listData = [];
  32270. var dimMax = 1;
  32271. buildHierarchy(dataRoot);
  32272. function buildHierarchy(dataNode, parentNode) {
  32273. var value = dataNode.value;
  32274. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  32275. listData.push(dataNode);
  32276. var node = new TreeNode(dataNode.name, tree);
  32277. parentNode
  32278. ? addChild(node, parentNode)
  32279. : (tree.root = node);
  32280. tree._nodes.push(node);
  32281. var children = dataNode.children;
  32282. if (children) {
  32283. for (var i = 0; i < children.length; i++) {
  32284. buildHierarchy(children[i], node);
  32285. }
  32286. }
  32287. }
  32288. tree.root.updateDepthAndHeight(0);
  32289. var dimensions = completeDimensions([{name: 'value'}], listData, {dimCount: dimMax});
  32290. var list = new List(dimensions, hostModel);
  32291. list.initData(listData);
  32292. linkList({
  32293. mainData: list,
  32294. struct: tree,
  32295. structAttr: 'tree'
  32296. });
  32297. tree.update();
  32298. return tree;
  32299. };
  32300. /**
  32301. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  32302. * so this function is not ready and not necessary to be public.
  32303. *
  32304. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  32305. */
  32306. function addChild(child, node) {
  32307. var children = node.children;
  32308. if (child.parentNode === node) {
  32309. return;
  32310. }
  32311. children.push(child);
  32312. child.parentNode = node;
  32313. }
  32314. /**
  32315. * @file Create data struct and define tree view's series model
  32316. */
  32317. SeriesModel.extend({
  32318. type: 'series.tree',
  32319. layoutInfo: null,
  32320. // can support the position parameters 'left', 'top','right','bottom', 'width',
  32321. // 'height' in the setOption() with 'merge' mode normal.
  32322. layoutMode: 'box',
  32323. /**
  32324. * Init a tree data structure from data in option series
  32325. * @param {Object} option the object used to config echarts view
  32326. * @return {module:echarts/data/List} storage initial data
  32327. */
  32328. getInitialData: function (option) {
  32329. //create an virtual root
  32330. var root = {name: option.name, children: option.data};
  32331. var leaves = option.leaves || {};
  32332. var treeOption = {};
  32333. treeOption.leaves = leaves;
  32334. var tree = Tree.createTree(root, this, treeOption);
  32335. var treeDepth = 0;
  32336. tree.eachNode('preorder', function (node) {
  32337. if (node.depth > treeDepth) {
  32338. treeDepth = node.depth;
  32339. }
  32340. });
  32341. var expandAndCollapse = option.expandAndCollapse;
  32342. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  32343. ? option.initialTreeDepth : treeDepth;
  32344. tree.root.eachNode('preorder', function (node) {
  32345. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  32346. node.isExpand = (item && item.collapsed != null)
  32347. ? !item.collapsed
  32348. : node.depth <= expandTreeDepth;
  32349. });
  32350. return tree.data;
  32351. },
  32352. /**
  32353. * @override
  32354. * @param {number} dataIndex
  32355. */
  32356. formatTooltip: function (dataIndex) {
  32357. var tree = this.getData().tree;
  32358. var realRoot = tree.root.children[0];
  32359. var node = tree.getNodeByDataIndex(dataIndex);
  32360. var value = node.getValue();
  32361. var name = node.name;
  32362. while (node && (node !== realRoot)) {
  32363. name = node.parentNode.name + '.' + name;
  32364. node = node.parentNode;
  32365. }
  32366. return encodeHTML(name + (
  32367. (isNaN(value) || value == null) ? '' : ' : ' + value
  32368. ));
  32369. },
  32370. defaultOption: {
  32371. zlevel: 0,
  32372. z: 2,
  32373. // the position of the whole view
  32374. left: '12%',
  32375. top: '12%',
  32376. right: '12%',
  32377. bottom: '12%',
  32378. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  32379. layout: 'orthogonal',
  32380. // the orient of orthoginal layout, can be setted to 'horizontal' or 'vertical'
  32381. orient: 'horizontal',
  32382. symbol: 'emptyCircle',
  32383. symbolSize: 7,
  32384. expandAndCollapse: true,
  32385. initialTreeDepth: 2,
  32386. lineStyle: {
  32387. normal: {
  32388. color: '#ccc',
  32389. width: 1.5,
  32390. curveness: 0.5
  32391. }
  32392. },
  32393. itemStyle: {
  32394. normal: {
  32395. color: 'lightsteelblue',
  32396. borderColor: '#c23531',
  32397. borderWidth: 1.5
  32398. }
  32399. },
  32400. label: {
  32401. normal: {
  32402. show: true,
  32403. color: '#555'
  32404. }
  32405. },
  32406. leaves: {
  32407. label: {
  32408. normal: {
  32409. show: true
  32410. }
  32411. }
  32412. },
  32413. animationEasing: 'linear',
  32414. animationDuration: 700,
  32415. animationDurationUpdate: 1000
  32416. }
  32417. });
  32418. /**
  32419. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  32420. * the tree.
  32421. * @see https://github.com/d3/d3-hierarchy
  32422. */
  32423. /**
  32424. * Initialize all computational message for following algorithm
  32425. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  32426. */
  32427. function init$2(root) {
  32428. root.hierNode = {
  32429. defaultAncestor: null,
  32430. ancestor: root,
  32431. prelim: 0,
  32432. modifier: 0,
  32433. change: 0,
  32434. shift: 0,
  32435. i: 0,
  32436. thread: null
  32437. };
  32438. var nodes = [root];
  32439. var node;
  32440. var children;
  32441. while (node = nodes.pop()) { // jshint ignore:line
  32442. children = node.children;
  32443. if (node.isExpand && children.length) {
  32444. var n = children.length;
  32445. for (var i = n - 1; i >= 0; i--) {
  32446. var child = children[i];
  32447. child.hierNode = {
  32448. defaultAncestor: null,
  32449. ancestor: child,
  32450. prelim: 0,
  32451. modifier: 0,
  32452. change: 0,
  32453. shift: 0,
  32454. i: i,
  32455. thread: null
  32456. };
  32457. nodes.push(child);
  32458. }
  32459. }
  32460. }
  32461. }
  32462. /**
  32463. * Computes a preliminary x coordinate for node. Before that, this function is
  32464. * applied recursively to the children of node, as well as the function
  32465. * apportion(). After spacing out the children by calling executeShifts(), the
  32466. * node is placed to the midpoint of its outermost children.
  32467. * @param {module:echarts/data/Tree~TreeNode} node
  32468. * @param {Function} separation
  32469. */
  32470. function firstWalk(node, separation) {
  32471. var children = node.isExpand ? node.children : [];
  32472. var siblings = node.parentNode.children;
  32473. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  32474. if (children.length) {
  32475. executeShifts(node);
  32476. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  32477. if (subtreeW) {
  32478. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  32479. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  32480. }
  32481. else {
  32482. node.hierNode.prelim = midPoint;
  32483. }
  32484. }
  32485. else if (subtreeW) {
  32486. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  32487. }
  32488. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  32489. }
  32490. /**
  32491. * Computes all real x-coordinates by summing up the modifiers recursively.
  32492. * @param {module:echarts/data/Tree~TreeNode} node
  32493. */
  32494. function secondWalk(node) {
  32495. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  32496. node.setLayout({x: nodeX}, true);
  32497. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  32498. }
  32499. function separation(cb) {
  32500. return arguments.length ? cb : defaultSeparation;
  32501. }
  32502. /**
  32503. * Transform the common coordinate to radial coordinate
  32504. * @param {number} x
  32505. * @param {number} y
  32506. * @return {Object}
  32507. */
  32508. function radialCoordinate(x, y) {
  32509. var radialCoor = {};
  32510. x -= Math.PI / 2;
  32511. radialCoor.x = y * Math.cos(x);
  32512. radialCoor.y = y * Math.sin(x);
  32513. return radialCoor;
  32514. }
  32515. /**
  32516. * Get the layout position of the whole view
  32517. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  32518. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  32519. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  32520. */
  32521. function getViewRect(seriesModel, api) {
  32522. return getLayoutRect(
  32523. seriesModel.getBoxLayoutParams(), {
  32524. width: api.getWidth(),
  32525. height: api.getHeight()
  32526. }
  32527. );
  32528. }
  32529. /**
  32530. * All other shifts, applied to the smaller subtrees between w- and w+, are
  32531. * performed by this function.
  32532. * @param {module:echarts/data/Tree~TreeNode} node
  32533. */
  32534. function executeShifts(node) {
  32535. var children = node.children;
  32536. var n = children.length;
  32537. var shift = 0;
  32538. var change = 0;
  32539. while (--n >= 0) {
  32540. var child = children[n];
  32541. child.hierNode.prelim += shift;
  32542. child.hierNode.modifier += shift;
  32543. change += child.hierNode.change;
  32544. shift += child.hierNode.shift + change;
  32545. }
  32546. }
  32547. /**
  32548. * The core of the algorithm. Here, a new subtree is combined with the
  32549. * previous subtrees. Threads are used to traverse the inside and outside
  32550. * contours of the left and right subtree up to the highest common level.
  32551. * Whenever two nodes of the inside contours conflict, we compute the left
  32552. * one of the greatest uncommon ancestors using the function nextAncestor()
  32553. * and call moveSubtree() to shift the subtree and prepare the shifts of
  32554. * smaller subtrees. Finally, we add a new thread (if necessary).
  32555. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  32556. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  32557. * @param {module:echarts/data/Tree~TreeNode} ancestor
  32558. * @param {Function} separation
  32559. * @return {module:echarts/data/Tree~TreeNode}
  32560. */
  32561. function apportion(subtreeV, subtreeW, ancestor, separation) {
  32562. if (subtreeW) {
  32563. var nodeOutRight = subtreeV;
  32564. var nodeInRight = subtreeV;
  32565. var nodeOutLeft = nodeInRight.parentNode.children[0];
  32566. var nodeInLeft = subtreeW;
  32567. var sumOutRight = nodeOutRight.hierNode.modifier;
  32568. var sumInRight = nodeInRight.hierNode.modifier;
  32569. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  32570. var sumInLeft = nodeInLeft.hierNode.modifier;
  32571. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  32572. nodeOutRight = nextRight(nodeOutRight);
  32573. nodeOutLeft = nextLeft(nodeOutLeft);
  32574. nodeOutRight.hierNode.ancestor = subtreeV;
  32575. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  32576. - sumInRight + separation(nodeInLeft, nodeInRight);
  32577. if (shift > 0) {
  32578. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  32579. sumInRight += shift;
  32580. sumOutRight += shift;
  32581. }
  32582. sumInLeft += nodeInLeft.hierNode.modifier;
  32583. sumInRight += nodeInRight.hierNode.modifier;
  32584. sumOutRight += nodeOutRight.hierNode.modifier;
  32585. sumOutLeft += nodeOutLeft.hierNode.modifier;
  32586. }
  32587. if (nodeInLeft && !nextRight(nodeOutRight)) {
  32588. nodeOutRight.hierNode.thread = nodeInLeft;
  32589. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  32590. }
  32591. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  32592. nodeOutLeft.hierNode.thread = nodeInRight;
  32593. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  32594. ancestor = subtreeV;
  32595. }
  32596. }
  32597. return ancestor;
  32598. }
  32599. /**
  32600. * This function is used to traverse the right contour of a subtree.
  32601. * It returns the rightmost child of node or the thread of node. The function
  32602. * returns null if and only if node is on the highest depth of its subtree.
  32603. * @param {module:echarts/data/Tree~TreeNode} node
  32604. * @return {module:echarts/data/Tree~TreeNode}
  32605. */
  32606. function nextRight(node) {
  32607. var children = node.children;
  32608. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  32609. }
  32610. /**
  32611. * This function is used to traverse the left contour of a subtree (or a subforest).
  32612. * It returns the leftmost child of node or the thread of node. The function
  32613. * returns null if and only if node is on the highest depth of its subtree.
  32614. * @param {module:echarts/data/Tree~TreeNode} node
  32615. * @return {module:echarts/data/Tree~TreeNode}
  32616. */
  32617. function nextLeft(node) {
  32618. var children = node.children;
  32619. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  32620. }
  32621. /**
  32622. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  32623. * Otherwise, returns the specified ancestor.
  32624. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  32625. * @param {module:echarts/data/Tree~TreeNode} node
  32626. * @param {module:echarts/data/Tree~TreeNode} ancestor
  32627. * @return {module:echarts/data/Tree~TreeNode}
  32628. */
  32629. function nextAncestor(nodeInLeft, node, ancestor) {
  32630. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  32631. ? nodeInLeft.hierNode.ancestor : ancestor;
  32632. }
  32633. /**
  32634. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  32635. * @param {module:echarts/data/Tree~TreeNode} wl
  32636. * @param {module:echarts/data/Tree~TreeNode} wr
  32637. * @param {number} shift [description]
  32638. */
  32639. function moveSubtree(wl, wr,shift) {
  32640. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  32641. wr.hierNode.change -= change;
  32642. wr.hierNode.shift += shift;
  32643. wr.hierNode.modifier += shift;
  32644. wr.hierNode.prelim += shift;
  32645. wl.hierNode.change += change;
  32646. }
  32647. function defaultSeparation(node1, node2) {
  32648. return node1.parentNode === node2.parentNode ? 1 : 2;
  32649. }
  32650. /**
  32651. * @file This file used to draw tree view
  32652. */
  32653. extendChartView({
  32654. type: 'tree',
  32655. /**
  32656. * Init the chart
  32657. * @override
  32658. * @param {module:echarts/model/Global} ecModel
  32659. * @param {module:echarts/ExtensionAPI} api
  32660. */
  32661. init: function (ecModel, api) {
  32662. /**
  32663. * @private
  32664. * @type {module:echarts/data/Tree}
  32665. */
  32666. this._oldTree;
  32667. /**
  32668. * @private
  32669. * @type {module:zrender/container/Group}
  32670. */
  32671. this._mainGroup = new Group();
  32672. this.group.add(this._mainGroup);
  32673. },
  32674. render: function (seriesModel, ecModel, api, payload) {
  32675. var data = seriesModel.getData();
  32676. var layoutInfo = seriesModel.layoutInfo;
  32677. var group = this._mainGroup;
  32678. var layout = seriesModel.get('layout');
  32679. if (layout === 'radial') {
  32680. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  32681. }
  32682. else {
  32683. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  32684. }
  32685. var oldData = this._data;
  32686. var seriesScope = {
  32687. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  32688. layout: layout,
  32689. orient: seriesModel.get('orient'),
  32690. curvature: seriesModel.get('lineStyle.normal.curveness'),
  32691. symbolRotate: seriesModel.get('symbolRotate'),
  32692. symbolOffset: seriesModel.get('symbolOffset'),
  32693. hoverAnimation: seriesModel.get('hoverAnimation'),
  32694. useNameLabel: true,
  32695. fadeIn: true
  32696. };
  32697. data.diff(oldData)
  32698. .add(function (newIdx) {
  32699. if (symbolNeedsDraw$1(data, newIdx)) {
  32700. // create node and edge
  32701. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  32702. }
  32703. })
  32704. .update(function (newIdx, oldIdx) {
  32705. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32706. if (!symbolNeedsDraw$1(data, newIdx)) {
  32707. symbolEl && removeNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  32708. return;
  32709. }
  32710. // update node and edge
  32711. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  32712. })
  32713. .remove(function (oldIdx) {
  32714. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32715. removeNode(data, oldIdx, symbolEl, group, seriesModel, seriesScope);
  32716. })
  32717. .execute();
  32718. if (seriesScope.expandAndCollapse === true) {
  32719. data.eachItemGraphicEl(function (el, dataIndex) {
  32720. el.off('click').on('click', function () {
  32721. api.dispatchAction({
  32722. type: 'treeExpandAndCollapse',
  32723. seriesId: seriesModel.id,
  32724. dataIndex: dataIndex
  32725. });
  32726. });
  32727. });
  32728. }
  32729. this._data = data;
  32730. },
  32731. dispose: function () {},
  32732. remove: function () {
  32733. this._mainGroup.removeAll();
  32734. this._data = null;
  32735. }
  32736. });
  32737. function symbolNeedsDraw$1(data, dataIndex) {
  32738. var layout = data.getItemLayout(dataIndex);
  32739. return layout
  32740. && !isNaN(layout.x) && !isNaN(layout.y)
  32741. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  32742. }
  32743. function getTreeNodeStyle(node, itemModel, seriesScope) {
  32744. seriesScope.itemModel = itemModel;
  32745. seriesScope.itemStyle = itemModel.getModel('itemStyle.normal').getItemStyle();
  32746. seriesScope.hoverItemStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  32747. seriesScope.lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  32748. seriesScope.labelModel = itemModel.getModel('label.normal');
  32749. seriesScope.hoverLabelModel = itemModel.getModel('label.emphasis');
  32750. if (node.isExpand === false && node.children.length !== 0) {
  32751. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  32752. }
  32753. else {
  32754. seriesScope.symbolInnerColor = '#fff';
  32755. }
  32756. return seriesScope;
  32757. }
  32758. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  32759. var isInit = !symbolEl;
  32760. var node = data.tree.getNodeByDataIndex(dataIndex);
  32761. var itemModel = node.getModel();
  32762. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  32763. var virtualRoot = data.tree.root;
  32764. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  32765. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  32766. var sourceLayout = source.getLayout();
  32767. var sourceOldLayout = sourceSymbolEl
  32768. ? {
  32769. x: sourceSymbolEl.position[0],
  32770. y: sourceSymbolEl.position[1],
  32771. rawX: sourceSymbolEl.__radialOldRawX,
  32772. rawY: sourceSymbolEl.__radialOldRawY
  32773. }
  32774. : sourceLayout;
  32775. var targetLayout = node.getLayout();
  32776. if (isInit) {
  32777. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  32778. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  32779. }
  32780. else {
  32781. symbolEl.updateData(data, dataIndex, seriesScope);
  32782. }
  32783. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  32784. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  32785. symbolEl.__radialRawX = targetLayout.rawX;
  32786. symbolEl.__radialRawY = targetLayout.rawY;
  32787. group.add(symbolEl);
  32788. data.setItemGraphicEl(dataIndex, symbolEl);
  32789. updateProps(symbolEl, {
  32790. position: [targetLayout.x, targetLayout.y]
  32791. }, seriesModel);
  32792. var symbolPath = symbolEl.getSymbolPath();
  32793. if (seriesScope.layout === 'radial') {
  32794. var realRoot = virtualRoot.children[0];
  32795. var rootLayout = realRoot.getLayout();
  32796. var length = realRoot.children.length;
  32797. var rad;
  32798. var isLeft;
  32799. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  32800. var center = {};
  32801. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  32802. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  32803. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  32804. if (rad < 0) {
  32805. rad = Math.PI * 2 + rad;
  32806. }
  32807. isLeft = center.x < rootLayout.x;
  32808. if (isLeft) {
  32809. rad = rad - Math.PI;
  32810. }
  32811. }
  32812. else {
  32813. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  32814. if (rad < 0) {
  32815. rad = Math.PI * 2 + rad;
  32816. }
  32817. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  32818. isLeft = targetLayout.x < rootLayout.x;
  32819. if (isLeft) {
  32820. rad = rad - Math.PI;
  32821. }
  32822. }
  32823. else {
  32824. isLeft = targetLayout.x > rootLayout.x;
  32825. if (!isLeft) {
  32826. rad = rad - Math.PI;
  32827. }
  32828. }
  32829. }
  32830. var textPosition = isLeft ? 'left' : 'right';
  32831. symbolPath.setStyle({
  32832. textPosition: textPosition,
  32833. textRotation: -rad,
  32834. textOrigin: 'center',
  32835. verticalAlign: 'middle'
  32836. });
  32837. }
  32838. if (node.parentNode && node.parentNode !== virtualRoot) {
  32839. var edge = symbolEl.__edge;
  32840. if (!edge) {
  32841. edge = symbolEl.__edge = new BezierCurve({
  32842. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  32843. style: defaults({opacity: 0}, seriesScope.lineStyle)
  32844. });
  32845. }
  32846. updateProps(edge, {
  32847. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  32848. style: {opacity: 1}
  32849. }, seriesModel);
  32850. group.add(edge);
  32851. }
  32852. }
  32853. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  32854. var node = data.tree.getNodeByDataIndex(dataIndex);
  32855. var virtualRoot = data.tree.root;
  32856. var itemModel = node.getModel();
  32857. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  32858. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  32859. var sourceLayout;
  32860. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  32861. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  32862. }
  32863. updateProps(symbolEl, {
  32864. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  32865. }, seriesModel, function () {
  32866. group.remove(symbolEl);
  32867. data.setItemGraphicEl(dataIndex, null);
  32868. });
  32869. symbolEl.fadeOut(null, {keepLabel: true});
  32870. var edge = symbolEl.__edge;
  32871. if (edge) {
  32872. updateProps(edge, {
  32873. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  32874. style: {
  32875. opacity: 0
  32876. }
  32877. }, seriesModel, function () {
  32878. group.remove(edge);
  32879. });
  32880. }
  32881. }
  32882. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  32883. var cpx1;
  32884. var cpy1;
  32885. var cpx2;
  32886. var cpy2;
  32887. var orient = seriesScope.orient;
  32888. if (seriesScope.layout === 'radial') {
  32889. var x1 = sourceLayout.rawX;
  32890. var y1 = sourceLayout.rawY;
  32891. var x2 = targetLayout.rawX;
  32892. var y2 = targetLayout.rawY;
  32893. var radialCoor1 = radialCoordinate(x1, y1);
  32894. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  32895. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  32896. var radialCoor4 = radialCoordinate(x2, y2);
  32897. return {
  32898. x1: radialCoor1.x,
  32899. y1: radialCoor1.y,
  32900. x2: radialCoor4.x,
  32901. y2: radialCoor4.y,
  32902. cpx1: radialCoor2.x,
  32903. cpy1: radialCoor2.y,
  32904. cpx2: radialCoor3.x,
  32905. cpy2: radialCoor3.y
  32906. };
  32907. }
  32908. else {
  32909. var x1 = sourceLayout.x;
  32910. var y1 = sourceLayout.y;
  32911. var x2 = targetLayout.x;
  32912. var y2 = targetLayout.y;
  32913. if (orient === 'horizontal') {
  32914. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  32915. cpy1 = y1;
  32916. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  32917. cpy2 = y2;
  32918. }
  32919. if (orient === 'vertical') {
  32920. cpx1 = x1;
  32921. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  32922. cpx2 = x2;
  32923. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  32924. }
  32925. return {
  32926. x1: x1,
  32927. y1: y1,
  32928. x2: x2,
  32929. y2: y2,
  32930. cpx1: cpx1,
  32931. cpy1: cpy1,
  32932. cpx2: cpx2,
  32933. cpy2: cpy2
  32934. };
  32935. }
  32936. }
  32937. registerAction({
  32938. type: 'treeExpandAndCollapse',
  32939. event: 'treeExpandAndCollapse',
  32940. update: 'update'
  32941. }, function (payload, ecModel) {
  32942. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  32943. var dataIndex = payload.dataIndex;
  32944. var tree = seriesModel.getData().tree;
  32945. var node = tree.getNodeByDataIndex(dataIndex);
  32946. node.isExpand = !node.isExpand;
  32947. });
  32948. });
  32949. /**
  32950. * Traverse the tree from bottom to top and do something
  32951. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  32952. * @param {Function} callback
  32953. */
  32954. function eachAfter (root, callback, separation) {
  32955. var nodes = [root];
  32956. var next = [];
  32957. var node;
  32958. while (node = nodes.pop()) { // jshint ignore:line
  32959. next.push(node);
  32960. if (node.isExpand) {
  32961. var children = node.children;
  32962. if (children.length) {
  32963. for (var i = 0; i < children.length; i++) {
  32964. nodes.push(children[i]);
  32965. }
  32966. }
  32967. }
  32968. }
  32969. while (node = next.pop()) { // jshint ignore:line
  32970. callback(node, separation);
  32971. }
  32972. }
  32973. /**
  32974. * Traverse the tree from top to bottom and do something
  32975. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  32976. * @param {Function} callback
  32977. */
  32978. function eachBefore (root, callback) {
  32979. var nodes = [root];
  32980. var node;
  32981. while (node = nodes.pop()) { // jshint ignore:line
  32982. callback(node);
  32983. if (node.isExpand) {
  32984. var children = node.children;
  32985. if (children.length) {
  32986. for (var i = children.length - 1; i >= 0; i--) {
  32987. nodes.push(children[i]);
  32988. }
  32989. }
  32990. }
  32991. }
  32992. }
  32993. var commonLayout = function (seriesModel, api) {
  32994. var layoutInfo = getViewRect(seriesModel, api);
  32995. seriesModel.layoutInfo = layoutInfo;
  32996. var layout = seriesModel.get('layout');
  32997. var width = 0;
  32998. var height = 0;
  32999. var separation$$1 = null;
  33000. if (layout === 'radial') {
  33001. width = 2 * Math.PI;
  33002. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  33003. separation$$1 = separation(function (node1, node2) {
  33004. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  33005. });
  33006. }
  33007. else {
  33008. width = layoutInfo.width;
  33009. height = layoutInfo.height;
  33010. separation$$1 = separation();
  33011. }
  33012. var virtualRoot = seriesModel.getData().tree.root;
  33013. var realRoot = virtualRoot.children[0];
  33014. init$2(virtualRoot);
  33015. eachAfter(realRoot, firstWalk, separation$$1);
  33016. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  33017. eachBefore(realRoot, secondWalk);
  33018. var left = realRoot;
  33019. var right = realRoot;
  33020. var bottom = realRoot;
  33021. eachBefore(realRoot, function (node) {
  33022. var x = node.getLayout().x;
  33023. if (x < left.getLayout().x) {
  33024. left = node;
  33025. }
  33026. if (x > right.getLayout().x) {
  33027. right = node;
  33028. }
  33029. if (node.depth > bottom.depth) {
  33030. bottom = node;
  33031. }
  33032. });
  33033. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  33034. var tx = delta - left.getLayout().x;
  33035. var kx = 0;
  33036. var ky = 0;
  33037. var coorX = 0;
  33038. var coorY = 0;
  33039. if (layout === 'radial') {
  33040. kx = width / (right.getLayout().x + delta + tx);
  33041. // here we use (node.depth - 1), bucause the real root's depth is 1
  33042. ky = height/ ((bottom.depth - 1) || 1);
  33043. eachBefore(realRoot, function (node) {
  33044. coorX = (node.getLayout().x + tx) * kx;
  33045. coorY = (node.depth - 1) * ky;
  33046. var finalCoor = radialCoordinate(coorX, coorY);
  33047. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  33048. });
  33049. }
  33050. else {
  33051. if (seriesModel.get('orient') === 'horizontal') {
  33052. ky = height / (right.getLayout().x + delta + tx);
  33053. kx = width / ((bottom.depth - 1) || 1);
  33054. eachBefore(realRoot, function (node) {
  33055. coorY = (node.getLayout().x + tx) * ky;
  33056. coorX = (node.depth - 1) * kx;
  33057. node.setLayout({x: coorX, y: coorY}, true);
  33058. });
  33059. }
  33060. else {
  33061. kx = width / (right.getLayout().x + delta + tx);
  33062. ky = height / ((bottom.depth - 1) || 1);
  33063. eachBefore(realRoot, function (node) {
  33064. coorX = (node.getLayout().x + tx) * kx;
  33065. coorY = (node.depth - 1) * ky;
  33066. node.setLayout({x: coorX, y: coorY}, true);
  33067. });
  33068. }
  33069. }
  33070. };
  33071. var orthogonalLayout = function (ecModel, api) {
  33072. ecModel.eachSeriesByType('tree', function (seriesModel) {
  33073. commonLayout(seriesModel, api);
  33074. });
  33075. };
  33076. var radialLayout = function (ecModel, api) {
  33077. ecModel.eachSeriesByType('tree', function (seriesModel) {
  33078. commonLayout(seriesModel, api);
  33079. });
  33080. };
  33081. registerVisual(curry(visualSymbol, 'tree', 'circle', null));
  33082. registerLayout(orthogonalLayout);
  33083. registerLayout(radialLayout);
  33084. function retrieveTargetInfo(payload, seriesModel) {
  33085. if (payload
  33086. && (
  33087. payload.type === 'treemapZoomToNode'
  33088. || payload.type === 'treemapRootToNode'
  33089. )
  33090. ) {
  33091. var root = seriesModel.getData().tree.root;
  33092. var targetNode = payload.targetNode;
  33093. if (targetNode && root.contains(targetNode)) {
  33094. return {node: targetNode};
  33095. }
  33096. var targetNodeId = payload.targetNodeId;
  33097. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  33098. return {node: targetNode};
  33099. }
  33100. }
  33101. }
  33102. // Not includes the given node at the last item.
  33103. function getPathToRoot(node) {
  33104. var path = [];
  33105. while (node) {
  33106. node = node.parentNode;
  33107. node && path.push(node);
  33108. }
  33109. return path.reverse();
  33110. }
  33111. function aboveViewRoot(viewRoot, node) {
  33112. var viewPath = getPathToRoot(viewRoot);
  33113. return indexOf(viewPath, node) >= 0;
  33114. }
  33115. // From root to the input node (the input node will be included).
  33116. function wrapTreePathInfo(node, seriesModel) {
  33117. var treePathInfo = [];
  33118. while (node) {
  33119. var nodeDataIndex = node.dataIndex;
  33120. treePathInfo.push({
  33121. name: node.name,
  33122. dataIndex: nodeDataIndex,
  33123. value: seriesModel.getRawValue(nodeDataIndex)
  33124. });
  33125. node = node.parentNode;
  33126. }
  33127. treePathInfo.reverse();
  33128. return treePathInfo;
  33129. }
  33130. SeriesModel.extend({
  33131. type: 'series.treemap',
  33132. layoutMode: 'box',
  33133. dependencies: ['grid', 'polar'],
  33134. /**
  33135. * @type {module:echarts/data/Tree~Node}
  33136. */
  33137. _viewRoot: null,
  33138. defaultOption: {
  33139. // Disable progressive rendering
  33140. progressive: 0,
  33141. hoverLayerThreshold: Infinity,
  33142. // center: ['50%', '50%'], // not supported in ec3.
  33143. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  33144. left: 'center',
  33145. top: 'middle',
  33146. right: null,
  33147. bottom: null,
  33148. width: '80%',
  33149. height: '80%',
  33150. sort: true, // Can be null or false or true
  33151. // (order by desc default, asc not supported yet (strange effect))
  33152. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  33153. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  33154. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  33155. // Count from zero (zero represents only view root).
  33156. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  33157. // to align specialized icon. ▷▶❒❐▼✚
  33158. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  33159. // target node area in the view area.
  33160. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  33161. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  33162. // If leafDepth is set and clicking a node which has children but
  33163. // be on left depth, the behaviour would be changing root. Otherwise
  33164. // use behavious defined above.
  33165. animation: true,
  33166. animationDurationUpdate: 900,
  33167. animationEasing: 'quinticInOut',
  33168. breadcrumb: {
  33169. show: true,
  33170. height: 22,
  33171. left: 'center',
  33172. top: 'bottom',
  33173. // right
  33174. // bottom
  33175. emptyItemWidth: 25, // Width of empty node.
  33176. itemStyle: {
  33177. normal: {
  33178. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  33179. borderColor: 'rgba(255,255,255,0.7)',
  33180. borderWidth: 1,
  33181. shadowColor: 'rgba(150,150,150,1)',
  33182. shadowBlur: 3,
  33183. shadowOffsetX: 0,
  33184. shadowOffsetY: 0,
  33185. textStyle: {
  33186. color: '#fff'
  33187. }
  33188. },
  33189. emphasis: {
  33190. textStyle: {}
  33191. }
  33192. }
  33193. },
  33194. label: {
  33195. normal: {
  33196. show: true,
  33197. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  33198. distance: 0,
  33199. padding: 5,
  33200. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  33201. // formatter: null,
  33202. color: '#fff',
  33203. ellipsis: true
  33204. // align
  33205. // verticalAlign
  33206. }
  33207. },
  33208. upperLabel: { // Label when node is parent.
  33209. normal: {
  33210. show: false,
  33211. position: [0, '50%'],
  33212. height: 20,
  33213. // formatter: null,
  33214. color: '#fff',
  33215. ellipsis: true,
  33216. // align: null,
  33217. verticalAlign: 'middle'
  33218. },
  33219. emphasis: {
  33220. show: true,
  33221. position: [0, '50%'],
  33222. color: '#fff',
  33223. ellipsis: true,
  33224. verticalAlign: 'middle'
  33225. }
  33226. },
  33227. itemStyle: {
  33228. normal: {
  33229. color: null, // Can be 'none' if not necessary.
  33230. colorAlpha: null, // Can be 'none' if not necessary.
  33231. colorSaturation: null, // Can be 'none' if not necessary.
  33232. borderWidth: 0,
  33233. gapWidth: 0,
  33234. borderColor: '#fff',
  33235. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  33236. // border color is evaluated by color of current node and
  33237. // borderColorSaturation.
  33238. },
  33239. emphasis: {
  33240. }
  33241. },
  33242. visualDimension: 0, // Can be 0, 1, 2, 3.
  33243. visualMin: null,
  33244. visualMax: null,
  33245. color: [], // + treemapSeries.color should not be modified. Please only modified
  33246. // level[n].color (if necessary).
  33247. // + Specify color list of each level. level[0].color would be global
  33248. // color list if not specified. (see method `setDefault`).
  33249. // + But set as a empty array to forbid fetch color from global palette
  33250. // when using nodeModel.get('color'), otherwise nodes on deep level
  33251. // will always has color palette set and are not able to inherit color
  33252. // from parent node.
  33253. // + TreemapSeries.color can not be set as 'none', otherwise effect
  33254. // legend color fetching (see seriesColor.js).
  33255. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  33256. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  33257. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  33258. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  33259. // be rendered. Only works when sort is 'asc' or 'desc'.
  33260. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  33261. // grandchildren will not show.
  33262. // Why grandchildren? If not grandchildren but children,
  33263. // some siblings show children and some not,
  33264. // the appearance may be mess and not consistent,
  33265. levels: [] // Each item: {
  33266. // visibleMin, itemStyle, visualDimension, label
  33267. // }
  33268. // data: {
  33269. // value: [],
  33270. // children: [],
  33271. // link: 'http://xxx.xxx.xxx',
  33272. // target: 'blank' or 'self'
  33273. // }
  33274. },
  33275. /**
  33276. * @override
  33277. */
  33278. getInitialData: function (option, ecModel) {
  33279. // Create a virtual root.
  33280. var root = {name: option.name, children: option.data};
  33281. completeTreeValue(root);
  33282. var levels = option.levels || [];
  33283. levels = option.levels = setDefault(levels, ecModel);
  33284. var treeOption = {};
  33285. treeOption.levels = levels;
  33286. // Make sure always a new tree is created when setOption,
  33287. // in TreemapView, we check whether oldTree === newTree
  33288. // to choose mappings approach among old shapes and new shapes.
  33289. return Tree.createTree(root, this, treeOption).data;
  33290. },
  33291. optionUpdated: function () {
  33292. this.resetViewRoot();
  33293. },
  33294. /**
  33295. * @override
  33296. * @param {number} dataIndex
  33297. * @param {boolean} [mutipleSeries=false]
  33298. */
  33299. formatTooltip: function (dataIndex) {
  33300. var data = this.getData();
  33301. var value = this.getRawValue(dataIndex);
  33302. var formattedValue = isArray(value)
  33303. ? addCommas(value[0]) : addCommas(value);
  33304. var name = data.getName(dataIndex);
  33305. return encodeHTML(name + ': ' + formattedValue);
  33306. },
  33307. /**
  33308. * Add tree path to tooltip param
  33309. *
  33310. * @override
  33311. * @param {number} dataIndex
  33312. * @return {Object}
  33313. */
  33314. getDataParams: function (dataIndex) {
  33315. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  33316. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  33317. params.treePathInfo = wrapTreePathInfo(node, this);
  33318. return params;
  33319. },
  33320. /**
  33321. * @public
  33322. * @param {Object} layoutInfo {
  33323. * x: containerGroup x
  33324. * y: containerGroup y
  33325. * width: containerGroup width
  33326. * height: containerGroup height
  33327. * }
  33328. */
  33329. setLayoutInfo: function (layoutInfo) {
  33330. /**
  33331. * @readOnly
  33332. * @type {Object}
  33333. */
  33334. this.layoutInfo = this.layoutInfo || {};
  33335. extend(this.layoutInfo, layoutInfo);
  33336. },
  33337. /**
  33338. * @param {string} id
  33339. * @return {number} index
  33340. */
  33341. mapIdToIndex: function (id) {
  33342. // A feature is implemented:
  33343. // index is monotone increasing with the sequence of
  33344. // input id at the first time.
  33345. // This feature can make sure that each data item and its
  33346. // mapped color have the same index between data list and
  33347. // color list at the beginning, which is useful for user
  33348. // to adjust data-color mapping.
  33349. /**
  33350. * @private
  33351. * @type {Object}
  33352. */
  33353. var idIndexMap = this._idIndexMap;
  33354. if (!idIndexMap) {
  33355. idIndexMap = this._idIndexMap = createHashMap();
  33356. /**
  33357. * @private
  33358. * @type {number}
  33359. */
  33360. this._idIndexMapCount = 0;
  33361. }
  33362. var index = idIndexMap.get(id);
  33363. if (index == null) {
  33364. idIndexMap.set(id, index = this._idIndexMapCount++);
  33365. }
  33366. return index;
  33367. },
  33368. getViewRoot: function () {
  33369. return this._viewRoot;
  33370. },
  33371. /**
  33372. * @param {module:echarts/data/Tree~Node} [viewRoot]
  33373. */
  33374. resetViewRoot: function (viewRoot) {
  33375. viewRoot
  33376. ? (this._viewRoot = viewRoot)
  33377. : (viewRoot = this._viewRoot);
  33378. var root = this.getData().tree.root;
  33379. if (!viewRoot
  33380. || (viewRoot !== root && !root.contains(viewRoot))
  33381. ) {
  33382. this._viewRoot = root;
  33383. }
  33384. }
  33385. });
  33386. /**
  33387. * @param {Object} dataNode
  33388. */
  33389. function completeTreeValue(dataNode) {
  33390. // Postorder travel tree.
  33391. // If value of none-leaf node is not set,
  33392. // calculate it by suming up the value of all children.
  33393. var sum = 0;
  33394. each$1(dataNode.children, function (child) {
  33395. completeTreeValue(child);
  33396. var childValue = child.value;
  33397. isArray(childValue) && (childValue = childValue[0]);
  33398. sum += childValue;
  33399. });
  33400. var thisValue = dataNode.value;
  33401. if (isArray(thisValue)) {
  33402. thisValue = thisValue[0];
  33403. }
  33404. if (thisValue == null || isNaN(thisValue)) {
  33405. thisValue = sum;
  33406. }
  33407. // Value should not less than 0.
  33408. if (thisValue < 0) {
  33409. thisValue = 0;
  33410. }
  33411. isArray(dataNode.value)
  33412. ? (dataNode.value[0] = thisValue)
  33413. : (dataNode.value = thisValue);
  33414. }
  33415. /**
  33416. * set default to level configuration
  33417. */
  33418. function setDefault(levels, ecModel) {
  33419. var globalColorList = ecModel.get('color');
  33420. if (!globalColorList) {
  33421. return;
  33422. }
  33423. levels = levels || [];
  33424. var hasColorDefine;
  33425. each$1(levels, function (levelDefine) {
  33426. var model = new Model(levelDefine);
  33427. var modelColor = model.get('color');
  33428. if (model.get('itemStyle.normal.color')
  33429. || (modelColor && modelColor !== 'none')
  33430. ) {
  33431. hasColorDefine = true;
  33432. }
  33433. });
  33434. if (!hasColorDefine) {
  33435. var level0 = levels[0] || (levels[0] = {});
  33436. level0.color = globalColorList.slice();
  33437. }
  33438. return levels;
  33439. }
  33440. var TEXT_PADDING = 8;
  33441. var ITEM_GAP = 8;
  33442. var ARRAY_LENGTH = 5;
  33443. function Breadcrumb(containerGroup) {
  33444. /**
  33445. * @private
  33446. * @type {module:zrender/container/Group}
  33447. */
  33448. this.group = new Group();
  33449. containerGroup.add(this.group);
  33450. }
  33451. Breadcrumb.prototype = {
  33452. constructor: Breadcrumb,
  33453. render: function (seriesModel, api, targetNode, onSelect) {
  33454. var model = seriesModel.getModel('breadcrumb');
  33455. var thisGroup = this.group;
  33456. thisGroup.removeAll();
  33457. if (!model.get('show') || !targetNode) {
  33458. return;
  33459. }
  33460. var normalStyleModel = model.getModel('itemStyle.normal');
  33461. // var emphasisStyleModel = model.getModel('itemStyle.emphasis');
  33462. var textStyleModel = normalStyleModel.getModel('textStyle');
  33463. var layoutParam = {
  33464. pos: {
  33465. left: model.get('left'),
  33466. right: model.get('right'),
  33467. top: model.get('top'),
  33468. bottom: model.get('bottom')
  33469. },
  33470. box: {
  33471. width: api.getWidth(),
  33472. height: api.getHeight()
  33473. },
  33474. emptyItemWidth: model.get('emptyItemWidth'),
  33475. totalWidth: 0,
  33476. renderList: []
  33477. };
  33478. this._prepare(targetNode, layoutParam, textStyleModel);
  33479. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  33480. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  33481. },
  33482. /**
  33483. * Prepare render list and total width
  33484. * @private
  33485. */
  33486. _prepare: function (targetNode, layoutParam, textStyleModel) {
  33487. for (var node = targetNode; node; node = node.parentNode) {
  33488. var text = node.getModel().get('name');
  33489. var textRect = textStyleModel.getTextRect(text);
  33490. var itemWidth = Math.max(
  33491. textRect.width + TEXT_PADDING * 2,
  33492. layoutParam.emptyItemWidth
  33493. );
  33494. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  33495. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  33496. }
  33497. },
  33498. /**
  33499. * @private
  33500. */
  33501. _renderContent: function (
  33502. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  33503. ) {
  33504. // Start rendering.
  33505. var lastX = 0;
  33506. var emptyItemWidth = layoutParam.emptyItemWidth;
  33507. var height = seriesModel.get('breadcrumb.height');
  33508. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  33509. var totalWidth = layoutParam.totalWidth;
  33510. var renderList = layoutParam.renderList;
  33511. for (var i = renderList.length - 1; i >= 0; i--) {
  33512. var item = renderList[i];
  33513. var itemNode = item.node;
  33514. var itemWidth = item.width;
  33515. var text = item.text;
  33516. // Hdie text and shorten width if necessary.
  33517. if (totalWidth > availableSize.width) {
  33518. totalWidth -= itemWidth - emptyItemWidth;
  33519. itemWidth = emptyItemWidth;
  33520. text = null;
  33521. }
  33522. var el = new Polygon({
  33523. shape: {
  33524. points: makeItemPoints(
  33525. lastX, 0, itemWidth, height,
  33526. i === renderList.length - 1, i === 0
  33527. )
  33528. },
  33529. style: defaults(
  33530. normalStyleModel.getItemStyle(),
  33531. {
  33532. lineJoin: 'bevel',
  33533. text: text,
  33534. textFill: textStyleModel.getTextColor(),
  33535. textFont: textStyleModel.getFont()
  33536. }
  33537. ),
  33538. z: 10,
  33539. onclick: curry(onSelect, itemNode)
  33540. });
  33541. this.group.add(el);
  33542. packEventData(el, seriesModel, itemNode);
  33543. lastX += itemWidth + ITEM_GAP;
  33544. }
  33545. },
  33546. /**
  33547. * @override
  33548. */
  33549. remove: function () {
  33550. this.group.removeAll();
  33551. }
  33552. };
  33553. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  33554. var points = [
  33555. [head ? x : x - ARRAY_LENGTH, y],
  33556. [x + itemWidth, y],
  33557. [x + itemWidth, y + itemHeight],
  33558. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  33559. ];
  33560. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  33561. !head && points.push([x, y + itemHeight / 2]);
  33562. return points;
  33563. }
  33564. // Package custom mouse event.
  33565. function packEventData(el, seriesModel, itemNode) {
  33566. el.eventData = {
  33567. componentType: 'series',
  33568. componentSubType: 'treemap',
  33569. seriesIndex: seriesModel.componentIndex,
  33570. seriesName: seriesModel.name,
  33571. seriesType: 'treemap',
  33572. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  33573. nodeData: {
  33574. dataIndex: itemNode && itemNode.dataIndex,
  33575. name: itemNode && itemNode.name
  33576. },
  33577. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  33578. };
  33579. }
  33580. /**
  33581. * @param {number} [time=500] Time in ms
  33582. * @param {string} [easing='linear']
  33583. * @param {number} [delay=0]
  33584. * @param {Function} [callback]
  33585. *
  33586. * @example
  33587. * // Animate position
  33588. * animation
  33589. * .createWrap()
  33590. * .add(el1, {position: [10, 10]})
  33591. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  33592. * .done(function () { // done })
  33593. * .start('cubicOut');
  33594. */
  33595. function createWrap() {
  33596. var storage = [];
  33597. var elExistsMap = {};
  33598. var doneCallback;
  33599. return {
  33600. /**
  33601. * Caution: a el can only be added once, otherwise 'done'
  33602. * might not be called. This method checks this (by el.id),
  33603. * suppresses adding and returns false when existing el found.
  33604. *
  33605. * @param {modele:zrender/Element} el
  33606. * @param {Object} target
  33607. * @param {number} [time=500]
  33608. * @param {number} [delay=0]
  33609. * @param {string} [easing='linear']
  33610. * @return {boolean} Whether adding succeeded.
  33611. *
  33612. * @example
  33613. * add(el, target, time, delay, easing);
  33614. * add(el, target, time, easing);
  33615. * add(el, target, time);
  33616. * add(el, target);
  33617. */
  33618. add: function (el, target, time, delay, easing) {
  33619. if (isString(delay)) {
  33620. easing = delay;
  33621. delay = 0;
  33622. }
  33623. if (elExistsMap[el.id]) {
  33624. return false;
  33625. }
  33626. elExistsMap[el.id] = 1;
  33627. storage.push(
  33628. {el: el, target: target, time: time, delay: delay, easing: easing}
  33629. );
  33630. return true;
  33631. },
  33632. /**
  33633. * Only execute when animation finished. Will not execute when any
  33634. * of 'stop' or 'stopAnimation' called.
  33635. *
  33636. * @param {Function} callback
  33637. */
  33638. done: function (callback) {
  33639. doneCallback = callback;
  33640. return this;
  33641. },
  33642. /**
  33643. * Will stop exist animation firstly.
  33644. */
  33645. start: function () {
  33646. var count = storage.length;
  33647. for (var i = 0, len = storage.length; i < len; i++) {
  33648. var item = storage[i];
  33649. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  33650. }
  33651. return this;
  33652. function done() {
  33653. count--;
  33654. if (!count) {
  33655. storage.length = 0;
  33656. elExistsMap = {};
  33657. doneCallback && doneCallback();
  33658. }
  33659. }
  33660. }
  33661. };
  33662. }
  33663. var bind$1 = bind;
  33664. var Group$2 = Group;
  33665. var Rect$1 = Rect;
  33666. var each$11 = each$1;
  33667. var DRAG_THRESHOLD = 3;
  33668. var PATH_LABEL_NOAMAL = ['label', 'normal'];
  33669. var PATH_LABEL_EMPHASIS = ['label', 'emphasis'];
  33670. var PATH_UPPERLABEL_NORMAL = ['upperLabel', 'normal'];
  33671. var PATH_UPPERLABEL_EMPHASIS = ['upperLabel', 'emphasis'];
  33672. var Z_BASE = 10; // Should bigger than every z.
  33673. var Z_BG = 1;
  33674. var Z_CONTENT = 2;
  33675. var getItemStyleEmphasis = makeStyleMapper([
  33676. ['fill', 'color'],
  33677. // `borderColor` and `borderWidth` has been occupied,
  33678. // so use `stroke` to indicate the stroke of the rect.
  33679. ['stroke', 'strokeColor'],
  33680. ['lineWidth', 'strokeWidth'],
  33681. ['shadowBlur'],
  33682. ['shadowOffsetX'],
  33683. ['shadowOffsetY'],
  33684. ['shadowColor']
  33685. ]);
  33686. var getItemStyleNormal = function (model) {
  33687. // Normal style props should include emphasis style props.
  33688. var itemStyle = getItemStyleEmphasis(model);
  33689. // Clear styles set by emphasis.
  33690. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  33691. return itemStyle;
  33692. };
  33693. extendChartView({
  33694. type: 'treemap',
  33695. /**
  33696. * @override
  33697. */
  33698. init: function (o, api) {
  33699. /**
  33700. * @private
  33701. * @type {module:zrender/container/Group}
  33702. */
  33703. this._containerGroup;
  33704. /**
  33705. * @private
  33706. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  33707. */
  33708. this._storage = createStorage();
  33709. /**
  33710. * @private
  33711. * @type {module:echarts/data/Tree}
  33712. */
  33713. this._oldTree;
  33714. /**
  33715. * @private
  33716. * @type {module:echarts/chart/treemap/Breadcrumb}
  33717. */
  33718. this._breadcrumb;
  33719. /**
  33720. * @private
  33721. * @type {module:echarts/component/helper/RoamController}
  33722. */
  33723. this._controller;
  33724. /**
  33725. * 'ready', 'animating'
  33726. * @private
  33727. */
  33728. this._state = 'ready';
  33729. },
  33730. /**
  33731. * @override
  33732. */
  33733. render: function (seriesModel, ecModel, api, payload) {
  33734. var models = ecModel.findComponents({
  33735. mainType: 'series', subType: 'treemap', query: payload
  33736. });
  33737. if (indexOf(models, seriesModel) < 0) {
  33738. return;
  33739. }
  33740. this.seriesModel = seriesModel;
  33741. this.api = api;
  33742. this.ecModel = ecModel;
  33743. var targetInfo = retrieveTargetInfo(payload, seriesModel);
  33744. var payloadType = payload && payload.type;
  33745. var layoutInfo = seriesModel.layoutInfo;
  33746. var isInit = !this._oldTree;
  33747. var thisStorage = this._storage;
  33748. // Mark new root when action is treemapRootToNode.
  33749. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  33750. ? {
  33751. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  33752. direction: payload.direction
  33753. }
  33754. : null;
  33755. var containerGroup = this._giveContainerGroup(layoutInfo);
  33756. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  33757. (
  33758. !isInit && (
  33759. !payloadType
  33760. || payloadType === 'treemapZoomToNode'
  33761. || payloadType === 'treemapRootToNode'
  33762. )
  33763. )
  33764. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  33765. : renderResult.renderFinally();
  33766. this._resetController(api);
  33767. this._renderBreadcrumb(seriesModel, api, targetInfo);
  33768. },
  33769. /**
  33770. * @private
  33771. */
  33772. _giveContainerGroup: function (layoutInfo) {
  33773. var containerGroup = this._containerGroup;
  33774. if (!containerGroup) {
  33775. // FIXME
  33776. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  33777. containerGroup = this._containerGroup = new Group$2();
  33778. this._initEvents(containerGroup);
  33779. this.group.add(containerGroup);
  33780. }
  33781. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  33782. return containerGroup;
  33783. },
  33784. /**
  33785. * @private
  33786. */
  33787. _doRender: function (containerGroup, seriesModel, reRoot) {
  33788. var thisTree = seriesModel.getData().tree;
  33789. var oldTree = this._oldTree;
  33790. // Clear last shape records.
  33791. var lastsForAnimation = createStorage();
  33792. var thisStorage = createStorage();
  33793. var oldStorage = this._storage;
  33794. var willInvisibleEls = [];
  33795. var doRenderNode = curry(
  33796. renderNode, seriesModel,
  33797. thisStorage, oldStorage, reRoot,
  33798. lastsForAnimation, willInvisibleEls
  33799. );
  33800. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  33801. // the oldTree is actually losted, so we can not find all of the old graphic
  33802. // elements from tree. So we use this stragegy: make element storage, move
  33803. // from old storage to new storage, clear old storage.
  33804. dualTravel(
  33805. thisTree.root ? [thisTree.root] : [],
  33806. (oldTree && oldTree.root) ? [oldTree.root] : [],
  33807. containerGroup,
  33808. thisTree === oldTree || !oldTree,
  33809. 0
  33810. );
  33811. // Process all removing.
  33812. var willDeleteEls = clearStorage(oldStorage);
  33813. this._oldTree = thisTree;
  33814. this._storage = thisStorage;
  33815. return {
  33816. lastsForAnimation: lastsForAnimation,
  33817. willDeleteEls: willDeleteEls,
  33818. renderFinally: renderFinally
  33819. };
  33820. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  33821. // When 'render' is triggered by action,
  33822. // 'this' and 'old' may be the same tree,
  33823. // we use rawIndex in that case.
  33824. if (sameTree) {
  33825. oldViewChildren = thisViewChildren;
  33826. each$11(thisViewChildren, function (child, index) {
  33827. !child.isRemoved() && processNode(index, index);
  33828. });
  33829. }
  33830. // Diff hierarchically (diff only in each subtree, but not whole).
  33831. // because, consistency of view is important.
  33832. else {
  33833. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  33834. .add(processNode)
  33835. .update(processNode)
  33836. .remove(curry(processNode, null))
  33837. .execute();
  33838. }
  33839. function getKey(node) {
  33840. // Identify by name or raw index.
  33841. return node.getId();
  33842. }
  33843. function processNode(newIndex, oldIndex) {
  33844. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  33845. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  33846. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  33847. group && dualTravel(
  33848. thisNode && thisNode.viewChildren || [],
  33849. oldNode && oldNode.viewChildren || [],
  33850. group,
  33851. sameTree,
  33852. depth + 1
  33853. );
  33854. }
  33855. }
  33856. function clearStorage(storage) {
  33857. var willDeleteEls = createStorage();
  33858. storage && each$11(storage, function (store, storageName) {
  33859. var delEls = willDeleteEls[storageName];
  33860. each$11(store, function (el) {
  33861. el && (delEls.push(el), el.__tmWillDelete = 1);
  33862. });
  33863. });
  33864. return willDeleteEls;
  33865. }
  33866. function renderFinally() {
  33867. each$11(willDeleteEls, function (els) {
  33868. each$11(els, function (el) {
  33869. el.parent && el.parent.remove(el);
  33870. });
  33871. });
  33872. each$11(willInvisibleEls, function (el) {
  33873. el.invisible = true;
  33874. // Setting invisible is for optimizing, so no need to set dirty,
  33875. // just mark as invisible.
  33876. el.dirty();
  33877. });
  33878. }
  33879. },
  33880. /**
  33881. * @private
  33882. */
  33883. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  33884. if (!seriesModel.get('animation')) {
  33885. return;
  33886. }
  33887. var duration = seriesModel.get('animationDurationUpdate');
  33888. var easing = seriesModel.get('animationEasing');
  33889. var animationWrap = createWrap();
  33890. // Make delete animations.
  33891. each$11(renderResult.willDeleteEls, function (store, storageName) {
  33892. each$11(store, function (el, rawIndex) {
  33893. if (el.invisible) {
  33894. return;
  33895. }
  33896. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  33897. var target;
  33898. if (reRoot && reRoot.direction === 'drillDown') {
  33899. target = parent === reRoot.rootNodeGroup
  33900. // This is the content element of view root.
  33901. // Only `content` will enter this branch, because
  33902. // `background` and `nodeGroup` will not be deleted.
  33903. ? {
  33904. shape: {
  33905. x: 0,
  33906. y: 0,
  33907. width: parent.__tmNodeWidth,
  33908. height: parent.__tmNodeHeight
  33909. },
  33910. style: {
  33911. opacity: 0
  33912. }
  33913. }
  33914. // Others.
  33915. : {style: {opacity: 0}};
  33916. }
  33917. else {
  33918. var targetX = 0;
  33919. var targetY = 0;
  33920. if (!parent.__tmWillDelete) {
  33921. // Let node animate to right-bottom corner, cooperating with fadeout,
  33922. // which is appropriate for user understanding.
  33923. // Divided by 2 for reRoot rolling up effect.
  33924. targetX = parent.__tmNodeWidth / 2;
  33925. targetY = parent.__tmNodeHeight / 2;
  33926. }
  33927. target = storageName === 'nodeGroup'
  33928. ? {position: [targetX, targetY], style: {opacity: 0}}
  33929. : {
  33930. shape: {x: targetX, y: targetY, width: 0, height: 0},
  33931. style: {opacity: 0}
  33932. };
  33933. }
  33934. target && animationWrap.add(el, target, duration, easing);
  33935. });
  33936. });
  33937. // Make other animations
  33938. each$11(this._storage, function (store, storageName) {
  33939. each$11(store, function (el, rawIndex) {
  33940. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  33941. var target = {};
  33942. if (!last) {
  33943. return;
  33944. }
  33945. if (storageName === 'nodeGroup') {
  33946. if (last.old) {
  33947. target.position = el.position.slice();
  33948. el.attr('position', last.old);
  33949. }
  33950. }
  33951. else {
  33952. if (last.old) {
  33953. target.shape = extend({}, el.shape);
  33954. el.setShape(last.old);
  33955. }
  33956. if (last.fadein) {
  33957. el.setStyle('opacity', 0);
  33958. target.style = {opacity: 1};
  33959. }
  33960. // When animation is stopped for succedent animation starting,
  33961. // el.style.opacity might not be 1
  33962. else if (el.style.opacity !== 1) {
  33963. target.style = {opacity: 1};
  33964. }
  33965. }
  33966. animationWrap.add(el, target, duration, easing);
  33967. });
  33968. }, this);
  33969. this._state = 'animating';
  33970. animationWrap
  33971. .done(bind$1(function () {
  33972. this._state = 'ready';
  33973. renderResult.renderFinally();
  33974. }, this))
  33975. .start();
  33976. },
  33977. /**
  33978. * @private
  33979. */
  33980. _resetController: function (api) {
  33981. var controller = this._controller;
  33982. // Init controller.
  33983. if (!controller) {
  33984. controller = this._controller = new RoamController(api.getZr());
  33985. controller.enable(this.seriesModel.get('roam'));
  33986. controller.on('pan', bind$1(this._onPan, this));
  33987. controller.on('zoom', bind$1(this._onZoom, this));
  33988. }
  33989. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  33990. controller.setPointerChecker(function (e, x, y) {
  33991. return rect.contain(x, y);
  33992. });
  33993. },
  33994. /**
  33995. * @private
  33996. */
  33997. _clearController: function () {
  33998. var controller = this._controller;
  33999. if (controller) {
  34000. controller.dispose();
  34001. controller = null;
  34002. }
  34003. },
  34004. /**
  34005. * @private
  34006. */
  34007. _onPan: function (dx, dy) {
  34008. if (this._state !== 'animating'
  34009. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  34010. ) {
  34011. // These param must not be cached.
  34012. var root = this.seriesModel.getData().tree.root;
  34013. if (!root) {
  34014. return;
  34015. }
  34016. var rootLayout = root.getLayout();
  34017. if (!rootLayout) {
  34018. return;
  34019. }
  34020. this.api.dispatchAction({
  34021. type: 'treemapMove',
  34022. from: this.uid,
  34023. seriesId: this.seriesModel.id,
  34024. rootRect: {
  34025. x: rootLayout.x + dx, y: rootLayout.y + dy,
  34026. width: rootLayout.width, height: rootLayout.height
  34027. }
  34028. });
  34029. }
  34030. },
  34031. /**
  34032. * @private
  34033. */
  34034. _onZoom: function (scale, mouseX, mouseY) {
  34035. if (this._state !== 'animating') {
  34036. // These param must not be cached.
  34037. var root = this.seriesModel.getData().tree.root;
  34038. if (!root) {
  34039. return;
  34040. }
  34041. var rootLayout = root.getLayout();
  34042. if (!rootLayout) {
  34043. return;
  34044. }
  34045. var rect = new BoundingRect(
  34046. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  34047. );
  34048. var layoutInfo = this.seriesModel.layoutInfo;
  34049. // Transform mouse coord from global to containerGroup.
  34050. mouseX -= layoutInfo.x;
  34051. mouseY -= layoutInfo.y;
  34052. // Scale root bounding rect.
  34053. var m = create$1();
  34054. translate(m, m, [-mouseX, -mouseY]);
  34055. scale$1(m, m, [scale, scale]);
  34056. translate(m, m, [mouseX, mouseY]);
  34057. rect.applyTransform(m);
  34058. this.api.dispatchAction({
  34059. type: 'treemapRender',
  34060. from: this.uid,
  34061. seriesId: this.seriesModel.id,
  34062. rootRect: {
  34063. x: rect.x, y: rect.y,
  34064. width: rect.width, height: rect.height
  34065. }
  34066. });
  34067. }
  34068. },
  34069. /**
  34070. * @private
  34071. */
  34072. _initEvents: function (containerGroup) {
  34073. containerGroup.on('click', function (e) {
  34074. if (this._state !== 'ready') {
  34075. return;
  34076. }
  34077. var nodeClick = this.seriesModel.get('nodeClick', true);
  34078. if (!nodeClick) {
  34079. return;
  34080. }
  34081. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  34082. if (!targetInfo) {
  34083. return;
  34084. }
  34085. var node = targetInfo.node;
  34086. if (node.getLayout().isLeafRoot) {
  34087. this._rootToNode(targetInfo);
  34088. }
  34089. else {
  34090. if (nodeClick === 'zoomToNode') {
  34091. this._zoomToNode(targetInfo);
  34092. }
  34093. else if (nodeClick === 'link') {
  34094. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  34095. var link = itemModel.get('link', true);
  34096. var linkTarget = itemModel.get('target', true) || 'blank';
  34097. link && window.open(link, linkTarget);
  34098. }
  34099. }
  34100. }, this);
  34101. },
  34102. /**
  34103. * @private
  34104. */
  34105. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  34106. if (!targetInfo) {
  34107. targetInfo = seriesModel.get('leafDepth', true) != null
  34108. ? {node: seriesModel.getViewRoot()}
  34109. // FIXME
  34110. // better way?
  34111. // Find breadcrumb tail on center of containerGroup.
  34112. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  34113. if (!targetInfo) {
  34114. targetInfo = {node: seriesModel.getData().tree.root};
  34115. }
  34116. }
  34117. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  34118. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  34119. function onSelect(node) {
  34120. if (this._state !== 'animating') {
  34121. aboveViewRoot(seriesModel.getViewRoot(), node)
  34122. ? this._rootToNode({node: node})
  34123. : this._zoomToNode({node: node});
  34124. }
  34125. }
  34126. },
  34127. /**
  34128. * @override
  34129. */
  34130. remove: function () {
  34131. this._clearController();
  34132. this._containerGroup && this._containerGroup.removeAll();
  34133. this._storage = createStorage();
  34134. this._state = 'ready';
  34135. this._breadcrumb && this._breadcrumb.remove();
  34136. },
  34137. dispose: function () {
  34138. this._clearController();
  34139. },
  34140. /**
  34141. * @private
  34142. */
  34143. _zoomToNode: function (targetInfo) {
  34144. this.api.dispatchAction({
  34145. type: 'treemapZoomToNode',
  34146. from: this.uid,
  34147. seriesId: this.seriesModel.id,
  34148. targetNode: targetInfo.node
  34149. });
  34150. },
  34151. /**
  34152. * @private
  34153. */
  34154. _rootToNode: function (targetInfo) {
  34155. this.api.dispatchAction({
  34156. type: 'treemapRootToNode',
  34157. from: this.uid,
  34158. seriesId: this.seriesModel.id,
  34159. targetNode: targetInfo.node
  34160. });
  34161. },
  34162. /**
  34163. * @public
  34164. * @param {number} x Global coord x.
  34165. * @param {number} y Global coord y.
  34166. * @return {Object} info If not found, return undefined;
  34167. * @return {number} info.node Target node.
  34168. * @return {number} info.offsetX x refer to target node.
  34169. * @return {number} info.offsetY y refer to target node.
  34170. */
  34171. findTarget: function (x, y) {
  34172. var targetInfo;
  34173. var viewRoot = this.seriesModel.getViewRoot();
  34174. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  34175. var bgEl = this._storage.background[node.getRawIndex()];
  34176. // If invisible, there might be no element.
  34177. if (bgEl) {
  34178. var point = bgEl.transformCoordToLocal(x, y);
  34179. var shape = bgEl.shape;
  34180. // For performance consideration, dont use 'getBoundingRect'.
  34181. if (shape.x <= point[0]
  34182. && point[0] <= shape.x + shape.width
  34183. && shape.y <= point[1]
  34184. && point[1] <= shape.y + shape.height
  34185. ) {
  34186. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  34187. }
  34188. else {
  34189. return false; // Suppress visit subtree.
  34190. }
  34191. }
  34192. }, this);
  34193. return targetInfo;
  34194. }
  34195. });
  34196. /**
  34197. * @inner
  34198. */
  34199. function createStorage() {
  34200. return {nodeGroup: [], background: [], content: []};
  34201. }
  34202. /**
  34203. * @inner
  34204. * @return Return undefined means do not travel further.
  34205. */
  34206. function renderNode(
  34207. seriesModel, thisStorage, oldStorage, reRoot,
  34208. lastsForAnimation, willInvisibleEls,
  34209. thisNode, oldNode, parentGroup, depth
  34210. ) {
  34211. // Whether under viewRoot.
  34212. if (!thisNode) {
  34213. // Deleting nodes will be performed finally. This method just find
  34214. // element from old storage, or create new element, set them to new
  34215. // storage, and set styles.
  34216. return;
  34217. }
  34218. // -------------------------------------------------------------------
  34219. // Start of closure variables available in "Procedures in renderNode".
  34220. var thisLayout = thisNode.getLayout();
  34221. if (!thisLayout || !thisLayout.isInView) {
  34222. return;
  34223. }
  34224. var thisWidth = thisLayout.width;
  34225. var thisHeight = thisLayout.height;
  34226. var borderWidth = thisLayout.borderWidth;
  34227. var thisInvisible = thisLayout.invisible;
  34228. var thisRawIndex = thisNode.getRawIndex();
  34229. var oldRawIndex = oldNode && oldNode.getRawIndex();
  34230. var thisViewChildren = thisNode.viewChildren;
  34231. var upperHeight = thisLayout.upperHeight;
  34232. var isParent = thisViewChildren && thisViewChildren.length;
  34233. var itemStyleNormalModel = thisNode.getModel('itemStyle.normal');
  34234. var itemStyleEmphasisModel = thisNode.getModel('itemStyle.emphasis');
  34235. // End of closure ariables available in "Procedures in renderNode".
  34236. // -----------------------------------------------------------------
  34237. // Node group
  34238. var group = giveGraphic('nodeGroup', Group$2);
  34239. if (!group) {
  34240. return;
  34241. }
  34242. parentGroup.add(group);
  34243. // x,y are not set when el is above view root.
  34244. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  34245. group.__tmNodeWidth = thisWidth;
  34246. group.__tmNodeHeight = thisHeight;
  34247. if (thisLayout.isAboveViewRoot) {
  34248. return group;
  34249. }
  34250. // Background
  34251. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  34252. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  34253. // No children, render content.
  34254. if (!isParent) {
  34255. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  34256. content && renderContent(group, content);
  34257. }
  34258. return group;
  34259. // ----------------------------
  34260. // | Procedures in renderNode |
  34261. // ----------------------------
  34262. function renderBackground(group, bg, useUpperLabel) {
  34263. // For tooltip.
  34264. bg.dataIndex = thisNode.dataIndex;
  34265. bg.seriesIndex = seriesModel.seriesIndex;
  34266. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  34267. var visualBorderColor = thisNode.getVisual('borderColor', true);
  34268. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  34269. updateStyle(bg, function () {
  34270. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  34271. normalStyle.fill = visualBorderColor;
  34272. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  34273. emphasisStyle.fill = emphasisBorderColor;
  34274. if (useUpperLabel) {
  34275. var upperLabelWidth = thisWidth - 2 * borderWidth;
  34276. prepareText(
  34277. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  34278. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  34279. );
  34280. }
  34281. // For old bg.
  34282. else {
  34283. normalStyle.text = emphasisStyle.text = null;
  34284. }
  34285. bg.setStyle(normalStyle);
  34286. setHoverStyle(bg, emphasisStyle);
  34287. });
  34288. group.add(bg);
  34289. }
  34290. function renderContent(group, content) {
  34291. // For tooltip.
  34292. content.dataIndex = thisNode.dataIndex;
  34293. content.seriesIndex = seriesModel.seriesIndex;
  34294. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  34295. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  34296. content.culling = true;
  34297. content.setShape({
  34298. x: borderWidth,
  34299. y: borderWidth,
  34300. width: contentWidth,
  34301. height: contentHeight
  34302. });
  34303. var visualColor = thisNode.getVisual('color', true);
  34304. updateStyle(content, function () {
  34305. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  34306. normalStyle.fill = visualColor;
  34307. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  34308. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  34309. content.setStyle(normalStyle);
  34310. setHoverStyle(content, emphasisStyle);
  34311. });
  34312. group.add(content);
  34313. }
  34314. function updateStyle(element, cb) {
  34315. if (!thisInvisible) {
  34316. // If invisible, do not set visual, otherwise the element will
  34317. // change immediately before animation. We think it is OK to
  34318. // remain its origin color when moving out of the view window.
  34319. cb();
  34320. if (!element.__tmWillVisible) {
  34321. element.invisible = false;
  34322. }
  34323. }
  34324. else {
  34325. // Delay invisible setting utill animation finished,
  34326. // avoid element vanish suddenly before animation.
  34327. !element.invisible && willInvisibleEls.push(element);
  34328. }
  34329. }
  34330. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  34331. var nodeModel = thisNode.getModel();
  34332. var text = retrieve(
  34333. seriesModel.getFormattedLabel(
  34334. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  34335. ),
  34336. nodeModel.get('name')
  34337. );
  34338. if (!upperLabelRect && thisLayout.isLeafRoot) {
  34339. var iconChar = seriesModel.get('drillDownIcon', true);
  34340. text = iconChar ? iconChar + ' ' + text : text;
  34341. }
  34342. var normalLabelModel = nodeModel.getModel(
  34343. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  34344. );
  34345. var emphasisLabelModel = nodeModel.getModel(
  34346. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  34347. );
  34348. var isShow = normalLabelModel.getShallow('show');
  34349. setLabelStyle(
  34350. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  34351. {
  34352. defaultText: isShow ? text : null,
  34353. autoColor: visualColor,
  34354. isRectText: true
  34355. }
  34356. );
  34357. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  34358. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  34359. ? {
  34360. outerWidth: width,
  34361. outerHeight: height,
  34362. minChar: 2
  34363. }
  34364. : null;
  34365. }
  34366. function giveGraphic(storageName, Ctor, depth, z) {
  34367. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  34368. var lasts = lastsForAnimation[storageName];
  34369. if (element) {
  34370. // Remove from oldStorage
  34371. oldStorage[storageName][oldRawIndex] = null;
  34372. prepareAnimationWhenHasOld(lasts, element, storageName);
  34373. }
  34374. // If invisible and no old element, do not create new element (for optimizing).
  34375. else if (!thisInvisible) {
  34376. element = new Ctor({z: calculateZ(depth, z)});
  34377. element.__tmDepth = depth;
  34378. element.__tmStorageName = storageName;
  34379. prepareAnimationWhenNoOld(lasts, element, storageName);
  34380. }
  34381. // Set to thisStorage
  34382. return (thisStorage[storageName][thisRawIndex] = element);
  34383. }
  34384. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  34385. var lastCfg = lasts[thisRawIndex] = {};
  34386. lastCfg.old = storageName === 'nodeGroup'
  34387. ? element.position.slice()
  34388. : extend({}, element.shape);
  34389. }
  34390. // If a element is new, we need to find the animation start point carefully,
  34391. // otherwise it will looks strange when 'zoomToNode'.
  34392. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  34393. var lastCfg = lasts[thisRawIndex] = {};
  34394. var parentNode = thisNode.parentNode;
  34395. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  34396. var parentOldX = 0;
  34397. var parentOldY = 0;
  34398. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  34399. // For convenience, get old bounding rect from background.
  34400. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  34401. if (!reRoot && parentOldBg && parentOldBg.old) {
  34402. parentOldX = parentOldBg.old.width;
  34403. parentOldY = parentOldBg.old.height;
  34404. }
  34405. // When no parent old shape found, its parent is new too,
  34406. // so we can just use {x:0, y:0}.
  34407. lastCfg.old = storageName === 'nodeGroup'
  34408. ? [0, parentOldY]
  34409. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  34410. }
  34411. // Fade in, user can be aware that these nodes are new.
  34412. lastCfg.fadein = storageName !== 'nodeGroup';
  34413. }
  34414. }
  34415. // We can not set all backgroud with the same z, Because the behaviour of
  34416. // drill down and roll up differ background creation sequence from tree
  34417. // hierarchy sequence, which cause that lowser background element overlap
  34418. // upper ones. So we calculate z based on depth.
  34419. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  34420. // treemap with large z overlaps other components.
  34421. function calculateZ(depth, zInLevel) {
  34422. var zb = depth * Z_BASE + zInLevel;
  34423. return (zb - 1) / zb;
  34424. }
  34425. /**
  34426. * @file Treemap action
  34427. */
  34428. var noop$1 = function () {};
  34429. var actionTypes = [
  34430. 'treemapZoomToNode',
  34431. 'treemapRender',
  34432. 'treemapMove'
  34433. ];
  34434. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  34435. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  34436. }
  34437. registerAction(
  34438. {type: 'treemapRootToNode', update: 'updateView'},
  34439. function (payload, ecModel) {
  34440. ecModel.eachComponent(
  34441. {mainType: 'series', subType: 'treemap', query: payload},
  34442. handleRootToNode
  34443. );
  34444. function handleRootToNode(model, index) {
  34445. var targetInfo = retrieveTargetInfo(payload, model);
  34446. if (targetInfo) {
  34447. var originViewRoot = model.getViewRoot();
  34448. if (originViewRoot) {
  34449. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  34450. ? 'rollUp' : 'drillDown';
  34451. }
  34452. model.resetViewRoot(targetInfo.node);
  34453. }
  34454. }
  34455. }
  34456. );
  34457. var each$12 = each$1;
  34458. var isObject$5 = isObject;
  34459. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  34460. /**
  34461. * @param {Object} option
  34462. * @param {string} [option.type] See visualHandlers.
  34463. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  34464. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  34465. * required when mappingMethod is 'linear'
  34466. * @param {Array.<Object>=} [option.pieceList] [
  34467. * {value: someValue},
  34468. * {interval: [min1, max1], visual: {...}},
  34469. * {interval: [min2, max2]}
  34470. * ],
  34471. * required when mappingMethod is 'piecewise'.
  34472. * Visual for only each piece can be specified.
  34473. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  34474. * required when mappingMethod is 'category'.
  34475. * If no option.categories, categories is set
  34476. * as [0, 1, 2, ...].
  34477. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  34478. * @param {(Array|Object|*)} [option.visual] Visual data.
  34479. * when mappingMethod is 'category',
  34480. * visual data can be array or object
  34481. * (like: {cate1: '#222', none: '#fff'})
  34482. * or primary types (which represents
  34483. * defualt category visual), otherwise visual
  34484. * can be array or primary (which will be
  34485. * normalized to array).
  34486. *
  34487. */
  34488. var VisualMapping = function (option) {
  34489. var mappingMethod = option.mappingMethod;
  34490. var visualType = option.type;
  34491. /**
  34492. * @readOnly
  34493. * @type {Object}
  34494. */
  34495. var thisOption = this.option = clone(option);
  34496. /**
  34497. * @readOnly
  34498. * @type {string}
  34499. */
  34500. this.type = visualType;
  34501. /**
  34502. * @readOnly
  34503. * @type {string}
  34504. */
  34505. this.mappingMethod = mappingMethod;
  34506. /**
  34507. * @private
  34508. * @type {Function}
  34509. */
  34510. this._normalizeData = normalizers[mappingMethod];
  34511. var visualHandler = visualHandlers[visualType];
  34512. /**
  34513. * @public
  34514. * @type {Function}
  34515. */
  34516. this.applyVisual = visualHandler.applyVisual;
  34517. /**
  34518. * @public
  34519. * @type {Function}
  34520. */
  34521. this.getColorMapper = visualHandler.getColorMapper;
  34522. /**
  34523. * @private
  34524. * @type {Function}
  34525. */
  34526. this._doMap = visualHandler._doMap[mappingMethod];
  34527. if (mappingMethod === 'piecewise') {
  34528. normalizeVisualRange(thisOption);
  34529. preprocessForPiecewise(thisOption);
  34530. }
  34531. else if (mappingMethod === 'category') {
  34532. thisOption.categories
  34533. ? preprocessForSpecifiedCategory(thisOption)
  34534. // categories is ordinal when thisOption.categories not specified,
  34535. // which need no more preprocess except normalize visual.
  34536. : normalizeVisualRange(thisOption, true);
  34537. }
  34538. else { // mappingMethod === 'linear' or 'fixed'
  34539. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  34540. normalizeVisualRange(thisOption);
  34541. }
  34542. };
  34543. VisualMapping.prototype = {
  34544. constructor: VisualMapping,
  34545. mapValueToVisual: function (value) {
  34546. var normalized = this._normalizeData(value);
  34547. return this._doMap(normalized, value);
  34548. },
  34549. getNormalizer: function () {
  34550. return bind(this._normalizeData, this);
  34551. }
  34552. };
  34553. var visualHandlers = VisualMapping.visualHandlers = {
  34554. color: {
  34555. applyVisual: makeApplyVisual('color'),
  34556. /**
  34557. * Create a mapper function
  34558. * @return {Function}
  34559. */
  34560. getColorMapper: function () {
  34561. var thisOption = this.option;
  34562. return bind(
  34563. thisOption.mappingMethod === 'category'
  34564. ? function (value, isNormalized) {
  34565. !isNormalized && (value = this._normalizeData(value));
  34566. return doMapCategory.call(this, value);
  34567. }
  34568. : function (value, isNormalized, out) {
  34569. // If output rgb array
  34570. // which will be much faster and useful in pixel manipulation
  34571. var returnRGBArray = !!out;
  34572. !isNormalized && (value = this._normalizeData(value));
  34573. out = fastLerp(value, thisOption.parsedVisual, out);
  34574. return returnRGBArray ? out : stringify(out, 'rgba');
  34575. },
  34576. this
  34577. );
  34578. },
  34579. _doMap: {
  34580. linear: function (normalized) {
  34581. return stringify(
  34582. fastLerp(normalized, this.option.parsedVisual),
  34583. 'rgba'
  34584. );
  34585. },
  34586. category: doMapCategory,
  34587. piecewise: function (normalized, value) {
  34588. var result = getSpecifiedVisual.call(this, value);
  34589. if (result == null) {
  34590. result = stringify(
  34591. fastLerp(normalized, this.option.parsedVisual),
  34592. 'rgba'
  34593. );
  34594. }
  34595. return result;
  34596. },
  34597. fixed: doMapFixed
  34598. }
  34599. },
  34600. colorHue: makePartialColorVisualHandler(function (color, value) {
  34601. return modifyHSL(color, value);
  34602. }),
  34603. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  34604. return modifyHSL(color, null, value);
  34605. }),
  34606. colorLightness: makePartialColorVisualHandler(function (color, value) {
  34607. return modifyHSL(color, null, null, value);
  34608. }),
  34609. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  34610. return modifyAlpha(color, value);
  34611. }),
  34612. opacity: {
  34613. applyVisual: makeApplyVisual('opacity'),
  34614. _doMap: makeDoMap([0, 1])
  34615. },
  34616. symbol: {
  34617. applyVisual: function (value, getter, setter) {
  34618. var symbolCfg = this.mapValueToVisual(value);
  34619. if (isString(symbolCfg)) {
  34620. setter('symbol', symbolCfg);
  34621. }
  34622. else if (isObject$5(symbolCfg)) {
  34623. for (var name in symbolCfg) {
  34624. if (symbolCfg.hasOwnProperty(name)) {
  34625. setter(name, symbolCfg[name]);
  34626. }
  34627. }
  34628. }
  34629. },
  34630. _doMap: {
  34631. linear: doMapToArray,
  34632. category: doMapCategory,
  34633. piecewise: function (normalized, value) {
  34634. var result = getSpecifiedVisual.call(this, value);
  34635. if (result == null) {
  34636. result = doMapToArray.call(this, normalized);
  34637. }
  34638. return result;
  34639. },
  34640. fixed: doMapFixed
  34641. }
  34642. },
  34643. symbolSize: {
  34644. applyVisual: makeApplyVisual('symbolSize'),
  34645. _doMap: makeDoMap([0, 1])
  34646. }
  34647. };
  34648. function preprocessForPiecewise(thisOption) {
  34649. var pieceList = thisOption.pieceList;
  34650. thisOption.hasSpecialVisual = false;
  34651. each$1(pieceList, function (piece, index) {
  34652. piece.originIndex = index;
  34653. // piece.visual is "result visual value" but not
  34654. // a visual range, so it does not need to be normalized.
  34655. if (piece.visual != null) {
  34656. thisOption.hasSpecialVisual = true;
  34657. }
  34658. });
  34659. }
  34660. function preprocessForSpecifiedCategory(thisOption) {
  34661. // Hash categories.
  34662. var categories = thisOption.categories;
  34663. var visual = thisOption.visual;
  34664. var categoryMap = thisOption.categoryMap = {};
  34665. each$12(categories, function (cate, index) {
  34666. categoryMap[cate] = index;
  34667. });
  34668. // Process visual map input.
  34669. if (!isArray(visual)) {
  34670. var visualArr = [];
  34671. if (isObject(visual)) {
  34672. each$12(visual, function (v, cate) {
  34673. var index = categoryMap[cate];
  34674. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  34675. });
  34676. }
  34677. else { // Is primary type, represents default visual.
  34678. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  34679. }
  34680. visual = setVisualToOption(thisOption, visualArr);
  34681. }
  34682. // Remove categories that has no visual,
  34683. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  34684. for (var i = categories.length - 1; i >= 0; i--) {
  34685. if (visual[i] == null) {
  34686. delete categoryMap[categories[i]];
  34687. categories.pop();
  34688. }
  34689. }
  34690. }
  34691. function normalizeVisualRange(thisOption, isCategory) {
  34692. var visual = thisOption.visual;
  34693. var visualArr = [];
  34694. if (isObject(visual)) {
  34695. each$12(visual, function (v) {
  34696. visualArr.push(v);
  34697. });
  34698. }
  34699. else if (visual != null) {
  34700. visualArr.push(visual);
  34701. }
  34702. var doNotNeedPair = {color: 1, symbol: 1};
  34703. if (!isCategory
  34704. && visualArr.length === 1
  34705. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  34706. ) {
  34707. // Do not care visualArr.length === 0, which is illegal.
  34708. visualArr[1] = visualArr[0];
  34709. }
  34710. setVisualToOption(thisOption, visualArr);
  34711. }
  34712. function makePartialColorVisualHandler(applyValue) {
  34713. return {
  34714. applyVisual: function (value, getter, setter) {
  34715. value = this.mapValueToVisual(value);
  34716. // Must not be array value
  34717. setter('color', applyValue(getter('color'), value));
  34718. },
  34719. _doMap: makeDoMap([0, 1])
  34720. };
  34721. }
  34722. function doMapToArray(normalized) {
  34723. var visual = this.option.visual;
  34724. return visual[
  34725. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  34726. ] || {};
  34727. }
  34728. function makeApplyVisual(visualType) {
  34729. return function (value, getter, setter) {
  34730. setter(visualType, this.mapValueToVisual(value));
  34731. };
  34732. }
  34733. function doMapCategory(normalized) {
  34734. var visual = this.option.visual;
  34735. return visual[
  34736. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  34737. ? normalized % visual.length
  34738. : normalized
  34739. ];
  34740. }
  34741. function doMapFixed() {
  34742. return this.option.visual[0];
  34743. }
  34744. function makeDoMap(sourceExtent) {
  34745. return {
  34746. linear: function (normalized) {
  34747. return linearMap(normalized, sourceExtent, this.option.visual, true);
  34748. },
  34749. category: doMapCategory,
  34750. piecewise: function (normalized, value) {
  34751. var result = getSpecifiedVisual.call(this, value);
  34752. if (result == null) {
  34753. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  34754. }
  34755. return result;
  34756. },
  34757. fixed: doMapFixed
  34758. };
  34759. }
  34760. function getSpecifiedVisual(value) {
  34761. var thisOption = this.option;
  34762. var pieceList = thisOption.pieceList;
  34763. if (thisOption.hasSpecialVisual) {
  34764. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  34765. var piece = pieceList[pieceIndex];
  34766. if (piece && piece.visual) {
  34767. return piece.visual[this.type];
  34768. }
  34769. }
  34770. }
  34771. function setVisualToOption(thisOption, visualArr) {
  34772. thisOption.visual = visualArr;
  34773. if (thisOption.type === 'color') {
  34774. thisOption.parsedVisual = map(visualArr, function (item) {
  34775. return parse(item);
  34776. });
  34777. }
  34778. return visualArr;
  34779. }
  34780. /**
  34781. * Normalizers by mapping methods.
  34782. */
  34783. var normalizers = {
  34784. linear: function (value) {
  34785. return linearMap(value, this.option.dataExtent, [0, 1], true);
  34786. },
  34787. piecewise: function (value) {
  34788. var pieceList = this.option.pieceList;
  34789. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  34790. if (pieceIndex != null) {
  34791. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  34792. }
  34793. },
  34794. category: function (value) {
  34795. var index = this.option.categories
  34796. ? this.option.categoryMap[value]
  34797. : value; // ordinal
  34798. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  34799. },
  34800. fixed: noop
  34801. };
  34802. /**
  34803. * List available visual types.
  34804. *
  34805. * @public
  34806. * @return {Array.<string>}
  34807. */
  34808. VisualMapping.listVisualTypes = function () {
  34809. var visualTypes = [];
  34810. each$1(visualHandlers, function (handler, key) {
  34811. visualTypes.push(key);
  34812. });
  34813. return visualTypes;
  34814. };
  34815. /**
  34816. * @public
  34817. */
  34818. VisualMapping.addVisualHandler = function (name, handler) {
  34819. visualHandlers[name] = handler;
  34820. };
  34821. /**
  34822. * @public
  34823. */
  34824. VisualMapping.isValidType = function (visualType) {
  34825. return visualHandlers.hasOwnProperty(visualType);
  34826. };
  34827. /**
  34828. * Convinent method.
  34829. * Visual can be Object or Array or primary type.
  34830. *
  34831. * @public
  34832. */
  34833. VisualMapping.eachVisual = function (visual, callback, context) {
  34834. if (isObject(visual)) {
  34835. each$1(visual, callback, context);
  34836. }
  34837. else {
  34838. callback.call(context, visual);
  34839. }
  34840. };
  34841. VisualMapping.mapVisual = function (visual, callback, context) {
  34842. var isPrimary;
  34843. var newVisual = isArray(visual)
  34844. ? []
  34845. : isObject(visual)
  34846. ? {}
  34847. : (isPrimary = true, null);
  34848. VisualMapping.eachVisual(visual, function (v, key) {
  34849. var newVal = callback.call(context, v, key);
  34850. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  34851. });
  34852. return newVisual;
  34853. };
  34854. /**
  34855. * @public
  34856. * @param {Object} obj
  34857. * @return {Object} new object containers visual values.
  34858. * If no visuals, return null.
  34859. */
  34860. VisualMapping.retrieveVisuals = function (obj) {
  34861. var ret = {};
  34862. var hasVisual;
  34863. obj && each$12(visualHandlers, function (h, visualType) {
  34864. if (obj.hasOwnProperty(visualType)) {
  34865. ret[visualType] = obj[visualType];
  34866. hasVisual = true;
  34867. }
  34868. });
  34869. return hasVisual ? ret : null;
  34870. };
  34871. /**
  34872. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  34873. *
  34874. * @public
  34875. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  34876. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  34877. * @return {Array.<string>} Sorted visual types.
  34878. */
  34879. VisualMapping.prepareVisualTypes = function (visualTypes) {
  34880. if (isObject$5(visualTypes)) {
  34881. var types = [];
  34882. each$12(visualTypes, function (item, type) {
  34883. types.push(type);
  34884. });
  34885. visualTypes = types;
  34886. }
  34887. else if (isArray(visualTypes)) {
  34888. visualTypes = visualTypes.slice();
  34889. }
  34890. else {
  34891. return [];
  34892. }
  34893. visualTypes.sort(function (type1, type2) {
  34894. // color should be front of colorSaturation, colorAlpha, ...
  34895. // symbol and symbolSize do not matter.
  34896. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  34897. ? 1 : -1;
  34898. });
  34899. return visualTypes;
  34900. };
  34901. /**
  34902. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  34903. * Other visuals are only depends on themself.
  34904. *
  34905. * @public
  34906. * @param {string} visualType1
  34907. * @param {string} visualType2
  34908. * @return {boolean}
  34909. */
  34910. VisualMapping.dependsOn = function (visualType1, visualType2) {
  34911. return visualType2 === 'color'
  34912. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  34913. : visualType1 === visualType2;
  34914. };
  34915. /**
  34916. * @param {number} value
  34917. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  34918. * Always from small to big.
  34919. * @param {boolean} [findClosestWhenOutside=false]
  34920. * @return {number} index
  34921. */
  34922. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  34923. var possibleI;
  34924. var abs = Infinity;
  34925. // value has the higher priority.
  34926. for (var i = 0, len = pieceList.length; i < len; i++) {
  34927. var pieceValue = pieceList[i].value;
  34928. if (pieceValue != null) {
  34929. if (pieceValue === value
  34930. // FIXME
  34931. // It is supposed to compare value according to value type of dimension,
  34932. // but currently value type can exactly be string or number.
  34933. // Compromise for numeric-like string (like '12'), especially
  34934. // in the case that visualMap.categories is ['22', '33'].
  34935. || (typeof pieceValue === 'string' && pieceValue === value + '')
  34936. ) {
  34937. return i;
  34938. }
  34939. findClosestWhenOutside && updatePossible(pieceValue, i);
  34940. }
  34941. }
  34942. for (var i = 0, len = pieceList.length; i < len; i++) {
  34943. var piece = pieceList[i];
  34944. var interval = piece.interval;
  34945. var close = piece.close;
  34946. if (interval) {
  34947. if (interval[0] === -Infinity) {
  34948. if (littleThan(close[1], value, interval[1])) {
  34949. return i;
  34950. }
  34951. }
  34952. else if (interval[1] === Infinity) {
  34953. if (littleThan(close[0], interval[0], value)) {
  34954. return i;
  34955. }
  34956. }
  34957. else if (
  34958. littleThan(close[0], interval[0], value)
  34959. && littleThan(close[1], value, interval[1])
  34960. ) {
  34961. return i;
  34962. }
  34963. findClosestWhenOutside && updatePossible(interval[0], i);
  34964. findClosestWhenOutside && updatePossible(interval[1], i);
  34965. }
  34966. }
  34967. if (findClosestWhenOutside) {
  34968. return value === Infinity
  34969. ? pieceList.length - 1
  34970. : value === -Infinity
  34971. ? 0
  34972. : possibleI;
  34973. }
  34974. function updatePossible(val, index) {
  34975. var newAbs = Math.abs(val - value);
  34976. if (newAbs < abs) {
  34977. abs = newAbs;
  34978. possibleI = index;
  34979. }
  34980. }
  34981. };
  34982. function littleThan(close, a, b) {
  34983. return close ? a <= b : a < b;
  34984. }
  34985. var isArray$2 = isArray;
  34986. var ITEM_STYLE_NORMAL = 'itemStyle.normal';
  34987. var treemapVisual = function (ecModel, api, payload) {
  34988. var condition = {mainType: 'series', subType: 'treemap', query: payload};
  34989. ecModel.eachComponent(condition, function (seriesModel) {
  34990. var tree = seriesModel.getData().tree;
  34991. var root = tree.root;
  34992. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  34993. if (root.isRemoved()) {
  34994. return;
  34995. }
  34996. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  34997. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  34998. });
  34999. travelTree(
  35000. root, // Visual should calculate from tree root but not view root.
  35001. {},
  35002. levelItemStyles,
  35003. seriesItemStyleModel,
  35004. seriesModel.getViewRoot().getAncestors(),
  35005. seriesModel
  35006. );
  35007. });
  35008. };
  35009. function travelTree(
  35010. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  35011. viewRootAncestors, seriesModel
  35012. ) {
  35013. var nodeModel = node.getModel();
  35014. var nodeLayout = node.getLayout();
  35015. // Optimize
  35016. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  35017. return;
  35018. }
  35019. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  35020. var levelItemStyle = levelItemStyles[node.depth];
  35021. var visuals = buildVisuals(
  35022. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  35023. );
  35024. // calculate border color
  35025. var borderColor = nodeItemStyleModel.get('borderColor');
  35026. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  35027. var thisNodeColor;
  35028. if (borderColorSaturation != null) {
  35029. // For performance, do not always execute 'calculateColor'.
  35030. thisNodeColor = calculateColor(visuals, node);
  35031. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  35032. }
  35033. node.setVisual('borderColor', borderColor);
  35034. var viewChildren = node.viewChildren;
  35035. if (!viewChildren || !viewChildren.length) {
  35036. thisNodeColor = calculateColor(visuals, node);
  35037. // Apply visual to this node.
  35038. node.setVisual('color', thisNodeColor);
  35039. }
  35040. else {
  35041. var mapping = buildVisualMapping(
  35042. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  35043. );
  35044. // Designate visual to children.
  35045. each$1(viewChildren, function (child, index) {
  35046. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  35047. if (child.depth >= viewRootAncestors.length
  35048. || child === viewRootAncestors[child.depth]
  35049. ) {
  35050. var childVisual = mapVisual$1(
  35051. nodeModel, visuals, child, index, mapping, seriesModel
  35052. );
  35053. travelTree(
  35054. child, childVisual, levelItemStyles, seriesItemStyleModel,
  35055. viewRootAncestors, seriesModel
  35056. );
  35057. }
  35058. });
  35059. }
  35060. }
  35061. function buildVisuals(
  35062. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  35063. ) {
  35064. var visuals = extend({}, designatedVisual);
  35065. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  35066. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  35067. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  35068. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  35069. val == null && (val = designatedVisual[visualName]);
  35070. val == null && (val = seriesItemStyleModel.get(visualName));
  35071. val != null && (visuals[visualName] = val);
  35072. });
  35073. return visuals;
  35074. }
  35075. function calculateColor(visuals) {
  35076. var color = getValueVisualDefine(visuals, 'color');
  35077. if (color) {
  35078. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  35079. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  35080. if (colorSaturation) {
  35081. color = modifyHSL(color, null, null, colorSaturation);
  35082. }
  35083. if (colorAlpha) {
  35084. color = modifyAlpha(color, colorAlpha);
  35085. }
  35086. return color;
  35087. }
  35088. }
  35089. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  35090. return thisNodeColor != null
  35091. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  35092. : null;
  35093. }
  35094. function getValueVisualDefine(visuals, name) {
  35095. var value = visuals[name];
  35096. if (value != null && value !== 'none') {
  35097. return value;
  35098. }
  35099. }
  35100. function buildVisualMapping(
  35101. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  35102. ) {
  35103. if (!viewChildren || !viewChildren.length) {
  35104. return;
  35105. }
  35106. var rangeVisual = getRangeVisual(nodeModel, 'color')
  35107. || (
  35108. visuals.color != null
  35109. && visuals.color !== 'none'
  35110. && (
  35111. getRangeVisual(nodeModel, 'colorAlpha')
  35112. || getRangeVisual(nodeModel, 'colorSaturation')
  35113. )
  35114. );
  35115. if (!rangeVisual) {
  35116. return;
  35117. }
  35118. var visualMin = nodeModel.get('visualMin');
  35119. var visualMax = nodeModel.get('visualMax');
  35120. var dataExtent = nodeLayout.dataExtent.slice();
  35121. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  35122. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  35123. var colorMappingBy = nodeModel.get('colorMappingBy');
  35124. var opt = {
  35125. type: rangeVisual.name,
  35126. dataExtent: dataExtent,
  35127. visual: rangeVisual.range
  35128. };
  35129. if (opt.type === 'color'
  35130. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  35131. ) {
  35132. opt.mappingMethod = 'category';
  35133. opt.loop = true;
  35134. // categories is ordinal, so do not set opt.categories.
  35135. }
  35136. else {
  35137. opt.mappingMethod = 'linear';
  35138. }
  35139. var mapping = new VisualMapping(opt);
  35140. mapping.__drColorMappingBy = colorMappingBy;
  35141. return mapping;
  35142. }
  35143. // Notice: If we dont have the attribute 'colorRange', but only use
  35144. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  35145. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  35146. // this problem will be encountered:
  35147. // If a level-1 node dont have children, and its siblings has children,
  35148. // and colorRange is set on level-1, then the node can not be colored.
  35149. // So we separate 'colorRange' and 'color' to different attributes.
  35150. function getRangeVisual(nodeModel, name) {
  35151. // 'colorRange', 'colorARange', 'colorSRange'.
  35152. // If not exsits on this node, fetch from levels and series.
  35153. var range = nodeModel.get(name);
  35154. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  35155. }
  35156. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  35157. var childVisuals = extend({}, visuals);
  35158. if (mapping) {
  35159. var mappingType = mapping.type;
  35160. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  35161. var value =
  35162. colorMappingBy === 'index'
  35163. ? index
  35164. : colorMappingBy === 'id'
  35165. ? seriesModel.mapIdToIndex(child.getId())
  35166. : child.getValue(nodeModel.get('visualDimension'));
  35167. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  35168. }
  35169. return childVisuals;
  35170. }
  35171. var mathMax$4 = Math.max;
  35172. var mathMin$4 = Math.min;
  35173. var retrieveValue$1 = retrieve;
  35174. var each$13 = each$1;
  35175. var PATH_BORDER_WIDTH = ['itemStyle', 'normal', 'borderWidth'];
  35176. var PATH_GAP_WIDTH = ['itemStyle', 'normal', 'gapWidth'];
  35177. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'normal', 'show'];
  35178. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'normal', 'height'];
  35179. /**
  35180. * @public
  35181. */
  35182. var treemapLayout = function (ecModel, api, payload) {
  35183. // Layout result in each node:
  35184. // {x, y, width, height, area, borderWidth}
  35185. var condition = {mainType: 'series', subType: 'treemap', query: payload};
  35186. ecModel.eachComponent(condition, function (seriesModel) {
  35187. var ecWidth = api.getWidth();
  35188. var ecHeight = api.getHeight();
  35189. var seriesOption = seriesModel.option;
  35190. var layoutInfo = getLayoutRect(
  35191. seriesModel.getBoxLayoutParams(),
  35192. {
  35193. width: api.getWidth(),
  35194. height: api.getHeight()
  35195. }
  35196. );
  35197. var size = seriesOption.size || []; // Compatible with ec2.
  35198. var containerWidth = parsePercent$1(
  35199. retrieveValue$1(layoutInfo.width, size[0]),
  35200. ecWidth
  35201. );
  35202. var containerHeight = parsePercent$1(
  35203. retrieveValue$1(layoutInfo.height, size[1]),
  35204. ecHeight
  35205. );
  35206. // Fetch payload info.
  35207. var payloadType = payload && payload.type;
  35208. var targetInfo = retrieveTargetInfo(payload, seriesModel);
  35209. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  35210. ? payload.rootRect : null;
  35211. var viewRoot = seriesModel.getViewRoot();
  35212. var viewAbovePath = getPathToRoot(viewRoot);
  35213. if (payloadType !== 'treemapMove') {
  35214. var rootSize = payloadType === 'treemapZoomToNode'
  35215. ? estimateRootSize(
  35216. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  35217. )
  35218. : rootRect
  35219. ? [rootRect.width, rootRect.height]
  35220. : [containerWidth, containerHeight];
  35221. var sort = seriesOption.sort;
  35222. if (sort && sort !== 'asc' && sort !== 'desc') {
  35223. sort = 'desc';
  35224. }
  35225. var options = {
  35226. squareRatio: seriesOption.squareRatio,
  35227. sort: sort,
  35228. leafDepth: seriesOption.leafDepth
  35229. };
  35230. // layout should be cleared because using updateView but not update.
  35231. viewRoot.hostTree.clearLayouts();
  35232. // TODO
  35233. // optimize: if out of view clip, do not layout.
  35234. // But take care that if do not render node out of view clip,
  35235. // how to calculate start po
  35236. var viewRootLayout = {
  35237. x: 0, y: 0,
  35238. width: rootSize[0], height: rootSize[1],
  35239. area: rootSize[0] * rootSize[1]
  35240. };
  35241. viewRoot.setLayout(viewRootLayout);
  35242. squarify(viewRoot, options, false, 0);
  35243. // Supplement layout.
  35244. var viewRootLayout = viewRoot.getLayout();
  35245. each$13(viewAbovePath, function (node, index) {
  35246. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  35247. node.setLayout(extend(
  35248. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  35249. viewRootLayout
  35250. ));
  35251. });
  35252. }
  35253. var treeRoot = seriesModel.getData().tree.root;
  35254. treeRoot.setLayout(
  35255. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  35256. true
  35257. );
  35258. seriesModel.setLayoutInfo(layoutInfo);
  35259. // FIXME
  35260. // 现在没有clip功能,暂时取ec高宽。
  35261. prunning(
  35262. treeRoot,
  35263. // Transform to base element coordinate system.
  35264. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  35265. viewAbovePath,
  35266. viewRoot,
  35267. 0
  35268. );
  35269. });
  35270. };
  35271. /**
  35272. * Layout treemap with squarify algorithm.
  35273. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  35274. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  35275. *
  35276. * @protected
  35277. * @param {module:echarts/data/Tree~TreeNode} node
  35278. * @param {Object} options
  35279. * @param {string} options.sort 'asc' or 'desc'
  35280. * @param {number} options.squareRatio
  35281. * @param {boolean} hideChildren
  35282. * @param {number} depth
  35283. */
  35284. function squarify(node, options, hideChildren, depth) {
  35285. var width;
  35286. var height;
  35287. if (node.isRemoved()) {
  35288. return;
  35289. }
  35290. var thisLayout = node.getLayout();
  35291. width = thisLayout.width;
  35292. height = thisLayout.height;
  35293. // Considering border and gap
  35294. var nodeModel = node.getModel();
  35295. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  35296. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  35297. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  35298. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  35299. var layoutOffset = borderWidth - halfGapWidth;
  35300. var layoutOffsetUpper = upperHeight - halfGapWidth;
  35301. var nodeModel = node.getModel();
  35302. node.setLayout({
  35303. borderWidth: borderWidth,
  35304. upperHeight: upperHeight,
  35305. upperLabelHeight: upperLabelHeight
  35306. }, true);
  35307. width = mathMax$4(width - 2 * layoutOffset, 0);
  35308. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  35309. var totalArea = width * height;
  35310. var viewChildren = initChildren(
  35311. node, nodeModel, totalArea, options, hideChildren, depth
  35312. );
  35313. if (!viewChildren.length) {
  35314. return;
  35315. }
  35316. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  35317. var rowFixedLength = mathMin$4(width, height);
  35318. var best = Infinity; // the best row score so far
  35319. var row = [];
  35320. row.area = 0;
  35321. for (var i = 0, len = viewChildren.length; i < len;) {
  35322. var child = viewChildren[i];
  35323. row.push(child);
  35324. row.area += child.getLayout().area;
  35325. var score = worst(row, rowFixedLength, options.squareRatio);
  35326. // continue with this orientation
  35327. if (score <= best) {
  35328. i++;
  35329. best = score;
  35330. }
  35331. // abort, and try a different orientation
  35332. else {
  35333. row.area -= row.pop().getLayout().area;
  35334. position(row, rowFixedLength, rect, halfGapWidth, false);
  35335. rowFixedLength = mathMin$4(rect.width, rect.height);
  35336. row.length = row.area = 0;
  35337. best = Infinity;
  35338. }
  35339. }
  35340. if (row.length) {
  35341. position(row, rowFixedLength, rect, halfGapWidth, true);
  35342. }
  35343. if (!hideChildren) {
  35344. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  35345. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  35346. hideChildren = true;
  35347. }
  35348. }
  35349. for (var i = 0, len = viewChildren.length; i < len; i++) {
  35350. squarify(viewChildren[i], options, hideChildren, depth + 1);
  35351. }
  35352. }
  35353. /**
  35354. * Set area to each child, and calculate data extent for visual coding.
  35355. */
  35356. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  35357. var viewChildren = node.children || [];
  35358. var orderBy = options.sort;
  35359. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  35360. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  35361. // leafDepth has higher priority.
  35362. if (hideChildren && !overLeafDepth) {
  35363. return (node.viewChildren = []);
  35364. }
  35365. // Sort children, order by desc.
  35366. viewChildren = filter(viewChildren, function (child) {
  35367. return !child.isRemoved();
  35368. });
  35369. sort$1(viewChildren, orderBy);
  35370. var info = statistic(nodeModel, viewChildren, orderBy);
  35371. if (info.sum === 0) {
  35372. return (node.viewChildren = []);
  35373. }
  35374. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  35375. if (info.sum === 0) {
  35376. return (node.viewChildren = []);
  35377. }
  35378. // Set area to each child.
  35379. for (var i = 0, len = viewChildren.length; i < len; i++) {
  35380. var area = viewChildren[i].getValue() / info.sum * totalArea;
  35381. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  35382. viewChildren[i].setLayout({area: area});
  35383. }
  35384. if (overLeafDepth) {
  35385. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  35386. viewChildren.length = 0;
  35387. }
  35388. node.viewChildren = viewChildren;
  35389. node.setLayout({dataExtent: info.dataExtent}, true);
  35390. return viewChildren;
  35391. }
  35392. /**
  35393. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  35394. */
  35395. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  35396. // visibleMin is not supported yet when no option.sort.
  35397. if (!orderBy) {
  35398. return sum;
  35399. }
  35400. var visibleMin = nodeModel.get('visibleMin');
  35401. var len = orderedChildren.length;
  35402. var deletePoint = len;
  35403. // Always travel from little value to big value.
  35404. for (var i = len - 1; i >= 0; i--) {
  35405. var value = orderedChildren[
  35406. orderBy === 'asc' ? len - i - 1 : i
  35407. ].getValue();
  35408. if (value / sum * totalArea < visibleMin) {
  35409. deletePoint = i;
  35410. sum -= value;
  35411. }
  35412. }
  35413. orderBy === 'asc'
  35414. ? orderedChildren.splice(0, len - deletePoint)
  35415. : orderedChildren.splice(deletePoint, len - deletePoint);
  35416. return sum;
  35417. }
  35418. /**
  35419. * Sort
  35420. */
  35421. function sort$1(viewChildren, orderBy) {
  35422. if (orderBy) {
  35423. viewChildren.sort(function (a, b) {
  35424. var diff = orderBy === 'asc'
  35425. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  35426. return diff === 0
  35427. ? (orderBy === 'asc'
  35428. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  35429. )
  35430. : diff;
  35431. });
  35432. }
  35433. return viewChildren;
  35434. }
  35435. /**
  35436. * Statistic
  35437. */
  35438. function statistic(nodeModel, children, orderBy) {
  35439. // Calculate sum.
  35440. var sum = 0;
  35441. for (var i = 0, len = children.length; i < len; i++) {
  35442. sum += children[i].getValue();
  35443. }
  35444. // Statistic data extent for latter visual coding.
  35445. // Notice: data extent should be calculate based on raw children
  35446. // but not filtered view children, otherwise visual mapping will not
  35447. // be stable when zoom (where children is filtered by visibleMin).
  35448. var dimension = nodeModel.get('visualDimension');
  35449. var dataExtent;
  35450. // The same as area dimension.
  35451. if (!children || !children.length) {
  35452. dataExtent = [NaN, NaN];
  35453. }
  35454. else if (dimension === 'value' && orderBy) {
  35455. dataExtent = [
  35456. children[children.length - 1].getValue(),
  35457. children[0].getValue()
  35458. ];
  35459. orderBy === 'asc' && dataExtent.reverse();
  35460. }
  35461. // Other dimension.
  35462. else {
  35463. var dataExtent = [Infinity, -Infinity];
  35464. each$13(children, function (child) {
  35465. var value = child.getValue(dimension);
  35466. value < dataExtent[0] && (dataExtent[0] = value);
  35467. value > dataExtent[1] && (dataExtent[1] = value);
  35468. });
  35469. }
  35470. return {sum: sum, dataExtent: dataExtent};
  35471. }
  35472. /**
  35473. * Computes the score for the specified row,
  35474. * as the worst aspect ratio.
  35475. */
  35476. function worst(row, rowFixedLength, ratio) {
  35477. var areaMax = 0;
  35478. var areaMin = Infinity;
  35479. for (var i = 0, area, len = row.length; i < len; i++) {
  35480. area = row[i].getLayout().area;
  35481. if (area) {
  35482. area < areaMin && (areaMin = area);
  35483. area > areaMax && (areaMax = area);
  35484. }
  35485. }
  35486. var squareArea = row.area * row.area;
  35487. var f = rowFixedLength * rowFixedLength * ratio;
  35488. return squareArea
  35489. ? mathMax$4(
  35490. (f * areaMax) / squareArea,
  35491. squareArea / (f * areaMin)
  35492. )
  35493. : Infinity;
  35494. }
  35495. /**
  35496. * Positions the specified row of nodes. Modifies `rect`.
  35497. */
  35498. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  35499. // When rowFixedLength === rect.width,
  35500. // it is horizontal subdivision,
  35501. // rowFixedLength is the width of the subdivision,
  35502. // rowOtherLength is the height of the subdivision,
  35503. // and nodes will be positioned from left to right.
  35504. // wh[idx0WhenH] means: when horizontal,
  35505. // wh[idx0WhenH] => wh[0] => 'width'.
  35506. // xy[idx1WhenH] => xy[1] => 'y'.
  35507. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  35508. var idx1WhenH = 1 - idx0WhenH;
  35509. var xy = ['x', 'y'];
  35510. var wh = ['width', 'height'];
  35511. var last = rect[xy[idx0WhenH]];
  35512. var rowOtherLength = rowFixedLength
  35513. ? row.area / rowFixedLength : 0;
  35514. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  35515. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  35516. }
  35517. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  35518. var node = row[i];
  35519. var nodeLayout = {};
  35520. var step = rowOtherLength
  35521. ? node.getLayout().area / rowOtherLength : 0;
  35522. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  35523. // We use Math.max/min to avoid negative width/height when considering gap width.
  35524. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  35525. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  35526. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  35527. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  35528. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  35529. last += modWH;
  35530. node.setLayout(nodeLayout, true);
  35531. }
  35532. rect[xy[idx1WhenH]] += rowOtherLength;
  35533. rect[wh[idx1WhenH]] -= rowOtherLength;
  35534. }
  35535. // Return [containerWidth, containerHeight] as defualt.
  35536. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  35537. // If targetInfo.node exists, we zoom to the node,
  35538. // so estimate whold width and heigth by target node.
  35539. var currNode = (targetInfo || {}).node;
  35540. var defaultSize = [containerWidth, containerHeight];
  35541. if (!currNode || currNode === viewRoot) {
  35542. return defaultSize;
  35543. }
  35544. var parent;
  35545. var viewArea = containerWidth * containerHeight;
  35546. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  35547. while (parent = currNode.parentNode) { // jshint ignore:line
  35548. var sum = 0;
  35549. var siblings = parent.children;
  35550. for (var i = 0, len = siblings.length; i < len; i++) {
  35551. sum += siblings[i].getValue();
  35552. }
  35553. var currNodeValue = currNode.getValue();
  35554. if (currNodeValue === 0) {
  35555. return defaultSize;
  35556. }
  35557. area *= sum / currNodeValue;
  35558. // Considering border, suppose aspect ratio is 1.
  35559. var parentModel = parent.getModel();
  35560. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  35561. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  35562. area += 4 * borderWidth * borderWidth
  35563. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  35564. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  35565. currNode = parent;
  35566. }
  35567. area < viewArea && (area = viewArea);
  35568. var scale = Math.pow(area / viewArea, 0.5);
  35569. return [containerWidth * scale, containerHeight * scale];
  35570. }
  35571. // Root postion base on coord of containerGroup
  35572. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  35573. if (rootRect) {
  35574. return {x: rootRect.x, y: rootRect.y};
  35575. }
  35576. var defaultPosition = {x: 0, y: 0};
  35577. if (!targetInfo) {
  35578. return defaultPosition;
  35579. }
  35580. // If targetInfo is fetched by 'retrieveTargetInfo',
  35581. // old tree and new tree are the same tree,
  35582. // so the node still exists and we can visit it.
  35583. var targetNode = targetInfo.node;
  35584. var layout = targetNode.getLayout();
  35585. if (!layout) {
  35586. return defaultPosition;
  35587. }
  35588. // Transform coord from local to container.
  35589. var targetCenter = [layout.width / 2, layout.height / 2];
  35590. var node = targetNode;
  35591. while (node) {
  35592. var nodeLayout = node.getLayout();
  35593. targetCenter[0] += nodeLayout.x;
  35594. targetCenter[1] += nodeLayout.y;
  35595. node = node.parentNode;
  35596. }
  35597. return {
  35598. x: layoutInfo.width / 2 - targetCenter[0],
  35599. y: layoutInfo.height / 2 - targetCenter[1]
  35600. };
  35601. }
  35602. // Mark nodes visible for prunning when visual coding and rendering.
  35603. // Prunning depends on layout and root position, so we have to do it after layout.
  35604. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  35605. var nodeLayout = node.getLayout();
  35606. var nodeInViewAbovePath = viewAbovePath[depth];
  35607. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  35608. if (
  35609. (nodeInViewAbovePath && !isAboveViewRoot)
  35610. || (depth === viewAbovePath.length && node !== viewRoot)
  35611. ) {
  35612. return;
  35613. }
  35614. node.setLayout({
  35615. // isInView means: viewRoot sub tree + viewAbovePath
  35616. isInView: true,
  35617. // invisible only means: outside view clip so that the node can not
  35618. // see but still layout for animation preparation but not render.
  35619. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  35620. isAboveViewRoot: isAboveViewRoot
  35621. }, true);
  35622. // Transform to child coordinate.
  35623. var childClipRect = new BoundingRect(
  35624. clipRect.x - nodeLayout.x,
  35625. clipRect.y - nodeLayout.y,
  35626. clipRect.width,
  35627. clipRect.height
  35628. );
  35629. each$13(node.viewChildren || [], function (child) {
  35630. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  35631. });
  35632. }
  35633. function getUpperLabelHeight(model) {
  35634. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  35635. }
  35636. registerVisual(treemapVisual);
  35637. registerLayout(treemapLayout);
  35638. /**
  35639. * Graph data structure
  35640. *
  35641. * @module echarts/data/Graph
  35642. * @author Yi Shen(https://www.github.com/pissang)
  35643. */
  35644. // id may be function name of Object, add a prefix to avoid this problem.
  35645. function generateNodeKey (id) {
  35646. return '_EC_' + id;
  35647. }
  35648. /**
  35649. * @alias module:echarts/data/Graph
  35650. * @constructor
  35651. * @param {boolean} directed
  35652. */
  35653. var Graph = function(directed) {
  35654. /**
  35655. * 是否是有向图
  35656. * @type {boolean}
  35657. * @private
  35658. */
  35659. this._directed = directed || false;
  35660. /**
  35661. * @type {Array.<module:echarts/data/Graph.Node>}
  35662. * @readOnly
  35663. */
  35664. this.nodes = [];
  35665. /**
  35666. * @type {Array.<module:echarts/data/Graph.Edge>}
  35667. * @readOnly
  35668. */
  35669. this.edges = [];
  35670. /**
  35671. * @type {Object.<string, module:echarts/data/Graph.Node>}
  35672. * @private
  35673. */
  35674. this._nodesMap = {};
  35675. /**
  35676. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  35677. * @private
  35678. */
  35679. this._edgesMap = {};
  35680. /**
  35681. * @type {module:echarts/data/List}
  35682. * @readOnly
  35683. */
  35684. this.data;
  35685. /**
  35686. * @type {module:echarts/data/List}
  35687. * @readOnly
  35688. */
  35689. this.edgeData;
  35690. };
  35691. var graphProto = Graph.prototype;
  35692. /**
  35693. * @type {string}
  35694. */
  35695. graphProto.type = 'graph';
  35696. /**
  35697. * If is directed graph
  35698. * @return {boolean}
  35699. */
  35700. graphProto.isDirected = function () {
  35701. return this._directed;
  35702. };
  35703. /**
  35704. * Add a new node
  35705. * @param {string} id
  35706. * @param {number} [dataIndex]
  35707. */
  35708. graphProto.addNode = function (id, dataIndex) {
  35709. id = id || ('' + dataIndex);
  35710. var nodesMap = this._nodesMap;
  35711. if (nodesMap[generateNodeKey(id)]) {
  35712. if (__DEV__) {
  35713. console.error('Graph nodes have duplicate name or id');
  35714. }
  35715. return;
  35716. }
  35717. var node = new Node(id, dataIndex);
  35718. node.hostGraph = this;
  35719. this.nodes.push(node);
  35720. nodesMap[generateNodeKey(id)] = node;
  35721. return node;
  35722. };
  35723. /**
  35724. * Get node by data index
  35725. * @param {number} dataIndex
  35726. * @return {module:echarts/data/Graph~Node}
  35727. */
  35728. graphProto.getNodeByIndex = function (dataIndex) {
  35729. var rawIdx = this.data.getRawIndex(dataIndex);
  35730. return this.nodes[rawIdx];
  35731. };
  35732. /**
  35733. * Get node by id
  35734. * @param {string} id
  35735. * @return {module:echarts/data/Graph.Node}
  35736. */
  35737. graphProto.getNodeById = function (id) {
  35738. return this._nodesMap[generateNodeKey(id)];
  35739. };
  35740. /**
  35741. * Add a new edge
  35742. * @param {number|string|module:echarts/data/Graph.Node} n1
  35743. * @param {number|string|module:echarts/data/Graph.Node} n2
  35744. * @param {number} [dataIndex=-1]
  35745. * @return {module:echarts/data/Graph.Edge}
  35746. */
  35747. graphProto.addEdge = function (n1, n2, dataIndex) {
  35748. var nodesMap = this._nodesMap;
  35749. var edgesMap = this._edgesMap;
  35750. // PNEDING
  35751. if (typeof n1 === 'number') {
  35752. n1 = this.nodes[n1];
  35753. }
  35754. if (typeof n2 === 'number') {
  35755. n2 = this.nodes[n2];
  35756. }
  35757. if (!(n1 instanceof Node)) {
  35758. n1 = nodesMap[generateNodeKey(n1)];
  35759. }
  35760. if (!(n2 instanceof Node)) {
  35761. n2 = nodesMap[generateNodeKey(n2)];
  35762. }
  35763. if (!n1 || !n2) {
  35764. return;
  35765. }
  35766. var key = n1.id + '-' + n2.id;
  35767. // PENDING
  35768. if (edgesMap[key]) {
  35769. return;
  35770. }
  35771. var edge = new Edge(n1, n2, dataIndex);
  35772. edge.hostGraph = this;
  35773. if (this._directed) {
  35774. n1.outEdges.push(edge);
  35775. n2.inEdges.push(edge);
  35776. }
  35777. n1.edges.push(edge);
  35778. if (n1 !== n2) {
  35779. n2.edges.push(edge);
  35780. }
  35781. this.edges.push(edge);
  35782. edgesMap[key] = edge;
  35783. return edge;
  35784. };
  35785. /**
  35786. * Get edge by data index
  35787. * @param {number} dataIndex
  35788. * @return {module:echarts/data/Graph~Node}
  35789. */
  35790. graphProto.getEdgeByIndex = function (dataIndex) {
  35791. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  35792. return this.edges[rawIdx];
  35793. };
  35794. /**
  35795. * Get edge by two linked nodes
  35796. * @param {module:echarts/data/Graph.Node|string} n1
  35797. * @param {module:echarts/data/Graph.Node|string} n2
  35798. * @return {module:echarts/data/Graph.Edge}
  35799. */
  35800. graphProto.getEdge = function (n1, n2) {
  35801. if (n1 instanceof Node) {
  35802. n1 = n1.id;
  35803. }
  35804. if (n2 instanceof Node) {
  35805. n2 = n2.id;
  35806. }
  35807. var edgesMap = this._edgesMap;
  35808. if (this._directed) {
  35809. return edgesMap[n1 + '-' + n2];
  35810. } else {
  35811. return edgesMap[n1 + '-' + n2]
  35812. || edgesMap[n2 + '-' + n1];
  35813. }
  35814. };
  35815. /**
  35816. * Iterate all nodes
  35817. * @param {Function} cb
  35818. * @param {*} [context]
  35819. */
  35820. graphProto.eachNode = function (cb, context) {
  35821. var nodes = this.nodes;
  35822. var len = nodes.length;
  35823. for (var i = 0; i < len; i++) {
  35824. if (nodes[i].dataIndex >= 0) {
  35825. cb.call(context, nodes[i], i);
  35826. }
  35827. }
  35828. };
  35829. /**
  35830. * Iterate all edges
  35831. * @param {Function} cb
  35832. * @param {*} [context]
  35833. */
  35834. graphProto.eachEdge = function (cb, context) {
  35835. var edges = this.edges;
  35836. var len = edges.length;
  35837. for (var i = 0; i < len; i++) {
  35838. if (edges[i].dataIndex >= 0
  35839. && edges[i].node1.dataIndex >= 0
  35840. && edges[i].node2.dataIndex >= 0
  35841. ) {
  35842. cb.call(context, edges[i], i);
  35843. }
  35844. }
  35845. };
  35846. /**
  35847. * Breadth first traverse
  35848. * @param {Function} cb
  35849. * @param {module:echarts/data/Graph.Node} startNode
  35850. * @param {string} [direction='none'] 'none'|'in'|'out'
  35851. * @param {*} [context]
  35852. */
  35853. graphProto.breadthFirstTraverse = function (
  35854. cb, startNode, direction, context
  35855. ) {
  35856. if (!(startNode instanceof Node)) {
  35857. startNode = this._nodesMap[generateNodeKey(startNode)];
  35858. }
  35859. if (!startNode) {
  35860. return;
  35861. }
  35862. var edgeType = direction === 'out'
  35863. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  35864. for (var i = 0; i < this.nodes.length; i++) {
  35865. this.nodes[i].__visited = false;
  35866. }
  35867. if (cb.call(context, startNode, null)) {
  35868. return;
  35869. }
  35870. var queue = [startNode];
  35871. while (queue.length) {
  35872. var currentNode = queue.shift();
  35873. var edges = currentNode[edgeType];
  35874. for (var i = 0; i < edges.length; i++) {
  35875. var e = edges[i];
  35876. var otherNode = e.node1 === currentNode
  35877. ? e.node2 : e.node1;
  35878. if (!otherNode.__visited) {
  35879. if (cb.call(context, otherNode, currentNode)) {
  35880. // Stop traversing
  35881. return;
  35882. }
  35883. queue.push(otherNode);
  35884. otherNode.__visited = true;
  35885. }
  35886. }
  35887. }
  35888. };
  35889. // TODO
  35890. // graphProto.depthFirstTraverse = function (
  35891. // cb, startNode, direction, context
  35892. // ) {
  35893. // };
  35894. // Filter update
  35895. graphProto.update = function () {
  35896. var data = this.data;
  35897. var edgeData = this.edgeData;
  35898. var nodes = this.nodes;
  35899. var edges = this.edges;
  35900. for (var i = 0, len = nodes.length; i < len; i++) {
  35901. nodes[i].dataIndex = -1;
  35902. }
  35903. for (var i = 0, len = data.count(); i < len; i++) {
  35904. nodes[data.getRawIndex(i)].dataIndex = i;
  35905. }
  35906. edgeData.filterSelf(function (idx) {
  35907. var edge = edges[edgeData.getRawIndex(idx)];
  35908. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  35909. });
  35910. // Update edge
  35911. for (var i = 0, len = edges.length; i < len; i++) {
  35912. edges[i].dataIndex = -1;
  35913. }
  35914. for (var i = 0, len = edgeData.count(); i < len; i++) {
  35915. edges[edgeData.getRawIndex(i)].dataIndex = i;
  35916. }
  35917. };
  35918. /**
  35919. * @return {module:echarts/data/Graph}
  35920. */
  35921. graphProto.clone = function () {
  35922. var graph = new Graph(this._directed);
  35923. var nodes = this.nodes;
  35924. var edges = this.edges;
  35925. for (var i = 0; i < nodes.length; i++) {
  35926. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  35927. }
  35928. for (var i = 0; i < edges.length; i++) {
  35929. var e = edges[i];
  35930. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  35931. }
  35932. return graph;
  35933. };
  35934. /**
  35935. * @alias module:echarts/data/Graph.Node
  35936. */
  35937. function Node(id, dataIndex) {
  35938. /**
  35939. * @type {string}
  35940. */
  35941. this.id = id == null ? '' : id;
  35942. /**
  35943. * @type {Array.<module:echarts/data/Graph.Edge>}
  35944. */
  35945. this.inEdges = [];
  35946. /**
  35947. * @type {Array.<module:echarts/data/Graph.Edge>}
  35948. */
  35949. this.outEdges = [];
  35950. /**
  35951. * @type {Array.<module:echarts/data/Graph.Edge>}
  35952. */
  35953. this.edges = [];
  35954. /**
  35955. * @type {module:echarts/data/Graph}
  35956. */
  35957. this.hostGraph;
  35958. /**
  35959. * @type {number}
  35960. */
  35961. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  35962. }
  35963. Node.prototype = {
  35964. constructor: Node,
  35965. /**
  35966. * @return {number}
  35967. */
  35968. degree: function () {
  35969. return this.edges.length;
  35970. },
  35971. /**
  35972. * @return {number}
  35973. */
  35974. inDegree: function () {
  35975. return this.inEdges.length;
  35976. },
  35977. /**
  35978. * @return {number}
  35979. */
  35980. outDegree: function () {
  35981. return this.outEdges.length;
  35982. },
  35983. /**
  35984. * @param {string} [path]
  35985. * @return {module:echarts/model/Model}
  35986. */
  35987. getModel: function (path) {
  35988. if (this.dataIndex < 0) {
  35989. return;
  35990. }
  35991. var graph = this.hostGraph;
  35992. var itemModel = graph.data.getItemModel(this.dataIndex);
  35993. return itemModel.getModel(path);
  35994. }
  35995. };
  35996. /**
  35997. * 图边
  35998. * @alias module:echarts/data/Graph.Edge
  35999. * @param {module:echarts/data/Graph.Node} n1
  36000. * @param {module:echarts/data/Graph.Node} n2
  36001. * @param {number} [dataIndex=-1]
  36002. */
  36003. function Edge(n1, n2, dataIndex) {
  36004. /**
  36005. * 节点1,如果是有向图则为源节点
  36006. * @type {module:echarts/data/Graph.Node}
  36007. */
  36008. this.node1 = n1;
  36009. /**
  36010. * 节点2,如果是有向图则为目标节点
  36011. * @type {module:echarts/data/Graph.Node}
  36012. */
  36013. this.node2 = n2;
  36014. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  36015. }
  36016. /**
  36017. * @param {string} [path]
  36018. * @return {module:echarts/model/Model}
  36019. */
  36020. Edge.prototype.getModel = function (path) {
  36021. if (this.dataIndex < 0) {
  36022. return;
  36023. }
  36024. var graph = this.hostGraph;
  36025. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  36026. return itemModel.getModel(path);
  36027. };
  36028. var createGraphDataProxyMixin = function (hostName, dataName) {
  36029. return {
  36030. /**
  36031. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  36032. * @return {number}
  36033. */
  36034. getValue: function (dimension) {
  36035. var data = this[hostName][dataName];
  36036. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  36037. },
  36038. /**
  36039. * @param {Object|string} key
  36040. * @param {*} [value]
  36041. */
  36042. setVisual: function (key, value) {
  36043. this.dataIndex >= 0
  36044. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  36045. },
  36046. /**
  36047. * @param {string} key
  36048. * @return {boolean}
  36049. */
  36050. getVisual: function (key, ignoreParent) {
  36051. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  36052. },
  36053. /**
  36054. * @param {Object} layout
  36055. * @return {boolean} [merge=false]
  36056. */
  36057. setLayout: function (layout, merge$$1) {
  36058. this.dataIndex >= 0
  36059. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  36060. },
  36061. /**
  36062. * @return {Object}
  36063. */
  36064. getLayout: function () {
  36065. return this[hostName][dataName].getItemLayout(this.dataIndex);
  36066. },
  36067. /**
  36068. * @return {module:zrender/Element}
  36069. */
  36070. getGraphicEl: function () {
  36071. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  36072. },
  36073. /**
  36074. * @return {number}
  36075. */
  36076. getRawIndex: function () {
  36077. return this[hostName][dataName].getRawIndex(this.dataIndex);
  36078. }
  36079. };
  36080. };
  36081. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  36082. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  36083. Graph.Node = Node;
  36084. Graph.Edge = Edge;
  36085. var createGraphFromNodeEdge = function (nodes, edges, hostModel, directed, beforeLink) {
  36086. var graph = new Graph(directed);
  36087. for (var i = 0; i < nodes.length; i++) {
  36088. graph.addNode(retrieve(
  36089. // Id, name, dataIndex
  36090. nodes[i].id, nodes[i].name, i
  36091. ), i);
  36092. }
  36093. var linkNameList = [];
  36094. var validEdges = [];
  36095. var linkCount = 0;
  36096. for (var i = 0; i < edges.length; i++) {
  36097. var link = edges[i];
  36098. var source = link.source;
  36099. var target = link.target;
  36100. // addEdge may fail when source or target not exists
  36101. if (graph.addEdge(source, target, linkCount)) {
  36102. validEdges.push(link);
  36103. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  36104. linkCount++;
  36105. }
  36106. }
  36107. var coordSys = hostModel.get('coordinateSystem');
  36108. var nodeData;
  36109. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  36110. nodeData = createListFromArray(nodes, hostModel, hostModel.ecModel);
  36111. }
  36112. else {
  36113. // FIXME
  36114. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  36115. // FIXME
  36116. var dimensionNames = completeDimensions(
  36117. ((coordSysCtor && coordSysCtor.type !== 'view') ? (coordSysCtor.dimensions || []) : []).concat(['value']),
  36118. nodes
  36119. );
  36120. nodeData = new List(dimensionNames, hostModel);
  36121. nodeData.initData(nodes);
  36122. }
  36123. var edgeData = new List(['value'], hostModel);
  36124. edgeData.initData(validEdges, linkNameList);
  36125. beforeLink && beforeLink(nodeData, edgeData);
  36126. linkList({
  36127. mainData: nodeData,
  36128. struct: graph,
  36129. structAttr: 'graph',
  36130. datas: {node: nodeData, edge: edgeData},
  36131. datasAttr: {node: 'data', edge: 'edgeData'}
  36132. });
  36133. // Update dataIndex of nodes and edges because invalid edge may be removed
  36134. graph.update();
  36135. return graph;
  36136. };
  36137. var GraphSeries = extendSeriesModel({
  36138. type: 'series.graph',
  36139. init: function (option) {
  36140. GraphSeries.superApply(this, 'init', arguments);
  36141. // Provide data for legend select
  36142. this.legendDataProvider = function () {
  36143. return this._categoriesData;
  36144. };
  36145. this.fillDataTextStyle(option.edges || option.links);
  36146. this._updateCategoriesData();
  36147. },
  36148. mergeOption: function (option) {
  36149. GraphSeries.superApply(this, 'mergeOption', arguments);
  36150. this.fillDataTextStyle(option.edges || option.links);
  36151. this._updateCategoriesData();
  36152. },
  36153. mergeDefaultAndTheme: function (option) {
  36154. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  36155. defaultEmphasis(option.edgeLabel, ['show']);
  36156. },
  36157. getInitialData: function (option, ecModel) {
  36158. var edges = option.edges || option.links || [];
  36159. var nodes = option.data || option.nodes || [];
  36160. var self = this;
  36161. if (nodes && edges) {
  36162. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  36163. }
  36164. function beforeLink(nodeData, edgeData) {
  36165. // Overwrite nodeData.getItemModel to
  36166. nodeData.wrapMethod('getItemModel', function (model) {
  36167. var categoriesModels = self._categoriesModels;
  36168. var categoryIdx = model.getShallow('category');
  36169. var categoryModel = categoriesModels[categoryIdx];
  36170. if (categoryModel) {
  36171. categoryModel.parentModel = model.parentModel;
  36172. model.parentModel = categoryModel;
  36173. }
  36174. return model;
  36175. });
  36176. var edgeLabelModel = self.getModel('edgeLabel');
  36177. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  36178. var fakeSeriesModel = new Model(
  36179. {label: edgeLabelModel.option},
  36180. edgeLabelModel.parentModel,
  36181. ecModel
  36182. );
  36183. edgeData.wrapMethod('getItemModel', function (model) {
  36184. model.customizeGetParent(edgeGetParent);
  36185. return model;
  36186. });
  36187. function edgeGetParent(path) {
  36188. path = this.parsePath(path);
  36189. return (path && path[0] === 'label')
  36190. ? fakeSeriesModel
  36191. : this.parentModel;
  36192. }
  36193. }
  36194. },
  36195. /**
  36196. * @return {module:echarts/data/Graph}
  36197. */
  36198. getGraph: function () {
  36199. return this.getData().graph;
  36200. },
  36201. /**
  36202. * @return {module:echarts/data/List}
  36203. */
  36204. getEdgeData: function () {
  36205. return this.getGraph().edgeData;
  36206. },
  36207. /**
  36208. * @return {module:echarts/data/List}
  36209. */
  36210. getCategoriesData: function () {
  36211. return this._categoriesData;
  36212. },
  36213. /**
  36214. * @override
  36215. */
  36216. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  36217. if (dataType === 'edge') {
  36218. var nodeData = this.getData();
  36219. var params = this.getDataParams(dataIndex, dataType);
  36220. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  36221. var sourceName = nodeData.getName(edge.node1.dataIndex);
  36222. var targetName = nodeData.getName(edge.node2.dataIndex);
  36223. var html = [];
  36224. sourceName != null && html.push(sourceName);
  36225. targetName != null && html.push(targetName);
  36226. html = encodeHTML(html.join(' > '));
  36227. if (params.value) {
  36228. html += ' : ' + encodeHTML(params.value);
  36229. }
  36230. return html;
  36231. }
  36232. else { // dataType === 'node' or empty
  36233. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  36234. }
  36235. },
  36236. _updateCategoriesData: function () {
  36237. var categories = map(this.option.categories || [], function (category) {
  36238. // Data must has value
  36239. return category.value != null ? category : extend({
  36240. value: 0
  36241. }, category);
  36242. });
  36243. var categoriesData = new List(['value'], this);
  36244. categoriesData.initData(categories);
  36245. this._categoriesData = categoriesData;
  36246. this._categoriesModels = categoriesData.mapArray(function (idx) {
  36247. return categoriesData.getItemModel(idx, true);
  36248. });
  36249. },
  36250. setZoom: function (zoom) {
  36251. this.option.zoom = zoom;
  36252. },
  36253. setCenter: function (center) {
  36254. this.option.center = center;
  36255. },
  36256. isAnimationEnabled: function () {
  36257. return GraphSeries.superCall(this, 'isAnimationEnabled')
  36258. // Not enable animation when do force layout
  36259. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  36260. },
  36261. defaultOption: {
  36262. zlevel: 0,
  36263. z: 2,
  36264. coordinateSystem: 'view',
  36265. // Default option for all coordinate systems
  36266. // xAxisIndex: 0,
  36267. // yAxisIndex: 0,
  36268. // polarIndex: 0,
  36269. // geoIndex: 0,
  36270. legendHoverLink: true,
  36271. hoverAnimation: true,
  36272. layout: null,
  36273. focusNodeAdjacency: false,
  36274. // Configuration of circular layout
  36275. circular: {
  36276. rotateLabel: false
  36277. },
  36278. // Configuration of force directed layout
  36279. force: {
  36280. initLayout: null,
  36281. // Node repulsion. Can be an array to represent range.
  36282. repulsion: [0, 50],
  36283. gravity: 0.1,
  36284. // Edge length. Can be an array to represent range.
  36285. edgeLength: 30,
  36286. layoutAnimation: true
  36287. },
  36288. left: 'center',
  36289. top: 'center',
  36290. // right: null,
  36291. // bottom: null,
  36292. // width: '80%',
  36293. // height: '80%',
  36294. symbol: 'circle',
  36295. symbolSize: 10,
  36296. edgeSymbol: ['none', 'none'],
  36297. edgeSymbolSize: 10,
  36298. edgeLabel: {
  36299. normal: {
  36300. position: 'middle'
  36301. },
  36302. emphasis: {}
  36303. },
  36304. draggable: false,
  36305. roam: false,
  36306. // Default on center of graph
  36307. center: null,
  36308. zoom: 1,
  36309. // Symbol size scale ratio in roam
  36310. nodeScaleRatio: 0.6,
  36311. // cursor: null,
  36312. // categories: [],
  36313. // data: []
  36314. // Or
  36315. // nodes: []
  36316. //
  36317. // links: []
  36318. // Or
  36319. // edges: []
  36320. label: {
  36321. normal: {
  36322. show: false,
  36323. formatter: '{b}'
  36324. },
  36325. emphasis: {
  36326. show: true
  36327. }
  36328. },
  36329. itemStyle: {
  36330. normal: {},
  36331. emphasis: {}
  36332. },
  36333. lineStyle: {
  36334. normal: {
  36335. color: '#aaa',
  36336. width: 1,
  36337. curveness: 0,
  36338. opacity: 0.5
  36339. },
  36340. emphasis: {}
  36341. }
  36342. }
  36343. });
  36344. /**
  36345. * Line path for bezier and straight line draw
  36346. */
  36347. var straightLineProto = Line.prototype;
  36348. var bezierCurveProto = BezierCurve.prototype;
  36349. function isLine(shape) {
  36350. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  36351. }
  36352. var LinePath = extendShape({
  36353. type: 'ec-line',
  36354. style: {
  36355. stroke: '#000',
  36356. fill: null
  36357. },
  36358. shape: {
  36359. x1: 0,
  36360. y1: 0,
  36361. x2: 0,
  36362. y2: 0,
  36363. percent: 1,
  36364. cpx1: null,
  36365. cpy1: null
  36366. },
  36367. buildPath: function (ctx, shape) {
  36368. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  36369. },
  36370. pointAt: function (t) {
  36371. return isLine(this.shape)
  36372. ? straightLineProto.pointAt.call(this, t)
  36373. : bezierCurveProto.pointAt.call(this, t);
  36374. },
  36375. tangentAt: function (t) {
  36376. var shape = this.shape;
  36377. var p = isLine(shape)
  36378. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  36379. : bezierCurveProto.tangentAt.call(this, t);
  36380. return normalize(p, p);
  36381. }
  36382. });
  36383. /**
  36384. * @module echarts/chart/helper/Line
  36385. */
  36386. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  36387. function makeSymbolTypeKey(symbolCategory) {
  36388. return '_' + symbolCategory + 'Type';
  36389. }
  36390. /**
  36391. * @inner
  36392. */
  36393. function createSymbol$1(name, lineData, idx) {
  36394. var color = lineData.getItemVisual(idx, 'color');
  36395. var symbolType = lineData.getItemVisual(idx, name);
  36396. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  36397. if (!symbolType || symbolType === 'none') {
  36398. return;
  36399. }
  36400. if (!isArray(symbolSize)) {
  36401. symbolSize = [symbolSize, symbolSize];
  36402. }
  36403. var symbolPath = createSymbol(
  36404. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  36405. symbolSize[0], symbolSize[1], color
  36406. );
  36407. symbolPath.name = name;
  36408. return symbolPath;
  36409. }
  36410. function createLine(points) {
  36411. var line = new LinePath({
  36412. name: 'line'
  36413. });
  36414. setLinePoints(line.shape, points);
  36415. return line;
  36416. }
  36417. function setLinePoints(targetShape, points) {
  36418. var p1 = points[0];
  36419. var p2 = points[1];
  36420. var cp1 = points[2];
  36421. targetShape.x1 = p1[0];
  36422. targetShape.y1 = p1[1];
  36423. targetShape.x2 = p2[0];
  36424. targetShape.y2 = p2[1];
  36425. targetShape.percent = 1;
  36426. if (cp1) {
  36427. targetShape.cpx1 = cp1[0];
  36428. targetShape.cpy1 = cp1[1];
  36429. }
  36430. else {
  36431. targetShape.cpx1 = NaN;
  36432. targetShape.cpy1 = NaN;
  36433. }
  36434. }
  36435. function updateSymbolAndLabelBeforeLineUpdate () {
  36436. var lineGroup = this;
  36437. var symbolFrom = lineGroup.childOfName('fromSymbol');
  36438. var symbolTo = lineGroup.childOfName('toSymbol');
  36439. var label = lineGroup.childOfName('label');
  36440. // Quick reject
  36441. if (!symbolFrom && !symbolTo && label.ignore) {
  36442. return;
  36443. }
  36444. var invScale = 1;
  36445. var parentNode = this.parent;
  36446. while (parentNode) {
  36447. if (parentNode.scale) {
  36448. invScale /= parentNode.scale[0];
  36449. }
  36450. parentNode = parentNode.parent;
  36451. }
  36452. var line = lineGroup.childOfName('line');
  36453. // If line not changed
  36454. // FIXME Parent scale changed
  36455. if (!this.__dirty && !line.__dirty) {
  36456. return;
  36457. }
  36458. var percent = line.shape.percent;
  36459. var fromPos = line.pointAt(0);
  36460. var toPos = line.pointAt(percent);
  36461. var d = sub([], toPos, fromPos);
  36462. normalize(d, d);
  36463. if (symbolFrom) {
  36464. symbolFrom.attr('position', fromPos);
  36465. var tangent = line.tangentAt(0);
  36466. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  36467. tangent[1], tangent[0]
  36468. ));
  36469. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  36470. }
  36471. if (symbolTo) {
  36472. symbolTo.attr('position', toPos);
  36473. var tangent = line.tangentAt(1);
  36474. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  36475. tangent[1], tangent[0]
  36476. ));
  36477. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  36478. }
  36479. if (!label.ignore) {
  36480. label.attr('position', toPos);
  36481. var textPosition;
  36482. var textAlign;
  36483. var textVerticalAlign;
  36484. var distance$$1 = 5 * invScale;
  36485. // End
  36486. if (label.__position === 'end') {
  36487. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  36488. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  36489. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  36490. }
  36491. // Middle
  36492. else if (label.__position === 'middle') {
  36493. var halfPercent = percent / 2;
  36494. var tangent = line.tangentAt(halfPercent);
  36495. var n = [tangent[1], -tangent[0]];
  36496. var cp = line.pointAt(halfPercent);
  36497. if (n[1] > 0) {
  36498. n[0] = -n[0];
  36499. n[1] = -n[1];
  36500. }
  36501. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  36502. textAlign = 'center';
  36503. textVerticalAlign = 'bottom';
  36504. var rotation = -Math.atan2(tangent[1], tangent[0]);
  36505. if (toPos[0] < fromPos[0]) {
  36506. rotation = Math.PI + rotation;
  36507. }
  36508. label.attr('rotation', rotation);
  36509. }
  36510. // Start
  36511. else {
  36512. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  36513. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  36514. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  36515. }
  36516. label.attr({
  36517. style: {
  36518. // Use the user specified text align and baseline first
  36519. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  36520. textAlign: label.__textAlign || textAlign
  36521. },
  36522. position: textPosition,
  36523. scale: [invScale, invScale]
  36524. });
  36525. }
  36526. }
  36527. /**
  36528. * @constructor
  36529. * @extends {module:zrender/graphic/Group}
  36530. * @alias {module:echarts/chart/helper/Line}
  36531. */
  36532. function Line$1(lineData, idx, seriesScope) {
  36533. Group.call(this);
  36534. this._createLine(lineData, idx, seriesScope);
  36535. }
  36536. var lineProto = Line$1.prototype;
  36537. // Update symbol position and rotation
  36538. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  36539. lineProto._createLine = function (lineData, idx, seriesScope) {
  36540. var seriesModel = lineData.hostModel;
  36541. var linePoints = lineData.getItemLayout(idx);
  36542. var line = createLine(linePoints);
  36543. line.shape.percent = 0;
  36544. initProps(line, {
  36545. shape: {
  36546. percent: 1
  36547. }
  36548. }, seriesModel, idx);
  36549. this.add(line);
  36550. var label = new Text({
  36551. name: 'label'
  36552. });
  36553. this.add(label);
  36554. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36555. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  36556. // symbols must added after line to make sure
  36557. // it will be updated after line#update.
  36558. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  36559. this.add(symbol);
  36560. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  36561. }, this);
  36562. this._updateCommonStl(lineData, idx, seriesScope);
  36563. };
  36564. lineProto.updateData = function (lineData, idx, seriesScope) {
  36565. var seriesModel = lineData.hostModel;
  36566. var line = this.childOfName('line');
  36567. var linePoints = lineData.getItemLayout(idx);
  36568. var target = {
  36569. shape: {}
  36570. };
  36571. setLinePoints(target.shape, linePoints);
  36572. updateProps(line, target, seriesModel, idx);
  36573. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36574. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  36575. var key = makeSymbolTypeKey(symbolCategory);
  36576. // Symbol changed
  36577. if (this[key] !== symbolType) {
  36578. this.remove(this.childOfName(symbolCategory));
  36579. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  36580. this.add(symbol);
  36581. }
  36582. this[key] = symbolType;
  36583. }, this);
  36584. this._updateCommonStl(lineData, idx, seriesScope);
  36585. };
  36586. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  36587. var seriesModel = lineData.hostModel;
  36588. var line = this.childOfName('line');
  36589. var lineStyle = seriesScope && seriesScope.lineStyle;
  36590. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  36591. var labelModel = seriesScope && seriesScope.labelModel;
  36592. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  36593. // Optimization for large dataset
  36594. if (!seriesScope || lineData.hasItemOption) {
  36595. var itemModel = lineData.getItemModel(idx);
  36596. lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  36597. hoverLineStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  36598. labelModel = itemModel.getModel('label.normal');
  36599. hoverLabelModel = itemModel.getModel('label.emphasis');
  36600. }
  36601. var visualColor = lineData.getItemVisual(idx, 'color');
  36602. var visualOpacity = retrieve3(
  36603. lineData.getItemVisual(idx, 'opacity'),
  36604. lineStyle.opacity,
  36605. 1
  36606. );
  36607. line.useStyle(defaults(
  36608. {
  36609. strokeNoScale: true,
  36610. fill: 'none',
  36611. stroke: visualColor,
  36612. opacity: visualOpacity
  36613. },
  36614. lineStyle
  36615. ));
  36616. line.hoverStyle = hoverLineStyle;
  36617. // Update symbol
  36618. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36619. var symbol = this.childOfName(symbolCategory);
  36620. if (symbol) {
  36621. symbol.setColor(visualColor);
  36622. symbol.setStyle({
  36623. opacity: visualOpacity
  36624. });
  36625. }
  36626. }, this);
  36627. var showLabel = labelModel.getShallow('show');
  36628. var hoverShowLabel = hoverLabelModel.getShallow('show');
  36629. var label = this.childOfName('label');
  36630. var defaultLabelColor;
  36631. var defaultText;
  36632. var normalText;
  36633. var emphasisText;
  36634. if (showLabel || hoverShowLabel) {
  36635. var rawVal = seriesModel.getRawValue(idx);
  36636. defaultText = rawVal == null
  36637. ? defaultText = lineData.getName(idx)
  36638. : isFinite(rawVal)
  36639. ? round(rawVal)
  36640. : rawVal;
  36641. defaultLabelColor = visualColor || '#000';
  36642. normalText = retrieve2(
  36643. seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType),
  36644. defaultText
  36645. );
  36646. emphasisText = retrieve2(
  36647. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  36648. normalText
  36649. );
  36650. }
  36651. // label.afterUpdate = lineAfterUpdate;
  36652. if (showLabel) {
  36653. var labelStyle = setTextStyle(label.style, labelModel, {
  36654. text: normalText
  36655. }, {
  36656. autoColor: defaultLabelColor
  36657. });
  36658. label.__textAlign = labelStyle.textAlign;
  36659. label.__verticalAlign = labelStyle.textVerticalAlign;
  36660. // 'start', 'middle', 'end'
  36661. label.__position = labelModel.get('position') || 'middle';
  36662. }
  36663. else {
  36664. label.setStyle('text', null);
  36665. }
  36666. if (hoverShowLabel) {
  36667. // Only these properties supported in this emphasis style here.
  36668. label.hoverStyle = {
  36669. text: emphasisText,
  36670. textFill: hoverLabelModel.getTextColor(true),
  36671. // For merging hover style to normal style, do not use
  36672. // `hoverLabelModel.getFont()` here.
  36673. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  36674. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  36675. fontSize: hoverLabelModel.getShallow('fontSize'),
  36676. fontFamily: hoverLabelModel.getShallow('fontFamily')
  36677. };
  36678. }
  36679. else {
  36680. label.hoverStyle = {
  36681. text: null
  36682. };
  36683. }
  36684. label.ignore = !showLabel && !hoverShowLabel;
  36685. setHoverStyle(this);
  36686. };
  36687. lineProto.highlight = function () {
  36688. this.trigger('emphasis');
  36689. };
  36690. lineProto.downplay = function () {
  36691. this.trigger('normal');
  36692. };
  36693. lineProto.updateLayout = function (lineData, idx) {
  36694. this.setLinePoints(lineData.getItemLayout(idx));
  36695. };
  36696. lineProto.setLinePoints = function (points) {
  36697. var linePath = this.childOfName('line');
  36698. setLinePoints(linePath.shape, points);
  36699. linePath.dirty();
  36700. };
  36701. inherits(Line$1, Group);
  36702. /**
  36703. * @module echarts/chart/helper/LineDraw
  36704. */
  36705. function isPointNaN(pt) {
  36706. return isNaN(pt[0]) || isNaN(pt[1]);
  36707. }
  36708. function lineNeedsDraw(pts) {
  36709. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  36710. }
  36711. /**
  36712. * @alias module:echarts/component/marker/LineDraw
  36713. * @constructor
  36714. */
  36715. function LineDraw(ctor) {
  36716. this._ctor = ctor || Line$1;
  36717. this.group = new Group();
  36718. }
  36719. var lineDrawProto = LineDraw.prototype;
  36720. /**
  36721. * @param {module:echarts/data/List} lineData
  36722. */
  36723. lineDrawProto.updateData = function (lineData) {
  36724. var oldLineData = this._lineData;
  36725. var group = this.group;
  36726. var LineCtor = this._ctor;
  36727. var hostModel = lineData.hostModel;
  36728. var seriesScope = {
  36729. lineStyle: hostModel.getModel('lineStyle.normal').getLineStyle(),
  36730. hoverLineStyle: hostModel.getModel('lineStyle.emphasis').getLineStyle(),
  36731. labelModel: hostModel.getModel('label.normal'),
  36732. hoverLabelModel: hostModel.getModel('label.emphasis')
  36733. };
  36734. lineData.diff(oldLineData)
  36735. .add(function (idx) {
  36736. if (!lineNeedsDraw(lineData.getItemLayout(idx))) {
  36737. return;
  36738. }
  36739. var lineGroup = new LineCtor(lineData, idx, seriesScope);
  36740. lineData.setItemGraphicEl(idx, lineGroup);
  36741. group.add(lineGroup);
  36742. })
  36743. .update(function (newIdx, oldIdx) {
  36744. var lineGroup = oldLineData.getItemGraphicEl(oldIdx);
  36745. if (!lineNeedsDraw(lineData.getItemLayout(newIdx))) {
  36746. group.remove(lineGroup);
  36747. return;
  36748. }
  36749. if (!lineGroup) {
  36750. lineGroup = new LineCtor(lineData, newIdx, seriesScope);
  36751. }
  36752. else {
  36753. lineGroup.updateData(lineData, newIdx, seriesScope);
  36754. }
  36755. lineData.setItemGraphicEl(newIdx, lineGroup);
  36756. group.add(lineGroup);
  36757. })
  36758. .remove(function (idx) {
  36759. group.remove(oldLineData.getItemGraphicEl(idx));
  36760. })
  36761. .execute();
  36762. this._lineData = lineData;
  36763. };
  36764. lineDrawProto.updateLayout = function () {
  36765. var lineData = this._lineData;
  36766. lineData.eachItemGraphicEl(function (el, idx) {
  36767. el.updateLayout(lineData, idx);
  36768. }, this);
  36769. };
  36770. lineDrawProto.remove = function () {
  36771. this.group.removeAll();
  36772. };
  36773. var v1 = [];
  36774. var v2 = [];
  36775. var v3 = [];
  36776. var quadraticAt$1 = quadraticAt;
  36777. var v2DistSquare = distSquare;
  36778. var mathAbs$1 = Math.abs;
  36779. function intersectCurveCircle(curvePoints, center, radius) {
  36780. var p0 = curvePoints[0];
  36781. var p1 = curvePoints[1];
  36782. var p2 = curvePoints[2];
  36783. var d = Infinity;
  36784. var t;
  36785. var radiusSquare = radius * radius;
  36786. var interval = 0.1;
  36787. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  36788. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  36789. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  36790. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  36791. if (diff < d) {
  36792. d = diff;
  36793. t = _t;
  36794. }
  36795. }
  36796. // Assume the segment is monotone,Find root through Bisection method
  36797. // At most 32 iteration
  36798. for (var i = 0; i < 32; i++) {
  36799. // var prev = t - interval;
  36800. var next = t + interval;
  36801. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  36802. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  36803. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  36804. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  36805. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  36806. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  36807. var diff = v2DistSquare(v2, center) - radiusSquare;
  36808. if (mathAbs$1(diff) < 1e-2) {
  36809. break;
  36810. }
  36811. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  36812. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  36813. interval /= 2;
  36814. if (diff < 0) {
  36815. if (nextDiff >= 0) {
  36816. t = t + interval;
  36817. }
  36818. else {
  36819. t = t - interval;
  36820. }
  36821. }
  36822. else {
  36823. if (nextDiff >= 0) {
  36824. t = t - interval;
  36825. }
  36826. else {
  36827. t = t + interval;
  36828. }
  36829. }
  36830. }
  36831. return t;
  36832. }
  36833. // Adjust edge to avoid
  36834. var adjustEdge = function (graph, scale$$1) {
  36835. var tmp0 = [];
  36836. var quadraticSubdivide$$1 = quadraticSubdivide;
  36837. var pts = [[], [], []];
  36838. var pts2 = [[], []];
  36839. var v = [];
  36840. scale$$1 /= 2;
  36841. function getSymbolSize(node) {
  36842. var symbolSize = node.getVisual('symbolSize');
  36843. if (symbolSize instanceof Array) {
  36844. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  36845. }
  36846. return symbolSize;
  36847. }
  36848. graph.eachEdge(function (edge, idx) {
  36849. var linePoints = edge.getLayout();
  36850. var fromSymbol = edge.getVisual('fromSymbol');
  36851. var toSymbol = edge.getVisual('toSymbol');
  36852. if (!linePoints.__original) {
  36853. linePoints.__original = [
  36854. clone$1(linePoints[0]),
  36855. clone$1(linePoints[1])
  36856. ];
  36857. if (linePoints[2]) {
  36858. linePoints.__original.push(clone$1(linePoints[2]));
  36859. }
  36860. }
  36861. var originalPoints = linePoints.__original;
  36862. // Quadratic curve
  36863. if (linePoints[2] != null) {
  36864. copy(pts[0], originalPoints[0]);
  36865. copy(pts[1], originalPoints[2]);
  36866. copy(pts[2], originalPoints[1]);
  36867. if (fromSymbol && fromSymbol != 'none') {
  36868. var symbolSize = getSymbolSize(edge.node1);
  36869. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  36870. // Subdivide and get the second
  36871. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  36872. pts[0][0] = tmp0[3];
  36873. pts[1][0] = tmp0[4];
  36874. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  36875. pts[0][1] = tmp0[3];
  36876. pts[1][1] = tmp0[4];
  36877. }
  36878. if (toSymbol && toSymbol != 'none') {
  36879. var symbolSize = getSymbolSize(edge.node2);
  36880. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  36881. // Subdivide and get the first
  36882. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  36883. pts[1][0] = tmp0[1];
  36884. pts[2][0] = tmp0[2];
  36885. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  36886. pts[1][1] = tmp0[1];
  36887. pts[2][1] = tmp0[2];
  36888. }
  36889. // Copy back to layout
  36890. copy(linePoints[0], pts[0]);
  36891. copy(linePoints[1], pts[2]);
  36892. copy(linePoints[2], pts[1]);
  36893. }
  36894. // Line
  36895. else {
  36896. copy(pts2[0], originalPoints[0]);
  36897. copy(pts2[1], originalPoints[1]);
  36898. sub(v, pts2[1], pts2[0]);
  36899. normalize(v, v);
  36900. if (fromSymbol && fromSymbol != 'none') {
  36901. var symbolSize = getSymbolSize(edge.node1);
  36902. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  36903. }
  36904. if (toSymbol && toSymbol != 'none') {
  36905. var symbolSize = getSymbolSize(edge.node2);
  36906. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  36907. }
  36908. copy(linePoints[0], pts2[0]);
  36909. copy(linePoints[1], pts2[1]);
  36910. }
  36911. });
  36912. };
  36913. var nodeOpacityPath = ['itemStyle', 'normal', 'opacity'];
  36914. var lineOpacityPath = ['lineStyle', 'normal', 'opacity'];
  36915. function getItemOpacity(item, opacityPath) {
  36916. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  36917. }
  36918. function fadeOutItem(item, opacityPath, opacityRatio) {
  36919. var el = item.getGraphicEl();
  36920. var opacity = getItemOpacity(item, opacityPath);
  36921. if (opacityRatio != null) {
  36922. opacity == null && (opacity = 1);
  36923. opacity *= opacityRatio;
  36924. }
  36925. el.downplay && el.downplay();
  36926. el.traverse(function (child) {
  36927. if (child.type !== 'group') {
  36928. child.setStyle('opacity', opacity);
  36929. }
  36930. });
  36931. }
  36932. function fadeInItem(item, opacityPath) {
  36933. var opacity = getItemOpacity(item, opacityPath);
  36934. var el = item.getGraphicEl();
  36935. el.highlight && el.highlight();
  36936. el.traverse(function (child) {
  36937. if (child.type !== 'group') {
  36938. child.setStyle('opacity', opacity);
  36939. }
  36940. });
  36941. }
  36942. extendChartView({
  36943. type: 'graph',
  36944. init: function (ecModel, api) {
  36945. var symbolDraw = new SymbolDraw();
  36946. var lineDraw = new LineDraw();
  36947. var group = this.group;
  36948. this._controller = new RoamController(api.getZr());
  36949. this._controllerHost = {target: group};
  36950. group.add(symbolDraw.group);
  36951. group.add(lineDraw.group);
  36952. this._symbolDraw = symbolDraw;
  36953. this._lineDraw = lineDraw;
  36954. this._firstRender = true;
  36955. },
  36956. render: function (seriesModel, ecModel, api) {
  36957. var coordSys = seriesModel.coordinateSystem;
  36958. this._model = seriesModel;
  36959. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  36960. var symbolDraw = this._symbolDraw;
  36961. var lineDraw = this._lineDraw;
  36962. var group = this.group;
  36963. if (coordSys.type === 'view') {
  36964. var groupNewProp = {
  36965. position: coordSys.position,
  36966. scale: coordSys.scale
  36967. };
  36968. if (this._firstRender) {
  36969. group.attr(groupNewProp);
  36970. }
  36971. else {
  36972. updateProps(group, groupNewProp, seriesModel);
  36973. }
  36974. }
  36975. // Fix edge contact point with node
  36976. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  36977. var data = seriesModel.getData();
  36978. symbolDraw.updateData(data);
  36979. var edgeData = seriesModel.getEdgeData();
  36980. lineDraw.updateData(edgeData);
  36981. this._updateNodeAndLinkScale();
  36982. this._updateController(seriesModel, ecModel, api);
  36983. clearTimeout(this._layoutTimeout);
  36984. var forceLayout = seriesModel.forceLayout;
  36985. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  36986. if (forceLayout) {
  36987. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  36988. }
  36989. data.eachItemGraphicEl(function (el, idx) {
  36990. var itemModel = data.getItemModel(idx);
  36991. // Update draggable
  36992. el.off('drag').off('dragend');
  36993. var draggable = data.getItemModel(idx).get('draggable');
  36994. if (draggable) {
  36995. el.on('drag', function () {
  36996. if (forceLayout) {
  36997. forceLayout.warmUp();
  36998. !this._layouting
  36999. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  37000. forceLayout.setFixed(idx);
  37001. // Write position back to layout
  37002. data.setItemLayout(idx, el.position);
  37003. }
  37004. }, this).on('dragend', function () {
  37005. if (forceLayout) {
  37006. forceLayout.setUnfixed(idx);
  37007. }
  37008. }, this);
  37009. }
  37010. el.setDraggable(draggable && forceLayout);
  37011. el.off('mouseover', el.__focusNodeAdjacency);
  37012. el.off('mouseout', el.__unfocusNodeAdjacency);
  37013. if (itemModel.get('focusNodeAdjacency')) {
  37014. el.on('mouseover', el.__focusNodeAdjacency = function () {
  37015. api.dispatchAction({
  37016. type: 'focusNodeAdjacency',
  37017. seriesId: seriesModel.id,
  37018. dataIndex: el.dataIndex
  37019. });
  37020. });
  37021. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  37022. api.dispatchAction({
  37023. type: 'unfocusNodeAdjacency',
  37024. seriesId: seriesModel.id
  37025. });
  37026. });
  37027. }
  37028. }, this);
  37029. data.graph.eachEdge(function (edge) {
  37030. var el = edge.getGraphicEl();
  37031. el.off('mouseover', el.__focusNodeAdjacency);
  37032. el.off('mouseout', el.__unfocusNodeAdjacency);
  37033. if (edge.getModel().get('focusNodeAdjacency')) {
  37034. el.on('mouseover', el.__focusNodeAdjacency = function () {
  37035. api.dispatchAction({
  37036. type: 'focusNodeAdjacency',
  37037. seriesId: seriesModel.id,
  37038. edgeDataIndex: edge.dataIndex
  37039. });
  37040. });
  37041. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  37042. api.dispatchAction({
  37043. type: 'unfocusNodeAdjacency',
  37044. seriesId: seriesModel.id
  37045. });
  37046. });
  37047. }
  37048. });
  37049. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  37050. && seriesModel.get('circular.rotateLabel');
  37051. var cx = data.getLayout('cx');
  37052. var cy = data.getLayout('cy');
  37053. data.eachItemGraphicEl(function (el, idx) {
  37054. var symbolPath = el.getSymbolPath();
  37055. if (circularRotateLabel) {
  37056. var pos = data.getItemLayout(idx);
  37057. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  37058. if (rad < 0) {
  37059. rad = Math.PI * 2 + rad;
  37060. }
  37061. var isLeft = pos[0] < cx;
  37062. if (isLeft) {
  37063. rad = rad - Math.PI;
  37064. }
  37065. var textPosition = isLeft ? 'left' : 'right';
  37066. symbolPath.setStyle({
  37067. textRotation: -rad,
  37068. textPosition: textPosition,
  37069. textOrigin: 'center'
  37070. });
  37071. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  37072. }
  37073. else {
  37074. symbolPath.setStyle({
  37075. textRotation: 0
  37076. });
  37077. }
  37078. });
  37079. this._firstRender = false;
  37080. },
  37081. dispose: function () {
  37082. this._controller && this._controller.dispose();
  37083. this._controllerHost = {};
  37084. },
  37085. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  37086. var data = this._model.getData();
  37087. var graph = data.graph;
  37088. var dataIndex = payload.dataIndex;
  37089. var edgeDataIndex = payload.edgeDataIndex;
  37090. var node = graph.getNodeByIndex(dataIndex);
  37091. var edge = graph.getEdgeByIndex(edgeDataIndex);
  37092. if (!node && !edge) {
  37093. return;
  37094. }
  37095. graph.eachNode(function (node) {
  37096. fadeOutItem(node, nodeOpacityPath, 0.1);
  37097. });
  37098. graph.eachEdge(function (edge) {
  37099. fadeOutItem(edge, lineOpacityPath, 0.1);
  37100. });
  37101. if (node) {
  37102. fadeInItem(node, nodeOpacityPath);
  37103. each$1(node.edges, function (adjacentEdge) {
  37104. if (adjacentEdge.dataIndex < 0) {
  37105. return;
  37106. }
  37107. fadeInItem(adjacentEdge, lineOpacityPath);
  37108. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  37109. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  37110. });
  37111. }
  37112. if (edge) {
  37113. fadeInItem(edge, lineOpacityPath);
  37114. fadeInItem(edge.node1, nodeOpacityPath);
  37115. fadeInItem(edge.node2, nodeOpacityPath);
  37116. }
  37117. },
  37118. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  37119. var graph = this._model.getData().graph;
  37120. graph.eachNode(function (node) {
  37121. fadeOutItem(node, nodeOpacityPath);
  37122. });
  37123. graph.eachEdge(function (edge) {
  37124. fadeOutItem(edge, lineOpacityPath);
  37125. });
  37126. },
  37127. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  37128. var self = this;
  37129. (function step() {
  37130. forceLayout.step(function (stopped) {
  37131. self.updateLayout(self._model);
  37132. (self._layouting = !stopped) && (
  37133. layoutAnimation
  37134. ? (self._layoutTimeout = setTimeout(step, 16))
  37135. : step()
  37136. );
  37137. });
  37138. })();
  37139. },
  37140. _updateController: function (seriesModel, ecModel, api) {
  37141. var controller = this._controller;
  37142. var controllerHost = this._controllerHost;
  37143. var group = this.group;
  37144. controller.setPointerChecker(function (e, x, y) {
  37145. var rect = group.getBoundingRect();
  37146. rect.applyTransform(group.transform);
  37147. return rect.contain(x, y)
  37148. && !onIrrelevantElement(e, api, seriesModel);
  37149. });
  37150. if (seriesModel.coordinateSystem.type !== 'view') {
  37151. controller.disable();
  37152. return;
  37153. }
  37154. controller.enable(seriesModel.get('roam'));
  37155. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  37156. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  37157. controller
  37158. .off('pan')
  37159. .off('zoom')
  37160. .on('pan', function (dx, dy) {
  37161. updateViewOnPan(controllerHost, dx, dy);
  37162. api.dispatchAction({
  37163. seriesId: seriesModel.id,
  37164. type: 'graphRoam',
  37165. dx: dx,
  37166. dy: dy
  37167. });
  37168. })
  37169. .on('zoom', function (zoom, mouseX, mouseY) {
  37170. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  37171. api.dispatchAction({
  37172. seriesId: seriesModel.id,
  37173. type: 'graphRoam',
  37174. zoom: zoom,
  37175. originX: mouseX,
  37176. originY: mouseY
  37177. });
  37178. this._updateNodeAndLinkScale();
  37179. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  37180. this._lineDraw.updateLayout();
  37181. }, this);
  37182. },
  37183. _updateNodeAndLinkScale: function () {
  37184. var seriesModel = this._model;
  37185. var data = seriesModel.getData();
  37186. var nodeScale = this._getNodeGlobalScale(seriesModel);
  37187. var invScale = [nodeScale, nodeScale];
  37188. data.eachItemGraphicEl(function (el, idx) {
  37189. el.attr('scale', invScale);
  37190. });
  37191. },
  37192. _getNodeGlobalScale: function (seriesModel) {
  37193. var coordSys = seriesModel.coordinateSystem;
  37194. if (coordSys.type !== 'view') {
  37195. return 1;
  37196. }
  37197. var nodeScaleRatio = this._nodeScaleRatio;
  37198. var groupScale = coordSys.scale;
  37199. var groupZoom = (groupScale && groupScale[0]) || 1;
  37200. // Scale node when zoom changes
  37201. var roamZoom = coordSys.getZoom();
  37202. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  37203. return nodeScale / groupZoom;
  37204. },
  37205. updateLayout: function (seriesModel) {
  37206. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  37207. this._symbolDraw.updateLayout();
  37208. this._lineDraw.updateLayout();
  37209. },
  37210. remove: function (ecModel, api) {
  37211. this._symbolDraw && this._symbolDraw.remove();
  37212. this._lineDraw && this._lineDraw.remove();
  37213. }
  37214. });
  37215. var actionInfo = {
  37216. type: 'graphRoam',
  37217. event: 'graphRoam',
  37218. update: 'none'
  37219. };
  37220. /**
  37221. * @payload
  37222. * @property {string} name Series name
  37223. * @property {number} [dx]
  37224. * @property {number} [dy]
  37225. * @property {number} [zoom]
  37226. * @property {number} [originX]
  37227. * @property {number} [originY]
  37228. */
  37229. registerAction(actionInfo, function (payload, ecModel) {
  37230. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  37231. var coordSys = seriesModel.coordinateSystem;
  37232. var res = updateCenterAndZoom(coordSys, payload);
  37233. seriesModel.setCenter
  37234. && seriesModel.setCenter(res.center);
  37235. seriesModel.setZoom
  37236. && seriesModel.setZoom(res.zoom);
  37237. });
  37238. });
  37239. /**
  37240. * @payload
  37241. * @property {number} [seriesIndex]
  37242. * @property {string} [seriesId]
  37243. * @property {string} [seriesName]
  37244. * @property {number} [dataIndex]
  37245. */
  37246. registerAction({
  37247. type: 'focusNodeAdjacency',
  37248. event: 'focusNodeAdjacency',
  37249. update: 'series.graph:focusNodeAdjacency'
  37250. }, function () {});
  37251. /**
  37252. * @payload
  37253. * @property {number} [seriesIndex]
  37254. * @property {string} [seriesId]
  37255. * @property {string} [seriesName]
  37256. */
  37257. registerAction({
  37258. type: 'unfocusNodeAdjacency',
  37259. event: 'unfocusNodeAdjacency',
  37260. update: 'series.graph:unfocusNodeAdjacency'
  37261. }, function () {});
  37262. var categoryFilter = function (ecModel) {
  37263. var legendModels = ecModel.findComponents({
  37264. mainType: 'legend'
  37265. });
  37266. if (!legendModels || !legendModels.length) {
  37267. return;
  37268. }
  37269. ecModel.eachSeriesByType('graph', function (graphSeries) {
  37270. var categoriesData = graphSeries.getCategoriesData();
  37271. var graph = graphSeries.getGraph();
  37272. var data = graph.data;
  37273. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  37274. data.filterSelf(function (idx) {
  37275. var model = data.getItemModel(idx);
  37276. var category = model.getShallow('category');
  37277. if (category != null) {
  37278. if (typeof category === 'number') {
  37279. category = categoryNames[category];
  37280. }
  37281. // If in any legend component the status is not selected.
  37282. for (var i = 0; i < legendModels.length; i++) {
  37283. if (!legendModels[i].isSelected(category)) {
  37284. return false;
  37285. }
  37286. }
  37287. }
  37288. return true;
  37289. });
  37290. }, this);
  37291. };
  37292. var categoryVisual = function (ecModel) {
  37293. var paletteScope = {};
  37294. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37295. var categoriesData = seriesModel.getCategoriesData();
  37296. var data = seriesModel.getData();
  37297. var categoryNameIdxMap = {};
  37298. categoriesData.each(function (idx) {
  37299. var name = categoriesData.getName(idx);
  37300. // Add prefix to avoid conflict with Object.prototype.
  37301. categoryNameIdxMap['ec-' + name] = idx;
  37302. var itemModel = categoriesData.getItemModel(idx);
  37303. var color = itemModel.get('itemStyle.normal.color')
  37304. || seriesModel.getColorFromPalette(name, paletteScope);
  37305. categoriesData.setItemVisual(idx, 'color', color);
  37306. });
  37307. // Assign category color to visual
  37308. if (categoriesData.count()) {
  37309. data.each(function (idx) {
  37310. var model = data.getItemModel(idx);
  37311. var category = model.getShallow('category');
  37312. if (category != null) {
  37313. if (typeof category === 'string') {
  37314. category = categoryNameIdxMap['ec-' + category];
  37315. }
  37316. if (!data.getItemVisual(idx, 'color', true)) {
  37317. data.setItemVisual(
  37318. idx, 'color',
  37319. categoriesData.getItemVisual(category, 'color')
  37320. );
  37321. }
  37322. }
  37323. });
  37324. }
  37325. });
  37326. };
  37327. function normalize$1(a) {
  37328. if (!(a instanceof Array)) {
  37329. a = [a, a];
  37330. }
  37331. return a;
  37332. }
  37333. var edgeVisual = function (ecModel) {
  37334. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37335. var graph = seriesModel.getGraph();
  37336. var edgeData = seriesModel.getEdgeData();
  37337. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  37338. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  37339. var colorQuery = 'lineStyle.normal.color'.split('.');
  37340. var opacityQuery = 'lineStyle.normal.opacity'.split('.');
  37341. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  37342. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  37343. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  37344. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  37345. edgeData.setVisual('color', seriesModel.get(colorQuery));
  37346. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  37347. edgeData.each(function (idx) {
  37348. var itemModel = edgeData.getItemModel(idx);
  37349. var edge = graph.getEdgeByIndex(idx);
  37350. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  37351. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  37352. // Edge visual must after node visual
  37353. var color = itemModel.get(colorQuery);
  37354. var opacity = itemModel.get(opacityQuery);
  37355. switch (color) {
  37356. case 'source':
  37357. color = edge.node1.getVisual('color');
  37358. break;
  37359. case 'target':
  37360. color = edge.node2.getVisual('color');
  37361. break;
  37362. }
  37363. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  37364. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  37365. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  37366. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  37367. edge.setVisual('color', color);
  37368. edge.setVisual('opacity', opacity);
  37369. });
  37370. });
  37371. };
  37372. function simpleLayout$1(seriesModel) {
  37373. var coordSys = seriesModel.coordinateSystem;
  37374. if (coordSys && coordSys.type !== 'view') {
  37375. return;
  37376. }
  37377. var graph = seriesModel.getGraph();
  37378. graph.eachNode(function (node) {
  37379. var model = node.getModel();
  37380. node.setLayout([+model.get('x'), +model.get('y')]);
  37381. });
  37382. simpleLayoutEdge(graph);
  37383. }
  37384. function simpleLayoutEdge(graph) {
  37385. graph.eachEdge(function (edge) {
  37386. var curveness = edge.getModel().get('lineStyle.normal.curveness') || 0;
  37387. var p1 = clone$1(edge.node1.getLayout());
  37388. var p2 = clone$1(edge.node2.getLayout());
  37389. var points = [p1, p2];
  37390. if (+curveness) {
  37391. points.push([
  37392. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  37393. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  37394. ]);
  37395. }
  37396. edge.setLayout(points);
  37397. });
  37398. }
  37399. var simpleLayout = function (ecModel, api) {
  37400. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37401. var layout = seriesModel.get('layout');
  37402. var coordSys = seriesModel.coordinateSystem;
  37403. if (coordSys && coordSys.type !== 'view') {
  37404. var data = seriesModel.getData();
  37405. var dimensions = coordSys.dimensions;
  37406. data.each(dimensions, function () {
  37407. var hasValue;
  37408. var args = arguments;
  37409. var value = [];
  37410. for (var i = 0; i < dimensions.length; i++) {
  37411. if (!isNaN(args[i])) {
  37412. hasValue = true;
  37413. }
  37414. value.push(args[i]);
  37415. }
  37416. var idx = args[args.length - 1];
  37417. if (hasValue) {
  37418. data.setItemLayout(idx, coordSys.dataToPoint(value));
  37419. }
  37420. else {
  37421. // Also {Array.<number>}, not undefined to avoid if...else... statement
  37422. data.setItemLayout(idx, [NaN, NaN]);
  37423. }
  37424. });
  37425. simpleLayoutEdge(data.graph);
  37426. }
  37427. else if (!layout || layout === 'none') {
  37428. simpleLayout$1(seriesModel);
  37429. }
  37430. });
  37431. };
  37432. function circularLayout$1(seriesModel) {
  37433. var coordSys = seriesModel.coordinateSystem;
  37434. if (coordSys && coordSys.type !== 'view') {
  37435. return;
  37436. }
  37437. var rect = coordSys.getBoundingRect();
  37438. var nodeData = seriesModel.getData();
  37439. var graph = nodeData.graph;
  37440. var angle = 0;
  37441. var sum = nodeData.getSum('value');
  37442. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  37443. var cx = rect.width / 2 + rect.x;
  37444. var cy = rect.height / 2 + rect.y;
  37445. var r = Math.min(rect.width, rect.height) / 2;
  37446. graph.eachNode(function (node) {
  37447. var value = node.getValue('value');
  37448. angle += unitAngle * (sum ? value : 1) / 2;
  37449. node.setLayout([
  37450. r * Math.cos(angle) + cx,
  37451. r * Math.sin(angle) + cy
  37452. ]);
  37453. angle += unitAngle * (sum ? value : 1) / 2;
  37454. });
  37455. nodeData.setLayout({
  37456. cx: cx,
  37457. cy: cy
  37458. });
  37459. graph.eachEdge(function (edge) {
  37460. var curveness = edge.getModel().get('lineStyle.normal.curveness') || 0;
  37461. var p1 = clone$1(edge.node1.getLayout());
  37462. var p2 = clone$1(edge.node2.getLayout());
  37463. var cp1;
  37464. var x12 = (p1[0] + p2[0]) / 2;
  37465. var y12 = (p1[1] + p2[1]) / 2;
  37466. if (+curveness) {
  37467. curveness *= 3;
  37468. cp1 = [
  37469. cx * curveness + x12 * (1 - curveness),
  37470. cy * curveness + y12 * (1 - curveness)
  37471. ];
  37472. }
  37473. edge.setLayout([p1, p2, cp1]);
  37474. });
  37475. }
  37476. var circularLayout = function (ecModel) {
  37477. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37478. if (seriesModel.get('layout') === 'circular') {
  37479. circularLayout$1(seriesModel);
  37480. }
  37481. });
  37482. };
  37483. var scaleAndAdd$2 = scaleAndAdd;
  37484. // function adjacentNode(n, e) {
  37485. // return e.n1 === n ? e.n2 : e.n1;
  37486. // }
  37487. function forceLayout$1(nodes, edges, opts) {
  37488. var rect = opts.rect;
  37489. var width = rect.width;
  37490. var height = rect.height;
  37491. var center = [rect.x + width / 2, rect.y + height / 2];
  37492. // var scale = opts.scale || 1;
  37493. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  37494. // for (var i = 0; i < edges.length; i++) {
  37495. // var e = edges[i];
  37496. // var n1 = e.n1;
  37497. // var n2 = e.n2;
  37498. // n1.edges = n1.edges || [];
  37499. // n2.edges = n2.edges || [];
  37500. // n1.edges.push(e);
  37501. // n2.edges.push(e);
  37502. // }
  37503. // Init position
  37504. for (var i = 0; i < nodes.length; i++) {
  37505. var n = nodes[i];
  37506. if (!n.p) {
  37507. // Use the position from first adjecent node with defined position
  37508. // Or use a random position
  37509. // From d3
  37510. // if (n.edges) {
  37511. // var j = -1;
  37512. // while (++j < n.edges.length) {
  37513. // var e = n.edges[j];
  37514. // var other = adjacentNode(n, e);
  37515. // if (other.p) {
  37516. // n.p = vec2.clone(other.p);
  37517. // break;
  37518. // }
  37519. // }
  37520. // }
  37521. // if (!n.p) {
  37522. n.p = create(
  37523. width * (Math.random() - 0.5) + center[0],
  37524. height * (Math.random() - 0.5) + center[1]
  37525. );
  37526. // }
  37527. }
  37528. n.pp = clone$1(n.p);
  37529. n.edges = null;
  37530. }
  37531. // Formula in 'Graph Drawing by Force-directed Placement'
  37532. // var k = scale * Math.sqrt(width * height / nodes.length);
  37533. // var k2 = k * k;
  37534. var friction = 0.6;
  37535. return {
  37536. warmUp: function () {
  37537. friction = 0.5;
  37538. },
  37539. setFixed: function (idx) {
  37540. nodes[idx].fixed = true;
  37541. },
  37542. setUnfixed: function (idx) {
  37543. nodes[idx].fixed = false;
  37544. },
  37545. step: function (cb) {
  37546. var v12 = [];
  37547. var nLen = nodes.length;
  37548. for (var i = 0; i < edges.length; i++) {
  37549. var e = edges[i];
  37550. var n1 = e.n1;
  37551. var n2 = e.n2;
  37552. sub(v12, n2.p, n1.p);
  37553. var d = len(v12) - e.d;
  37554. var w = n2.w / (n1.w + n2.w);
  37555. if (isNaN(w)) {
  37556. w = 0;
  37557. }
  37558. normalize(v12, v12);
  37559. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  37560. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  37561. }
  37562. // Gravity
  37563. for (var i = 0; i < nLen; i++) {
  37564. var n = nodes[i];
  37565. if (!n.fixed) {
  37566. sub(v12, center, n.p);
  37567. // var d = vec2.len(v12);
  37568. // vec2.scale(v12, v12, 1 / d);
  37569. // var gravityFactor = gravity;
  37570. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  37571. }
  37572. }
  37573. // Repulsive
  37574. // PENDING
  37575. for (var i = 0; i < nLen; i++) {
  37576. var n1 = nodes[i];
  37577. for (var j = i + 1; j < nLen; j++) {
  37578. var n2 = nodes[j];
  37579. sub(v12, n2.p, n1.p);
  37580. var d = len(v12);
  37581. if (d === 0) {
  37582. // Random repulse
  37583. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  37584. d = 1;
  37585. }
  37586. var repFact = (n1.rep + n2.rep) / d / d;
  37587. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  37588. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  37589. }
  37590. }
  37591. var v = [];
  37592. for (var i = 0; i < nLen; i++) {
  37593. var n = nodes[i];
  37594. if (!n.fixed) {
  37595. sub(v, n.p, n.pp);
  37596. scaleAndAdd$2(n.p, n.p, v, friction);
  37597. copy(n.pp, n.p);
  37598. }
  37599. }
  37600. friction = friction * 0.992;
  37601. cb && cb(nodes, edges, friction < 0.01);
  37602. }
  37603. };
  37604. }
  37605. var forceLayout = function (ecModel) {
  37606. ecModel.eachSeriesByType('graph', function (graphSeries) {
  37607. var coordSys = graphSeries.coordinateSystem;
  37608. if (coordSys && coordSys.type !== 'view') {
  37609. return;
  37610. }
  37611. if (graphSeries.get('layout') === 'force') {
  37612. var preservedPoints = graphSeries.preservedPoints || {};
  37613. var graph = graphSeries.getGraph();
  37614. var nodeData = graph.data;
  37615. var edgeData = graph.edgeData;
  37616. var forceModel = graphSeries.getModel('force');
  37617. var initLayout = forceModel.get('initLayout');
  37618. if (graphSeries.preservedPoints) {
  37619. nodeData.each(function (idx) {
  37620. var id = nodeData.getId(idx);
  37621. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  37622. });
  37623. }
  37624. else if (!initLayout || initLayout === 'none') {
  37625. simpleLayout$1(graphSeries);
  37626. }
  37627. else if (initLayout === 'circular') {
  37628. circularLayout$1(graphSeries);
  37629. }
  37630. var nodeDataExtent = nodeData.getDataExtent('value');
  37631. var edgeDataExtent = edgeData.getDataExtent('value');
  37632. // var edgeDataExtent = edgeData.getDataExtent('value');
  37633. var repulsion = forceModel.get('repulsion');
  37634. var edgeLength = forceModel.get('edgeLength');
  37635. if (!isArray(repulsion)) {
  37636. repulsion = [repulsion, repulsion];
  37637. }
  37638. if (!isArray(edgeLength)) {
  37639. edgeLength = [edgeLength, edgeLength];
  37640. }
  37641. // Larger value has smaller length
  37642. edgeLength = [edgeLength[1], edgeLength[0]];
  37643. var nodes = nodeData.mapArray('value', function (value, idx) {
  37644. var point = nodeData.getItemLayout(idx);
  37645. var rep = linearMap(value, nodeDataExtent, repulsion);
  37646. if (isNaN(rep)) {
  37647. rep = (repulsion[0] + repulsion[1]) / 2;
  37648. }
  37649. return {
  37650. w: rep,
  37651. rep: rep,
  37652. fixed: nodeData.getItemModel(idx).get('fixed'),
  37653. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  37654. };
  37655. });
  37656. var edges = edgeData.mapArray('value', function (value, idx) {
  37657. var edge = graph.getEdgeByIndex(idx);
  37658. var d = linearMap(value, edgeDataExtent, edgeLength);
  37659. if (isNaN(d)) {
  37660. d = (edgeLength[0] + edgeLength[1]) / 2;
  37661. }
  37662. return {
  37663. n1: nodes[edge.node1.dataIndex],
  37664. n2: nodes[edge.node2.dataIndex],
  37665. d: d,
  37666. curveness: edge.getModel().get('lineStyle.normal.curveness') || 0
  37667. };
  37668. });
  37669. var coordSys = graphSeries.coordinateSystem;
  37670. var rect = coordSys.getBoundingRect();
  37671. var forceInstance = forceLayout$1(nodes, edges, {
  37672. rect: rect,
  37673. gravity: forceModel.get('gravity')
  37674. });
  37675. var oldStep = forceInstance.step;
  37676. forceInstance.step = function (cb) {
  37677. for (var i = 0, l = nodes.length; i < l; i++) {
  37678. if (nodes[i].fixed) {
  37679. // Write back to layout instance
  37680. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  37681. }
  37682. }
  37683. oldStep(function (nodes, edges, stopped) {
  37684. for (var i = 0, l = nodes.length; i < l; i++) {
  37685. if (!nodes[i].fixed) {
  37686. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  37687. }
  37688. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  37689. }
  37690. for (var i = 0, l = edges.length; i < l; i++) {
  37691. var e = edges[i];
  37692. var edge = graph.getEdgeByIndex(i);
  37693. var p1 = e.n1.p;
  37694. var p2 = e.n2.p;
  37695. var points = edge.getLayout();
  37696. points = points ? points.slice() : [];
  37697. points[0] = points[0] || [];
  37698. points[1] = points[1] || [];
  37699. copy(points[0], p1);
  37700. copy(points[1], p2);
  37701. if (+e.curveness) {
  37702. points[2] = [
  37703. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  37704. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  37705. ];
  37706. }
  37707. edge.setLayout(points);
  37708. }
  37709. // Update layout
  37710. cb && cb(stopped);
  37711. });
  37712. };
  37713. graphSeries.forceLayout = forceInstance;
  37714. graphSeries.preservedPoints = preservedPoints;
  37715. // Step to get the layout
  37716. forceInstance.step();
  37717. }
  37718. else {
  37719. // Remove prev injected forceLayout instance
  37720. graphSeries.forceLayout = null;
  37721. }
  37722. });
  37723. };
  37724. // FIXME Where to create the simple view coordinate system
  37725. function getViewRect$1(seriesModel, api, aspect) {
  37726. var option = seriesModel.getBoxLayoutParams();
  37727. option.aspect = aspect;
  37728. return getLayoutRect(option, {
  37729. width: api.getWidth(),
  37730. height: api.getHeight()
  37731. });
  37732. }
  37733. var createView = function (ecModel, api) {
  37734. var viewList = [];
  37735. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37736. var coordSysType = seriesModel.get('coordinateSystem');
  37737. if (!coordSysType || coordSysType === 'view') {
  37738. var data = seriesModel.getData();
  37739. var positions = data.mapArray(function (idx) {
  37740. var itemModel = data.getItemModel(idx);
  37741. return [+itemModel.get('x'), +itemModel.get('y')];
  37742. });
  37743. var min = [];
  37744. var max = [];
  37745. fromPoints(positions, min, max);
  37746. // If width or height is 0
  37747. if (max[0] - min[0] === 0) {
  37748. max[0] += 1;
  37749. min[0] -= 1;
  37750. }
  37751. if (max[1] - min[1] === 0) {
  37752. max[1] += 1;
  37753. min[1] -= 1;
  37754. }
  37755. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  37756. // FIXME If get view rect after data processed?
  37757. var viewRect = getViewRect$1(seriesModel, api, aspect);
  37758. // Position may be NaN, use view rect instead
  37759. if (isNaN(aspect)) {
  37760. min = [viewRect.x, viewRect.y];
  37761. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  37762. }
  37763. var bbWidth = max[0] - min[0];
  37764. var bbHeight = max[1] - min[1];
  37765. var viewWidth = viewRect.width;
  37766. var viewHeight = viewRect.height;
  37767. var viewCoordSys = seriesModel.coordinateSystem = new View();
  37768. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  37769. viewCoordSys.setBoundingRect(
  37770. min[0], min[1], bbWidth, bbHeight
  37771. );
  37772. viewCoordSys.setViewRect(
  37773. viewRect.x, viewRect.y, viewWidth, viewHeight
  37774. );
  37775. // Update roam info
  37776. viewCoordSys.setCenter(seriesModel.get('center'));
  37777. viewCoordSys.setZoom(seriesModel.get('zoom'));
  37778. viewList.push(viewCoordSys);
  37779. }
  37780. });
  37781. return viewList;
  37782. };
  37783. registerProcessor(categoryFilter);
  37784. registerVisual(curry(
  37785. visualSymbol, 'graph', 'circle', null
  37786. ));
  37787. registerVisual(categoryVisual);
  37788. registerVisual(edgeVisual);
  37789. registerLayout(simpleLayout);
  37790. registerLayout(circularLayout);
  37791. registerLayout(forceLayout);
  37792. // Graph view coordinate system
  37793. registerCoordinateSystem('graphView', {
  37794. create: createView
  37795. });
  37796. var GaugeSeries = SeriesModel.extend({
  37797. type: 'series.gauge',
  37798. getInitialData: function (option, ecModel) {
  37799. var list = new List(['value'], this);
  37800. var dataOpt = option.data || [];
  37801. if (!isArray(dataOpt)) {
  37802. dataOpt = [dataOpt];
  37803. }
  37804. // Only use the first data item
  37805. list.initData(dataOpt);
  37806. return list;
  37807. },
  37808. defaultOption: {
  37809. zlevel: 0,
  37810. z: 2,
  37811. // 默认全局居中
  37812. center: ['50%', '50%'],
  37813. legendHoverLink: true,
  37814. radius: '75%',
  37815. startAngle: 225,
  37816. endAngle: -45,
  37817. clockwise: true,
  37818. // 最小值
  37819. min: 0,
  37820. // 最大值
  37821. max: 100,
  37822. // 分割段数,默认为10
  37823. splitNumber: 10,
  37824. // 坐标轴线
  37825. axisLine: {
  37826. // 默认显示,属性show控制显示与否
  37827. show: true,
  37828. lineStyle: { // 属性lineStyle控制线条样式
  37829. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  37830. width: 30
  37831. }
  37832. },
  37833. // 分隔线
  37834. splitLine: {
  37835. // 默认显示,属性show控制显示与否
  37836. show: true,
  37837. // 属性length控制线长
  37838. length: 30,
  37839. // 属性lineStyle(详见lineStyle)控制线条样式
  37840. lineStyle: {
  37841. color: '#eee',
  37842. width: 2,
  37843. type: 'solid'
  37844. }
  37845. },
  37846. // 坐标轴小标记
  37847. axisTick: {
  37848. // 属性show控制显示与否,默认不显示
  37849. show: true,
  37850. // 每份split细分多少段
  37851. splitNumber: 5,
  37852. // 属性length控制线长
  37853. length: 8,
  37854. // 属性lineStyle控制线条样式
  37855. lineStyle: {
  37856. color: '#eee',
  37857. width: 1,
  37858. type: 'solid'
  37859. }
  37860. },
  37861. axisLabel: {
  37862. show: true,
  37863. distance: 5,
  37864. // formatter: null,
  37865. color: 'auto'
  37866. },
  37867. pointer: {
  37868. show: true,
  37869. length: '80%',
  37870. width: 8
  37871. },
  37872. itemStyle: {
  37873. normal: {
  37874. color: 'auto'
  37875. }
  37876. },
  37877. title: {
  37878. show: true,
  37879. // x, y,单位px
  37880. offsetCenter: [0, '-40%'],
  37881. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  37882. color: '#333',
  37883. fontSize: 15
  37884. },
  37885. detail: {
  37886. show: true,
  37887. backgroundColor: 'rgba(0,0,0,0)',
  37888. borderWidth: 0,
  37889. borderColor: '#ccc',
  37890. width: 100,
  37891. height: null, // self-adaption
  37892. padding: [5, 10],
  37893. // x, y,单位px
  37894. offsetCenter: [0, '40%'],
  37895. // formatter: null,
  37896. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  37897. color: 'auto',
  37898. fontSize: 30
  37899. }
  37900. }
  37901. });
  37902. var PointerPath = Path.extend({
  37903. type: 'echartsGaugePointer',
  37904. shape: {
  37905. angle: 0,
  37906. width: 10,
  37907. r: 10,
  37908. x: 0,
  37909. y: 0
  37910. },
  37911. buildPath: function (ctx, shape) {
  37912. var mathCos = Math.cos;
  37913. var mathSin = Math.sin;
  37914. var r = shape.r;
  37915. var width = shape.width;
  37916. var angle = shape.angle;
  37917. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  37918. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  37919. angle = shape.angle - Math.PI / 2;
  37920. ctx.moveTo(x, y);
  37921. ctx.lineTo(
  37922. shape.x + mathCos(angle) * width,
  37923. shape.y + mathSin(angle) * width
  37924. );
  37925. ctx.lineTo(
  37926. shape.x + mathCos(shape.angle) * r,
  37927. shape.y + mathSin(shape.angle) * r
  37928. );
  37929. ctx.lineTo(
  37930. shape.x - mathCos(angle) * width,
  37931. shape.y - mathSin(angle) * width
  37932. );
  37933. ctx.lineTo(x, y);
  37934. return;
  37935. }
  37936. });
  37937. function parsePosition(seriesModel, api) {
  37938. var center = seriesModel.get('center');
  37939. var width = api.getWidth();
  37940. var height = api.getHeight();
  37941. var size = Math.min(width, height);
  37942. var cx = parsePercent$1(center[0], api.getWidth());
  37943. var cy = parsePercent$1(center[1], api.getHeight());
  37944. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  37945. return {
  37946. cx: cx,
  37947. cy: cy,
  37948. r: r
  37949. };
  37950. }
  37951. function formatLabel(label, labelFormatter) {
  37952. if (labelFormatter) {
  37953. if (typeof labelFormatter === 'string') {
  37954. label = labelFormatter.replace('{value}', label != null ? label : '');
  37955. }
  37956. else if (typeof labelFormatter === 'function') {
  37957. label = labelFormatter(label);
  37958. }
  37959. }
  37960. return label;
  37961. }
  37962. var PI2$5 = Math.PI * 2;
  37963. var GaugeView = Chart.extend({
  37964. type: 'gauge',
  37965. render: function (seriesModel, ecModel, api) {
  37966. this.group.removeAll();
  37967. var colorList = seriesModel.get('axisLine.lineStyle.color');
  37968. var posInfo = parsePosition(seriesModel, api);
  37969. this._renderMain(
  37970. seriesModel, ecModel, api, colorList, posInfo
  37971. );
  37972. },
  37973. dispose: function () {},
  37974. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  37975. var group = this.group;
  37976. var axisLineModel = seriesModel.getModel('axisLine');
  37977. var lineStyleModel = axisLineModel.getModel('lineStyle');
  37978. var clockwise = seriesModel.get('clockwise');
  37979. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  37980. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  37981. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  37982. var prevEndAngle = startAngle;
  37983. var axisLineWidth = lineStyleModel.get('width');
  37984. for (var i = 0; i < colorList.length; i++) {
  37985. // Clamp
  37986. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  37987. var endAngle = startAngle + angleRangeSpan * percent;
  37988. var sector = new Sector({
  37989. shape: {
  37990. startAngle: prevEndAngle,
  37991. endAngle: endAngle,
  37992. cx: posInfo.cx,
  37993. cy: posInfo.cy,
  37994. clockwise: clockwise,
  37995. r0: posInfo.r - axisLineWidth,
  37996. r: posInfo.r
  37997. },
  37998. silent: true
  37999. });
  38000. sector.setStyle({
  38001. fill: colorList[i][1]
  38002. });
  38003. sector.setStyle(lineStyleModel.getLineStyle(
  38004. // Because we use sector to simulate arc
  38005. // so the properties for stroking are useless
  38006. ['color', 'borderWidth', 'borderColor']
  38007. ));
  38008. group.add(sector);
  38009. prevEndAngle = endAngle;
  38010. }
  38011. var getColor = function (percent) {
  38012. // Less than 0
  38013. if (percent <= 0) {
  38014. return colorList[0][1];
  38015. }
  38016. for (var i = 0; i < colorList.length; i++) {
  38017. if (colorList[i][0] >= percent
  38018. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  38019. ) {
  38020. return colorList[i][1];
  38021. }
  38022. }
  38023. // More than 1
  38024. return colorList[i - 1][1];
  38025. };
  38026. if (!clockwise) {
  38027. var tmp = startAngle;
  38028. startAngle = endAngle;
  38029. endAngle = tmp;
  38030. }
  38031. this._renderTicks(
  38032. seriesModel, ecModel, api, getColor, posInfo,
  38033. startAngle, endAngle, clockwise
  38034. );
  38035. this._renderPointer(
  38036. seriesModel, ecModel, api, getColor, posInfo,
  38037. startAngle, endAngle, clockwise
  38038. );
  38039. this._renderTitle(
  38040. seriesModel, ecModel, api, getColor, posInfo
  38041. );
  38042. this._renderDetail(
  38043. seriesModel, ecModel, api, getColor, posInfo
  38044. );
  38045. },
  38046. _renderTicks: function (
  38047. seriesModel, ecModel, api, getColor, posInfo,
  38048. startAngle, endAngle, clockwise
  38049. ) {
  38050. var group = this.group;
  38051. var cx = posInfo.cx;
  38052. var cy = posInfo.cy;
  38053. var r = posInfo.r;
  38054. var minVal = +seriesModel.get('min');
  38055. var maxVal = +seriesModel.get('max');
  38056. var splitLineModel = seriesModel.getModel('splitLine');
  38057. var tickModel = seriesModel.getModel('axisTick');
  38058. var labelModel = seriesModel.getModel('axisLabel');
  38059. var splitNumber = seriesModel.get('splitNumber');
  38060. var subSplitNumber = tickModel.get('splitNumber');
  38061. var splitLineLen = parsePercent$1(
  38062. splitLineModel.get('length'), r
  38063. );
  38064. var tickLen = parsePercent$1(
  38065. tickModel.get('length'), r
  38066. );
  38067. var angle = startAngle;
  38068. var step = (endAngle - startAngle) / splitNumber;
  38069. var subStep = step / subSplitNumber;
  38070. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  38071. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  38072. for (var i = 0; i <= splitNumber; i++) {
  38073. var unitX = Math.cos(angle);
  38074. var unitY = Math.sin(angle);
  38075. // Split line
  38076. if (splitLineModel.get('show')) {
  38077. var splitLine = new Line({
  38078. shape: {
  38079. x1: unitX * r + cx,
  38080. y1: unitY * r + cy,
  38081. x2: unitX * (r - splitLineLen) + cx,
  38082. y2: unitY * (r - splitLineLen) + cy
  38083. },
  38084. style: splitLineStyle,
  38085. silent: true
  38086. });
  38087. if (splitLineStyle.stroke === 'auto') {
  38088. splitLine.setStyle({
  38089. stroke: getColor(i / splitNumber)
  38090. });
  38091. }
  38092. group.add(splitLine);
  38093. }
  38094. // Label
  38095. if (labelModel.get('show')) {
  38096. var label = formatLabel(
  38097. round(i / splitNumber * (maxVal - minVal) + minVal),
  38098. labelModel.get('formatter')
  38099. );
  38100. var distance = labelModel.get('distance');
  38101. var autoColor = getColor(i / splitNumber);
  38102. group.add(new Text({
  38103. style: setTextStyle({}, labelModel, {
  38104. text: label,
  38105. x: unitX * (r - splitLineLen - distance) + cx,
  38106. y: unitY * (r - splitLineLen - distance) + cy,
  38107. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  38108. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  38109. }, {autoColor: autoColor}),
  38110. silent: true
  38111. }));
  38112. }
  38113. // Axis tick
  38114. if (tickModel.get('show') && i !== splitNumber) {
  38115. for (var j = 0; j <= subSplitNumber; j++) {
  38116. var unitX = Math.cos(angle);
  38117. var unitY = Math.sin(angle);
  38118. var tickLine = new Line({
  38119. shape: {
  38120. x1: unitX * r + cx,
  38121. y1: unitY * r + cy,
  38122. x2: unitX * (r - tickLen) + cx,
  38123. y2: unitY * (r - tickLen) + cy
  38124. },
  38125. silent: true,
  38126. style: tickLineStyle
  38127. });
  38128. if (tickLineStyle.stroke === 'auto') {
  38129. tickLine.setStyle({
  38130. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  38131. });
  38132. }
  38133. group.add(tickLine);
  38134. angle += subStep;
  38135. }
  38136. angle -= subStep;
  38137. }
  38138. else {
  38139. angle += step;
  38140. }
  38141. }
  38142. },
  38143. _renderPointer: function (
  38144. seriesModel, ecModel, api, getColor, posInfo,
  38145. startAngle, endAngle, clockwise
  38146. ) {
  38147. var group = this.group;
  38148. var oldData = this._data;
  38149. if (!seriesModel.get('pointer.show')) {
  38150. // Remove old element
  38151. oldData && oldData.eachItemGraphicEl(function (el) {
  38152. group.remove(el);
  38153. });
  38154. return;
  38155. }
  38156. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  38157. var angleExtent = [startAngle, endAngle];
  38158. var data = seriesModel.getData();
  38159. data.diff(oldData)
  38160. .add(function (idx) {
  38161. var pointer = new PointerPath({
  38162. shape: {
  38163. angle: startAngle
  38164. }
  38165. });
  38166. initProps(pointer, {
  38167. shape: {
  38168. angle: linearMap(data.get('value', idx), valueExtent, angleExtent, true)
  38169. }
  38170. }, seriesModel);
  38171. group.add(pointer);
  38172. data.setItemGraphicEl(idx, pointer);
  38173. })
  38174. .update(function (newIdx, oldIdx) {
  38175. var pointer = oldData.getItemGraphicEl(oldIdx);
  38176. updateProps(pointer, {
  38177. shape: {
  38178. angle: linearMap(data.get('value', newIdx), valueExtent, angleExtent, true)
  38179. }
  38180. }, seriesModel);
  38181. group.add(pointer);
  38182. data.setItemGraphicEl(newIdx, pointer);
  38183. })
  38184. .remove(function (idx) {
  38185. var pointer = oldData.getItemGraphicEl(idx);
  38186. group.remove(pointer);
  38187. })
  38188. .execute();
  38189. data.eachItemGraphicEl(function (pointer, idx) {
  38190. var itemModel = data.getItemModel(idx);
  38191. var pointerModel = itemModel.getModel('pointer');
  38192. pointer.setShape({
  38193. x: posInfo.cx,
  38194. y: posInfo.cy,
  38195. width: parsePercent$1(
  38196. pointerModel.get('width'), posInfo.r
  38197. ),
  38198. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  38199. });
  38200. pointer.useStyle(itemModel.getModel('itemStyle.normal').getItemStyle());
  38201. if (pointer.style.fill === 'auto') {
  38202. pointer.setStyle('fill', getColor(
  38203. linearMap(data.get('value', idx), valueExtent, [0, 1], true)
  38204. ));
  38205. }
  38206. setHoverStyle(
  38207. pointer, itemModel.getModel('itemStyle.emphasis').getItemStyle()
  38208. );
  38209. });
  38210. this._data = data;
  38211. },
  38212. _renderTitle: function (
  38213. seriesModel, ecModel, api, getColor, posInfo
  38214. ) {
  38215. var titleModel = seriesModel.getModel('title');
  38216. if (titleModel.get('show')) {
  38217. var offsetCenter = titleModel.get('offsetCenter');
  38218. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  38219. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  38220. var minVal = +seriesModel.get('min');
  38221. var maxVal = +seriesModel.get('max');
  38222. var value = seriesModel.getData().get('value', 0);
  38223. var autoColor = getColor(
  38224. linearMap(value, [minVal, maxVal], [0, 1], true)
  38225. );
  38226. this.group.add(new Text({
  38227. silent: true,
  38228. style: setTextStyle({}, titleModel, {
  38229. x: x,
  38230. y: y,
  38231. // FIXME First data name ?
  38232. text: seriesModel.getData().getName(0),
  38233. textAlign: 'center',
  38234. textVerticalAlign: 'middle'
  38235. }, {autoColor: autoColor, forceRich: true})
  38236. }));
  38237. }
  38238. },
  38239. _renderDetail: function (
  38240. seriesModel, ecModel, api, getColor, posInfo
  38241. ) {
  38242. var detailModel = seriesModel.getModel('detail');
  38243. var minVal = +seriesModel.get('min');
  38244. var maxVal = +seriesModel.get('max');
  38245. if (detailModel.get('show')) {
  38246. var offsetCenter = detailModel.get('offsetCenter');
  38247. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  38248. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  38249. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  38250. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  38251. var value = seriesModel.getData().get('value', 0);
  38252. var autoColor = getColor(
  38253. linearMap(value, [minVal, maxVal], [0, 1], true)
  38254. );
  38255. this.group.add(new Text({
  38256. silent: true,
  38257. style: setTextStyle({}, detailModel, {
  38258. x: x,
  38259. y: y,
  38260. text: formatLabel(
  38261. // FIXME First data name ?
  38262. value, detailModel.get('formatter')
  38263. ),
  38264. textWidth: isNaN(width) ? null : width,
  38265. textHeight: isNaN(height) ? null : height,
  38266. textAlign: 'center',
  38267. textVerticalAlign: 'middle'
  38268. }, {autoColor: autoColor, forceRich: true})
  38269. }));
  38270. }
  38271. }
  38272. });
  38273. var FunnelSeries = extendSeriesModel({
  38274. type: 'series.funnel',
  38275. init: function (option) {
  38276. FunnelSeries.superApply(this, 'init', arguments);
  38277. // Enable legend selection for each data item
  38278. // Use a function instead of direct access because data reference may changed
  38279. this.legendDataProvider = function () {
  38280. return this.getRawData();
  38281. };
  38282. // Extend labelLine emphasis
  38283. this._defaultLabelLine(option);
  38284. },
  38285. getInitialData: function (option, ecModel) {
  38286. var dimensions = completeDimensions(['value'], option.data);
  38287. var list = new List(dimensions, this);
  38288. list.initData(option.data);
  38289. return list;
  38290. },
  38291. _defaultLabelLine: function (option) {
  38292. // Extend labelLine emphasis
  38293. defaultEmphasis(option.labelLine, ['show']);
  38294. var labelLineNormalOpt = option.labelLine.normal;
  38295. var labelLineEmphasisOpt = option.labelLine.emphasis;
  38296. // Not show label line if `label.normal.show = false`
  38297. labelLineNormalOpt.show = labelLineNormalOpt.show
  38298. && option.label.normal.show;
  38299. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38300. && option.label.emphasis.show;
  38301. },
  38302. // Overwrite
  38303. getDataParams: function (dataIndex) {
  38304. var data = this.getData();
  38305. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  38306. var sum = data.getSum('value');
  38307. // Percent is 0 if sum is 0
  38308. params.percent = !sum ? 0 : +(data.get('value', dataIndex) / sum * 100).toFixed(2);
  38309. params.$vars.push('percent');
  38310. return params;
  38311. },
  38312. defaultOption: {
  38313. zlevel: 0, // 一级层叠
  38314. z: 2, // 二级层叠
  38315. legendHoverLink: true,
  38316. left: 80,
  38317. top: 60,
  38318. right: 80,
  38319. bottom: 60,
  38320. // width: {totalWidth} - left - right,
  38321. // height: {totalHeight} - top - bottom,
  38322. // 默认取数据最小最大值
  38323. // min: 0,
  38324. // max: 100,
  38325. minSize: '0%',
  38326. maxSize: '100%',
  38327. sort: 'descending', // 'ascending', 'descending'
  38328. gap: 0,
  38329. funnelAlign: 'center',
  38330. label: {
  38331. normal: {
  38332. show: true,
  38333. position: 'outer'
  38334. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38335. },
  38336. emphasis: {
  38337. show: true
  38338. }
  38339. },
  38340. labelLine: {
  38341. normal: {
  38342. show: true,
  38343. length: 20,
  38344. lineStyle: {
  38345. // color: 各异,
  38346. width: 1,
  38347. type: 'solid'
  38348. }
  38349. },
  38350. emphasis: {}
  38351. },
  38352. itemStyle: {
  38353. normal: {
  38354. // color: 各异,
  38355. borderColor: '#fff',
  38356. borderWidth: 1
  38357. },
  38358. emphasis: {
  38359. // color: 各异,
  38360. }
  38361. }
  38362. }
  38363. });
  38364. /**
  38365. * Piece of pie including Sector, Label, LabelLine
  38366. * @constructor
  38367. * @extends {module:zrender/graphic/Group}
  38368. */
  38369. function FunnelPiece(data, idx) {
  38370. Group.call(this);
  38371. var polygon = new Polygon();
  38372. var labelLine = new Polyline();
  38373. var text = new Text();
  38374. this.add(polygon);
  38375. this.add(labelLine);
  38376. this.add(text);
  38377. this.updateData(data, idx, true);
  38378. // Hover to change label and labelLine
  38379. function onEmphasis() {
  38380. labelLine.ignore = labelLine.hoverIgnore;
  38381. text.ignore = text.hoverIgnore;
  38382. }
  38383. function onNormal() {
  38384. labelLine.ignore = labelLine.normalIgnore;
  38385. text.ignore = text.normalIgnore;
  38386. }
  38387. this.on('emphasis', onEmphasis)
  38388. .on('normal', onNormal)
  38389. .on('mouseover', onEmphasis)
  38390. .on('mouseout', onNormal);
  38391. }
  38392. var funnelPieceProto = FunnelPiece.prototype;
  38393. var opacityAccessPath = ['itemStyle', 'normal', 'opacity'];
  38394. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  38395. var polygon = this.childAt(0);
  38396. var seriesModel = data.hostModel;
  38397. var itemModel = data.getItemModel(idx);
  38398. var layout = data.getItemLayout(idx);
  38399. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  38400. opacity = opacity == null ? 1 : opacity;
  38401. // Reset style
  38402. polygon.useStyle({});
  38403. if (firstCreate) {
  38404. polygon.setShape({
  38405. points: layout.points
  38406. });
  38407. polygon.setStyle({ opacity : 0 });
  38408. initProps(polygon, {
  38409. style: {
  38410. opacity: opacity
  38411. }
  38412. }, seriesModel, idx);
  38413. }
  38414. else {
  38415. updateProps(polygon, {
  38416. style: {
  38417. opacity: opacity
  38418. },
  38419. shape: {
  38420. points: layout.points
  38421. }
  38422. }, seriesModel, idx);
  38423. }
  38424. // Update common style
  38425. var itemStyleModel = itemModel.getModel('itemStyle');
  38426. var visualColor = data.getItemVisual(idx, 'color');
  38427. polygon.setStyle(
  38428. defaults(
  38429. {
  38430. lineJoin: 'round',
  38431. fill: visualColor
  38432. },
  38433. itemStyleModel.getModel('normal').getItemStyle(['opacity'])
  38434. )
  38435. );
  38436. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  38437. this._updateLabel(data, idx);
  38438. setHoverStyle(this);
  38439. };
  38440. funnelPieceProto._updateLabel = function (data, idx) {
  38441. var labelLine = this.childAt(1);
  38442. var labelText = this.childAt(2);
  38443. var seriesModel = data.hostModel;
  38444. var itemModel = data.getItemModel(idx);
  38445. var layout = data.getItemLayout(idx);
  38446. var labelLayout = layout.label;
  38447. var visualColor = data.getItemVisual(idx, 'color');
  38448. updateProps(labelLine, {
  38449. shape: {
  38450. points: labelLayout.linePoints || labelLayout.linePoints
  38451. }
  38452. }, seriesModel, idx);
  38453. updateProps(labelText, {
  38454. style: {
  38455. x: labelLayout.x,
  38456. y: labelLayout.y
  38457. }
  38458. }, seriesModel, idx);
  38459. labelText.attr({
  38460. rotation: labelLayout.rotation,
  38461. origin: [labelLayout.x, labelLayout.y],
  38462. z2: 10
  38463. });
  38464. var labelModel = itemModel.getModel('label.normal');
  38465. var labelHoverModel = itemModel.getModel('label.emphasis');
  38466. var labelLineModel = itemModel.getModel('labelLine.normal');
  38467. var labelLineHoverModel = itemModel.getModel('labelLine.emphasis');
  38468. var visualColor = data.getItemVisual(idx, 'color');
  38469. setLabelStyle(
  38470. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38471. {
  38472. labelFetcher: data.hostModel,
  38473. labelDataIndex: idx,
  38474. defaultText: data.getName(idx),
  38475. autoColor: visualColor,
  38476. useInsideStyle: !!labelLayout.inside
  38477. },
  38478. {
  38479. textAlign: labelLayout.textAlign,
  38480. textVerticalAlign: labelLayout.verticalAlign
  38481. }
  38482. );
  38483. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38484. labelText.hoverIgnore = !labelHoverModel.get('show');
  38485. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38486. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38487. // Default use item visual color
  38488. labelLine.setStyle({
  38489. stroke: visualColor
  38490. });
  38491. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38492. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38493. };
  38494. inherits(FunnelPiece, Group);
  38495. var FunnelView = Chart.extend({
  38496. type: 'funnel',
  38497. render: function (seriesModel, ecModel, api) {
  38498. var data = seriesModel.getData();
  38499. var oldData = this._data;
  38500. var group = this.group;
  38501. data.diff(oldData)
  38502. .add(function (idx) {
  38503. var funnelPiece = new FunnelPiece(data, idx);
  38504. data.setItemGraphicEl(idx, funnelPiece);
  38505. group.add(funnelPiece);
  38506. })
  38507. .update(function (newIdx, oldIdx) {
  38508. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38509. piePiece.updateData(data, newIdx);
  38510. group.add(piePiece);
  38511. data.setItemGraphicEl(newIdx, piePiece);
  38512. })
  38513. .remove(function (idx) {
  38514. var piePiece = oldData.getItemGraphicEl(idx);
  38515. group.remove(piePiece);
  38516. })
  38517. .execute();
  38518. this._data = data;
  38519. },
  38520. remove: function () {
  38521. this.group.removeAll();
  38522. this._data = null;
  38523. },
  38524. dispose: function () {}
  38525. });
  38526. function getViewRect$2(seriesModel, api) {
  38527. return getLayoutRect(
  38528. seriesModel.getBoxLayoutParams(), {
  38529. width: api.getWidth(),
  38530. height: api.getHeight()
  38531. }
  38532. );
  38533. }
  38534. function getSortedIndices(data, sort) {
  38535. var valueArr = data.mapArray('value', function (val) {
  38536. return val;
  38537. });
  38538. var indices = [];
  38539. var isAscending = sort === 'ascending';
  38540. for (var i = 0, len = data.count(); i < len; i++) {
  38541. indices[i] = i;
  38542. }
  38543. // Add custom sortable function & none sortable opetion by "options.sort"
  38544. if (typeof sort === 'function') {
  38545. indices.sort(sort);
  38546. } else if (sort !== 'none') {
  38547. indices.sort(function (a, b) {
  38548. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  38549. });
  38550. }
  38551. return indices;
  38552. }
  38553. function labelLayout$1(data) {
  38554. data.each(function (idx) {
  38555. var itemModel = data.getItemModel(idx);
  38556. var labelModel = itemModel.getModel('label.normal');
  38557. var labelPosition = labelModel.get('position');
  38558. var labelLineModel = itemModel.getModel('labelLine.normal');
  38559. var layout = data.getItemLayout(idx);
  38560. var points = layout.points;
  38561. var isLabelInside = labelPosition === 'inner'
  38562. || labelPosition === 'inside' || labelPosition === 'center';
  38563. var textAlign;
  38564. var textX;
  38565. var textY;
  38566. var linePoints;
  38567. if (isLabelInside) {
  38568. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  38569. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  38570. textAlign = 'center';
  38571. linePoints = [
  38572. [textX, textY], [textX, textY]
  38573. ];
  38574. }
  38575. else {
  38576. var x1;
  38577. var y1;
  38578. var x2;
  38579. var labelLineLen = labelLineModel.get('length');
  38580. if (labelPosition === 'left') {
  38581. // Left side
  38582. x1 = (points[3][0] + points[0][0]) / 2;
  38583. y1 = (points[3][1] + points[0][1]) / 2;
  38584. x2 = x1 - labelLineLen;
  38585. textX = x2 - 5;
  38586. textAlign = 'right';
  38587. }
  38588. else {
  38589. // Right side
  38590. x1 = (points[1][0] + points[2][0]) / 2;
  38591. y1 = (points[1][1] + points[2][1]) / 2;
  38592. x2 = x1 + labelLineLen;
  38593. textX = x2 + 5;
  38594. textAlign = 'left';
  38595. }
  38596. var y2 = y1;
  38597. linePoints = [[x1, y1], [x2, y2]];
  38598. textY = y2;
  38599. }
  38600. layout.label = {
  38601. linePoints: linePoints,
  38602. x: textX,
  38603. y: textY,
  38604. verticalAlign: 'middle',
  38605. textAlign: textAlign,
  38606. inside: isLabelInside
  38607. };
  38608. });
  38609. }
  38610. var funnelLayout = function (ecModel, api, payload) {
  38611. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  38612. var data = seriesModel.getData();
  38613. var sort = seriesModel.get('sort');
  38614. var viewRect = getViewRect$2(seriesModel, api);
  38615. var indices = getSortedIndices(data, sort);
  38616. var sizeExtent = [
  38617. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  38618. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  38619. ];
  38620. var dataExtent = data.getDataExtent('value');
  38621. var min = seriesModel.get('min');
  38622. var max = seriesModel.get('max');
  38623. if (min == null) {
  38624. min = Math.min(dataExtent[0], 0);
  38625. }
  38626. if (max == null) {
  38627. max = dataExtent[1];
  38628. }
  38629. var funnelAlign = seriesModel.get('funnelAlign');
  38630. var gap = seriesModel.get('gap');
  38631. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  38632. var y = viewRect.y;
  38633. var getLinePoints = function (idx, offY) {
  38634. // End point index is data.count() and we assign it 0
  38635. var val = data.get('value', idx) || 0;
  38636. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  38637. var x0;
  38638. switch (funnelAlign) {
  38639. case 'left':
  38640. x0 = viewRect.x;
  38641. break;
  38642. case 'center':
  38643. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  38644. break;
  38645. case 'right':
  38646. x0 = viewRect.x + viewRect.width - itemWidth;
  38647. break;
  38648. }
  38649. return [
  38650. [x0, offY],
  38651. [x0 + itemWidth, offY]
  38652. ];
  38653. };
  38654. if (sort === 'ascending') {
  38655. // From bottom to top
  38656. itemHeight = -itemHeight;
  38657. gap = -gap;
  38658. y += viewRect.height;
  38659. indices = indices.reverse();
  38660. }
  38661. for (var i = 0; i < indices.length; i++) {
  38662. var idx = indices[i];
  38663. var nextIdx = indices[i + 1];
  38664. var start = getLinePoints(idx, y);
  38665. var end = getLinePoints(nextIdx, y + itemHeight);
  38666. y += itemHeight + gap;
  38667. data.setItemLayout(idx, {
  38668. points: start.concat(end.slice().reverse())
  38669. });
  38670. }
  38671. labelLayout$1(data);
  38672. });
  38673. };
  38674. registerVisual(curry(dataColor, 'funnel'));
  38675. registerLayout(funnelLayout);
  38676. registerProcessor(curry(dataFilter, 'funnel'));
  38677. var parallelPreprocessor = function (option) {
  38678. createParallelIfNeeded(option);
  38679. mergeAxisOptionFromParallel(option);
  38680. };
  38681. /**
  38682. * Create a parallel coordinate if not exists.
  38683. * @inner
  38684. */
  38685. function createParallelIfNeeded(option) {
  38686. if (option.parallel) {
  38687. return;
  38688. }
  38689. var hasParallelSeries = false;
  38690. each$1(option.series, function (seriesOpt) {
  38691. if (seriesOpt && seriesOpt.type === 'parallel') {
  38692. hasParallelSeries = true;
  38693. }
  38694. });
  38695. if (hasParallelSeries) {
  38696. option.parallel = [{}];
  38697. }
  38698. }
  38699. /**
  38700. * Merge aixs definition from parallel option (if exists) to axis option.
  38701. * @inner
  38702. */
  38703. function mergeAxisOptionFromParallel(option) {
  38704. var axes = normalizeToArray(option.parallelAxis);
  38705. each$1(axes, function (axisOption) {
  38706. if (!isObject(axisOption)) {
  38707. return;
  38708. }
  38709. var parallelIndex = axisOption.parallelIndex || 0;
  38710. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  38711. if (parallelOption && parallelOption.parallelAxisDefault) {
  38712. merge(axisOption, parallelOption.parallelAxisDefault, false);
  38713. }
  38714. });
  38715. }
  38716. /**
  38717. * @constructor module:echarts/coord/parallel/ParallelAxis
  38718. * @extends {module:echarts/coord/Axis}
  38719. * @param {string} dim
  38720. * @param {*} scale
  38721. * @param {Array.<number>} coordExtent
  38722. * @param {string} axisType
  38723. */
  38724. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  38725. Axis.call(this, dim, scale, coordExtent);
  38726. /**
  38727. * Axis type
  38728. * - 'category'
  38729. * - 'value'
  38730. * - 'time'
  38731. * - 'log'
  38732. * @type {string}
  38733. */
  38734. this.type = axisType || 'value';
  38735. /**
  38736. * @type {number}
  38737. * @readOnly
  38738. */
  38739. this.axisIndex = axisIndex;
  38740. };
  38741. ParallelAxis.prototype = {
  38742. constructor: ParallelAxis,
  38743. /**
  38744. * Axis model
  38745. * @param {module:echarts/coord/parallel/AxisModel}
  38746. */
  38747. model: null,
  38748. /**
  38749. * @override
  38750. */
  38751. isHorizontal: function () {
  38752. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  38753. }
  38754. };
  38755. inherits(ParallelAxis, Axis);
  38756. /**
  38757. * Calculate slider move result.
  38758. * Usage:
  38759. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  38760. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  38761. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  38762. *
  38763. * @param {number} delta Move length.
  38764. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  38765. * handleEnds will be modified in this method.
  38766. * @param {Array.<number>} extent handleEnds is restricted by extent.
  38767. * extent[0] should less or equals than extent[1].
  38768. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  38769. * where the input minSpan and maxSpan will not work.
  38770. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  38771. * If not set, handle0 and cross handle1. If set as a non-negative
  38772. * number (including `0`), handles will push each other when reaching
  38773. * the minSpan.
  38774. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  38775. * @return {Array.<number>} The input handleEnds.
  38776. */
  38777. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  38778. // Normalize firstly.
  38779. handleEnds[0] = restrict$1(handleEnds[0], extent);
  38780. handleEnds[1] = restrict$1(handleEnds[1], extent);
  38781. delta = delta || 0;
  38782. var extentSpan = extent[1] - extent[0];
  38783. // Notice maxSpan and minSpan can be null/undefined.
  38784. if (minSpan != null) {
  38785. minSpan = restrict$1(minSpan, [0, extentSpan]);
  38786. }
  38787. if (maxSpan != null) {
  38788. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  38789. }
  38790. if (handleIndex === 'all') {
  38791. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  38792. handleIndex = 0;
  38793. }
  38794. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  38795. handleEnds[handleIndex] += delta;
  38796. // Restrict in extent.
  38797. var extentMinSpan = minSpan || 0;
  38798. var realExtent = extent.slice();
  38799. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  38800. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  38801. // Expand span.
  38802. var currDistSign = getSpanSign(handleEnds, handleIndex);
  38803. if (minSpan != null && (
  38804. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  38805. )) {
  38806. // If minSpan exists, 'cross' is forbinden.
  38807. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  38808. }
  38809. // Shrink span.
  38810. var currDistSign = getSpanSign(handleEnds, handleIndex);
  38811. if (maxSpan != null && currDistSign.span > maxSpan) {
  38812. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  38813. }
  38814. return handleEnds;
  38815. };
  38816. function getSpanSign(handleEnds, handleIndex) {
  38817. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  38818. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  38819. // is at left of handleEnds[1] for non-cross case.
  38820. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  38821. }
  38822. function restrict$1(value, extend) {
  38823. return Math.min(extend[1], Math.max(extend[0], value));
  38824. }
  38825. /**
  38826. * Parallel Coordinates
  38827. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  38828. */
  38829. var each$14 = each$1;
  38830. var mathMin$5 = Math.min;
  38831. var mathMax$5 = Math.max;
  38832. var mathFloor$2 = Math.floor;
  38833. var mathCeil$2 = Math.ceil;
  38834. var round$2 = round;
  38835. var PI$3 = Math.PI;
  38836. function Parallel(parallelModel, ecModel, api) {
  38837. /**
  38838. * key: dimension
  38839. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  38840. * @private
  38841. */
  38842. this._axesMap = createHashMap();
  38843. /**
  38844. * key: dimension
  38845. * value: {position: [], rotation, }
  38846. * @type {Object.<string, Object>}
  38847. * @private
  38848. */
  38849. this._axesLayout = {};
  38850. /**
  38851. * Always follow axis order.
  38852. * @type {Array.<string>}
  38853. * @readOnly
  38854. */
  38855. this.dimensions = parallelModel.dimensions;
  38856. /**
  38857. * @type {module:zrender/core/BoundingRect}
  38858. */
  38859. this._rect;
  38860. /**
  38861. * @type {module:echarts/coord/parallel/ParallelModel}
  38862. */
  38863. this._model = parallelModel;
  38864. this._init(parallelModel, ecModel, api);
  38865. }
  38866. Parallel.prototype = {
  38867. type: 'parallel',
  38868. constructor: Parallel,
  38869. /**
  38870. * Initialize cartesian coordinate systems
  38871. * @private
  38872. */
  38873. _init: function (parallelModel, ecModel, api) {
  38874. var dimensions = parallelModel.dimensions;
  38875. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  38876. each$14(dimensions, function (dim, idx) {
  38877. var axisIndex = parallelAxisIndex[idx];
  38878. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  38879. var axis = this._axesMap.set(dim, new ParallelAxis(
  38880. dim,
  38881. createScaleByModel(axisModel),
  38882. [0, 0],
  38883. axisModel.get('type'),
  38884. axisIndex
  38885. ));
  38886. var isCategory = axis.type === 'category';
  38887. axis.onBand = isCategory && axisModel.get('boundaryGap');
  38888. axis.inverse = axisModel.get('inverse');
  38889. // Injection
  38890. axisModel.axis = axis;
  38891. axis.model = axisModel;
  38892. axis.coordinateSystem = axisModel.coordinateSystem = this;
  38893. }, this);
  38894. },
  38895. /**
  38896. * Update axis scale after data processed
  38897. * @param {module:echarts/model/Global} ecModel
  38898. * @param {module:echarts/ExtensionAPI} api
  38899. */
  38900. update: function (ecModel, api) {
  38901. this._updateAxesFromSeries(this._model, ecModel);
  38902. },
  38903. /**
  38904. * @override
  38905. */
  38906. containPoint: function (point) {
  38907. var layoutInfo = this._makeLayoutInfo();
  38908. var axisBase = layoutInfo.axisBase;
  38909. var layoutBase = layoutInfo.layoutBase;
  38910. var pixelDimIndex = layoutInfo.pixelDimIndex;
  38911. var pAxis = point[1 - pixelDimIndex];
  38912. var pLayout = point[pixelDimIndex];
  38913. return pAxis >= axisBase
  38914. && pAxis <= axisBase + layoutInfo.axisLength
  38915. && pLayout >= layoutBase
  38916. && pLayout <= layoutBase + layoutInfo.layoutLength;
  38917. },
  38918. getModel: function () {
  38919. return this._model;
  38920. },
  38921. /**
  38922. * Update properties from series
  38923. * @private
  38924. */
  38925. _updateAxesFromSeries: function (parallelModel, ecModel) {
  38926. ecModel.eachSeries(function (seriesModel) {
  38927. if (!parallelModel.contains(seriesModel, ecModel)) {
  38928. return;
  38929. }
  38930. var data = seriesModel.getData();
  38931. each$14(this.dimensions, function (dim) {
  38932. var axis = this._axesMap.get(dim);
  38933. axis.scale.unionExtentFromData(data, dim);
  38934. niceScaleExtent(axis.scale, axis.model);
  38935. }, this);
  38936. }, this);
  38937. },
  38938. /**
  38939. * Resize the parallel coordinate system.
  38940. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  38941. * @param {module:echarts/ExtensionAPI} api
  38942. */
  38943. resize: function (parallelModel, api) {
  38944. this._rect = getLayoutRect(
  38945. parallelModel.getBoxLayoutParams(),
  38946. {
  38947. width: api.getWidth(),
  38948. height: api.getHeight()
  38949. }
  38950. );
  38951. this._layoutAxes();
  38952. },
  38953. /**
  38954. * @return {module:zrender/core/BoundingRect}
  38955. */
  38956. getRect: function () {
  38957. return this._rect;
  38958. },
  38959. /**
  38960. * @private
  38961. */
  38962. _makeLayoutInfo: function () {
  38963. var parallelModel = this._model;
  38964. var rect = this._rect;
  38965. var xy = ['x', 'y'];
  38966. var wh = ['width', 'height'];
  38967. var layout = parallelModel.get('layout');
  38968. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  38969. var layoutLength = rect[wh[pixelDimIndex]];
  38970. var layoutExtent = [0, layoutLength];
  38971. var axisCount = this.dimensions.length;
  38972. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  38973. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  38974. var axisExpandable = parallelModel.get('axisExpandable')
  38975. && axisCount > 3
  38976. && axisCount > axisExpandCount
  38977. && axisExpandCount > 1
  38978. && axisExpandWidth > 0
  38979. && layoutLength > 0;
  38980. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  38981. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  38982. // where collapsed axes should be overlapped.
  38983. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  38984. var winSize;
  38985. if (!axisExpandWindow) {
  38986. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  38987. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  38988. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  38989. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  38990. }
  38991. else {
  38992. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  38993. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  38994. }
  38995. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  38996. // Avoid axisCollapseWidth is too small.
  38997. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  38998. // Find the first and last indices > ewin[0] and < ewin[1].
  38999. var winInnerIndices = [
  39000. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  39001. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  39002. ];
  39003. // Pos in ec coordinates.
  39004. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  39005. return {
  39006. layout: layout,
  39007. pixelDimIndex: pixelDimIndex,
  39008. layoutBase: rect[xy[pixelDimIndex]],
  39009. layoutLength: layoutLength,
  39010. axisBase: rect[xy[1 - pixelDimIndex]],
  39011. axisLength: rect[wh[1 - pixelDimIndex]],
  39012. axisExpandable: axisExpandable,
  39013. axisExpandWidth: axisExpandWidth,
  39014. axisCollapseWidth: axisCollapseWidth,
  39015. axisExpandWindow: axisExpandWindow,
  39016. axisCount: axisCount,
  39017. winInnerIndices: winInnerIndices,
  39018. axisExpandWindow0Pos: axisExpandWindow0Pos
  39019. };
  39020. },
  39021. /**
  39022. * @private
  39023. */
  39024. _layoutAxes: function () {
  39025. var rect = this._rect;
  39026. var axes = this._axesMap;
  39027. var dimensions = this.dimensions;
  39028. var layoutInfo = this._makeLayoutInfo();
  39029. var layout = layoutInfo.layout;
  39030. axes.each(function (axis) {
  39031. var axisExtent = [0, layoutInfo.axisLength];
  39032. var idx = axis.inverse ? 1 : 0;
  39033. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  39034. });
  39035. each$14(dimensions, function (dim, idx) {
  39036. var posInfo = (layoutInfo.axisExpandable
  39037. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  39038. )(idx, layoutInfo);
  39039. var positionTable = {
  39040. horizontal: {
  39041. x: posInfo.position,
  39042. y: layoutInfo.axisLength
  39043. },
  39044. vertical: {
  39045. x: 0,
  39046. y: posInfo.position
  39047. }
  39048. };
  39049. var rotationTable = {
  39050. horizontal: PI$3 / 2,
  39051. vertical: 0
  39052. };
  39053. var position = [
  39054. positionTable[layout].x + rect.x,
  39055. positionTable[layout].y + rect.y
  39056. ];
  39057. var rotation = rotationTable[layout];
  39058. var transform = create$1();
  39059. rotate(transform, transform, rotation);
  39060. translate(transform, transform, position);
  39061. // TODO
  39062. // tick等排布信息。
  39063. // TODO
  39064. // 根据axis order 更新 dimensions顺序。
  39065. this._axesLayout[dim] = {
  39066. position: position,
  39067. rotation: rotation,
  39068. transform: transform,
  39069. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  39070. axisLabelShow: posInfo.axisLabelShow,
  39071. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  39072. tickDirection: 1,
  39073. labelDirection: 1,
  39074. labelInterval: axes.get(dim).getLabelInterval()
  39075. };
  39076. }, this);
  39077. },
  39078. /**
  39079. * Get axis by dim.
  39080. * @param {string} dim
  39081. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  39082. */
  39083. getAxis: function (dim) {
  39084. return this._axesMap.get(dim);
  39085. },
  39086. /**
  39087. * Convert a dim value of a single item of series data to Point.
  39088. * @param {*} value
  39089. * @param {string} dim
  39090. * @return {Array}
  39091. */
  39092. dataToPoint: function (value, dim) {
  39093. return this.axisCoordToPoint(
  39094. this._axesMap.get(dim).dataToCoord(value),
  39095. dim
  39096. );
  39097. },
  39098. /**
  39099. * Travel data for one time, get activeState of each data item.
  39100. * @param {module:echarts/data/List} data
  39101. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  39102. * {number} dataIndex
  39103. * @param {Object} context
  39104. */
  39105. eachActiveState: function (data, callback, context) {
  39106. var dimensions = this.dimensions;
  39107. var axesMap = this._axesMap;
  39108. var hasActiveSet = this.hasAxisBrushed();
  39109. for (var i = 0, len = data.count(); i < len; i++) {
  39110. var values = data.getValues(dimensions, i);
  39111. var activeState;
  39112. if (!hasActiveSet) {
  39113. activeState = 'normal';
  39114. }
  39115. else {
  39116. activeState = 'active';
  39117. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  39118. var dimName = dimensions[j];
  39119. var state = axesMap.get(dimName).model.getActiveState(values[j], j);
  39120. if (state === 'inactive') {
  39121. activeState = 'inactive';
  39122. break;
  39123. }
  39124. }
  39125. }
  39126. callback.call(context, activeState, i);
  39127. }
  39128. },
  39129. /**
  39130. * Whether has any activeSet.
  39131. * @return {boolean}
  39132. */
  39133. hasAxisBrushed: function () {
  39134. var dimensions = this.dimensions;
  39135. var axesMap = this._axesMap;
  39136. var hasActiveSet = false;
  39137. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  39138. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  39139. hasActiveSet = true;
  39140. }
  39141. }
  39142. return hasActiveSet;
  39143. },
  39144. /**
  39145. * Convert coords of each axis to Point.
  39146. * Return point. For example: [10, 20]
  39147. * @param {Array.<number>} coords
  39148. * @param {string} dim
  39149. * @return {Array.<number>}
  39150. */
  39151. axisCoordToPoint: function (coord, dim) {
  39152. var axisLayout = this._axesLayout[dim];
  39153. return applyTransform$1([coord, 0], axisLayout.transform);
  39154. },
  39155. /**
  39156. * Get axis layout.
  39157. */
  39158. getAxisLayout: function (dim) {
  39159. return clone(this._axesLayout[dim]);
  39160. },
  39161. /**
  39162. * @param {Array.<number>} point
  39163. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  39164. */
  39165. getSlidedAxisExpandWindow: function (point) {
  39166. var layoutInfo = this._makeLayoutInfo();
  39167. var pixelDimIndex = layoutInfo.pixelDimIndex;
  39168. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  39169. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  39170. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  39171. // Out of the area of coordinate system.
  39172. if (!this.containPoint(point)) {
  39173. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  39174. }
  39175. // Conver the point from global to expand coordinates.
  39176. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  39177. // For dragging operation convenience, the window should not be
  39178. // slided when mouse is the center area of the window.
  39179. var delta;
  39180. var behavior = 'slide';
  39181. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  39182. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  39183. // But consider touch device, jump is necessary.
  39184. var useJump = triggerArea[0] != null;
  39185. if (axisCollapseWidth) {
  39186. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  39187. behavior = 'jump';
  39188. delta = pointCoord - winSize * triggerArea[2];
  39189. }
  39190. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  39191. behavior = 'jump';
  39192. delta = pointCoord - winSize * (1 - triggerArea[2]);
  39193. }
  39194. else {
  39195. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  39196. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  39197. && (delta = 0);
  39198. }
  39199. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  39200. delta
  39201. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  39202. // Avoid nonsense triger on mousemove.
  39203. : (behavior = 'none');
  39204. }
  39205. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  39206. else {
  39207. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  39208. var pos = extent[1] * pointCoord / winSize;
  39209. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  39210. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  39211. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  39212. }
  39213. return {
  39214. axisExpandWindow: axisExpandWindow,
  39215. behavior: behavior
  39216. };
  39217. }
  39218. };
  39219. function restrict(len, extent) {
  39220. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  39221. }
  39222. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  39223. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  39224. return {
  39225. position: step * axisIndex,
  39226. axisNameAvailableWidth: step,
  39227. axisLabelShow: true
  39228. };
  39229. }
  39230. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  39231. var layoutLength = layoutInfo.layoutLength;
  39232. var axisExpandWidth = layoutInfo.axisExpandWidth;
  39233. var axisCount = layoutInfo.axisCount;
  39234. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  39235. var winInnerIndices = layoutInfo.winInnerIndices;
  39236. var position;
  39237. var axisNameAvailableWidth = axisCollapseWidth;
  39238. var axisLabelShow = false;
  39239. var nameTruncateMaxWidth;
  39240. if (axisIndex < winInnerIndices[0]) {
  39241. position = axisIndex * axisCollapseWidth;
  39242. nameTruncateMaxWidth = axisCollapseWidth;
  39243. }
  39244. else if (axisIndex <= winInnerIndices[1]) {
  39245. position = layoutInfo.axisExpandWindow0Pos
  39246. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  39247. axisNameAvailableWidth = axisExpandWidth;
  39248. axisLabelShow = true;
  39249. }
  39250. else {
  39251. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  39252. nameTruncateMaxWidth = axisCollapseWidth;
  39253. }
  39254. return {
  39255. position: position,
  39256. axisNameAvailableWidth: axisNameAvailableWidth,
  39257. axisLabelShow: axisLabelShow,
  39258. nameTruncateMaxWidth: nameTruncateMaxWidth
  39259. };
  39260. }
  39261. /**
  39262. * Parallel coordinate system creater.
  39263. */
  39264. function create$2(ecModel, api) {
  39265. var coordSysList = [];
  39266. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  39267. var coordSys = new Parallel(parallelModel, ecModel, api);
  39268. coordSys.name = 'parallel_' + idx;
  39269. coordSys.resize(parallelModel, api);
  39270. parallelModel.coordinateSystem = coordSys;
  39271. coordSys.model = parallelModel;
  39272. coordSysList.push(coordSys);
  39273. });
  39274. // Inject the coordinateSystems into seriesModel
  39275. ecModel.eachSeries(function (seriesModel) {
  39276. if (seriesModel.get('coordinateSystem') === 'parallel') {
  39277. var parallelModel = ecModel.queryComponents({
  39278. mainType: 'parallel',
  39279. index: seriesModel.get('parallelIndex'),
  39280. id: seriesModel.get('parallelId')
  39281. })[0];
  39282. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  39283. }
  39284. });
  39285. return coordSysList;
  39286. }
  39287. CoordinateSystemManager.register('parallel', {create: create$2});
  39288. var AxisModel$2 = ComponentModel.extend({
  39289. type: 'baseParallelAxis',
  39290. /**
  39291. * @type {module:echarts/coord/parallel/Axis}
  39292. */
  39293. axis: null,
  39294. /**
  39295. * @type {Array.<Array.<number>}
  39296. * @readOnly
  39297. */
  39298. activeIntervals: [],
  39299. /**
  39300. * @return {Object}
  39301. */
  39302. getAreaSelectStyle: function () {
  39303. return makeStyleMapper(
  39304. [
  39305. ['fill', 'color'],
  39306. ['lineWidth', 'borderWidth'],
  39307. ['stroke', 'borderColor'],
  39308. ['width', 'width'],
  39309. ['opacity', 'opacity']
  39310. ]
  39311. )(this.getModel('areaSelectStyle'));
  39312. },
  39313. /**
  39314. * The code of this feature is put on AxisModel but not ParallelAxis,
  39315. * because axisModel can be alive after echarts updating but instance of
  39316. * ParallelAxis having been disposed. this._activeInterval should be kept
  39317. * when action dispatched (i.e. legend click).
  39318. *
  39319. * @param {Array.<Array<number>>} intervals interval.length === 0
  39320. * means set all active.
  39321. * @public
  39322. */
  39323. setActiveIntervals: function (intervals) {
  39324. var activeIntervals = this.activeIntervals = clone(intervals);
  39325. // Normalize
  39326. if (activeIntervals) {
  39327. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  39328. asc(activeIntervals[i]);
  39329. }
  39330. }
  39331. },
  39332. /**
  39333. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  39334. * value can not be input.
  39335. * @return {string} 'normal': no activeIntervals set,
  39336. * 'active',
  39337. * 'inactive'.
  39338. * @public
  39339. */
  39340. getActiveState: function (value) {
  39341. var activeIntervals = this.activeIntervals;
  39342. if (!activeIntervals.length) {
  39343. return 'normal';
  39344. }
  39345. if (value == null) {
  39346. return 'inactive';
  39347. }
  39348. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  39349. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  39350. return 'active';
  39351. }
  39352. }
  39353. return 'inactive';
  39354. }
  39355. });
  39356. var defaultOption$1 = {
  39357. type: 'value',
  39358. /**
  39359. * @type {Array.<number>}
  39360. */
  39361. dim: null, // 0, 1, 2, ...
  39362. // parallelIndex: null,
  39363. areaSelectStyle: {
  39364. width: 20,
  39365. borderWidth: 1,
  39366. borderColor: 'rgba(160,197,232)',
  39367. color: 'rgba(160,197,232)',
  39368. opacity: 0.3
  39369. },
  39370. realtime: true, // Whether realtime update view when select.
  39371. z: 10
  39372. };
  39373. merge(AxisModel$2.prototype, axisModelCommonMixin);
  39374. function getAxisType$1(axisName, option) {
  39375. return option.type || (option.data ? 'category' : 'value');
  39376. }
  39377. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  39378. ComponentModel.extend({
  39379. type: 'parallel',
  39380. dependencies: ['parallelAxis'],
  39381. /**
  39382. * @type {module:echarts/coord/parallel/Parallel}
  39383. */
  39384. coordinateSystem: null,
  39385. /**
  39386. * Each item like: 'dim0', 'dim1', 'dim2', ...
  39387. * @type {Array.<string>}
  39388. * @readOnly
  39389. */
  39390. dimensions: null,
  39391. /**
  39392. * Coresponding to dimensions.
  39393. * @type {Array.<number>}
  39394. * @readOnly
  39395. */
  39396. parallelAxisIndex: null,
  39397. layoutMode: 'box',
  39398. defaultOption: {
  39399. zlevel: 0,
  39400. z: 0,
  39401. left: 80,
  39402. top: 60,
  39403. right: 80,
  39404. bottom: 60,
  39405. // width: {totalWidth} - left - right,
  39406. // height: {totalHeight} - top - bottom,
  39407. layout: 'horizontal', // 'horizontal' or 'vertical'
  39408. // FIXME
  39409. // naming?
  39410. axisExpandable: false,
  39411. axisExpandCenter: null,
  39412. axisExpandCount: 0,
  39413. axisExpandWidth: 50, // FIXME '10%' ?
  39414. axisExpandRate: 17,
  39415. axisExpandDebounce: 50,
  39416. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  39417. // Do not doc to user until necessary.
  39418. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  39419. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  39420. parallelAxisDefault: null
  39421. },
  39422. /**
  39423. * @override
  39424. */
  39425. init: function () {
  39426. ComponentModel.prototype.init.apply(this, arguments);
  39427. this.mergeOption({});
  39428. },
  39429. /**
  39430. * @override
  39431. */
  39432. mergeOption: function (newOption) {
  39433. var thisOption = this.option;
  39434. newOption && merge(thisOption, newOption, true);
  39435. this._initDimensions();
  39436. },
  39437. /**
  39438. * Whether series or axis is in this coordinate system.
  39439. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  39440. * @param {module:echarts/model/Global} ecModel
  39441. */
  39442. contains: function (model, ecModel) {
  39443. var parallelIndex = model.get('parallelIndex');
  39444. return parallelIndex != null
  39445. && ecModel.getComponent('parallel', parallelIndex) === this;
  39446. },
  39447. setAxisExpand: function (opt) {
  39448. each$1(
  39449. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  39450. function (name) {
  39451. if (opt.hasOwnProperty(name)) {
  39452. this.option[name] = opt[name];
  39453. }
  39454. },
  39455. this
  39456. );
  39457. },
  39458. /**
  39459. * @private
  39460. */
  39461. _initDimensions: function () {
  39462. var dimensions = this.dimensions = [];
  39463. var parallelAxisIndex = this.parallelAxisIndex = [];
  39464. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  39465. // Can not use this.contains here, because
  39466. // initialization has not been completed yet.
  39467. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  39468. }, this);
  39469. each$1(axisModels, function (axisModel) {
  39470. dimensions.push('dim' + axisModel.get('dim'));
  39471. parallelAxisIndex.push(axisModel.componentIndex);
  39472. });
  39473. }
  39474. });
  39475. /**
  39476. * @payload
  39477. * @property {string} parallelAxisId
  39478. * @property {Array.<Array.<number>>} intervals
  39479. */
  39480. var actionInfo$1 = {
  39481. type: 'axisAreaSelect',
  39482. event: 'axisAreaSelected',
  39483. update: 'updateVisual'
  39484. };
  39485. registerAction(actionInfo$1, function (payload, ecModel) {
  39486. ecModel.eachComponent(
  39487. {mainType: 'parallelAxis', query: payload},
  39488. function (parallelAxisModel) {
  39489. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  39490. }
  39491. );
  39492. });
  39493. /**
  39494. * @payload
  39495. */
  39496. registerAction('parallelAxisExpand', function (payload, ecModel) {
  39497. ecModel.eachComponent(
  39498. {mainType: 'parallel', query: payload},
  39499. function (parallelModel) {
  39500. parallelModel.setAxisExpand(payload);
  39501. }
  39502. );
  39503. });
  39504. var curry$2 = curry;
  39505. var each$15 = each$1;
  39506. var map$3 = map;
  39507. var mathMin$6 = Math.min;
  39508. var mathMax$6 = Math.max;
  39509. var mathPow$2 = Math.pow;
  39510. var COVER_Z = 10000;
  39511. var UNSELECT_THRESHOLD = 6;
  39512. var MIN_RESIZE_LINE_WIDTH = 6;
  39513. var MUTEX_RESOURCE_KEY = 'globalPan';
  39514. var DIRECTION_MAP = {
  39515. w: [0, 0],
  39516. e: [0, 1],
  39517. n: [1, 0],
  39518. s: [1, 1]
  39519. };
  39520. var CURSOR_MAP = {
  39521. w: 'ew',
  39522. e: 'ew',
  39523. n: 'ns',
  39524. s: 'ns',
  39525. ne: 'nesw',
  39526. sw: 'nesw',
  39527. nw: 'nwse',
  39528. se: 'nwse'
  39529. };
  39530. var DEFAULT_BRUSH_OPT = {
  39531. brushStyle: {
  39532. lineWidth: 2,
  39533. stroke: 'rgba(0,0,0,0.3)',
  39534. fill: 'rgba(0,0,0,0.1)'
  39535. },
  39536. transformable: true,
  39537. brushMode: 'single',
  39538. removeOnClick: false
  39539. };
  39540. var baseUID = 0;
  39541. /**
  39542. * @alias module:echarts/component/helper/BrushController
  39543. * @constructor
  39544. * @mixin {module:zrender/mixin/Eventful}
  39545. * @event module:echarts/component/helper/BrushController#brush
  39546. * params:
  39547. * areas: Array.<Array>, coord relates to container group,
  39548. * If no container specified, to global.
  39549. * opt {
  39550. * isEnd: boolean,
  39551. * removeOnClick: boolean
  39552. * }
  39553. *
  39554. * @param {module:zrender/zrender~ZRender} zr
  39555. */
  39556. function BrushController(zr) {
  39557. if (__DEV__) {
  39558. assert(zr);
  39559. }
  39560. Eventful.call(this);
  39561. /**
  39562. * @type {module:zrender/zrender~ZRender}
  39563. * @private
  39564. */
  39565. this._zr = zr;
  39566. /**
  39567. * @type {module:zrender/container/Group}
  39568. * @readOnly
  39569. */
  39570. this.group = new Group();
  39571. /**
  39572. * Only for drawing (after enabledBrush).
  39573. * 'line', 'rect', 'polygon' or false
  39574. * If passing false/null/undefined, disable brush.
  39575. * If passing 'auto', determined by panel.defaultBrushType
  39576. * @private
  39577. * @type {string}
  39578. */
  39579. this._brushType;
  39580. /**
  39581. * Only for drawing (after enabledBrush).
  39582. *
  39583. * @private
  39584. * @type {Object}
  39585. */
  39586. this._brushOption;
  39587. /**
  39588. * @private
  39589. * @type {Object}
  39590. */
  39591. this._panels;
  39592. /**
  39593. * @private
  39594. * @type {Array.<nubmer>}
  39595. */
  39596. this._track = [];
  39597. /**
  39598. * @private
  39599. * @type {boolean}
  39600. */
  39601. this._dragging;
  39602. /**
  39603. * @private
  39604. * @type {Array}
  39605. */
  39606. this._covers = [];
  39607. /**
  39608. * @private
  39609. * @type {moudule:zrender/container/Group}
  39610. */
  39611. this._creatingCover;
  39612. /**
  39613. * `true` means global panel
  39614. * @private
  39615. * @type {module:zrender/container/Group|boolean}
  39616. */
  39617. this._creatingPanel;
  39618. /**
  39619. * @private
  39620. * @type {boolean}
  39621. */
  39622. this._enableGlobalPan;
  39623. /**
  39624. * @private
  39625. * @type {boolean}
  39626. */
  39627. if (__DEV__) {
  39628. this._mounted;
  39629. }
  39630. /**
  39631. * @private
  39632. * @type {string}
  39633. */
  39634. this._uid = 'brushController_' + baseUID++;
  39635. /**
  39636. * @private
  39637. * @type {Object}
  39638. */
  39639. this._handlers = {};
  39640. each$15(mouseHandlers, function (handler, eventName) {
  39641. this._handlers[eventName] = bind(handler, this);
  39642. }, this);
  39643. }
  39644. BrushController.prototype = {
  39645. constructor: BrushController,
  39646. /**
  39647. * If set to null/undefined/false, select disabled.
  39648. * @param {Object} brushOption
  39649. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  39650. * If passing false/null/undefined, disable brush.
  39651. * If passing 'auto', determined by panel.defaultBrushType.
  39652. * ('auto' can not be used in global panel)
  39653. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  39654. * @param {boolean} [brushOption.transformable=true]
  39655. * @param {boolean} [brushOption.removeOnClick=false]
  39656. * @param {Object} [brushOption.brushStyle]
  39657. * @param {number} [brushOption.brushStyle.width]
  39658. * @param {number} [brushOption.brushStyle.lineWidth]
  39659. * @param {string} [brushOption.brushStyle.stroke]
  39660. * @param {string} [brushOption.brushStyle.fill]
  39661. * @param {number} [brushOption.z]
  39662. */
  39663. enableBrush: function (brushOption) {
  39664. if (__DEV__) {
  39665. assert(this._mounted);
  39666. }
  39667. this._brushType && doDisableBrush(this);
  39668. brushOption.brushType && doEnableBrush(this, brushOption);
  39669. return this;
  39670. },
  39671. /**
  39672. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  39673. * Each items: {
  39674. * panelId, // mandatory.
  39675. * clipPath, // mandatory. function.
  39676. * isTargetByCursor, // mandatory. function.
  39677. * defaultBrushType, // optional, only used when brushType is 'auto'.
  39678. * getLinearBrushOtherExtent, // optional. function.
  39679. * }
  39680. */
  39681. setPanels: function (panelOpts) {
  39682. if (panelOpts && panelOpts.length) {
  39683. var panels = this._panels = {};
  39684. each$1(panelOpts, function (panelOpts) {
  39685. panels[panelOpts.panelId] = clone(panelOpts);
  39686. });
  39687. }
  39688. else {
  39689. this._panels = null;
  39690. }
  39691. return this;
  39692. },
  39693. /**
  39694. * @param {Object} [opt]
  39695. * @return {boolean} [opt.enableGlobalPan=false]
  39696. */
  39697. mount: function (opt) {
  39698. opt = opt || {};
  39699. if (__DEV__) {
  39700. this._mounted = true; // should be at first.
  39701. }
  39702. this._enableGlobalPan = opt.enableGlobalPan;
  39703. var thisGroup = this.group;
  39704. this._zr.add(thisGroup);
  39705. thisGroup.attr({
  39706. position: opt.position || [0, 0],
  39707. rotation: opt.rotation || 0,
  39708. scale: opt.scale || [1, 1]
  39709. });
  39710. this._transform = thisGroup.getLocalTransform();
  39711. return this;
  39712. },
  39713. eachCover: function (cb, context) {
  39714. each$15(this._covers, cb, context);
  39715. },
  39716. /**
  39717. * Update covers.
  39718. * @param {Array.<Object>} brushOptionList Like:
  39719. * [
  39720. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  39721. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  39722. * ...
  39723. * ]
  39724. * `brushType` is required in each cover info. (can not be 'auto')
  39725. * `id` is not mandatory.
  39726. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  39727. * If brushOptionList is null/undefined, all covers removed.
  39728. */
  39729. updateCovers: function (brushOptionList) {
  39730. if (__DEV__) {
  39731. assert(this._mounted);
  39732. }
  39733. brushOptionList = map(brushOptionList, function (brushOption) {
  39734. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  39735. });
  39736. var tmpIdPrefix = '\0-brush-index-';
  39737. var oldCovers = this._covers;
  39738. var newCovers = this._covers = [];
  39739. var controller = this;
  39740. var creatingCover = this._creatingCover;
  39741. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  39742. .add(addOrUpdate)
  39743. .update(addOrUpdate)
  39744. .remove(remove)
  39745. .execute();
  39746. return this;
  39747. function getKey(brushOption, index) {
  39748. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  39749. + '-' + brushOption.brushType;
  39750. }
  39751. function oldGetKey(cover, index) {
  39752. return getKey(cover.__brushOption, index);
  39753. }
  39754. function addOrUpdate(newIndex, oldIndex) {
  39755. var newBrushOption = brushOptionList[newIndex];
  39756. // Consider setOption in event listener of brushSelect,
  39757. // where updating cover when creating should be forbiden.
  39758. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  39759. newCovers[newIndex] = oldCovers[oldIndex];
  39760. }
  39761. else {
  39762. var cover = newCovers[newIndex] = oldIndex != null
  39763. ? (
  39764. oldCovers[oldIndex].__brushOption = newBrushOption,
  39765. oldCovers[oldIndex]
  39766. )
  39767. : endCreating(controller, createCover(controller, newBrushOption));
  39768. updateCoverAfterCreation(controller, cover);
  39769. }
  39770. }
  39771. function remove(oldIndex) {
  39772. if (oldCovers[oldIndex] !== creatingCover) {
  39773. controller.group.remove(oldCovers[oldIndex]);
  39774. }
  39775. }
  39776. },
  39777. unmount: function () {
  39778. if (__DEV__) {
  39779. if (!this._mounted) {
  39780. return;
  39781. }
  39782. }
  39783. this.enableBrush(false);
  39784. // container may 'removeAll' outside.
  39785. clearCovers(this);
  39786. this._zr.remove(this.group);
  39787. if (__DEV__) {
  39788. this._mounted = false; // should be at last.
  39789. }
  39790. return this;
  39791. },
  39792. dispose: function () {
  39793. this.unmount();
  39794. this.off();
  39795. }
  39796. };
  39797. mixin(BrushController, Eventful);
  39798. function doEnableBrush(controller, brushOption) {
  39799. var zr = controller._zr;
  39800. // Consider roam, which takes globalPan too.
  39801. if (!controller._enableGlobalPan) {
  39802. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  39803. }
  39804. each$15(controller._handlers, function (handler, eventName) {
  39805. zr.on(eventName, handler);
  39806. });
  39807. controller._brushType = brushOption.brushType;
  39808. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  39809. }
  39810. function doDisableBrush(controller) {
  39811. var zr = controller._zr;
  39812. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  39813. each$15(controller._handlers, function (handler, eventName) {
  39814. zr.off(eventName, handler);
  39815. });
  39816. controller._brushType = controller._brushOption = null;
  39817. }
  39818. function createCover(controller, brushOption) {
  39819. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  39820. cover.__brushOption = brushOption;
  39821. updateZ$1(cover, brushOption);
  39822. controller.group.add(cover);
  39823. return cover;
  39824. }
  39825. function endCreating(controller, creatingCover) {
  39826. var coverRenderer = getCoverRenderer(creatingCover);
  39827. if (coverRenderer.endCreating) {
  39828. coverRenderer.endCreating(controller, creatingCover);
  39829. updateZ$1(creatingCover, creatingCover.__brushOption);
  39830. }
  39831. return creatingCover;
  39832. }
  39833. function updateCoverShape(controller, cover) {
  39834. var brushOption = cover.__brushOption;
  39835. getCoverRenderer(cover).updateCoverShape(
  39836. controller, cover, brushOption.range, brushOption
  39837. );
  39838. }
  39839. function updateZ$1(cover, brushOption) {
  39840. var z = brushOption.z;
  39841. z == null && (z = COVER_Z);
  39842. cover.traverse(function (el) {
  39843. el.z = z;
  39844. el.z2 = z; // Consider in given container.
  39845. });
  39846. }
  39847. function updateCoverAfterCreation(controller, cover) {
  39848. getCoverRenderer(cover).updateCommon(controller, cover);
  39849. updateCoverShape(controller, cover);
  39850. }
  39851. function getCoverRenderer(cover) {
  39852. return coverRenderers[cover.__brushOption.brushType];
  39853. }
  39854. // return target panel or `true` (means global panel)
  39855. function getPanelByPoint(controller, e, localCursorPoint) {
  39856. var panels = controller._panels;
  39857. if (!panels) {
  39858. return true; // Global panel
  39859. }
  39860. var panel;
  39861. var transform = controller._transform;
  39862. each$15(panels, function (pn) {
  39863. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  39864. });
  39865. return panel;
  39866. }
  39867. // Return a panel or true
  39868. function getPanelByCover(controller, cover) {
  39869. var panels = controller._panels;
  39870. if (!panels) {
  39871. return true; // Global panel
  39872. }
  39873. var panelId = cover.__brushOption.panelId;
  39874. // User may give cover without coord sys info,
  39875. // which is then treated as global panel.
  39876. return panelId != null ? panels[panelId] : true;
  39877. }
  39878. function clearCovers(controller) {
  39879. var covers = controller._covers;
  39880. var originalLength = covers.length;
  39881. each$15(covers, function (cover) {
  39882. controller.group.remove(cover);
  39883. }, controller);
  39884. covers.length = 0;
  39885. return !!originalLength;
  39886. }
  39887. function trigger(controller, opt) {
  39888. var areas = map$3(controller._covers, function (cover) {
  39889. var brushOption = cover.__brushOption;
  39890. var range = clone(brushOption.range);
  39891. return {
  39892. brushType: brushOption.brushType,
  39893. panelId: brushOption.panelId,
  39894. range: range
  39895. };
  39896. });
  39897. controller.trigger('brush', areas, {
  39898. isEnd: !!opt.isEnd,
  39899. removeOnClick: !!opt.removeOnClick
  39900. });
  39901. }
  39902. function shouldShowCover(controller) {
  39903. var track = controller._track;
  39904. if (!track.length) {
  39905. return false;
  39906. }
  39907. var p2 = track[track.length - 1];
  39908. var p1 = track[0];
  39909. var dx = p2[0] - p1[0];
  39910. var dy = p2[1] - p1[1];
  39911. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  39912. return dist > UNSELECT_THRESHOLD;
  39913. }
  39914. function getTrackEnds(track) {
  39915. var tail = track.length - 1;
  39916. tail < 0 && (tail = 0);
  39917. return [track[0], track[tail]];
  39918. }
  39919. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  39920. var cover = new Group();
  39921. cover.add(new Rect({
  39922. name: 'main',
  39923. style: makeStyle(brushOption),
  39924. silent: true,
  39925. draggable: true,
  39926. cursor: 'move',
  39927. drift: curry$2(doDrift, controller, cover, 'nswe'),
  39928. ondragend: curry$2(trigger, controller, {isEnd: true})
  39929. }));
  39930. each$15(
  39931. edgeNames,
  39932. function (name) {
  39933. cover.add(new Rect({
  39934. name: name,
  39935. style: {opacity: 0},
  39936. draggable: true,
  39937. silent: true,
  39938. invisible: true,
  39939. drift: curry$2(doDrift, controller, cover, name),
  39940. ondragend: curry$2(trigger, controller, {isEnd: true})
  39941. }));
  39942. }
  39943. );
  39944. return cover;
  39945. }
  39946. function updateBaseRect(controller, cover, localRange, brushOption) {
  39947. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  39948. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  39949. var x = localRange[0][0];
  39950. var y = localRange[1][0];
  39951. var xa = x - lineWidth / 2;
  39952. var ya = y - lineWidth / 2;
  39953. var x2 = localRange[0][1];
  39954. var y2 = localRange[1][1];
  39955. var x2a = x2 - handleSize + lineWidth / 2;
  39956. var y2a = y2 - handleSize + lineWidth / 2;
  39957. var width = x2 - x;
  39958. var height = y2 - y;
  39959. var widtha = width + lineWidth;
  39960. var heighta = height + lineWidth;
  39961. updateRectShape(controller, cover, 'main', x, y, width, height);
  39962. if (brushOption.transformable) {
  39963. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  39964. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  39965. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  39966. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  39967. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  39968. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  39969. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  39970. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  39971. }
  39972. }
  39973. function updateCommon(controller, cover) {
  39974. var brushOption = cover.__brushOption;
  39975. var transformable = brushOption.transformable;
  39976. var mainEl = cover.childAt(0);
  39977. mainEl.useStyle(makeStyle(brushOption));
  39978. mainEl.attr({
  39979. silent: !transformable,
  39980. cursor: transformable ? 'move' : 'default'
  39981. });
  39982. each$15(
  39983. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  39984. function (name) {
  39985. var el = cover.childOfName(name);
  39986. var globalDir = getGlobalDirection(controller, name);
  39987. el && el.attr({
  39988. silent: !transformable,
  39989. invisible: !transformable,
  39990. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  39991. });
  39992. }
  39993. );
  39994. }
  39995. function updateRectShape(controller, cover, name, x, y, w, h) {
  39996. var el = cover.childOfName(name);
  39997. el && el.setShape(pointsToRect(
  39998. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  39999. ));
  40000. }
  40001. function makeStyle(brushOption) {
  40002. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  40003. }
  40004. function formatRectRange(x, y, x2, y2) {
  40005. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  40006. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  40007. return [
  40008. [min[0], max[0]], // x range
  40009. [min[1], max[1]] // y range
  40010. ];
  40011. }
  40012. function getTransform$1(controller) {
  40013. return getTransform(controller.group);
  40014. }
  40015. function getGlobalDirection(controller, localDirection) {
  40016. if (localDirection.length > 1) {
  40017. localDirection = localDirection.split('');
  40018. var globalDir = [
  40019. getGlobalDirection(controller, localDirection[0]),
  40020. getGlobalDirection(controller, localDirection[1])
  40021. ];
  40022. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  40023. return globalDir.join('');
  40024. }
  40025. else {
  40026. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  40027. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  40028. var globalDir = transformDirection(
  40029. map$$1[localDirection], getTransform$1(controller)
  40030. );
  40031. return inverseMap[globalDir];
  40032. }
  40033. }
  40034. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  40035. var brushOption = cover.__brushOption;
  40036. var rectRange = toRectRange(brushOption.range);
  40037. var localDelta = toLocalDelta(controller, dx, dy);
  40038. each$15(name.split(''), function (namePart) {
  40039. var ind = DIRECTION_MAP[namePart];
  40040. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  40041. });
  40042. brushOption.range = fromRectRange(formatRectRange(
  40043. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  40044. ));
  40045. updateCoverAfterCreation(controller, cover);
  40046. trigger(controller, {isEnd: false});
  40047. }
  40048. function driftPolygon(controller, cover, dx, dy, e) {
  40049. var range = cover.__brushOption.range;
  40050. var localDelta = toLocalDelta(controller, dx, dy);
  40051. each$15(range, function (point) {
  40052. point[0] += localDelta[0];
  40053. point[1] += localDelta[1];
  40054. });
  40055. updateCoverAfterCreation(controller, cover);
  40056. trigger(controller, {isEnd: false});
  40057. }
  40058. function toLocalDelta(controller, dx, dy) {
  40059. var thisGroup = controller.group;
  40060. var localD = thisGroup.transformCoordToLocal(dx, dy);
  40061. var localZero = thisGroup.transformCoordToLocal(0, 0);
  40062. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  40063. }
  40064. function clipByPanel(controller, cover, data) {
  40065. var panel = getPanelByCover(controller, cover);
  40066. return (panel && panel !== true)
  40067. ? panel.clipPath(data, controller._transform)
  40068. : clone(data);
  40069. }
  40070. function pointsToRect(points) {
  40071. var xmin = mathMin$6(points[0][0], points[1][0]);
  40072. var ymin = mathMin$6(points[0][1], points[1][1]);
  40073. var xmax = mathMax$6(points[0][0], points[1][0]);
  40074. var ymax = mathMax$6(points[0][1], points[1][1]);
  40075. return {
  40076. x: xmin,
  40077. y: ymin,
  40078. width: xmax - xmin,
  40079. height: ymax - ymin
  40080. };
  40081. }
  40082. function resetCursor(controller, e, localCursorPoint) {
  40083. // Check active
  40084. if (!controller._brushType) {
  40085. return;
  40086. }
  40087. var zr = controller._zr;
  40088. var covers = controller._covers;
  40089. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  40090. // Check whether in covers.
  40091. if (!controller._dragging) {
  40092. for (var i = 0; i < covers.length; i++) {
  40093. var brushOption = covers[i].__brushOption;
  40094. if (currPanel
  40095. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  40096. && coverRenderers[brushOption.brushType].contain(
  40097. covers[i], localCursorPoint[0], localCursorPoint[1]
  40098. )
  40099. ) {
  40100. // Use cursor style set on cover.
  40101. return;
  40102. }
  40103. }
  40104. }
  40105. currPanel && zr.setCursorStyle('crosshair');
  40106. }
  40107. function preventDefault(e) {
  40108. var rawE = e.event;
  40109. rawE.preventDefault && rawE.preventDefault();
  40110. }
  40111. function mainShapeContain(cover, x, y) {
  40112. return cover.childOfName('main').contain(x, y);
  40113. }
  40114. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  40115. var creatingCover = controller._creatingCover;
  40116. var panel = controller._creatingPanel;
  40117. var thisBrushOption = controller._brushOption;
  40118. var eventParams;
  40119. controller._track.push(localCursorPoint.slice());
  40120. if (shouldShowCover(controller) || creatingCover) {
  40121. if (panel && !creatingCover) {
  40122. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  40123. var brushOption = clone(thisBrushOption);
  40124. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  40125. brushOption.panelId = panel === true ? null : panel.panelId;
  40126. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  40127. controller._covers.push(creatingCover);
  40128. }
  40129. if (creatingCover) {
  40130. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  40131. var coverBrushOption = creatingCover.__brushOption;
  40132. coverBrushOption.range = coverRenderer.getCreatingRange(
  40133. clipByPanel(controller, creatingCover, controller._track)
  40134. );
  40135. if (isEnd) {
  40136. endCreating(controller, creatingCover);
  40137. coverRenderer.updateCommon(controller, creatingCover);
  40138. }
  40139. updateCoverShape(controller, creatingCover);
  40140. eventParams = {isEnd: isEnd};
  40141. }
  40142. }
  40143. else if (
  40144. isEnd
  40145. && thisBrushOption.brushMode === 'single'
  40146. && thisBrushOption.removeOnClick
  40147. ) {
  40148. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  40149. // But a single click do not clear covers, because user may have casual
  40150. // clicks (for example, click on other component and do not expect covers
  40151. // disappear).
  40152. // Only some cover removed, trigger action, but not every click trigger action.
  40153. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  40154. eventParams = {isEnd: isEnd, removeOnClick: true};
  40155. }
  40156. }
  40157. return eventParams;
  40158. }
  40159. function determineBrushType(brushType, panel) {
  40160. if (brushType === 'auto') {
  40161. if (__DEV__) {
  40162. assert(
  40163. panel && panel.defaultBrushType,
  40164. 'MUST have defaultBrushType when brushType is "atuo"'
  40165. );
  40166. }
  40167. return panel.defaultBrushType;
  40168. }
  40169. return brushType;
  40170. }
  40171. var mouseHandlers = {
  40172. mousedown: function (e) {
  40173. if (this._dragging) {
  40174. // In case some browser do not support globalOut,
  40175. // and release mose out side the browser.
  40176. handleDragEnd.call(this, e);
  40177. }
  40178. else if (!e.target || !e.target.draggable) {
  40179. preventDefault(e);
  40180. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40181. this._creatingCover = null;
  40182. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  40183. if (panel) {
  40184. this._dragging = true;
  40185. this._track = [localCursorPoint.slice()];
  40186. }
  40187. }
  40188. },
  40189. mousemove: function (e) {
  40190. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40191. resetCursor(this, e, localCursorPoint);
  40192. if (this._dragging) {
  40193. preventDefault(e);
  40194. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  40195. eventParams && trigger(this, eventParams);
  40196. }
  40197. },
  40198. mouseup: handleDragEnd //,
  40199. // FIXME
  40200. // in tooltip, globalout should not be triggered.
  40201. // globalout: handleDragEnd
  40202. };
  40203. function handleDragEnd(e) {
  40204. if (this._dragging) {
  40205. preventDefault(e);
  40206. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40207. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  40208. this._dragging = false;
  40209. this._track = [];
  40210. this._creatingCover = null;
  40211. // trigger event shoule be at final, after procedure will be nested.
  40212. eventParams && trigger(this, eventParams);
  40213. }
  40214. }
  40215. /**
  40216. * key: brushType
  40217. * @type {Object}
  40218. */
  40219. var coverRenderers = {
  40220. lineX: getLineRenderer(0),
  40221. lineY: getLineRenderer(1),
  40222. rect: {
  40223. createCover: function (controller, brushOption) {
  40224. return createBaseRectCover(
  40225. curry$2(
  40226. driftRect,
  40227. function (range) {
  40228. return range;
  40229. },
  40230. function (range) {
  40231. return range;
  40232. }
  40233. ),
  40234. controller,
  40235. brushOption,
  40236. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  40237. );
  40238. },
  40239. getCreatingRange: function (localTrack) {
  40240. var ends = getTrackEnds(localTrack);
  40241. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  40242. },
  40243. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40244. updateBaseRect(controller, cover, localRange, brushOption);
  40245. },
  40246. updateCommon: updateCommon,
  40247. contain: mainShapeContain
  40248. },
  40249. polygon: {
  40250. createCover: function (controller, brushOption) {
  40251. var cover = new Group();
  40252. // Do not use graphic.Polygon because graphic.Polyline do not close the
  40253. // border of the shape when drawing, which is a better experience for user.
  40254. cover.add(new Polyline({
  40255. name: 'main',
  40256. style: makeStyle(brushOption),
  40257. silent: true
  40258. }));
  40259. return cover;
  40260. },
  40261. getCreatingRange: function (localTrack) {
  40262. return localTrack;
  40263. },
  40264. endCreating: function (controller, cover) {
  40265. cover.remove(cover.childAt(0));
  40266. // Use graphic.Polygon close the shape.
  40267. cover.add(new Polygon({
  40268. name: 'main',
  40269. draggable: true,
  40270. drift: curry$2(driftPolygon, controller, cover),
  40271. ondragend: curry$2(trigger, controller, {isEnd: true})
  40272. }));
  40273. },
  40274. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40275. cover.childAt(0).setShape({
  40276. points: clipByPanel(controller, cover, localRange)
  40277. });
  40278. },
  40279. updateCommon: updateCommon,
  40280. contain: mainShapeContain
  40281. }
  40282. };
  40283. function getLineRenderer(xyIndex) {
  40284. return {
  40285. createCover: function (controller, brushOption) {
  40286. return createBaseRectCover(
  40287. curry$2(
  40288. driftRect,
  40289. function (range) {
  40290. var rectRange = [range, [0, 100]];
  40291. xyIndex && rectRange.reverse();
  40292. return rectRange;
  40293. },
  40294. function (rectRange) {
  40295. return rectRange[xyIndex];
  40296. }
  40297. ),
  40298. controller,
  40299. brushOption,
  40300. [['w', 'e'], ['n', 's']][xyIndex]
  40301. );
  40302. },
  40303. getCreatingRange: function (localTrack) {
  40304. var ends = getTrackEnds(localTrack);
  40305. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  40306. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  40307. return [min, max];
  40308. },
  40309. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40310. var otherExtent;
  40311. // If brushWidth not specified, fit the panel.
  40312. var panel = getPanelByCover(controller, cover);
  40313. if (panel !== true && panel.getLinearBrushOtherExtent) {
  40314. otherExtent = panel.getLinearBrushOtherExtent(
  40315. xyIndex, controller._transform
  40316. );
  40317. }
  40318. else {
  40319. var zr = controller._zr;
  40320. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  40321. }
  40322. var rectRange = [localRange, otherExtent];
  40323. xyIndex && rectRange.reverse();
  40324. updateBaseRect(controller, cover, rectRange, brushOption);
  40325. },
  40326. updateCommon: updateCommon,
  40327. contain: mainShapeContain
  40328. };
  40329. }
  40330. function makeRectPanelClipPath(rect) {
  40331. rect = normalizeRect(rect);
  40332. return function (localPoints, transform) {
  40333. return clipPointsByRect(localPoints, rect);
  40334. };
  40335. }
  40336. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  40337. rect = normalizeRect(rect);
  40338. return function (xyIndex) {
  40339. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  40340. var brushWidth = idx ? rect.width : rect.height;
  40341. var base = idx ? rect.x : rect.y;
  40342. return [base, base + (brushWidth || 0)];
  40343. };
  40344. }
  40345. function makeRectIsTargetByCursor(rect, api, targetModel) {
  40346. rect = normalizeRect(rect);
  40347. return function (e, localCursorPoint, transform) {
  40348. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  40349. && !onIrrelevantElement(e, api, targetModel);
  40350. };
  40351. }
  40352. // Consider width/height is negative.
  40353. function normalizeRect(rect) {
  40354. return BoundingRect.create(rect);
  40355. }
  40356. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  40357. var AxisView$2 = extendComponentView({
  40358. type: 'parallelAxis',
  40359. /**
  40360. * @override
  40361. */
  40362. init: function (ecModel, api) {
  40363. AxisView$2.superApply(this, 'init', arguments);
  40364. /**
  40365. * @type {module:echarts/component/helper/BrushController}
  40366. */
  40367. (this._brushController = new BrushController(api.getZr()))
  40368. .on('brush', bind(this._onBrush, this));
  40369. },
  40370. /**
  40371. * @override
  40372. */
  40373. render: function (axisModel, ecModel, api, payload) {
  40374. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  40375. return;
  40376. }
  40377. this.axisModel = axisModel;
  40378. this.api = api;
  40379. this.group.removeAll();
  40380. var oldAxisGroup = this._axisGroup;
  40381. this._axisGroup = new Group();
  40382. this.group.add(this._axisGroup);
  40383. if (!axisModel.get('show')) {
  40384. return;
  40385. }
  40386. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  40387. var coordSys = coordSysModel.coordinateSystem;
  40388. var areaSelectStyle = axisModel.getAreaSelectStyle();
  40389. var areaWidth = areaSelectStyle.width;
  40390. var dim = axisModel.axis.dim;
  40391. var axisLayout = coordSys.getAxisLayout(dim);
  40392. var builderOpt = extend(
  40393. {strokeContainThreshold: areaWidth},
  40394. axisLayout
  40395. );
  40396. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  40397. each$1(elementList, axisBuilder.add, axisBuilder);
  40398. this._axisGroup.add(axisBuilder.getGroup());
  40399. this._refreshBrushController(
  40400. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  40401. );
  40402. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  40403. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  40404. },
  40405. /**
  40406. * @override
  40407. */
  40408. updateVisual: function (axisModel, ecModel, api, payload) {
  40409. this._brushController && this._brushController
  40410. .updateCovers(getCoverInfoList(axisModel));
  40411. },
  40412. _refreshBrushController: function (
  40413. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  40414. ) {
  40415. // After filtering, axis may change, select area needs to be update.
  40416. var extent = axisModel.axis.getExtent();
  40417. var extentLen = extent[1] - extent[0];
  40418. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  40419. // width/height might be negative, which will be
  40420. // normalized in BoundingRect.
  40421. var rect = BoundingRect.create({
  40422. x: extent[0],
  40423. y: -areaWidth / 2,
  40424. width: extentLen,
  40425. height: areaWidth
  40426. });
  40427. rect.x -= extra;
  40428. rect.width += 2 * extra;
  40429. this._brushController
  40430. .mount({
  40431. enableGlobalPan: true,
  40432. rotation: builderOpt.rotation,
  40433. position: builderOpt.position
  40434. })
  40435. .setPanels([{
  40436. panelId: 'pl',
  40437. clipPath: makeRectPanelClipPath(rect),
  40438. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  40439. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  40440. }])
  40441. .enableBrush({
  40442. brushType: 'lineX',
  40443. brushStyle: areaSelectStyle,
  40444. removeOnClick: true
  40445. })
  40446. .updateCovers(getCoverInfoList(axisModel));
  40447. },
  40448. _onBrush: function (coverInfoList, opt) {
  40449. // Do not cache these object, because the mey be changed.
  40450. var axisModel = this.axisModel;
  40451. var axis = axisModel.axis;
  40452. var intervals = map(coverInfoList, function (coverInfo) {
  40453. return [
  40454. axis.coordToData(coverInfo.range[0], true),
  40455. axis.coordToData(coverInfo.range[1], true)
  40456. ];
  40457. });
  40458. // If realtime is true, action is not dispatched on drag end, because
  40459. // the drag end emits the same params with the last drag move event,
  40460. // and may have some delay when using touch pad.
  40461. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  40462. this.api.dispatchAction({
  40463. type: 'axisAreaSelect',
  40464. parallelAxisId: axisModel.id,
  40465. intervals: intervals
  40466. });
  40467. }
  40468. },
  40469. /**
  40470. * @override
  40471. */
  40472. dispose: function () {
  40473. this._brushController.dispose();
  40474. }
  40475. });
  40476. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  40477. return payload
  40478. && payload.type === 'axisAreaSelect'
  40479. && ecModel.findComponents(
  40480. {mainType: 'parallelAxis', query: payload}
  40481. )[0] === axisModel;
  40482. }
  40483. function getCoverInfoList(axisModel) {
  40484. var axis = axisModel.axis;
  40485. return map(axisModel.activeIntervals, function (interval) {
  40486. return {
  40487. brushType: 'lineX',
  40488. panelId: 'pl',
  40489. range: [
  40490. axis.dataToCoord(interval[0], true),
  40491. axis.dataToCoord(interval[1], true)
  40492. ]
  40493. };
  40494. });
  40495. }
  40496. function getCoordSysModel(axisModel, ecModel) {
  40497. return ecModel.getComponent(
  40498. 'parallel', axisModel.get('parallelIndex')
  40499. );
  40500. }
  40501. var CLICK_THRESHOLD = 5; // > 4
  40502. // Parallel view
  40503. extendComponentView({
  40504. type: 'parallel',
  40505. render: function (parallelModel, ecModel, api) {
  40506. this._model = parallelModel;
  40507. this._api = api;
  40508. if (!this._handlers) {
  40509. this._handlers = {};
  40510. each$1(handlers, function (handler, eventName) {
  40511. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  40512. }, this);
  40513. }
  40514. createOrUpdate(
  40515. this,
  40516. '_throttledDispatchExpand',
  40517. parallelModel.get('axisExpandRate'),
  40518. 'fixRate'
  40519. );
  40520. },
  40521. dispose: function (ecModel, api) {
  40522. each$1(this._handlers, function (handler, eventName) {
  40523. api.getZr().off(eventName, handler);
  40524. });
  40525. this._handlers = null;
  40526. },
  40527. /**
  40528. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  40529. */
  40530. _throttledDispatchExpand: function (opt) {
  40531. this._dispatchExpand(opt);
  40532. },
  40533. _dispatchExpand: function (opt) {
  40534. opt && this._api.dispatchAction(
  40535. extend({type: 'parallelAxisExpand'}, opt)
  40536. );
  40537. }
  40538. });
  40539. var handlers = {
  40540. mousedown: function (e) {
  40541. if (checkTrigger(this, 'click')) {
  40542. this._mouseDownPoint = [e.offsetX, e.offsetY];
  40543. }
  40544. },
  40545. mouseup: function (e) {
  40546. var mouseDownPoint = this._mouseDownPoint;
  40547. if (checkTrigger(this, 'click') && mouseDownPoint) {
  40548. var point = [e.offsetX, e.offsetY];
  40549. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  40550. + Math.pow(mouseDownPoint[1] - point[1], 2);
  40551. if (dist > CLICK_THRESHOLD) {
  40552. return;
  40553. }
  40554. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  40555. [e.offsetX, e.offsetY]
  40556. );
  40557. result.behavior !== 'none' && this._dispatchExpand({
  40558. axisExpandWindow: result.axisExpandWindow
  40559. });
  40560. }
  40561. this._mouseDownPoint = null;
  40562. },
  40563. mousemove: function (e) {
  40564. // Should do nothing when brushing.
  40565. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  40566. return;
  40567. }
  40568. var model = this._model;
  40569. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  40570. [e.offsetX, e.offsetY]
  40571. );
  40572. var behavior = result.behavior;
  40573. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  40574. this._throttledDispatchExpand(
  40575. behavior === 'none'
  40576. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  40577. : {
  40578. axisExpandWindow: result.axisExpandWindow,
  40579. // Jumping uses animation, and sliding suppresses animation.
  40580. animation: behavior === 'jump' ? null : false
  40581. }
  40582. );
  40583. }
  40584. };
  40585. function checkTrigger(view, triggerOn) {
  40586. var model = view._model;
  40587. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  40588. }
  40589. registerPreprocessor(parallelPreprocessor);
  40590. SeriesModel.extend({
  40591. type: 'series.parallel',
  40592. dependencies: ['parallel'],
  40593. visualColorAccessPath: 'lineStyle.normal.color',
  40594. getInitialData: function (option, ecModel) {
  40595. var parallelModel = ecModel.getComponent(
  40596. 'parallel', this.get('parallelIndex')
  40597. );
  40598. var parallelAxisIndices = parallelModel.parallelAxisIndex;
  40599. var rawData = option.data;
  40600. var modelDims = parallelModel.dimensions;
  40601. var dataDims = generateDataDims(modelDims, rawData);
  40602. var dataDimsInfo = map(dataDims, function (dim, dimIndex) {
  40603. var modelDimsIndex = indexOf(modelDims, dim);
  40604. var axisModel = modelDimsIndex >= 0 && ecModel.getComponent(
  40605. 'parallelAxis', parallelAxisIndices[modelDimsIndex]
  40606. );
  40607. if (axisModel && axisModel.get('type') === 'category') {
  40608. translateCategoryValue(axisModel, dim, rawData);
  40609. return {name: dim, type: 'ordinal'};
  40610. }
  40611. else if (modelDimsIndex < 0) {
  40612. return completeDimensions.guessOrdinal(rawData, dimIndex)
  40613. ? {name: dim, type: 'ordinal'}
  40614. : dim;
  40615. }
  40616. else {
  40617. return dim;
  40618. }
  40619. });
  40620. var list = new List(dataDimsInfo, this);
  40621. list.initData(rawData);
  40622. // Anication is forbiden in progressive data mode.
  40623. if (this.option.progressive) {
  40624. this.option.animation = false;
  40625. }
  40626. return list;
  40627. },
  40628. /**
  40629. * User can get data raw indices on 'axisAreaSelected' event received.
  40630. *
  40631. * @public
  40632. * @param {string} activeState 'active' or 'inactive' or 'normal'
  40633. * @return {Array.<number>} Raw indices
  40634. */
  40635. getRawIndicesByActiveState: function (activeState) {
  40636. var coordSys = this.coordinateSystem;
  40637. var data = this.getData();
  40638. var indices = [];
  40639. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  40640. if (activeState === theActiveState) {
  40641. indices.push(data.getRawIndex(dataIndex));
  40642. }
  40643. });
  40644. return indices;
  40645. },
  40646. defaultOption: {
  40647. zlevel: 0, // 一级层叠
  40648. z: 2, // 二级层叠
  40649. coordinateSystem: 'parallel',
  40650. parallelIndex: 0,
  40651. label: {
  40652. normal: {
  40653. show: false
  40654. },
  40655. emphasis: {
  40656. show: false
  40657. }
  40658. },
  40659. inactiveOpacity: 0.05,
  40660. activeOpacity: 1,
  40661. lineStyle: {
  40662. normal: {
  40663. width: 1,
  40664. opacity: 0.45,
  40665. type: 'solid'
  40666. }
  40667. },
  40668. progressive: false, // 100
  40669. smooth: false,
  40670. animationEasing: 'linear'
  40671. }
  40672. });
  40673. function translateCategoryValue(axisModel, dim, rawData) {
  40674. var axisData = axisModel.get('data');
  40675. var numberDim = convertDimNameToNumber(dim);
  40676. if (axisData && axisData.length) {
  40677. each$1(rawData, function (dataItem) {
  40678. if (!dataItem) {
  40679. return;
  40680. }
  40681. // FIXME
  40682. // time consuming, should use hash?
  40683. var index = indexOf(axisData, dataItem[numberDim]);
  40684. dataItem[numberDim] = index >= 0 ? index : NaN;
  40685. });
  40686. }
  40687. // FIXME
  40688. // 如果没有设置axis data, 应自动算出,或者提示。
  40689. }
  40690. function convertDimNameToNumber(dimName) {
  40691. return +dimName.replace('dim', '');
  40692. }
  40693. function generateDataDims(modelDims, rawData) {
  40694. // parallelModel.dimension should not be regarded as data
  40695. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  40696. // We detect max dim by parallelModel.dimensions and fist
  40697. // item in rawData arbitrarily.
  40698. var maxDimNum = 0;
  40699. each$1(modelDims, function (dimName) {
  40700. var numberDim = convertDimNameToNumber(dimName);
  40701. numberDim > maxDimNum && (maxDimNum = numberDim);
  40702. });
  40703. var firstItem = rawData[0];
  40704. if (firstItem && firstItem.length - 1 > maxDimNum) {
  40705. maxDimNum = firstItem.length - 1;
  40706. }
  40707. var dataDims = [];
  40708. for (var i = 0; i <= maxDimNum; i++) {
  40709. dataDims.push('dim' + i);
  40710. }
  40711. return dataDims;
  40712. }
  40713. var SMOOTH = 0.3;
  40714. var ParallelView = Chart.extend({
  40715. type: 'parallel',
  40716. init: function () {
  40717. /**
  40718. * @type {module:zrender/container/Group}
  40719. * @private
  40720. */
  40721. this._dataGroup = new Group();
  40722. this.group.add(this._dataGroup);
  40723. /**
  40724. * @type {module:echarts/data/List}
  40725. */
  40726. this._data;
  40727. },
  40728. /**
  40729. * @override
  40730. */
  40731. render: function (seriesModel, ecModel, api, payload) {
  40732. this._renderForNormal(seriesModel, payload);
  40733. // this[
  40734. // seriesModel.option.progressive
  40735. // ? '_renderForProgressive'
  40736. // : '_renderForNormal'
  40737. // ](seriesModel);
  40738. },
  40739. dispose: function () {},
  40740. /**
  40741. * @private
  40742. */
  40743. _renderForNormal: function (seriesModel, payload) {
  40744. var dataGroup = this._dataGroup;
  40745. var data = seriesModel.getData();
  40746. var oldData = this._data;
  40747. var coordSys = seriesModel.coordinateSystem;
  40748. var dimensions = coordSys.dimensions;
  40749. var option = seriesModel.option;
  40750. var smooth = option.smooth ? SMOOTH : null;
  40751. // Consider switch between progressive and not.
  40752. // oldData && oldData.__plProgressive && dataGroup.removeAll();
  40753. data.diff(oldData)
  40754. .add(add)
  40755. .update(update)
  40756. .remove(remove)
  40757. .execute();
  40758. // Update style
  40759. updateElCommon(data, smooth);
  40760. // First create
  40761. if (!this._data) {
  40762. var clipPath = createGridClipShape$1(
  40763. coordSys, seriesModel, function () {
  40764. // Callback will be invoked immediately if there is no animation
  40765. setTimeout(function () {
  40766. dataGroup.removeClipPath();
  40767. });
  40768. }
  40769. );
  40770. dataGroup.setClipPath(clipPath);
  40771. }
  40772. this._data = data;
  40773. function add(newDataIndex) {
  40774. addEl(data, dataGroup, newDataIndex, dimensions, coordSys, null, smooth);
  40775. }
  40776. function update(newDataIndex, oldDataIndex) {
  40777. var line = oldData.getItemGraphicEl(oldDataIndex);
  40778. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  40779. data.setItemGraphicEl(newDataIndex, line);
  40780. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  40781. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  40782. }
  40783. function remove(oldDataIndex) {
  40784. var line = oldData.getItemGraphicEl(oldDataIndex);
  40785. dataGroup.remove(line);
  40786. }
  40787. },
  40788. /**
  40789. * @private
  40790. */
  40791. // _renderForProgressive: function (seriesModel) {
  40792. // var dataGroup = this._dataGroup;
  40793. // var data = seriesModel.getData();
  40794. // var oldData = this._data;
  40795. // var coordSys = seriesModel.coordinateSystem;
  40796. // var dimensions = coordSys.dimensions;
  40797. // var option = seriesModel.option;
  40798. // var progressive = option.progressive;
  40799. // var smooth = option.smooth ? SMOOTH : null;
  40800. // // In progressive animation is disabled, so use simple data diff,
  40801. // // which effects performance less.
  40802. // // (Typically performance for data with length 7000+ like:
  40803. // // simpleDiff: 60ms, addEl: 184ms,
  40804. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  40805. // if (simpleDiff(oldData, data, dimensions)) {
  40806. // dataGroup.removeAll();
  40807. // data.each(function (dataIndex) {
  40808. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  40809. // });
  40810. // }
  40811. // updateElCommon(data, progressive, smooth);
  40812. // // Consider switch between progressive and not.
  40813. // data.__plProgressive = true;
  40814. // this._data = data;
  40815. // },
  40816. /**
  40817. * @override
  40818. */
  40819. remove: function () {
  40820. this._dataGroup && this._dataGroup.removeAll();
  40821. this._data = null;
  40822. }
  40823. });
  40824. function createGridClipShape$1(coordSys, seriesModel, cb) {
  40825. var parallelModel = coordSys.model;
  40826. var rect = coordSys.getRect();
  40827. var rectEl = new Rect({
  40828. shape: {
  40829. x: rect.x,
  40830. y: rect.y,
  40831. width: rect.width,
  40832. height: rect.height
  40833. }
  40834. });
  40835. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  40836. rectEl.setShape(dim, 0);
  40837. initProps(rectEl, {
  40838. shape: {
  40839. width: rect.width,
  40840. height: rect.height
  40841. }
  40842. }, seriesModel, cb);
  40843. return rectEl;
  40844. }
  40845. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  40846. var points = [];
  40847. for (var i = 0; i < dimensions.length; i++) {
  40848. var dimName = dimensions[i];
  40849. var value = data.get(dimName, dataIndex);
  40850. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  40851. points.push(coordSys.dataToPoint(value, dimName));
  40852. }
  40853. }
  40854. return points;
  40855. }
  40856. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  40857. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  40858. var line = new Polyline({
  40859. shape: {points: points},
  40860. silent: true,
  40861. z2: 10
  40862. });
  40863. dataGroup.add(line);
  40864. data.setItemGraphicEl(dataIndex, line);
  40865. }
  40866. function updateElCommon(data, smooth) {
  40867. var seriesStyleModel = data.hostModel.getModel('lineStyle.normal');
  40868. var lineStyle = seriesStyleModel.getLineStyle();
  40869. data.eachItemGraphicEl(function (line, dataIndex) {
  40870. if (data.hasItemOption) {
  40871. var itemModel = data.getItemModel(dataIndex);
  40872. var lineStyleModel = itemModel.getModel('lineStyle.normal', seriesStyleModel);
  40873. lineStyle = lineStyleModel.getLineStyle(['color', 'stroke']);
  40874. }
  40875. line.useStyle(extend(lineStyle, {
  40876. fill: null,
  40877. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  40878. stroke: data.getItemVisual(dataIndex, 'color'),
  40879. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  40880. opacity: data.getItemVisual(dataIndex, 'opacity')
  40881. }));
  40882. line.shape.smooth = smooth;
  40883. });
  40884. }
  40885. // function simpleDiff(oldData, newData, dimensions) {
  40886. // var oldLen;
  40887. // if (!oldData
  40888. // || !oldData.__plProgressive
  40889. // || (oldLen = oldData.count()) !== newData.count()
  40890. // ) {
  40891. // return true;
  40892. // }
  40893. // var dimLen = dimensions.length;
  40894. // for (var i = 0; i < oldLen; i++) {
  40895. // for (var j = 0; j < dimLen; j++) {
  40896. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  40897. // return true;
  40898. // }
  40899. // }
  40900. // }
  40901. // return false;
  40902. // }
  40903. // FIXME
  40904. // 公用方法?
  40905. function isEmptyValue(val, axisType) {
  40906. return axisType === 'category'
  40907. ? val == null
  40908. : (val == null || isNaN(val)); // axisType === 'value'
  40909. }
  40910. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  40911. var parallelVisual = function (ecModel) {
  40912. ecModel.eachSeriesByType('parallel', function (seriesModel) {
  40913. var itemStyleModel = seriesModel.getModel('itemStyle.normal');
  40914. var lineStyleModel = seriesModel.getModel('lineStyle.normal');
  40915. var globalColors = ecModel.get('color');
  40916. var color = lineStyleModel.get('color')
  40917. || itemStyleModel.get('color')
  40918. || globalColors[seriesModel.seriesIndex % globalColors.length];
  40919. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  40920. var activeOpacity = seriesModel.get('activeOpacity');
  40921. var lineStyle = seriesModel.getModel('lineStyle.normal').getLineStyle();
  40922. var coordSys = seriesModel.coordinateSystem;
  40923. var data = seriesModel.getData();
  40924. var opacityMap = {
  40925. normal: lineStyle.opacity,
  40926. active: activeOpacity,
  40927. inactive: inactiveOpacity
  40928. };
  40929. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  40930. var itemModel = data.getItemModel(dataIndex);
  40931. var opacity = opacityMap[activeState];
  40932. if (activeState === 'normal') {
  40933. var itemOpacity = itemModel.get(opacityAccessPath$1, true);
  40934. itemOpacity != null && (opacity = itemOpacity);
  40935. }
  40936. data.setItemVisual(dataIndex, 'opacity', opacity);
  40937. });
  40938. data.setVisual('color', color);
  40939. });
  40940. };
  40941. registerVisual(parallelVisual);
  40942. /**
  40943. * @file Get initial data and define sankey view's series model
  40944. * @author Deqing Li(annong035@gmail.com)
  40945. */
  40946. var SankeySeries = SeriesModel.extend({
  40947. type: 'series.sankey',
  40948. layoutInfo: null,
  40949. /**
  40950. * Init a graph data structure from data in option series
  40951. *
  40952. * @param {Object} option the object used to config echarts view
  40953. * @return {module:echarts/data/List} storage initial data
  40954. */
  40955. getInitialData: function (option) {
  40956. var links = option.edges || option.links;
  40957. var nodes = option.data || option.nodes;
  40958. if (nodes && links) {
  40959. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  40960. return graph.data;
  40961. }
  40962. },
  40963. /**
  40964. * Return the graphic data structure
  40965. *
  40966. * @return {module:echarts/data/Graph} graphic data structure
  40967. */
  40968. getGraph: function () {
  40969. return this.getData().graph;
  40970. },
  40971. /**
  40972. * Get edge data of graphic data structure
  40973. *
  40974. * @return {module:echarts/data/List} data structure of list
  40975. */
  40976. getEdgeData: function () {
  40977. return this.getGraph().edgeData;
  40978. },
  40979. /**
  40980. * @override
  40981. */
  40982. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  40983. // dataType === 'node' or empty do not show tooltip by default
  40984. if (dataType === 'edge') {
  40985. var params = this.getDataParams(dataIndex, dataType);
  40986. var rawDataOpt = params.data;
  40987. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  40988. if (params.value) {
  40989. html += ' : ' + params.value;
  40990. }
  40991. return encodeHTML(html);
  40992. }
  40993. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  40994. },
  40995. defaultOption: {
  40996. zlevel: 0,
  40997. z: 2,
  40998. coordinateSystem: 'view',
  40999. layout: null,
  41000. // the position of the whole view
  41001. left: '5%',
  41002. top: '5%',
  41003. right: '20%',
  41004. bottom: '5%',
  41005. // the dx of the node
  41006. nodeWidth: 20,
  41007. // the vertical distance between two nodes
  41008. nodeGap: 8,
  41009. // the number of iterations to change the position of the node
  41010. layoutIterations: 32,
  41011. label: {
  41012. normal: {
  41013. show: true,
  41014. position: 'right',
  41015. color: '#000',
  41016. fontSize: 12
  41017. },
  41018. emphasis: {
  41019. show: true
  41020. }
  41021. },
  41022. itemStyle: {
  41023. normal: {
  41024. borderWidth: 1,
  41025. borderColor: '#333'
  41026. }
  41027. },
  41028. lineStyle: {
  41029. normal: {
  41030. color: '#314656',
  41031. opacity: 0.2,
  41032. curveness: 0.5
  41033. },
  41034. emphasis: {
  41035. opacity: 0.6
  41036. }
  41037. },
  41038. animationEasing: 'linear',
  41039. animationDuration: 1000
  41040. }
  41041. });
  41042. /**
  41043. * @file The file used to draw sankey view
  41044. * @author Deqing Li(annong035@gmail.com)
  41045. */
  41046. var SankeyShape = extendShape({
  41047. shape: {
  41048. x1: 0, y1: 0,
  41049. x2: 0, y2: 0,
  41050. cpx1: 0, cpy1: 0,
  41051. cpx2: 0, cpy2: 0,
  41052. extent: 0
  41053. },
  41054. buildPath: function (ctx, shape) {
  41055. var halfExtent = shape.extent / 2;
  41056. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  41057. ctx.bezierCurveTo(
  41058. shape.cpx1, shape.cpy1 - halfExtent,
  41059. shape.cpx2, shape.cpy2 - halfExtent,
  41060. shape.x2, shape.y2 - halfExtent
  41061. );
  41062. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  41063. ctx.bezierCurveTo(
  41064. shape.cpx2, shape.cpy2 + halfExtent,
  41065. shape.cpx1, shape.cpy1 + halfExtent,
  41066. shape.x1, shape.y1 + halfExtent
  41067. );
  41068. ctx.closePath();
  41069. }
  41070. });
  41071. extendChartView({
  41072. type: 'sankey',
  41073. /**
  41074. * @private
  41075. * @type {module:echarts/chart/sankey/SankeySeries}
  41076. */
  41077. _model: null,
  41078. render: function (seriesModel, ecModel, api) {
  41079. var graph = seriesModel.getGraph();
  41080. var group = this.group;
  41081. var layoutInfo = seriesModel.layoutInfo;
  41082. var nodeData = seriesModel.getData();
  41083. var edgeData = seriesModel.getData('edge');
  41084. this._model = seriesModel;
  41085. group.removeAll();
  41086. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  41087. // generate a bezire Curve for each edge
  41088. graph.eachEdge(function (edge) {
  41089. var curve = new SankeyShape();
  41090. curve.dataIndex = edge.dataIndex;
  41091. curve.seriesIndex = seriesModel.seriesIndex;
  41092. curve.dataType = 'edge';
  41093. var lineStyleModel = edge.getModel('lineStyle.normal');
  41094. var curvature = lineStyleModel.get('curveness');
  41095. var n1Layout = edge.node1.getLayout();
  41096. var n2Layout = edge.node2.getLayout();
  41097. var edgeLayout = edge.getLayout();
  41098. curve.shape.extent = Math.max(1, edgeLayout.dy);
  41099. var x1 = n1Layout.x + n1Layout.dx;
  41100. var y1 = n1Layout.y + edgeLayout.sy + edgeLayout.dy / 2;
  41101. var x2 = n2Layout.x;
  41102. var y2 = n2Layout.y + edgeLayout.ty + edgeLayout.dy / 2;
  41103. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  41104. var cpy1 = y1;
  41105. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  41106. var cpy2 = y2;
  41107. curve.setShape({
  41108. x1: x1,
  41109. y1: y1,
  41110. x2: x2,
  41111. y2: y2,
  41112. cpx1: cpx1,
  41113. cpy1: cpy1,
  41114. cpx2: cpx2,
  41115. cpy2: cpy2
  41116. });
  41117. curve.setStyle(lineStyleModel.getItemStyle());
  41118. // Special color, use source node color or target node color
  41119. switch (curve.style.fill) {
  41120. case 'source':
  41121. curve.style.fill = edge.node1.getVisual('color');
  41122. break;
  41123. case 'target':
  41124. curve.style.fill = edge.node2.getVisual('color');
  41125. break;
  41126. }
  41127. setHoverStyle(curve, edge.getModel('lineStyle.emphasis').getItemStyle());
  41128. group.add(curve);
  41129. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  41130. });
  41131. // generate a rect for each node
  41132. graph.eachNode(function (node) {
  41133. var layout = node.getLayout();
  41134. var itemModel = node.getModel();
  41135. var labelModel = itemModel.getModel('label.normal');
  41136. var labelHoverModel = itemModel.getModel('label.emphasis');
  41137. var rect = new Rect({
  41138. shape: {
  41139. x: layout.x,
  41140. y: layout.y,
  41141. width: node.getLayout().dx,
  41142. height: node.getLayout().dy
  41143. },
  41144. style: itemModel.getModel('itemStyle.normal').getItemStyle()
  41145. });
  41146. var hoverStyle = node.getModel('itemStyle.emphasis').getItemStyle();
  41147. setLabelStyle(
  41148. rect.style, hoverStyle, labelModel, labelHoverModel,
  41149. {
  41150. labelFetcher: seriesModel,
  41151. labelDataIndex: node.dataIndex,
  41152. defaultText: node.id,
  41153. isRectText: true
  41154. }
  41155. );
  41156. rect.setStyle('fill', node.getVisual('color'));
  41157. setHoverStyle(rect, hoverStyle);
  41158. group.add(rect);
  41159. nodeData.setItemGraphicEl(node.dataIndex, rect);
  41160. rect.dataType = 'node';
  41161. });
  41162. if (!this._data && seriesModel.get('animation')) {
  41163. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  41164. group.removeClipPath();
  41165. }));
  41166. }
  41167. this._data = seriesModel.getData();
  41168. },
  41169. dispose: function () {}
  41170. });
  41171. // add animation to the view
  41172. function createGridClipShape$2(rect, seriesModel, cb) {
  41173. var rectEl = new Rect({
  41174. shape: {
  41175. x: rect.x - 10,
  41176. y: rect.y - 10,
  41177. width: 0,
  41178. height: rect.height + 20
  41179. }
  41180. });
  41181. initProps(rectEl, {
  41182. shape: {
  41183. width: rect.width + 20,
  41184. height: rect.height + 20
  41185. }
  41186. }, seriesModel, cb);
  41187. return rectEl;
  41188. }
  41189. /**
  41190. * nest helper used to group by the array.
  41191. * can specified the keys and sort the keys.
  41192. */
  41193. function nest() {
  41194. var keysFunction = [];
  41195. var sortKeysFunction = [];
  41196. /**
  41197. * map an Array into the mapObject.
  41198. * @param {Array} array
  41199. * @param {number} depth
  41200. */
  41201. function map$$1(array, depth) {
  41202. if (depth >= keysFunction.length) {
  41203. return array;
  41204. }
  41205. var i = -1;
  41206. var n = array.length;
  41207. var keyFunction = keysFunction[depth++];
  41208. var mapObject = {};
  41209. var valuesByKey = {};
  41210. while (++i < n) {
  41211. var keyValue = keyFunction(array[i]);
  41212. var values = valuesByKey[keyValue];
  41213. if (values) {
  41214. values.push(array[i]);
  41215. }
  41216. else {
  41217. valuesByKey[keyValue] = [array[i]];
  41218. }
  41219. }
  41220. each$1(valuesByKey, function (value, key) {
  41221. mapObject[key] = map$$1(value, depth);
  41222. });
  41223. return mapObject;
  41224. }
  41225. /**
  41226. * transform the Map Object to multidimensional Array
  41227. * @param {Object} map
  41228. * @param {number} depth
  41229. */
  41230. function entriesMap(mapObject, depth) {
  41231. if (depth >= keysFunction.length) {
  41232. return mapObject;
  41233. }
  41234. var array = [];
  41235. var sortKeyFunction = sortKeysFunction[depth++];
  41236. each$1(mapObject, function (value, key) {
  41237. array.push({
  41238. key: key, values: entriesMap(value, depth)
  41239. });
  41240. });
  41241. if (sortKeyFunction) {
  41242. return array.sort(function (a, b) {
  41243. return sortKeyFunction(a.key, b.key);
  41244. });
  41245. }
  41246. else {
  41247. return array;
  41248. }
  41249. }
  41250. return {
  41251. /**
  41252. * specified the key to groupby the arrays.
  41253. * users can specified one more keys.
  41254. * @param {Function} d
  41255. */
  41256. key: function (d) {
  41257. keysFunction.push(d);
  41258. return this;
  41259. },
  41260. /**
  41261. * specified the comparator to sort the keys
  41262. * @param {Function} order
  41263. */
  41264. sortKeys: function (order) {
  41265. sortKeysFunction[keysFunction.length - 1] = order;
  41266. return this;
  41267. },
  41268. /**
  41269. * the array to be grouped by.
  41270. * @param {Array} array
  41271. */
  41272. entries: function (array) {
  41273. return entriesMap(map$$1(array, 0), 0);
  41274. }
  41275. };
  41276. }
  41277. /**
  41278. * @file The layout algorithm of sankey view
  41279. * @author Deqing Li(annong035@gmail.com)
  41280. */
  41281. var sankeyLayout = function (ecModel, api, payload) {
  41282. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  41283. var nodeWidth = seriesModel.get('nodeWidth');
  41284. var nodeGap = seriesModel.get('nodeGap');
  41285. var layoutInfo = getViewRect$3(seriesModel, api);
  41286. seriesModel.layoutInfo = layoutInfo;
  41287. var width = layoutInfo.width;
  41288. var height = layoutInfo.height;
  41289. var graph = seriesModel.getGraph();
  41290. var nodes = graph.nodes;
  41291. var edges = graph.edges;
  41292. computeNodeValues(nodes);
  41293. var filteredNodes = filter(nodes, function (node) {
  41294. return node.getLayout().value === 0;
  41295. });
  41296. var iterations = filteredNodes.length !== 0
  41297. ? 0 : seriesModel.get('layoutIterations');
  41298. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  41299. });
  41300. };
  41301. /**
  41302. * Get the layout position of the whole view
  41303. *
  41304. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  41305. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  41306. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  41307. */
  41308. function getViewRect$3(seriesModel, api) {
  41309. return getLayoutRect(
  41310. seriesModel.getBoxLayoutParams(), {
  41311. width: api.getWidth(),
  41312. height: api.getHeight()
  41313. }
  41314. );
  41315. }
  41316. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  41317. computeNodeBreadths(nodes, nodeWidth, width);
  41318. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  41319. computeEdgeDepths(nodes);
  41320. }
  41321. /**
  41322. * Compute the value of each node by summing the associated edge's value
  41323. *
  41324. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41325. */
  41326. function computeNodeValues(nodes) {
  41327. each$1(nodes, function (node) {
  41328. var value1 = sum(node.outEdges, getEdgeValue);
  41329. var value2 = sum(node.inEdges, getEdgeValue);
  41330. var value = Math.max(value1, value2);
  41331. node.setLayout({value: value}, true);
  41332. });
  41333. }
  41334. /**
  41335. * Compute the x-position for each node
  41336. *
  41337. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41338. * @param {number} nodeWidth the dx of the node
  41339. * @param {number} width the whole width of the area to draw the view
  41340. */
  41341. function computeNodeBreadths(nodes, nodeWidth, width) {
  41342. var remainNodes = nodes;
  41343. var nextNode = null;
  41344. var x = 0;
  41345. var kx = 0;
  41346. while (remainNodes.length) {
  41347. nextNode = [];
  41348. for (var i = 0, len = remainNodes.length; i < len; i++) {
  41349. var node = remainNodes[i];
  41350. node.setLayout({x: x}, true);
  41351. node.setLayout({dx: nodeWidth}, true);
  41352. for (var j = 0, lenj = node.outEdges.length; j < lenj; j++) {
  41353. nextNode.push(node.outEdges[j].node2);
  41354. }
  41355. }
  41356. remainNodes = nextNode;
  41357. ++x;
  41358. }
  41359. moveSinksRight(nodes, x);
  41360. kx = (width - nodeWidth) / (x - 1);
  41361. scaleNodeBreadths(nodes, kx);
  41362. }
  41363. /**
  41364. * All the node without outEgdes are assigned maximum x-position and
  41365. * be aligned in the last column.
  41366. *
  41367. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41368. * @param {number} x value (x-1) use to assign to node without outEdges
  41369. * as x-position
  41370. */
  41371. function moveSinksRight(nodes, x) {
  41372. each$1(nodes, function (node) {
  41373. if (!node.outEdges.length) {
  41374. node.setLayout({x: x - 1}, true);
  41375. }
  41376. });
  41377. }
  41378. /**
  41379. * Scale node x-position to the width
  41380. *
  41381. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41382. * @param {number} kx multiple used to scale nodes
  41383. */
  41384. function scaleNodeBreadths(nodes, kx) {
  41385. each$1(nodes, function (node) {
  41386. var nodeX = node.getLayout().x * kx;
  41387. node.setLayout({x: nodeX}, true);
  41388. });
  41389. }
  41390. /**
  41391. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  41392. *
  41393. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41394. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  41395. * @param {number} height the whole height of the area to draw the view
  41396. * @param {number} nodeGap the vertical distance between two nodes
  41397. * in the same column.
  41398. * @param {number} iterations the number of iterations for the algorithm
  41399. */
  41400. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  41401. var nodesByBreadth = nest()
  41402. .key(function (d) {
  41403. return d.getLayout().x;
  41404. })
  41405. .sortKeys(ascending)
  41406. .entries(nodes)
  41407. .map(function (d) {
  41408. return d.values;
  41409. });
  41410. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  41411. resolveCollisions(nodesByBreadth, nodeGap, height);
  41412. for (var alpha = 1; iterations > 0; iterations--) {
  41413. // 0.99 is a experience parameter, ensure that each iterations of
  41414. // changes as small as possible.
  41415. alpha *= 0.99;
  41416. relaxRightToLeft(nodesByBreadth, alpha);
  41417. resolveCollisions(nodesByBreadth, nodeGap, height);
  41418. relaxLeftToRight(nodesByBreadth, alpha);
  41419. resolveCollisions(nodesByBreadth, nodeGap, height);
  41420. }
  41421. }
  41422. /**
  41423. * Compute the original y-position for each node
  41424. *
  41425. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41426. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41427. * group by the array of all sankey nodes based on the nodes x-position.
  41428. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  41429. * @param {number} height the whole height of the area to draw the view
  41430. * @param {number} nodeGap the vertical distance between two nodes
  41431. */
  41432. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  41433. var kyArray = [];
  41434. each$1(nodesByBreadth, function (nodes) {
  41435. var n = nodes.length;
  41436. var sum = 0;
  41437. each$1(nodes, function (node) {
  41438. sum += node.getLayout().value;
  41439. });
  41440. var ky = (height - (n - 1) * nodeGap) / sum;
  41441. kyArray.push(ky);
  41442. });
  41443. kyArray.sort(function (a, b) {
  41444. return a - b;
  41445. });
  41446. var ky0 = kyArray[0];
  41447. each$1(nodesByBreadth, function (nodes) {
  41448. each$1(nodes, function (node, i) {
  41449. node.setLayout({y: i}, true);
  41450. var nodeDy = node.getLayout().value * ky0;
  41451. node.setLayout({dy: nodeDy}, true);
  41452. });
  41453. });
  41454. each$1(edges, function (edge) {
  41455. var edgeDy = +edge.getValue() * ky0;
  41456. edge.setLayout({dy: edgeDy}, true);
  41457. });
  41458. }
  41459. /**
  41460. * Resolve the collision of initialized depth (y-position)
  41461. *
  41462. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41463. * group by the array of all sankey nodes based on the nodes x-position.
  41464. * @param {number} nodeGap the vertical distance between two nodes
  41465. * @param {number} height the whole height of the area to draw the view
  41466. */
  41467. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  41468. each$1(nodesByBreadth, function (nodes) {
  41469. var node;
  41470. var dy;
  41471. var y0 = 0;
  41472. var n = nodes.length;
  41473. var i;
  41474. nodes.sort(ascendingDepth);
  41475. for (i = 0; i < n; i++) {
  41476. node = nodes[i];
  41477. dy = y0 - node.getLayout().y;
  41478. if (dy > 0) {
  41479. var nodeY = node.getLayout().y + dy;
  41480. node.setLayout({y: nodeY}, true);
  41481. }
  41482. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  41483. }
  41484. // if the bottommost node goes outside the bounds, push it back up
  41485. dy = y0 - nodeGap - height;
  41486. if (dy > 0) {
  41487. var nodeY = node.getLayout().y - dy;
  41488. node.setLayout({y: nodeY}, true);
  41489. y0 = node.getLayout().y;
  41490. for (i = n - 2; i >= 0; --i) {
  41491. node = nodes[i];
  41492. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  41493. if (dy > 0) {
  41494. nodeY = node.getLayout().y - dy;
  41495. node.setLayout({y: nodeY}, true);
  41496. }
  41497. y0 = node.getLayout().y;
  41498. }
  41499. }
  41500. });
  41501. }
  41502. /**
  41503. * Change the y-position of the nodes, except most the right side nodes
  41504. *
  41505. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41506. * group by the array of all sankey nodes based on the node x-position.
  41507. * @param {number} alpha parameter used to adjust the nodes y-position
  41508. */
  41509. function relaxRightToLeft(nodesByBreadth, alpha) {
  41510. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  41511. each$1(nodes, function (node) {
  41512. if (node.outEdges.length) {
  41513. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  41514. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  41515. node.setLayout({y: nodeY}, true);
  41516. }
  41517. });
  41518. });
  41519. }
  41520. function weightedTarget(edge) {
  41521. return center$1(edge.node2) * edge.getValue();
  41522. }
  41523. /**
  41524. * Change the y-position of the nodes, except most the left side nodes
  41525. *
  41526. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41527. * group by the array of all sankey nodes based on the node x-position.
  41528. * @param {number} alpha parameter used to adjust the nodes y-position
  41529. */
  41530. function relaxLeftToRight(nodesByBreadth, alpha) {
  41531. each$1(nodesByBreadth, function (nodes) {
  41532. each$1(nodes, function (node) {
  41533. if (node.inEdges.length) {
  41534. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  41535. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  41536. node.setLayout({y: nodeY}, true);
  41537. }
  41538. });
  41539. });
  41540. }
  41541. function weightedSource(edge) {
  41542. return center$1(edge.node1) * edge.getValue();
  41543. }
  41544. /**
  41545. * Compute the depth(y-position) of each edge
  41546. *
  41547. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41548. */
  41549. function computeEdgeDepths(nodes) {
  41550. each$1(nodes, function (node) {
  41551. node.outEdges.sort(ascendingTargetDepth);
  41552. node.inEdges.sort(ascendingSourceDepth);
  41553. });
  41554. each$1(nodes, function (node) {
  41555. var sy = 0;
  41556. var ty = 0;
  41557. each$1(node.outEdges, function (edge) {
  41558. edge.setLayout({sy: sy}, true);
  41559. sy += edge.getLayout().dy;
  41560. });
  41561. each$1(node.inEdges, function (edge) {
  41562. edge.setLayout({ty: ty}, true);
  41563. ty += edge.getLayout().dy;
  41564. });
  41565. });
  41566. }
  41567. function ascendingTargetDepth(a, b) {
  41568. return a.node2.getLayout().y - b.node2.getLayout().y;
  41569. }
  41570. function ascendingSourceDepth(a, b) {
  41571. return a.node1.getLayout().y - b.node1.getLayout().y;
  41572. }
  41573. function sum(array, f) {
  41574. var sum = 0;
  41575. var len = array.length;
  41576. var i = -1;
  41577. while (++i < len) {
  41578. var value = +f.call(array, array[i], i);
  41579. if (!isNaN(value)) {
  41580. sum += value;
  41581. }
  41582. }
  41583. return sum;
  41584. }
  41585. function center$1(node) {
  41586. return node.getLayout().y + node.getLayout().dy / 2;
  41587. }
  41588. function ascendingDepth(a, b) {
  41589. return a.getLayout().y - b.getLayout().y;
  41590. }
  41591. function ascending(a, b) {
  41592. return a < b ? -1 : a > b ? 1 : a === b ? 0 : NaN;
  41593. }
  41594. function getEdgeValue(edge) {
  41595. return edge.getValue();
  41596. }
  41597. /**
  41598. * @file Visual encoding for sankey view
  41599. * @author Deqing Li(annong035@gmail.com)
  41600. */
  41601. var sankeyVisual = function (ecModel, payload) {
  41602. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  41603. var graph = seriesModel.getGraph();
  41604. var nodes = graph.nodes;
  41605. nodes.sort(function (a, b) {
  41606. return a.getLayout().value - b.getLayout().value;
  41607. });
  41608. var minValue = nodes[0].getLayout().value;
  41609. var maxValue = nodes[nodes.length - 1].getLayout().value;
  41610. each$1(nodes, function (node) {
  41611. var mapping = new VisualMapping({
  41612. type: 'color',
  41613. mappingMethod: 'linear',
  41614. dataExtent: [minValue, maxValue],
  41615. visual: seriesModel.get('color')
  41616. });
  41617. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  41618. node.setVisual('color', mapValueToColor);
  41619. // If set itemStyle.normal.color
  41620. var itemModel = node.getModel();
  41621. var customColor = itemModel.get('itemStyle.normal.color');
  41622. if (customColor != null) {
  41623. node.setVisual('color', customColor);
  41624. }
  41625. });
  41626. });
  41627. };
  41628. registerLayout(sankeyLayout);
  41629. registerVisual(sankeyVisual);
  41630. /**
  41631. * @module echarts/chart/helper/Symbol
  41632. */
  41633. var WhiskerPath = Path.extend({
  41634. type: 'whiskerInBox',
  41635. shape: {},
  41636. buildPath: function (ctx, shape) {
  41637. for (var i in shape) {
  41638. if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
  41639. var pts = shape[i];
  41640. ctx.moveTo(pts[0][0], pts[0][1]);
  41641. ctx.lineTo(pts[1][0], pts[1][1]);
  41642. }
  41643. }
  41644. }
  41645. });
  41646. /**
  41647. * @constructor
  41648. * @alias {module:echarts/chart/helper/WhiskerBox}
  41649. * @param {module:echarts/data/List} data
  41650. * @param {number} idx
  41651. * @param {Function} styleUpdater
  41652. * @param {boolean} isInit
  41653. * @extends {module:zrender/graphic/Group}
  41654. */
  41655. function WhiskerBox(data, idx, styleUpdater, isInit) {
  41656. Group.call(this);
  41657. /**
  41658. * @type {number}
  41659. * @readOnly
  41660. */
  41661. this.bodyIndex;
  41662. /**
  41663. * @type {number}
  41664. * @readOnly
  41665. */
  41666. this.whiskerIndex;
  41667. /**
  41668. * @type {Function}
  41669. */
  41670. this.styleUpdater = styleUpdater;
  41671. this._createContent(data, idx, isInit);
  41672. this.updateData(data, idx, isInit);
  41673. /**
  41674. * Last series model.
  41675. * @type {module:echarts/model/Series}
  41676. */
  41677. this._seriesModel;
  41678. }
  41679. var whiskerBoxProto = WhiskerBox.prototype;
  41680. whiskerBoxProto._createContent = function (data, idx, isInit) {
  41681. var itemLayout = data.getItemLayout(idx);
  41682. var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
  41683. var count = 0;
  41684. // Whisker element.
  41685. this.add(new Polygon({
  41686. shape: {
  41687. points: isInit
  41688. ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
  41689. : itemLayout.bodyEnds
  41690. },
  41691. style: {strokeNoScale: true},
  41692. z2: 100
  41693. }));
  41694. this.bodyIndex = count++;
  41695. // Box element.
  41696. var whiskerEnds = map(itemLayout.whiskerEnds, function (ends) {
  41697. return isInit ? transInit(ends, constDim, itemLayout) : ends;
  41698. });
  41699. this.add(new WhiskerPath({
  41700. shape: makeWhiskerEndsShape(whiskerEnds),
  41701. style: {strokeNoScale: true},
  41702. z2: 100
  41703. }));
  41704. this.whiskerIndex = count++;
  41705. };
  41706. function transInit(points, dim, itemLayout) {
  41707. return map(points, function (point) {
  41708. point = point.slice();
  41709. point[dim] = itemLayout.initBaseline;
  41710. return point;
  41711. });
  41712. }
  41713. function makeWhiskerEndsShape(whiskerEnds) {
  41714. // zr animation only support 2-dim array.
  41715. var shape = {};
  41716. each$1(whiskerEnds, function (ends, i) {
  41717. shape['ends' + i] = ends;
  41718. });
  41719. return shape;
  41720. }
  41721. /**
  41722. * Update symbol properties
  41723. * @param {module:echarts/data/List} data
  41724. * @param {number} idx
  41725. */
  41726. whiskerBoxProto.updateData = function (data, idx, isInit) {
  41727. var seriesModel = this._seriesModel = data.hostModel;
  41728. var itemLayout = data.getItemLayout(idx);
  41729. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  41730. // this.childAt(this.bodyIndex).stopAnimation(true);
  41731. // this.childAt(this.whiskerIndex).stopAnimation(true);
  41732. updateMethod(
  41733. this.childAt(this.bodyIndex),
  41734. {shape: {points: itemLayout.bodyEnds}},
  41735. seriesModel, idx
  41736. );
  41737. updateMethod(
  41738. this.childAt(this.whiskerIndex),
  41739. {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
  41740. seriesModel, idx
  41741. );
  41742. this.styleUpdater.call(null, this, data, idx);
  41743. };
  41744. inherits(WhiskerBox, Group);
  41745. /**
  41746. * @constructor
  41747. * @alias module:echarts/chart/helper/WhiskerBoxDraw
  41748. */
  41749. function WhiskerBoxDraw(styleUpdater) {
  41750. this.group = new Group();
  41751. this.styleUpdater = styleUpdater;
  41752. }
  41753. var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;
  41754. /**
  41755. * Update symbols draw by new data
  41756. * @param {module:echarts/data/List} data
  41757. */
  41758. whiskerBoxDrawProto.updateData = function (data) {
  41759. var group = this.group;
  41760. var oldData = this._data;
  41761. var styleUpdater = this.styleUpdater;
  41762. data.diff(oldData)
  41763. .add(function (newIdx) {
  41764. if (data.hasValue(newIdx)) {
  41765. var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
  41766. data.setItemGraphicEl(newIdx, symbolEl);
  41767. group.add(symbolEl);
  41768. }
  41769. })
  41770. .update(function (newIdx, oldIdx) {
  41771. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  41772. // Empty data
  41773. if (!data.hasValue(newIdx)) {
  41774. group.remove(symbolEl);
  41775. return;
  41776. }
  41777. if (!symbolEl) {
  41778. symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
  41779. }
  41780. else {
  41781. symbolEl.updateData(data, newIdx);
  41782. }
  41783. // Add back
  41784. group.add(symbolEl);
  41785. data.setItemGraphicEl(newIdx, symbolEl);
  41786. })
  41787. .remove(function (oldIdx) {
  41788. var el = oldData.getItemGraphicEl(oldIdx);
  41789. el && group.remove(el);
  41790. })
  41791. .execute();
  41792. this._data = data;
  41793. };
  41794. /**
  41795. * Remove symbols.
  41796. * @param {module:echarts/data/List} data
  41797. */
  41798. whiskerBoxDrawProto.remove = function () {
  41799. var group = this.group;
  41800. var data = this._data;
  41801. this._data = null;
  41802. data && data.eachItemGraphicEl(function (el) {
  41803. el && group.remove(el);
  41804. });
  41805. };
  41806. var seriesModelMixin = {
  41807. /**
  41808. * @private
  41809. * @type {string}
  41810. */
  41811. _baseAxisDim: null,
  41812. /**
  41813. * @override
  41814. */
  41815. getInitialData: function (option, ecModel) {
  41816. // When both types of xAxis and yAxis are 'value', layout is
  41817. // needed to be specified by user. Otherwise, layout can be
  41818. // judged by which axis is category.
  41819. var categories;
  41820. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  41821. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  41822. var xAxisType = xAxisModel.get('type');
  41823. var yAxisType = yAxisModel.get('type');
  41824. var addOrdinal;
  41825. // FIXME
  41826. // 考虑时间轴
  41827. if (xAxisType === 'category') {
  41828. option.layout = 'horizontal';
  41829. categories = xAxisModel.getCategories();
  41830. addOrdinal = true;
  41831. }
  41832. else if (yAxisType === 'category') {
  41833. option.layout = 'vertical';
  41834. categories = yAxisModel.getCategories();
  41835. addOrdinal = true;
  41836. }
  41837. else {
  41838. option.layout = option.layout || 'horizontal';
  41839. }
  41840. var coordDims = ['x', 'y'];
  41841. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  41842. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  41843. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  41844. var data = option.data;
  41845. addOrdinal && each$1(data, function (item, index) {
  41846. if (item.value && isArray(item.value)) {
  41847. item.value.unshift(index);
  41848. } else {
  41849. isArray(item) && item.unshift(index);
  41850. }
  41851. });
  41852. var defaultValueDimensions = this.defaultValueDimensions;
  41853. var dimensions = [{
  41854. name: baseAxisDim,
  41855. otherDims: {
  41856. tooltip: false
  41857. },
  41858. dimsDef: ['base']
  41859. }, {
  41860. name: otherAxisDim,
  41861. dimsDef: defaultValueDimensions.slice()
  41862. }];
  41863. dimensions = completeDimensions(dimensions, data, {
  41864. encodeDef: this.get('encode'),
  41865. dimsDef: this.get('dimensions'),
  41866. // Consider empty data entry.
  41867. dimCount: defaultValueDimensions.length + 1
  41868. });
  41869. var list = new List(dimensions, this);
  41870. list.initData(data, categories ? categories.slice() : null);
  41871. return list;
  41872. },
  41873. /**
  41874. * If horizontal, base axis is x, otherwise y.
  41875. * @override
  41876. */
  41877. getBaseAxis: function () {
  41878. var dim = this._baseAxisDim;
  41879. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  41880. }
  41881. };
  41882. var viewMixin = {
  41883. init: function () {
  41884. /**
  41885. * Old data.
  41886. * @private
  41887. * @type {module:echarts/chart/helper/WhiskerBoxDraw}
  41888. */
  41889. var whiskerBoxDraw = this._whiskerBoxDraw = new WhiskerBoxDraw(
  41890. this.getStyleUpdater()
  41891. );
  41892. this.group.add(whiskerBoxDraw.group);
  41893. },
  41894. render: function (seriesModel, ecModel, api) {
  41895. this._whiskerBoxDraw.updateData(seriesModel.getData());
  41896. },
  41897. remove: function (ecModel) {
  41898. this._whiskerBoxDraw.remove();
  41899. }
  41900. };
  41901. var BoxplotSeries = SeriesModel.extend({
  41902. type: 'series.boxplot',
  41903. dependencies: ['xAxis', 'yAxis', 'grid'],
  41904. // TODO
  41905. // box width represents group size, so dimension should have 'size'.
  41906. /**
  41907. * @see <https://en.wikipedia.org/wiki/Box_plot>
  41908. * The meanings of 'min' and 'max' depend on user,
  41909. * and echarts do not need to know it.
  41910. * @readOnly
  41911. */
  41912. defaultValueDimensions: ['min', 'Q1', 'median', 'Q3', 'max'],
  41913. /**
  41914. * @type {Array.<string>}
  41915. * @readOnly
  41916. */
  41917. dimensions: null,
  41918. /**
  41919. * @override
  41920. */
  41921. defaultOption: {
  41922. zlevel: 0, // 一级层叠
  41923. z: 2, // 二级层叠
  41924. coordinateSystem: 'cartesian2d',
  41925. legendHoverLink: true,
  41926. hoverAnimation: true,
  41927. // xAxisIndex: 0,
  41928. // yAxisIndex: 0,
  41929. layout: null, // 'horizontal' or 'vertical'
  41930. boxWidth: [7, 50], // [min, max] can be percent of band width.
  41931. itemStyle: {
  41932. normal: {
  41933. color: '#fff',
  41934. borderWidth: 1
  41935. },
  41936. emphasis: {
  41937. borderWidth: 2,
  41938. shadowBlur: 5,
  41939. shadowOffsetX: 2,
  41940. shadowOffsetY: 2,
  41941. shadowColor: 'rgba(0,0,0,0.4)'
  41942. }
  41943. },
  41944. animationEasing: 'elasticOut',
  41945. animationDuration: 800
  41946. }
  41947. });
  41948. mixin(BoxplotSeries, seriesModelMixin, true);
  41949. var BoxplotView = Chart.extend({
  41950. type: 'boxplot',
  41951. getStyleUpdater: function () {
  41952. return updateStyle$1;
  41953. },
  41954. dispose: noop
  41955. });
  41956. mixin(BoxplotView, viewMixin, true);
  41957. // Update common properties
  41958. var normalStyleAccessPath$1 = ['itemStyle', 'normal'];
  41959. var emphasisStyleAccessPath$1 = ['itemStyle', 'emphasis'];
  41960. function updateStyle$1(itemGroup, data, idx) {
  41961. var itemModel = data.getItemModel(idx);
  41962. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$1);
  41963. var borderColor = data.getItemVisual(idx, 'color');
  41964. // Exclude borderColor.
  41965. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  41966. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  41967. whiskerEl.style.set(itemStyle);
  41968. whiskerEl.style.stroke = borderColor;
  41969. whiskerEl.dirty();
  41970. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  41971. bodyEl.style.set(itemStyle);
  41972. bodyEl.style.stroke = borderColor;
  41973. bodyEl.dirty();
  41974. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$1).getItemStyle();
  41975. setHoverStyle(itemGroup, hoverStyle);
  41976. }
  41977. var borderColorQuery = ['itemStyle', 'normal', 'borderColor'];
  41978. var boxplotVisual = function (ecModel, api) {
  41979. var globalColors = ecModel.get('color');
  41980. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  41981. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  41982. var data = seriesModel.getData();
  41983. data.setVisual({
  41984. legendSymbol: 'roundRect',
  41985. // Use name 'color' but not 'borderColor' for legend usage and
  41986. // visual coding from other component like dataRange.
  41987. color: seriesModel.get(borderColorQuery) || defaulColor
  41988. });
  41989. // Only visible series has each data be visual encoded
  41990. if (!ecModel.isSeriesFiltered(seriesModel)) {
  41991. data.each(function (idx) {
  41992. var itemModel = data.getItemModel(idx);
  41993. data.setItemVisual(
  41994. idx,
  41995. {color: itemModel.get(borderColorQuery, true)}
  41996. );
  41997. });
  41998. }
  41999. });
  42000. };
  42001. var each$16 = each$1;
  42002. var boxplotLayout = function (ecModel) {
  42003. var groupResult = groupSeriesByAxis(ecModel);
  42004. each$16(groupResult, function (groupItem) {
  42005. var seriesModels = groupItem.seriesModels;
  42006. if (!seriesModels.length) {
  42007. return;
  42008. }
  42009. calculateBase(groupItem);
  42010. each$16(seriesModels, function (seriesModel, idx) {
  42011. layoutSingleSeries(
  42012. seriesModel,
  42013. groupItem.boxOffsetList[idx],
  42014. groupItem.boxWidthList[idx]
  42015. );
  42016. });
  42017. });
  42018. };
  42019. /**
  42020. * Group series by axis.
  42021. */
  42022. function groupSeriesByAxis(ecModel) {
  42023. var result = [];
  42024. var axisList = [];
  42025. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  42026. var baseAxis = seriesModel.getBaseAxis();
  42027. var idx = indexOf(axisList, baseAxis);
  42028. if (idx < 0) {
  42029. idx = axisList.length;
  42030. axisList[idx] = baseAxis;
  42031. result[idx] = {axis: baseAxis, seriesModels: []};
  42032. }
  42033. result[idx].seriesModels.push(seriesModel);
  42034. });
  42035. return result;
  42036. }
  42037. /**
  42038. * Calculate offset and box width for each series.
  42039. */
  42040. function calculateBase(groupItem) {
  42041. var extent;
  42042. var baseAxis = groupItem.axis;
  42043. var seriesModels = groupItem.seriesModels;
  42044. var seriesCount = seriesModels.length;
  42045. var boxWidthList = groupItem.boxWidthList = [];
  42046. var boxOffsetList = groupItem.boxOffsetList = [];
  42047. var boundList = [];
  42048. var bandWidth;
  42049. if (baseAxis.type === 'category') {
  42050. bandWidth = baseAxis.getBandWidth();
  42051. }
  42052. else {
  42053. var maxDataCount = 0;
  42054. each$16(seriesModels, function (seriesModel) {
  42055. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  42056. });
  42057. extent = baseAxis.getExtent(),
  42058. Math.abs(extent[1] - extent[0]) / maxDataCount;
  42059. }
  42060. each$16(seriesModels, function (seriesModel) {
  42061. var boxWidthBound = seriesModel.get('boxWidth');
  42062. if (!isArray(boxWidthBound)) {
  42063. boxWidthBound = [boxWidthBound, boxWidthBound];
  42064. }
  42065. boundList.push([
  42066. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  42067. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  42068. ]);
  42069. });
  42070. var availableWidth = bandWidth * 0.8 - 2;
  42071. var boxGap = availableWidth / seriesCount * 0.3;
  42072. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  42073. var base = boxWidth / 2 - availableWidth / 2;
  42074. each$16(seriesModels, function (seriesModel, idx) {
  42075. boxOffsetList.push(base);
  42076. base += boxGap + boxWidth;
  42077. boxWidthList.push(
  42078. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  42079. );
  42080. });
  42081. }
  42082. /**
  42083. * Calculate points location for each series.
  42084. */
  42085. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  42086. var coordSys = seriesModel.coordinateSystem;
  42087. var data = seriesModel.getData();
  42088. var halfWidth = boxWidth / 2;
  42089. var chartLayout = seriesModel.get('layout');
  42090. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  42091. var constDim = 1 - variableDim;
  42092. var coordDims = ['x', 'y'];
  42093. var vDims = [];
  42094. var cDim;
  42095. each$1(data.dimensions, function (dimName) {
  42096. var dimInfo = data.getDimensionInfo(dimName);
  42097. var coordDim = dimInfo.coordDim;
  42098. if (coordDim === coordDims[constDim]) {
  42099. vDims.push(dimName);
  42100. }
  42101. else if (coordDim === coordDims[variableDim]) {
  42102. cDim = dimName;
  42103. }
  42104. });
  42105. if (cDim == null || vDims.length < 5) {
  42106. return;
  42107. }
  42108. data.each([cDim].concat(vDims), function () {
  42109. var args = arguments;
  42110. var axisDimVal = args[0];
  42111. var idx = args[vDims.length + 1];
  42112. var median = getPoint(args[3]);
  42113. var end1 = getPoint(args[1]);
  42114. var end5 = getPoint(args[5]);
  42115. var whiskerEnds = [
  42116. [end1, getPoint(args[2])],
  42117. [end5, getPoint(args[4])]
  42118. ];
  42119. layEndLine(end1);
  42120. layEndLine(end5);
  42121. layEndLine(median);
  42122. var bodyEnds = [];
  42123. addBodyEnd(whiskerEnds[0][1], 0);
  42124. addBodyEnd(whiskerEnds[1][1], 1);
  42125. data.setItemLayout(idx, {
  42126. chartLayout: chartLayout,
  42127. initBaseline: median[constDim],
  42128. median: median,
  42129. bodyEnds: bodyEnds,
  42130. whiskerEnds: whiskerEnds
  42131. });
  42132. function getPoint(val) {
  42133. var p = [];
  42134. p[variableDim] = axisDimVal;
  42135. p[constDim] = val;
  42136. var point;
  42137. if (isNaN(axisDimVal) || isNaN(val)) {
  42138. point = [NaN, NaN];
  42139. }
  42140. else {
  42141. point = coordSys.dataToPoint(p);
  42142. point[variableDim] += offset;
  42143. }
  42144. return point;
  42145. }
  42146. function addBodyEnd(point, start) {
  42147. var point1 = point.slice();
  42148. var point2 = point.slice();
  42149. point1[variableDim] += halfWidth;
  42150. point2[variableDim] -= halfWidth;
  42151. start
  42152. ? bodyEnds.push(point1, point2)
  42153. : bodyEnds.push(point2, point1);
  42154. }
  42155. function layEndLine(endCenter) {
  42156. var line = [endCenter.slice(), endCenter.slice()];
  42157. line[0][variableDim] -= halfWidth;
  42158. line[1][variableDim] += halfWidth;
  42159. whiskerEnds.push(line);
  42160. }
  42161. });
  42162. }
  42163. registerVisual(boxplotVisual);
  42164. registerLayout(boxplotLayout);
  42165. var CandlestickSeries = SeriesModel.extend({
  42166. type: 'series.candlestick',
  42167. dependencies: ['xAxis', 'yAxis', 'grid'],
  42168. /**
  42169. * @readOnly
  42170. */
  42171. defaultValueDimensions: ['open', 'close', 'lowest', 'highest'],
  42172. /**
  42173. * @type {Array.<string>}
  42174. * @readOnly
  42175. */
  42176. dimensions: null,
  42177. /**
  42178. * @override
  42179. */
  42180. defaultOption: {
  42181. zlevel: 0, // 一级层叠
  42182. z: 2, // 二级层叠
  42183. coordinateSystem: 'cartesian2d',
  42184. legendHoverLink: true,
  42185. hoverAnimation: true,
  42186. // xAxisIndex: 0,
  42187. // yAxisIndex: 0,
  42188. layout: null, // 'horizontal' or 'vertical'
  42189. itemStyle: {
  42190. normal: {
  42191. color: '#c23531', // 阳线 positive
  42192. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  42193. borderWidth: 1,
  42194. // FIXME
  42195. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  42196. borderColor: '#c23531',
  42197. borderColor0: '#314656'
  42198. },
  42199. emphasis: {
  42200. borderWidth: 2
  42201. }
  42202. },
  42203. barMaxWidth: null,
  42204. barMinWidth: null,
  42205. barWidth: null,
  42206. animationUpdate: false,
  42207. animationEasing: 'linear',
  42208. animationDuration: 300
  42209. },
  42210. /**
  42211. * Get dimension for shadow in dataZoom
  42212. * @return {string} dimension name
  42213. */
  42214. getShadowDim: function () {
  42215. return 'open';
  42216. },
  42217. brushSelector: function (dataIndex, data, selectors) {
  42218. var itemLayout = data.getItemLayout(dataIndex);
  42219. return selectors.rect(itemLayout.brushRect);
  42220. }
  42221. });
  42222. mixin(CandlestickSeries, seriesModelMixin, true);
  42223. var CandlestickView = Chart.extend({
  42224. type: 'candlestick',
  42225. getStyleUpdater: function () {
  42226. return updateStyle$2;
  42227. },
  42228. dispose: noop
  42229. });
  42230. mixin(CandlestickView, viewMixin, true);
  42231. // Update common properties
  42232. var normalStyleAccessPath$2 = ['itemStyle', 'normal'];
  42233. var emphasisStyleAccessPath$2 = ['itemStyle', 'emphasis'];
  42234. function updateStyle$2(itemGroup, data, idx) {
  42235. var itemModel = data.getItemModel(idx);
  42236. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$2);
  42237. var color = data.getItemVisual(idx, 'color');
  42238. var borderColor = data.getItemVisual(idx, 'borderColor') || color;
  42239. // Color must be excluded.
  42240. // Because symbol provide setColor individually to set fill and stroke
  42241. var itemStyle = normalItemStyleModel.getItemStyle(
  42242. ['color', 'color0', 'borderColor', 'borderColor0']
  42243. );
  42244. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  42245. whiskerEl.useStyle(itemStyle);
  42246. whiskerEl.style.stroke = borderColor;
  42247. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  42248. bodyEl.useStyle(itemStyle);
  42249. bodyEl.style.fill = color;
  42250. bodyEl.style.stroke = borderColor;
  42251. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$2).getItemStyle();
  42252. setHoverStyle(itemGroup, hoverStyle);
  42253. }
  42254. var preprocessor = function (option) {
  42255. if (!option || !isArray(option.series)) {
  42256. return;
  42257. }
  42258. // Translate 'k' to 'candlestick'.
  42259. each$1(option.series, function (seriesItem) {
  42260. if (isObject(seriesItem) && seriesItem.type === 'k') {
  42261. seriesItem.type = 'candlestick';
  42262. }
  42263. });
  42264. };
  42265. var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
  42266. var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
  42267. var positiveColorQuery = ['itemStyle', 'normal', 'color'];
  42268. var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
  42269. var candlestickVisual = function (ecModel, api) {
  42270. ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
  42271. var data = seriesModel.getData();
  42272. data.setVisual({
  42273. legendSymbol: 'roundRect'
  42274. });
  42275. // Only visible series has each data be visual encoded
  42276. if (!ecModel.isSeriesFiltered(seriesModel)) {
  42277. data.each(function (idx) {
  42278. var itemModel = data.getItemModel(idx);
  42279. var sign = data.getItemLayout(idx).sign;
  42280. data.setItemVisual(
  42281. idx,
  42282. {
  42283. color: itemModel.get(
  42284. sign > 0 ? positiveColorQuery : negativeColorQuery
  42285. ),
  42286. borderColor: itemModel.get(
  42287. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  42288. )
  42289. }
  42290. );
  42291. });
  42292. }
  42293. });
  42294. };
  42295. var retrieve2$1 = retrieve2;
  42296. var candlestickLayout = function (ecModel) {
  42297. ecModel.eachSeriesByType('candlestick', function (seriesModel) {
  42298. var coordSys = seriesModel.coordinateSystem;
  42299. var data = seriesModel.getData();
  42300. var candleWidth = calculateCandleWidth(seriesModel, data);
  42301. var chartLayout = seriesModel.get('layout');
  42302. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  42303. var constDim = 1 - variableDim;
  42304. var coordDims = ['x', 'y'];
  42305. var vDims = [];
  42306. var cDim;
  42307. each$1(data.dimensions, function (dimName) {
  42308. var dimInfo = data.getDimensionInfo(dimName);
  42309. var coordDim = dimInfo.coordDim;
  42310. if (coordDim === coordDims[constDim]) {
  42311. vDims.push(dimName);
  42312. }
  42313. else if (coordDim === coordDims[variableDim]) {
  42314. cDim = dimName;
  42315. }
  42316. });
  42317. if (cDim == null || vDims.length < 4) {
  42318. return;
  42319. }
  42320. var dataIndex = 0;
  42321. data.each([cDim].concat(vDims), function () {
  42322. var args = arguments;
  42323. var axisDimVal = args[0];
  42324. var idx = args[vDims.length + 1];
  42325. var openVal = args[1];
  42326. var closeVal = args[2];
  42327. var lowestVal = args[3];
  42328. var highestVal = args[4];
  42329. var ocLow = Math.min(openVal, closeVal);
  42330. var ocHigh = Math.max(openVal, closeVal);
  42331. var ocLowPoint = getPoint(ocLow);
  42332. var ocHighPoint = getPoint(ocHigh);
  42333. var lowestPoint = getPoint(lowestVal);
  42334. var highestPoint = getPoint(highestVal);
  42335. var whiskerEnds = [
  42336. [
  42337. subPixelOptimizePoint(highestPoint),
  42338. subPixelOptimizePoint(ocHighPoint)
  42339. ],
  42340. [
  42341. subPixelOptimizePoint(lowestPoint),
  42342. subPixelOptimizePoint(ocLowPoint)
  42343. ]
  42344. ];
  42345. var bodyEnds = [];
  42346. addBodyEnd(ocHighPoint, 0);
  42347. addBodyEnd(ocLowPoint, 1);
  42348. var sign;
  42349. if (openVal > closeVal) {
  42350. sign = -1;
  42351. }
  42352. else if (openVal < closeVal) {
  42353. sign = 1;
  42354. }
  42355. else {
  42356. // If close === open, compare with close of last record
  42357. if (dataIndex > 0) {
  42358. sign = data.getItemModel(dataIndex - 1).get()[2]
  42359. <= closeVal
  42360. ? 1
  42361. : -1;
  42362. }
  42363. else {
  42364. // No record of previous, set to be positive
  42365. sign = 1;
  42366. }
  42367. }
  42368. data.setItemLayout(idx, {
  42369. chartLayout: chartLayout,
  42370. sign: sign,
  42371. initBaseline: openVal > closeVal
  42372. ? ocHighPoint[constDim] : ocLowPoint[constDim], // open point.
  42373. bodyEnds: bodyEnds,
  42374. whiskerEnds: whiskerEnds,
  42375. brushRect: makeBrushRect()
  42376. });
  42377. ++dataIndex;
  42378. function getPoint(val) {
  42379. var p = [];
  42380. p[variableDim] = axisDimVal;
  42381. p[constDim] = val;
  42382. return (isNaN(axisDimVal) || isNaN(val))
  42383. ? [NaN, NaN]
  42384. : coordSys.dataToPoint(p);
  42385. }
  42386. function addBodyEnd(point, start) {
  42387. var point1 = point.slice();
  42388. var point2 = point.slice();
  42389. point1[variableDim] = subPixelOptimize(
  42390. point1[variableDim] + candleWidth / 2, 1, false
  42391. );
  42392. point2[variableDim] = subPixelOptimize(
  42393. point2[variableDim] - candleWidth / 2, 1, true
  42394. );
  42395. start
  42396. ? bodyEnds.push(point1, point2)
  42397. : bodyEnds.push(point2, point1);
  42398. }
  42399. function makeBrushRect() {
  42400. var pmin = getPoint(Math.min(openVal, closeVal, lowestVal, highestVal));
  42401. var pmax = getPoint(Math.max(openVal, closeVal, lowestVal, highestVal));
  42402. pmin[variableDim] -= candleWidth / 2;
  42403. pmax[variableDim] -= candleWidth / 2;
  42404. return {
  42405. x: pmin[0],
  42406. y: pmin[1],
  42407. width: constDim ? candleWidth : pmax[0] - pmin[0],
  42408. height: constDim ? pmax[1] - pmin[1] : candleWidth
  42409. };
  42410. }
  42411. function subPixelOptimizePoint(point) {
  42412. point[variableDim] = subPixelOptimize(point[variableDim], 1);
  42413. return point;
  42414. }
  42415. }, true);
  42416. });
  42417. };
  42418. function calculateCandleWidth(seriesModel, data) {
  42419. var baseAxis = seriesModel.getBaseAxis();
  42420. var extent;
  42421. var bandWidth = baseAxis.type === 'category'
  42422. ? baseAxis.getBandWidth()
  42423. : (
  42424. extent = baseAxis.getExtent(),
  42425. Math.abs(extent[1] - extent[0]) / data.count()
  42426. );
  42427. var barMaxWidth = parsePercent$1(
  42428. retrieve2$1(seriesModel.get('barMaxWidth'), bandWidth),
  42429. bandWidth
  42430. );
  42431. var barMinWidth = parsePercent$1(
  42432. retrieve2$1(seriesModel.get('barMinWidth'), 1),
  42433. bandWidth
  42434. );
  42435. var barWidth = seriesModel.get('barWidth');
  42436. return barWidth != null
  42437. ? parsePercent$1(barWidth, bandWidth)
  42438. // Put max outer to ensure bar visible in spite of overlap.
  42439. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  42440. }
  42441. registerPreprocessor(preprocessor);
  42442. registerVisual(candlestickVisual);
  42443. registerLayout(candlestickLayout);
  42444. SeriesModel.extend({
  42445. type: 'series.effectScatter',
  42446. dependencies: ['grid', 'polar'],
  42447. getInitialData: function (option, ecModel) {
  42448. var list = createListFromArray(option.data, this, ecModel);
  42449. return list;
  42450. },
  42451. brushSelector: 'point',
  42452. defaultOption: {
  42453. coordinateSystem: 'cartesian2d',
  42454. zlevel: 0,
  42455. z: 2,
  42456. legendHoverLink: true,
  42457. effectType: 'ripple',
  42458. progressive: 0,
  42459. // When to show the effect, option: 'render'|'emphasis'
  42460. showEffectOn: 'render',
  42461. // Ripple effect config
  42462. rippleEffect: {
  42463. period: 4,
  42464. // Scale of ripple
  42465. scale: 2.5,
  42466. // Brush type can be fill or stroke
  42467. brushType: 'fill'
  42468. },
  42469. // Cartesian coordinate system
  42470. // xAxisIndex: 0,
  42471. // yAxisIndex: 0,
  42472. // Polar coordinate system
  42473. // polarIndex: 0,
  42474. // Geo coordinate system
  42475. // geoIndex: 0,
  42476. // symbol: null, // 图形类型
  42477. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  42478. // symbolRotate: null, // 图形旋转控制
  42479. // large: false,
  42480. // Available when large is true
  42481. // largeThreshold: 2000,
  42482. // itemStyle: {
  42483. // normal: {
  42484. // opacity: 1
  42485. // }
  42486. // }
  42487. }
  42488. });
  42489. /**
  42490. * Symbol with ripple effect
  42491. * @module echarts/chart/helper/EffectSymbol
  42492. */
  42493. var EFFECT_RIPPLE_NUMBER = 3;
  42494. function normalizeSymbolSize$1(symbolSize) {
  42495. if (!isArray(symbolSize)) {
  42496. symbolSize = [+symbolSize, +symbolSize];
  42497. }
  42498. return symbolSize;
  42499. }
  42500. function updateRipplePath(rippleGroup, effectCfg) {
  42501. rippleGroup.eachChild(function (ripplePath) {
  42502. ripplePath.attr({
  42503. z: effectCfg.z,
  42504. zlevel: effectCfg.zlevel,
  42505. style: {
  42506. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  42507. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  42508. }
  42509. });
  42510. });
  42511. }
  42512. /**
  42513. * @constructor
  42514. * @param {module:echarts/data/List} data
  42515. * @param {number} idx
  42516. * @extends {module:zrender/graphic/Group}
  42517. */
  42518. function EffectSymbol(data, idx) {
  42519. Group.call(this);
  42520. var symbol = new SymbolClz$1(data, idx);
  42521. var rippleGroup = new Group();
  42522. this.add(symbol);
  42523. this.add(rippleGroup);
  42524. rippleGroup.beforeUpdate = function () {
  42525. this.attr(symbol.getScale());
  42526. };
  42527. this.updateData(data, idx);
  42528. }
  42529. var effectSymbolProto = EffectSymbol.prototype;
  42530. effectSymbolProto.stopEffectAnimation = function () {
  42531. this.childAt(1).removeAll();
  42532. };
  42533. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  42534. var symbolType = effectCfg.symbolType;
  42535. var color = effectCfg.color;
  42536. var rippleGroup = this.childAt(1);
  42537. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  42538. // var ripplePath = createSymbol(
  42539. // symbolType, -0.5, -0.5, 1, 1, color
  42540. // );
  42541. // If width/height are set too small (e.g., set to 1) on ios10
  42542. // and macOS Sierra, a circle stroke become a rect, no matter what
  42543. // the scale is set. So we set width/height as 2. See #4136.
  42544. var ripplePath = createSymbol(
  42545. symbolType, -1, -1, 2, 2, color
  42546. );
  42547. ripplePath.attr({
  42548. style: {
  42549. strokeNoScale: true
  42550. },
  42551. z2: 99,
  42552. silent: true,
  42553. scale: [0.5, 0.5]
  42554. });
  42555. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  42556. // TODO Configurable effectCfg.period
  42557. ripplePath.animate('', true)
  42558. .when(effectCfg.period, {
  42559. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  42560. })
  42561. .delay(delay)
  42562. .start();
  42563. ripplePath.animateStyle(true)
  42564. .when(effectCfg.period, {
  42565. opacity: 0
  42566. })
  42567. .delay(delay)
  42568. .start();
  42569. rippleGroup.add(ripplePath);
  42570. }
  42571. updateRipplePath(rippleGroup, effectCfg);
  42572. };
  42573. /**
  42574. * Update effect symbol
  42575. */
  42576. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  42577. var oldEffectCfg = this._effectCfg;
  42578. var rippleGroup = this.childAt(1);
  42579. // Must reinitialize effect if following configuration changed
  42580. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  42581. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  42582. var propName = DIFFICULT_PROPS[i];
  42583. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  42584. this.stopEffectAnimation();
  42585. this.startEffectAnimation(effectCfg);
  42586. return;
  42587. }
  42588. }
  42589. updateRipplePath(rippleGroup, effectCfg);
  42590. };
  42591. /**
  42592. * Highlight symbol
  42593. */
  42594. effectSymbolProto.highlight = function () {
  42595. this.trigger('emphasis');
  42596. };
  42597. /**
  42598. * Downplay symbol
  42599. */
  42600. effectSymbolProto.downplay = function () {
  42601. this.trigger('normal');
  42602. };
  42603. /**
  42604. * Update symbol properties
  42605. * @param {module:echarts/data/List} data
  42606. * @param {number} idx
  42607. */
  42608. effectSymbolProto.updateData = function (data, idx) {
  42609. var seriesModel = data.hostModel;
  42610. this.childAt(0).updateData(data, idx);
  42611. var rippleGroup = this.childAt(1);
  42612. var itemModel = data.getItemModel(idx);
  42613. var symbolType = data.getItemVisual(idx, 'symbol');
  42614. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  42615. var color = data.getItemVisual(idx, 'color');
  42616. rippleGroup.attr('scale', symbolSize);
  42617. rippleGroup.traverse(function (ripplePath) {
  42618. ripplePath.attr({
  42619. fill: color
  42620. });
  42621. });
  42622. var symbolOffset = itemModel.getShallow('symbolOffset');
  42623. if (symbolOffset) {
  42624. var pos = rippleGroup.position;
  42625. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  42626. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  42627. }
  42628. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  42629. var effectCfg = {};
  42630. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  42631. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  42632. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  42633. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  42634. effectCfg.effectOffset = idx / data.count();
  42635. effectCfg.z = itemModel.getShallow('z') || 0;
  42636. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  42637. effectCfg.symbolType = symbolType;
  42638. effectCfg.color = color;
  42639. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  42640. if (effectCfg.showEffectOn === 'render') {
  42641. this._effectCfg
  42642. ? this.updateEffectAnimation(effectCfg)
  42643. : this.startEffectAnimation(effectCfg);
  42644. this._effectCfg = effectCfg;
  42645. }
  42646. else {
  42647. // Not keep old effect config
  42648. this._effectCfg = null;
  42649. this.stopEffectAnimation();
  42650. var symbol = this.childAt(0);
  42651. var onEmphasis = function () {
  42652. symbol.highlight();
  42653. if (effectCfg.showEffectOn !== 'render') {
  42654. this.startEffectAnimation(effectCfg);
  42655. }
  42656. };
  42657. var onNormal = function () {
  42658. symbol.downplay();
  42659. if (effectCfg.showEffectOn !== 'render') {
  42660. this.stopEffectAnimation();
  42661. }
  42662. };
  42663. this.on('mouseover', onEmphasis, this)
  42664. .on('mouseout', onNormal, this)
  42665. .on('emphasis', onEmphasis, this)
  42666. .on('normal', onNormal, this);
  42667. }
  42668. this._effectCfg = effectCfg;
  42669. };
  42670. effectSymbolProto.fadeOut = function (cb) {
  42671. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  42672. cb && cb();
  42673. };
  42674. inherits(EffectSymbol, Group);
  42675. extendChartView({
  42676. type: 'effectScatter',
  42677. init: function () {
  42678. this._symbolDraw = new SymbolDraw(EffectSymbol);
  42679. },
  42680. render: function (seriesModel, ecModel, api) {
  42681. var data = seriesModel.getData();
  42682. var effectSymbolDraw = this._symbolDraw;
  42683. effectSymbolDraw.updateData(data);
  42684. this.group.add(effectSymbolDraw.group);
  42685. },
  42686. updateLayout: function () {
  42687. this._symbolDraw.updateLayout();
  42688. },
  42689. remove: function (ecModel, api) {
  42690. this._symbolDraw && this._symbolDraw.remove(api);
  42691. },
  42692. dispose: function () {}
  42693. });
  42694. registerVisual(curry(
  42695. visualSymbol, 'effectScatter', 'circle', null
  42696. ));
  42697. registerLayout(curry(
  42698. layoutPoints, 'effectScatter'
  42699. ));
  42700. // Convert [ [{coord: []}, {coord: []}] ]
  42701. // to [ { coords: [[]] } ]
  42702. function preprocessOption(seriesOpt) {
  42703. var data = seriesOpt.data;
  42704. if (data && data[0] && data[0][0] && data[0][0].coord) {
  42705. if (__DEV__) {
  42706. console.warn('Lines data configuration has been changed to'
  42707. + ' { coords:[[1,2],[2,3]] }');
  42708. }
  42709. seriesOpt.data = map(data, function (itemOpt) {
  42710. var coords = [
  42711. itemOpt[0].coord, itemOpt[1].coord
  42712. ];
  42713. var target = {
  42714. coords: coords
  42715. };
  42716. if (itemOpt[0].name) {
  42717. target.fromName = itemOpt[0].name;
  42718. }
  42719. if (itemOpt[1].name) {
  42720. target.toName = itemOpt[1].name;
  42721. }
  42722. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  42723. });
  42724. }
  42725. }
  42726. var LinesSeries = SeriesModel.extend({
  42727. type: 'series.lines',
  42728. dependencies: ['grid', 'polar'],
  42729. visualColorAccessPath: 'lineStyle.normal.color',
  42730. init: function (option) {
  42731. // Not using preprocessor because mergeOption may not have series.type
  42732. preprocessOption(option);
  42733. LinesSeries.superApply(this, 'init', arguments);
  42734. },
  42735. mergeOption: function (option) {
  42736. preprocessOption(option);
  42737. LinesSeries.superApply(this, 'mergeOption', arguments);
  42738. },
  42739. getInitialData: function (option, ecModel) {
  42740. if (__DEV__) {
  42741. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  42742. if (!CoordSys) {
  42743. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  42744. }
  42745. }
  42746. var lineData = new List(['value'], this);
  42747. lineData.hasItemOption = false;
  42748. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  42749. // dataItem is simply coords
  42750. if (dataItem instanceof Array) {
  42751. return NaN;
  42752. }
  42753. else {
  42754. lineData.hasItemOption = true;
  42755. var value = dataItem.value;
  42756. if (value != null) {
  42757. return value instanceof Array ? value[dimIndex] : value;
  42758. }
  42759. }
  42760. });
  42761. return lineData;
  42762. },
  42763. formatTooltip: function (dataIndex) {
  42764. var data = this.getData();
  42765. var itemModel = data.getItemModel(dataIndex);
  42766. var name = itemModel.get('name');
  42767. if (name) {
  42768. return name;
  42769. }
  42770. var fromName = itemModel.get('fromName');
  42771. var toName = itemModel.get('toName');
  42772. var html = [];
  42773. fromName != null && html.push(fromName);
  42774. toName != null && html.push(toName);
  42775. return encodeHTML(html.join(' > '));
  42776. },
  42777. defaultOption: {
  42778. coordinateSystem: 'geo',
  42779. zlevel: 0,
  42780. z: 2,
  42781. legendHoverLink: true,
  42782. hoverAnimation: true,
  42783. // Cartesian coordinate system
  42784. xAxisIndex: 0,
  42785. yAxisIndex: 0,
  42786. symbol: ['none', 'none'],
  42787. symbolSize: [10, 10],
  42788. // Geo coordinate system
  42789. geoIndex: 0,
  42790. effect: {
  42791. show: false,
  42792. period: 4,
  42793. // Animation delay. support callback
  42794. // delay: 0,
  42795. // If move with constant speed px/sec
  42796. // period will be ignored if this property is > 0,
  42797. constantSpeed: 0,
  42798. symbol: 'circle',
  42799. symbolSize: 3,
  42800. loop: true,
  42801. // Length of trail, 0 - 1
  42802. trailLength: 0.2
  42803. // Same with lineStyle.normal.color
  42804. // color
  42805. },
  42806. large: false,
  42807. // Available when large is true
  42808. largeThreshold: 2000,
  42809. // If lines are polyline
  42810. // polyline not support curveness, label, animation
  42811. polyline: false,
  42812. label: {
  42813. normal: {
  42814. show: false,
  42815. position: 'end'
  42816. // distance: 5,
  42817. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  42818. }
  42819. },
  42820. lineStyle: {
  42821. normal: {
  42822. opacity: 0.5
  42823. }
  42824. }
  42825. }
  42826. });
  42827. /**
  42828. * Provide effect for line
  42829. * @module echarts/chart/helper/EffectLine
  42830. */
  42831. /**
  42832. * @constructor
  42833. * @extends {module:zrender/graphic/Group}
  42834. * @alias {module:echarts/chart/helper/Line}
  42835. */
  42836. function EffectLine(lineData, idx, seriesScope) {
  42837. Group.call(this);
  42838. this.add(this.createLine(lineData, idx, seriesScope));
  42839. this._updateEffectSymbol(lineData, idx);
  42840. }
  42841. var effectLineProto = EffectLine.prototype;
  42842. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  42843. return new Line$1(lineData, idx, seriesScope);
  42844. };
  42845. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  42846. var itemModel = lineData.getItemModel(idx);
  42847. var effectModel = itemModel.getModel('effect');
  42848. var size = effectModel.get('symbolSize');
  42849. var symbolType = effectModel.get('symbol');
  42850. if (!isArray(size)) {
  42851. size = [size, size];
  42852. }
  42853. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  42854. var symbol = this.childAt(1);
  42855. if (this._symbolType !== symbolType) {
  42856. // Remove previous
  42857. this.remove(symbol);
  42858. symbol = createSymbol(
  42859. symbolType, -0.5, -0.5, 1, 1, color
  42860. );
  42861. symbol.z2 = 100;
  42862. symbol.culling = true;
  42863. this.add(symbol);
  42864. }
  42865. // Symbol may be removed if loop is false
  42866. if (!symbol) {
  42867. return;
  42868. }
  42869. // Shadow color is same with color in default
  42870. symbol.setStyle('shadowColor', color);
  42871. symbol.setStyle(effectModel.getItemStyle(['color']));
  42872. symbol.attr('scale', size);
  42873. symbol.setColor(color);
  42874. symbol.attr('scale', size);
  42875. this._symbolType = symbolType;
  42876. this._updateEffectAnimation(lineData, effectModel, idx);
  42877. };
  42878. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  42879. var symbol = this.childAt(1);
  42880. if (!symbol) {
  42881. return;
  42882. }
  42883. var self = this;
  42884. var points = lineData.getItemLayout(idx);
  42885. var period = effectModel.get('period') * 1000;
  42886. var loop = effectModel.get('loop');
  42887. var constantSpeed = effectModel.get('constantSpeed');
  42888. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  42889. return idx / lineData.count() * period / 3;
  42890. });
  42891. var isDelayFunc = typeof delayExpr === 'function';
  42892. // Ignore when updating
  42893. symbol.ignore = true;
  42894. this.updateAnimationPoints(symbol, points);
  42895. if (constantSpeed > 0) {
  42896. period = this.getLineLength(symbol) / constantSpeed * 1000;
  42897. }
  42898. if (period !== this._period || loop !== this._loop) {
  42899. symbol.stopAnimation();
  42900. var delay = delayExpr;
  42901. if (isDelayFunc) {
  42902. delay = delayExpr(idx);
  42903. }
  42904. if (symbol.__t > 0) {
  42905. delay = -period * symbol.__t;
  42906. }
  42907. symbol.__t = 0;
  42908. var animator = symbol.animate('', loop)
  42909. .when(period, {
  42910. __t: 1
  42911. })
  42912. .delay(delay)
  42913. .during(function () {
  42914. self.updateSymbolPosition(symbol);
  42915. });
  42916. if (!loop) {
  42917. animator.done(function () {
  42918. self.remove(symbol);
  42919. });
  42920. }
  42921. animator.start();
  42922. }
  42923. this._period = period;
  42924. this._loop = loop;
  42925. };
  42926. effectLineProto.getLineLength = function (symbol) {
  42927. // Not so accurate
  42928. return (dist(symbol.__p1, symbol.__cp1)
  42929. + dist(symbol.__cp1, symbol.__p2));
  42930. };
  42931. effectLineProto.updateAnimationPoints = function (symbol, points) {
  42932. symbol.__p1 = points[0];
  42933. symbol.__p2 = points[1];
  42934. symbol.__cp1 = points[2] || [
  42935. (points[0][0] + points[1][0]) / 2,
  42936. (points[0][1] + points[1][1]) / 2
  42937. ];
  42938. };
  42939. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  42940. this.childAt(0).updateData(lineData, idx, seriesScope);
  42941. this._updateEffectSymbol(lineData, idx);
  42942. };
  42943. effectLineProto.updateSymbolPosition = function (symbol) {
  42944. var p1 = symbol.__p1;
  42945. var p2 = symbol.__p2;
  42946. var cp1 = symbol.__cp1;
  42947. var t = symbol.__t;
  42948. var pos = symbol.position;
  42949. var quadraticAt$$1 = quadraticAt;
  42950. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  42951. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  42952. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  42953. // Tangent
  42954. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  42955. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  42956. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  42957. symbol.ignore = false;
  42958. };
  42959. effectLineProto.updateLayout = function (lineData, idx) {
  42960. this.childAt(0).updateLayout(lineData, idx);
  42961. var effectModel = lineData.getItemModel(idx).getModel('effect');
  42962. this._updateEffectAnimation(lineData, effectModel, idx);
  42963. };
  42964. inherits(EffectLine, Group);
  42965. /**
  42966. * @module echarts/chart/helper/Line
  42967. */
  42968. /**
  42969. * @constructor
  42970. * @extends {module:zrender/graphic/Group}
  42971. * @alias {module:echarts/chart/helper/Polyline}
  42972. */
  42973. function Polyline$2(lineData, idx, seriesScope) {
  42974. Group.call(this);
  42975. this._createPolyline(lineData, idx, seriesScope);
  42976. }
  42977. var polylineProto = Polyline$2.prototype;
  42978. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  42979. // var seriesModel = lineData.hostModel;
  42980. var points = lineData.getItemLayout(idx);
  42981. var line = new Polyline({
  42982. shape: {
  42983. points: points
  42984. }
  42985. });
  42986. this.add(line);
  42987. this._updateCommonStl(lineData, idx, seriesScope);
  42988. };
  42989. polylineProto.updateData = function (lineData, idx, seriesScope) {
  42990. var seriesModel = lineData.hostModel;
  42991. var line = this.childAt(0);
  42992. var target = {
  42993. shape: {
  42994. points: lineData.getItemLayout(idx)
  42995. }
  42996. };
  42997. updateProps(line, target, seriesModel, idx);
  42998. this._updateCommonStl(lineData, idx, seriesScope);
  42999. };
  43000. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  43001. var line = this.childAt(0);
  43002. var itemModel = lineData.getItemModel(idx);
  43003. var visualColor = lineData.getItemVisual(idx, 'color');
  43004. var lineStyle = seriesScope && seriesScope.lineStyle;
  43005. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  43006. if (!seriesScope || lineData.hasItemOption) {
  43007. lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  43008. hoverLineStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  43009. }
  43010. line.useStyle(defaults(
  43011. {
  43012. strokeNoScale: true,
  43013. fill: 'none',
  43014. stroke: visualColor
  43015. },
  43016. lineStyle
  43017. ));
  43018. line.hoverStyle = hoverLineStyle;
  43019. setHoverStyle(this);
  43020. };
  43021. polylineProto.updateLayout = function (lineData, idx) {
  43022. var polyline = this.childAt(0);
  43023. polyline.setShape('points', lineData.getItemLayout(idx));
  43024. };
  43025. inherits(Polyline$2, Group);
  43026. /**
  43027. * Provide effect for line
  43028. * @module echarts/chart/helper/EffectLine
  43029. */
  43030. /**
  43031. * @constructor
  43032. * @extends {module:echarts/chart/helper/EffectLine}
  43033. * @alias {module:echarts/chart/helper/Polyline}
  43034. */
  43035. function EffectPolyline(lineData, idx, seriesScope) {
  43036. EffectLine.call(this, lineData, idx, seriesScope);
  43037. this._lastFrame = 0;
  43038. this._lastFramePercent = 0;
  43039. }
  43040. var effectPolylineProto = EffectPolyline.prototype;
  43041. // Overwrite
  43042. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  43043. return new Polyline$2(lineData, idx, seriesScope);
  43044. };
  43045. // Overwrite
  43046. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  43047. this._points = points;
  43048. var accLenArr = [0];
  43049. var len$$1 = 0;
  43050. for (var i = 1; i < points.length; i++) {
  43051. var p1 = points[i - 1];
  43052. var p2 = points[i];
  43053. len$$1 += dist(p1, p2);
  43054. accLenArr.push(len$$1);
  43055. }
  43056. if (len$$1 === 0) {
  43057. return;
  43058. }
  43059. for (var i = 0; i < accLenArr.length; i++) {
  43060. accLenArr[i] /= len$$1;
  43061. }
  43062. this._offsets = accLenArr;
  43063. this._length = len$$1;
  43064. };
  43065. // Overwrite
  43066. effectPolylineProto.getLineLength = function (symbol) {
  43067. return this._length;
  43068. };
  43069. // Overwrite
  43070. effectPolylineProto.updateSymbolPosition = function (symbol) {
  43071. var t = symbol.__t;
  43072. var points = this._points;
  43073. var offsets = this._offsets;
  43074. var len$$1 = points.length;
  43075. if (!offsets) {
  43076. // Has length 0
  43077. return;
  43078. }
  43079. var lastFrame = this._lastFrame;
  43080. var frame;
  43081. if (t < this._lastFramePercent) {
  43082. // Start from the next frame
  43083. // PENDING start from lastFrame ?
  43084. var start = Math.min(lastFrame + 1, len$$1 - 1);
  43085. for (frame = start; frame >= 0; frame--) {
  43086. if (offsets[frame] <= t) {
  43087. break;
  43088. }
  43089. }
  43090. // PENDING really need to do this ?
  43091. frame = Math.min(frame, len$$1 - 2);
  43092. }
  43093. else {
  43094. for (var frame = lastFrame; frame < len$$1; frame++) {
  43095. if (offsets[frame] > t) {
  43096. break;
  43097. }
  43098. }
  43099. frame = Math.min(frame - 1, len$$1 - 2);
  43100. }
  43101. lerp(
  43102. symbol.position, points[frame], points[frame + 1],
  43103. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  43104. );
  43105. var tx = points[frame + 1][0] - points[frame][0];
  43106. var ty = points[frame + 1][1] - points[frame][1];
  43107. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  43108. this._lastFrame = frame;
  43109. this._lastFramePercent = t;
  43110. symbol.ignore = false;
  43111. };
  43112. inherits(EffectPolyline, EffectLine);
  43113. // TODO Batch by color
  43114. var LargeLineShape = extendShape({
  43115. shape: {
  43116. polyline: false,
  43117. segs: []
  43118. },
  43119. buildPath: function (path, shape) {
  43120. var segs = shape.segs;
  43121. var isPolyline = shape.polyline;
  43122. for (var i = 0; i < segs.length; i++) {
  43123. var seg = segs[i];
  43124. if (isPolyline) {
  43125. path.moveTo(seg[0][0], seg[0][1]);
  43126. for (var j = 1; j < seg.length; j++) {
  43127. path.lineTo(seg[j][0], seg[j][1]);
  43128. }
  43129. }
  43130. else {
  43131. path.moveTo(seg[0][0], seg[0][1]);
  43132. if (seg.length > 2) {
  43133. path.quadraticCurveTo(seg[2][0], seg[2][1], seg[1][0], seg[1][1]);
  43134. }
  43135. else {
  43136. path.lineTo(seg[1][0], seg[1][1]);
  43137. }
  43138. }
  43139. }
  43140. },
  43141. findDataIndex: function (x, y) {
  43142. var shape = this.shape;
  43143. var segs = shape.segs;
  43144. var isPolyline = shape.polyline;
  43145. var lineWidth = Math.max(this.style.lineWidth, 1);
  43146. // Not consider transform
  43147. for (var i = 0; i < segs.length; i++) {
  43148. var seg = segs[i];
  43149. if (isPolyline) {
  43150. for (var j = 1; j < seg.length; j++) {
  43151. if (containStroke$1(
  43152. seg[j - 1][0], seg[j - 1][1], seg[j][0], seg[j][1], lineWidth, x, y
  43153. )) {
  43154. return i;
  43155. }
  43156. }
  43157. }
  43158. else {
  43159. if (seg.length > 2) {
  43160. if (containStroke$3(
  43161. seg[0][0], seg[0][1], seg[2][0], seg[2][1], seg[1][0], seg[1][1], lineWidth, x, y
  43162. )) {
  43163. return i;
  43164. }
  43165. }
  43166. else {
  43167. if (containStroke$1(
  43168. seg[0][0], seg[0][1], seg[1][0], seg[1][1], lineWidth, x, y
  43169. )) {
  43170. return i;
  43171. }
  43172. }
  43173. }
  43174. }
  43175. return -1;
  43176. }
  43177. });
  43178. function LargeLineDraw() {
  43179. this.group = new Group();
  43180. this._lineEl = new LargeLineShape();
  43181. }
  43182. var largeLineProto = LargeLineDraw.prototype;
  43183. /**
  43184. * Update symbols draw by new data
  43185. * @param {module:echarts/data/List} data
  43186. */
  43187. largeLineProto.updateData = function (data) {
  43188. this.group.removeAll();
  43189. var lineEl = this._lineEl;
  43190. var seriesModel = data.hostModel;
  43191. lineEl.setShape({
  43192. segs: data.mapArray(data.getItemLayout),
  43193. polyline: seriesModel.get('polyline')
  43194. });
  43195. lineEl.useStyle(
  43196. seriesModel.getModel('lineStyle.normal').getLineStyle()
  43197. );
  43198. var visualColor = data.getVisual('color');
  43199. if (visualColor) {
  43200. lineEl.setStyle('stroke', visualColor);
  43201. }
  43202. lineEl.setStyle('fill');
  43203. // Enable tooltip
  43204. // PENDING May have performance issue when path is extremely large
  43205. lineEl.seriesIndex = seriesModel.seriesIndex;
  43206. lineEl.on('mousemove', function (e) {
  43207. lineEl.dataIndex = null;
  43208. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  43209. if (dataIndex > 0) {
  43210. // Provide dataIndex for tooltip
  43211. lineEl.dataIndex = dataIndex;
  43212. }
  43213. });
  43214. // Add back
  43215. this.group.add(lineEl);
  43216. };
  43217. largeLineProto.updateLayout = function (seriesModel) {
  43218. var data = seriesModel.getData();
  43219. this._lineEl.setShape({
  43220. segs: data.mapArray(data.getItemLayout)
  43221. });
  43222. };
  43223. largeLineProto.remove = function () {
  43224. this.group.removeAll();
  43225. };
  43226. extendChartView({
  43227. type: 'lines',
  43228. init: function () {},
  43229. render: function (seriesModel, ecModel, api) {
  43230. var data = seriesModel.getData();
  43231. var lineDraw = this._lineDraw;
  43232. var hasEffect = seriesModel.get('effect.show');
  43233. var isPolyline = seriesModel.get('polyline');
  43234. var isLarge = seriesModel.get('large') && data.count() >= seriesModel.get('largeThreshold');
  43235. if (__DEV__) {
  43236. if (hasEffect && isLarge) {
  43237. console.warn('Large lines not support effect');
  43238. }
  43239. }
  43240. if (hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLarge !== this._isLarge) {
  43241. if (lineDraw) {
  43242. lineDraw.remove();
  43243. }
  43244. lineDraw = this._lineDraw = isLarge
  43245. ? new LargeLineDraw()
  43246. : new LineDraw(
  43247. isPolyline
  43248. ? (hasEffect ? EffectPolyline : Polyline$2)
  43249. : (hasEffect ? EffectLine : Line$1)
  43250. );
  43251. this._hasEffet = hasEffect;
  43252. this._isPolyline = isPolyline;
  43253. this._isLarge = isLarge;
  43254. }
  43255. var zlevel = seriesModel.get('zlevel');
  43256. var trailLength = seriesModel.get('effect.trailLength');
  43257. var zr = api.getZr();
  43258. // Avoid the drag cause ghost shadow
  43259. // FIXME Better way ?
  43260. // SVG doesn't support
  43261. var isSvg = zr.painter.getType() === 'svg';
  43262. if (!isSvg) {
  43263. zr.painter.getLayer(zlevel).clear(true);
  43264. }
  43265. // Config layer with motion blur
  43266. if (this._lastZlevel != null && !isSvg) {
  43267. zr.configLayer(this._lastZlevel, {
  43268. motionBlur: false
  43269. });
  43270. }
  43271. if (hasEffect && trailLength) {
  43272. if (__DEV__) {
  43273. var notInIndividual = false;
  43274. ecModel.eachSeries(function (otherSeriesModel) {
  43275. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  43276. notInIndividual = true;
  43277. }
  43278. });
  43279. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  43280. }
  43281. if (!isSvg) {
  43282. zr.configLayer(zlevel, {
  43283. motionBlur: true,
  43284. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  43285. });
  43286. }
  43287. }
  43288. this.group.add(lineDraw.group);
  43289. lineDraw.updateData(data);
  43290. this._lastZlevel = zlevel;
  43291. },
  43292. updateLayout: function (seriesModel, ecModel, api) {
  43293. this._lineDraw.updateLayout(seriesModel);
  43294. // Not use motion when dragging or zooming
  43295. var zr = api.getZr();
  43296. var isSvg = zr.painter.getType() === 'svg';
  43297. if (!isSvg) {
  43298. zr.painter.getLayer(this._lastZlevel).clear(true);
  43299. }
  43300. },
  43301. remove: function (ecModel, api) {
  43302. this._lineDraw && this._lineDraw.remove(api, true);
  43303. // Clear motion when lineDraw is removed
  43304. var zr = api.getZr();
  43305. var isSvg = zr.painter.getType() === 'svg';
  43306. if (!isSvg) {
  43307. zr.painter.getLayer(this._lastZlevel).clear(true);
  43308. }
  43309. },
  43310. dispose: function () {}
  43311. });
  43312. var linesLayout = function (ecModel) {
  43313. ecModel.eachSeriesByType('lines', function (seriesModel) {
  43314. var coordSys = seriesModel.coordinateSystem;
  43315. var lineData = seriesModel.getData();
  43316. // FIXME Use data dimensions ?
  43317. lineData.each(function (idx) {
  43318. var itemModel = lineData.getItemModel(idx);
  43319. var coords = (itemModel.option instanceof Array) ?
  43320. itemModel.option : itemModel.get('coords');
  43321. if (__DEV__) {
  43322. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  43323. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  43324. }
  43325. }
  43326. var pts = [];
  43327. if (seriesModel.get('polyline')) {
  43328. for (var i = 0; i < coords.length; i++) {
  43329. pts.push(coordSys.dataToPoint(coords[i]));
  43330. }
  43331. }
  43332. else {
  43333. pts[0] = coordSys.dataToPoint(coords[0]);
  43334. pts[1] = coordSys.dataToPoint(coords[1]);
  43335. var curveness = itemModel.get('lineStyle.normal.curveness');
  43336. if (+curveness) {
  43337. pts[2] = [
  43338. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  43339. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  43340. ];
  43341. }
  43342. }
  43343. lineData.setItemLayout(idx, pts);
  43344. });
  43345. });
  43346. };
  43347. function normalize$2(a) {
  43348. if (!(a instanceof Array)) {
  43349. a = [a, a];
  43350. }
  43351. return a;
  43352. }
  43353. var linesVisual = function (ecModel) {
  43354. ecModel.eachSeriesByType('lines', function (seriesModel) {
  43355. var data = seriesModel.getData();
  43356. var symbolType = normalize$2(seriesModel.get('symbol'));
  43357. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  43358. var opacityQuery = 'lineStyle.normal.opacity'.split('.');
  43359. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  43360. data.setVisual('toSymbol', symbolType && symbolType[1]);
  43361. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  43362. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  43363. data.setVisual('opacity', seriesModel.get(opacityQuery));
  43364. data.each(function (idx) {
  43365. var itemModel = data.getItemModel(idx);
  43366. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  43367. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  43368. var opacity = itemModel.get(opacityQuery);
  43369. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  43370. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  43371. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  43372. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  43373. data.setItemVisual(idx, 'opacity', opacity);
  43374. });
  43375. });
  43376. };
  43377. registerLayout(linesLayout);
  43378. registerVisual(linesVisual);
  43379. SeriesModel.extend({
  43380. type: 'series.heatmap',
  43381. getInitialData: function (option, ecModel) {
  43382. return createListFromArray(option.data, this, ecModel);
  43383. },
  43384. defaultOption: {
  43385. // Cartesian2D or geo
  43386. coordinateSystem: 'cartesian2d',
  43387. zlevel: 0,
  43388. z: 2,
  43389. // Cartesian coordinate system
  43390. // xAxisIndex: 0,
  43391. // yAxisIndex: 0,
  43392. // Geo coordinate system
  43393. geoIndex: 0,
  43394. blurSize: 30,
  43395. pointSize: 20,
  43396. maxOpacity: 1,
  43397. minOpacity: 0
  43398. }
  43399. });
  43400. /**
  43401. * @file defines echarts Heatmap Chart
  43402. * @author Ovilia (me@zhangwenli.com)
  43403. * Inspired by https://github.com/mourner/simpleheat
  43404. *
  43405. * @module
  43406. */
  43407. var GRADIENT_LEVELS = 256;
  43408. /**
  43409. * Heatmap Chart
  43410. *
  43411. * @class
  43412. */
  43413. function Heatmap() {
  43414. var canvas = createCanvas();
  43415. this.canvas = canvas;
  43416. this.blurSize = 30;
  43417. this.pointSize = 20;
  43418. this.maxOpacity = 1;
  43419. this.minOpacity = 0;
  43420. this._gradientPixels = {};
  43421. }
  43422. Heatmap.prototype = {
  43423. /**
  43424. * Renders Heatmap and returns the rendered canvas
  43425. * @param {Array} data array of data, each has x, y, value
  43426. * @param {number} width canvas width
  43427. * @param {number} height canvas height
  43428. */
  43429. update: function(data, width, height, normalize, colorFunc, isInRange) {
  43430. var brush = this._getBrush();
  43431. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  43432. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  43433. var r = this.pointSize + this.blurSize;
  43434. var canvas = this.canvas;
  43435. var ctx = canvas.getContext('2d');
  43436. var len = data.length;
  43437. canvas.width = width;
  43438. canvas.height = height;
  43439. for (var i = 0; i < len; ++i) {
  43440. var p = data[i];
  43441. var x = p[0];
  43442. var y = p[1];
  43443. var value = p[2];
  43444. // calculate alpha using value
  43445. var alpha = normalize(value);
  43446. // draw with the circle brush with alpha
  43447. ctx.globalAlpha = alpha;
  43448. ctx.drawImage(brush, x - r, y - r);
  43449. }
  43450. if (!canvas.width || !canvas.height) {
  43451. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  43452. // 'CanvasRenderingContext2D': The source height is 0."
  43453. return canvas;
  43454. }
  43455. // colorize the canvas using alpha value and set with gradient
  43456. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  43457. var pixels = imageData.data;
  43458. var offset = 0;
  43459. var pixelLen = pixels.length;
  43460. var minOpacity = this.minOpacity;
  43461. var maxOpacity = this.maxOpacity;
  43462. var diffOpacity = maxOpacity - minOpacity;
  43463. while(offset < pixelLen) {
  43464. var alpha = pixels[offset + 3] / 256;
  43465. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  43466. // Simple optimize to ignore the empty data
  43467. if (alpha > 0) {
  43468. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  43469. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  43470. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  43471. pixels[offset++] = gradient[gradientOffset];
  43472. pixels[offset++] = gradient[gradientOffset + 1];
  43473. pixels[offset++] = gradient[gradientOffset + 2];
  43474. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  43475. }
  43476. else {
  43477. offset += 4;
  43478. }
  43479. }
  43480. ctx.putImageData(imageData, 0, 0);
  43481. return canvas;
  43482. },
  43483. /**
  43484. * get canvas of a black circle brush used for canvas to draw later
  43485. * @private
  43486. * @returns {Object} circle brush canvas
  43487. */
  43488. _getBrush: function() {
  43489. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  43490. // set brush size
  43491. var r = this.pointSize + this.blurSize;
  43492. var d = r * 2;
  43493. brushCanvas.width = d;
  43494. brushCanvas.height = d;
  43495. var ctx = brushCanvas.getContext('2d');
  43496. ctx.clearRect(0, 0, d, d);
  43497. // in order to render shadow without the distinct circle,
  43498. // draw the distinct circle in an invisible place,
  43499. // and use shadowOffset to draw shadow in the center of the canvas
  43500. ctx.shadowOffsetX = d;
  43501. ctx.shadowBlur = this.blurSize;
  43502. // draw the shadow in black, and use alpha and shadow blur to generate
  43503. // color in color map
  43504. ctx.shadowColor = '#000';
  43505. // draw circle in the left to the canvas
  43506. ctx.beginPath();
  43507. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  43508. ctx.closePath();
  43509. ctx.fill();
  43510. return brushCanvas;
  43511. },
  43512. /**
  43513. * get gradient color map
  43514. * @private
  43515. */
  43516. _getGradient: function (data, colorFunc, state) {
  43517. var gradientPixels = this._gradientPixels;
  43518. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  43519. var color = [0, 0, 0, 0];
  43520. var off = 0;
  43521. for (var i = 0; i < 256; i++) {
  43522. colorFunc[state](i / 255, true, color);
  43523. pixelsSingleState[off++] = color[0];
  43524. pixelsSingleState[off++] = color[1];
  43525. pixelsSingleState[off++] = color[2];
  43526. pixelsSingleState[off++] = color[3];
  43527. }
  43528. return pixelsSingleState;
  43529. }
  43530. };
  43531. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  43532. var dataSpan = dataExtent[1] - dataExtent[0];
  43533. pieceList = map(pieceList, function (piece) {
  43534. return {
  43535. interval: [
  43536. (piece.interval[0] - dataExtent[0]) / dataSpan,
  43537. (piece.interval[1] - dataExtent[0]) / dataSpan
  43538. ]
  43539. };
  43540. });
  43541. var len = pieceList.length;
  43542. var lastIndex = 0;
  43543. return function (val) {
  43544. // Try to find in the location of the last found
  43545. for (var i = lastIndex; i < len; i++) {
  43546. var interval = pieceList[i].interval;
  43547. if (interval[0] <= val && val <= interval[1]) {
  43548. lastIndex = i;
  43549. break;
  43550. }
  43551. }
  43552. if (i === len) { // Not found, back interation
  43553. for (var i = lastIndex - 1; i >= 0; i--) {
  43554. var interval = pieceList[i].interval;
  43555. if (interval[0] <= val && val <= interval[1]) {
  43556. lastIndex = i;
  43557. break;
  43558. }
  43559. }
  43560. }
  43561. return i >= 0 && i < len && selected[i];
  43562. };
  43563. }
  43564. function getIsInContinuousRange(dataExtent, range) {
  43565. var dataSpan = dataExtent[1] - dataExtent[0];
  43566. range = [
  43567. (range[0] - dataExtent[0]) / dataSpan,
  43568. (range[1] - dataExtent[0]) / dataSpan
  43569. ];
  43570. return function (val) {
  43571. return val >= range[0] && val <= range[1];
  43572. };
  43573. }
  43574. function isGeoCoordSys(coordSys) {
  43575. var dimensions = coordSys.dimensions;
  43576. // Not use coorSys.type === 'geo' because coordSys maybe extended
  43577. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  43578. }
  43579. extendChartView({
  43580. type: 'heatmap',
  43581. render: function (seriesModel, ecModel, api) {
  43582. var visualMapOfThisSeries;
  43583. ecModel.eachComponent('visualMap', function (visualMap) {
  43584. visualMap.eachTargetSeries(function (targetSeries) {
  43585. if (targetSeries === seriesModel) {
  43586. visualMapOfThisSeries = visualMap;
  43587. }
  43588. });
  43589. });
  43590. if (__DEV__) {
  43591. if (!visualMapOfThisSeries) {
  43592. throw new Error('Heatmap must use with visualMap');
  43593. }
  43594. }
  43595. this.group.removeAll();
  43596. var coordSys = seriesModel.coordinateSystem;
  43597. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  43598. this._renderOnCartesianAndCalendar(coordSys, seriesModel, api);
  43599. }
  43600. else if (isGeoCoordSys(coordSys)) {
  43601. this._renderOnGeo(
  43602. coordSys, seriesModel, visualMapOfThisSeries, api
  43603. );
  43604. }
  43605. },
  43606. dispose: function () {},
  43607. _renderOnCartesianAndCalendar: function (coordSys, seriesModel, api) {
  43608. if (coordSys.type === 'cartesian2d') {
  43609. var xAxis = coordSys.getAxis('x');
  43610. var yAxis = coordSys.getAxis('y');
  43611. if (__DEV__) {
  43612. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  43613. throw new Error('Heatmap on cartesian must have two category axes');
  43614. }
  43615. if (!(xAxis.onBand && yAxis.onBand)) {
  43616. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  43617. }
  43618. }
  43619. var width = xAxis.getBandWidth();
  43620. var height = yAxis.getBandWidth();
  43621. }
  43622. var group = this.group;
  43623. var data = seriesModel.getData();
  43624. var itemStyleQuery = 'itemStyle.normal';
  43625. var hoverItemStyleQuery = 'itemStyle.emphasis';
  43626. var labelQuery = 'label.normal';
  43627. var hoverLabelQuery = 'label.emphasis';
  43628. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  43629. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  43630. var labelModel = seriesModel.getModel('label.normal');
  43631. var hoverLabelModel = seriesModel.getModel('label.emphasis');
  43632. var coordSysType = coordSys.type;
  43633. var dataDims = coordSysType === 'cartesian2d'
  43634. ? [
  43635. seriesModel.coordDimToDataDim('x')[0],
  43636. seriesModel.coordDimToDataDim('y')[0],
  43637. seriesModel.coordDimToDataDim('value')[0]
  43638. ]
  43639. : [
  43640. seriesModel.coordDimToDataDim('time')[0],
  43641. seriesModel.coordDimToDataDim('value')[0]
  43642. ];
  43643. data.each(function (idx) {
  43644. var rect;
  43645. if (coordSysType === 'cartesian2d') {
  43646. // Ignore empty data
  43647. if (isNaN(data.get(dataDims[2], idx))) {
  43648. return;
  43649. }
  43650. var point = coordSys.dataToPoint([
  43651. data.get(dataDims[0], idx),
  43652. data.get(dataDims[1], idx)
  43653. ]);
  43654. rect = new Rect({
  43655. shape: {
  43656. x: point[0] - width / 2,
  43657. y: point[1] - height / 2,
  43658. width: width,
  43659. height: height
  43660. },
  43661. style: {
  43662. fill: data.getItemVisual(idx, 'color'),
  43663. opacity: data.getItemVisual(idx, 'opacity')
  43664. }
  43665. });
  43666. }
  43667. else {
  43668. // Ignore empty data
  43669. if (isNaN(data.get(dataDims[1], idx))) {
  43670. return;
  43671. }
  43672. rect = new Rect({
  43673. z2: 1,
  43674. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  43675. style: {
  43676. fill: data.getItemVisual(idx, 'color'),
  43677. opacity: data.getItemVisual(idx, 'opacity')
  43678. }
  43679. });
  43680. }
  43681. var itemModel = data.getItemModel(idx);
  43682. // Optimization for large datset
  43683. if (data.hasItemOption) {
  43684. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  43685. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  43686. labelModel = itemModel.getModel(labelQuery);
  43687. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  43688. }
  43689. var rawValue = seriesModel.getRawValue(idx);
  43690. var defaultText = '-';
  43691. if (rawValue && rawValue[2] != null) {
  43692. defaultText = rawValue[2];
  43693. }
  43694. setLabelStyle(
  43695. style, hoverStl, labelModel, hoverLabelModel,
  43696. {
  43697. labelFetcher: seriesModel,
  43698. labelDataIndex: idx,
  43699. defaultText: defaultText,
  43700. isRectText: true
  43701. }
  43702. );
  43703. rect.setStyle(style);
  43704. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  43705. group.add(rect);
  43706. data.setItemGraphicEl(idx, rect);
  43707. });
  43708. },
  43709. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  43710. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  43711. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  43712. // if (!visualMapping) {
  43713. // throw new Error('Data range must have color visuals');
  43714. // }
  43715. var data = seriesModel.getData();
  43716. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  43717. hmLayer.blurSize = seriesModel.get('blurSize');
  43718. hmLayer.pointSize = seriesModel.get('pointSize');
  43719. hmLayer.minOpacity = seriesModel.get('minOpacity');
  43720. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  43721. var rect = geo.getViewRect().clone();
  43722. var roamTransform = geo.getRoamTransform().transform;
  43723. rect.applyTransform(roamTransform);
  43724. // Clamp on viewport
  43725. var x = Math.max(rect.x, 0);
  43726. var y = Math.max(rect.y, 0);
  43727. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  43728. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  43729. var width = x2 - x;
  43730. var height = y2 - y;
  43731. var points = data.mapArray(['lng', 'lat', 'value'], function (lng, lat, value) {
  43732. var pt = geo.dataToPoint([lng, lat]);
  43733. pt[0] -= x;
  43734. pt[1] -= y;
  43735. pt.push(value);
  43736. return pt;
  43737. });
  43738. var dataExtent = visualMapModel.getExtent();
  43739. var isInRange = visualMapModel.type === 'visualMap.continuous'
  43740. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  43741. : getIsInPiecewiseRange(
  43742. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  43743. );
  43744. hmLayer.update(
  43745. points, width, height,
  43746. inRangeVisuals.color.getNormalizer(),
  43747. {
  43748. inRange: inRangeVisuals.color.getColorMapper(),
  43749. outOfRange: outOfRangeVisuals.color.getColorMapper()
  43750. },
  43751. isInRange
  43752. );
  43753. var img = new ZImage({
  43754. style: {
  43755. width: width,
  43756. height: height,
  43757. x: x,
  43758. y: y,
  43759. image: hmLayer.canvas
  43760. },
  43761. silent: true
  43762. });
  43763. this.group.add(img);
  43764. }
  43765. });
  43766. var PictorialBarSeries = BaseBarSeries.extend({
  43767. type: 'series.pictorialBar',
  43768. dependencies: ['grid'],
  43769. defaultOption: {
  43770. symbol: 'circle', // Customized bar shape
  43771. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  43772. symbolRotate: null,
  43773. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  43774. symbolOffset: null,
  43775. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  43776. // Auto margin by defualt.
  43777. symbolRepeat: false, // false/null/undefined, means no repeat.
  43778. // Can be true, means auto calculate repeat times and cut by data.
  43779. // Can be a number, specifies repeat times, and do not cut by data.
  43780. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  43781. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  43782. symbolClip: false,
  43783. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  43784. symbolPatternSize: 400, // 400 * 400 px
  43785. barGap: '-100%', // In most case, overlap is needed.
  43786. // z can be set in data item, which is z2 actually.
  43787. // Disable progressive
  43788. progressive: 0,
  43789. hoverAnimation: false // Open only when needed.
  43790. },
  43791. getInitialData: function (option) {
  43792. // Disable stack.
  43793. option.stack = null;
  43794. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  43795. }
  43796. });
  43797. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'normal', 'borderWidth'];
  43798. // index: +isHorizontal
  43799. var LAYOUT_ATTRS = [
  43800. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  43801. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  43802. ];
  43803. var pathForLineWidth = new Circle();
  43804. var BarView$1 = extendChartView({
  43805. type: 'pictorialBar',
  43806. render: function (seriesModel, ecModel, api) {
  43807. var group = this.group;
  43808. var data = seriesModel.getData();
  43809. var oldData = this._data;
  43810. var cartesian = seriesModel.coordinateSystem;
  43811. var baseAxis = cartesian.getBaseAxis();
  43812. var isHorizontal = !!baseAxis.isHorizontal();
  43813. var coordSysRect = cartesian.grid.getRect();
  43814. var opt = {
  43815. ecSize: {width: api.getWidth(), height: api.getHeight()},
  43816. seriesModel: seriesModel,
  43817. coordSys: cartesian,
  43818. coordSysExtent: [
  43819. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  43820. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  43821. ],
  43822. isHorizontal: isHorizontal,
  43823. valueDim: LAYOUT_ATTRS[+isHorizontal],
  43824. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  43825. };
  43826. data.diff(oldData)
  43827. .add(function (dataIndex) {
  43828. if (!data.hasValue(dataIndex)) {
  43829. return;
  43830. }
  43831. var itemModel = getItemModel(data, dataIndex);
  43832. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  43833. var bar = createBar(data, opt, symbolMeta);
  43834. data.setItemGraphicEl(dataIndex, bar);
  43835. group.add(bar);
  43836. updateCommon$1(bar, opt, symbolMeta);
  43837. })
  43838. .update(function (newIndex, oldIndex) {
  43839. var bar = oldData.getItemGraphicEl(oldIndex);
  43840. if (!data.hasValue(newIndex)) {
  43841. group.remove(bar);
  43842. return;
  43843. }
  43844. var itemModel = getItemModel(data, newIndex);
  43845. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  43846. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  43847. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  43848. group.remove(bar);
  43849. data.setItemGraphicEl(newIndex, null);
  43850. bar = null;
  43851. }
  43852. if (bar) {
  43853. updateBar(bar, opt, symbolMeta);
  43854. }
  43855. else {
  43856. bar = createBar(data, opt, symbolMeta, true);
  43857. }
  43858. data.setItemGraphicEl(newIndex, bar);
  43859. bar.__pictorialSymbolMeta = symbolMeta;
  43860. // Add back
  43861. group.add(bar);
  43862. updateCommon$1(bar, opt, symbolMeta);
  43863. })
  43864. .remove(function (dataIndex) {
  43865. var bar = oldData.getItemGraphicEl(dataIndex);
  43866. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  43867. })
  43868. .execute();
  43869. this._data = data;
  43870. return this.group;
  43871. },
  43872. dispose: noop,
  43873. remove: function (ecModel, api) {
  43874. var group = this.group;
  43875. var data = this._data;
  43876. if (ecModel.get('animation')) {
  43877. if (data) {
  43878. data.eachItemGraphicEl(function (bar) {
  43879. removeBar(data, bar.dataIndex, ecModel, bar);
  43880. });
  43881. }
  43882. }
  43883. else {
  43884. group.removeAll();
  43885. }
  43886. }
  43887. });
  43888. // Set or calculate default value about symbol, and calculate layout info.
  43889. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  43890. var layout = data.getItemLayout(dataIndex);
  43891. var symbolRepeat = itemModel.get('symbolRepeat');
  43892. var symbolClip = itemModel.get('symbolClip');
  43893. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  43894. var symbolRotate = itemModel.get('symbolRotate');
  43895. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  43896. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  43897. var isAnimationEnabled = itemModel.isAnimationEnabled();
  43898. var symbolMeta = {
  43899. dataIndex: dataIndex,
  43900. layout: layout,
  43901. itemModel: itemModel,
  43902. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  43903. color: data.getItemVisual(dataIndex, 'color'),
  43904. symbolClip: symbolClip,
  43905. symbolRepeat: symbolRepeat,
  43906. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  43907. symbolPatternSize: symbolPatternSize,
  43908. rotation: rotation,
  43909. animationModel: isAnimationEnabled ? itemModel : null,
  43910. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  43911. z2: itemModel.getShallow('z', true) || 0
  43912. };
  43913. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  43914. prepareSymbolSize(
  43915. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  43916. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  43917. );
  43918. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  43919. var symbolSize = symbolMeta.symbolSize;
  43920. var symbolOffset = itemModel.get('symbolOffset');
  43921. if (isArray(symbolOffset)) {
  43922. symbolOffset = [
  43923. parsePercent$1(symbolOffset[0], symbolSize[0]),
  43924. parsePercent$1(symbolOffset[1], symbolSize[1])
  43925. ];
  43926. }
  43927. prepareLayoutInfo(
  43928. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  43929. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  43930. opt, symbolMeta
  43931. );
  43932. return symbolMeta;
  43933. }
  43934. // bar length can be negative.
  43935. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  43936. var valueDim = opt.valueDim;
  43937. var symbolBoundingData = itemModel.get('symbolBoundingData');
  43938. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  43939. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  43940. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  43941. var boundingLength;
  43942. if (isArray(symbolBoundingData)) {
  43943. var symbolBoundingExtent = [
  43944. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  43945. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  43946. ];
  43947. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  43948. boundingLength = symbolBoundingExtent[pxSignIdx];
  43949. }
  43950. else if (symbolBoundingData != null) {
  43951. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  43952. }
  43953. else if (symbolRepeat) {
  43954. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  43955. }
  43956. else {
  43957. boundingLength = layout[valueDim.wh];
  43958. }
  43959. output.boundingLength = boundingLength;
  43960. if (symbolRepeat) {
  43961. output.repeatCutLength = layout[valueDim.wh];
  43962. }
  43963. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  43964. }
  43965. function convertToCoordOnAxis(axis, value) {
  43966. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  43967. }
  43968. // Support ['100%', '100%']
  43969. function prepareSymbolSize(
  43970. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  43971. pxSign, symbolPatternSize, opt, output
  43972. ) {
  43973. var valueDim = opt.valueDim;
  43974. var categoryDim = opt.categoryDim;
  43975. var categorySize = Math.abs(layout[categoryDim.wh]);
  43976. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  43977. if (isArray(symbolSize)) {
  43978. symbolSize = symbolSize.slice();
  43979. }
  43980. else {
  43981. if (symbolSize == null) {
  43982. symbolSize = '100%';
  43983. }
  43984. symbolSize = [symbolSize, symbolSize];
  43985. }
  43986. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  43987. // to complicated to calculate real percent value if considering scaled lineWidth.
  43988. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  43989. // which can be tolerated in pictorial chart.
  43990. symbolSize[categoryDim.index] = parsePercent$1(
  43991. symbolSize[categoryDim.index],
  43992. categorySize
  43993. );
  43994. symbolSize[valueDim.index] = parsePercent$1(
  43995. symbolSize[valueDim.index],
  43996. symbolRepeat ? categorySize : Math.abs(boundingLength)
  43997. );
  43998. output.symbolSize = symbolSize;
  43999. // If x or y is less than zero, show reversed shape.
  44000. var symbolScale = output.symbolScale = [
  44001. symbolSize[0] / symbolPatternSize,
  44002. symbolSize[1] / symbolPatternSize
  44003. ];
  44004. // Follow convention, 'right' and 'top' is the normal scale.
  44005. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  44006. }
  44007. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  44008. // In symbols are drawn with scale, so do not need to care about the case that width
  44009. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  44010. // be calculated.
  44011. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  44012. if (valueLineWidth) {
  44013. pathForLineWidth.attr({
  44014. scale: symbolScale.slice(),
  44015. rotation: rotation
  44016. });
  44017. pathForLineWidth.updateTransform();
  44018. valueLineWidth /= pathForLineWidth.getLineScale();
  44019. valueLineWidth *= symbolScale[opt.valueDim.index];
  44020. }
  44021. output.valueLineWidth = valueLineWidth;
  44022. }
  44023. function prepareLayoutInfo(
  44024. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  44025. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  44026. ) {
  44027. var categoryDim = opt.categoryDim;
  44028. var valueDim = opt.valueDim;
  44029. var pxSign = output.pxSign;
  44030. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  44031. var pathLen = unitLength;
  44032. // Note: rotation will not effect the layout of symbols, because user may
  44033. // want symbols to rotate on its center, which should not be translated
  44034. // when rotating.
  44035. if (symbolRepeat) {
  44036. var absBoundingLength = Math.abs(boundingLength);
  44037. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  44038. var hasEndGap = false;
  44039. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  44040. hasEndGap = true;
  44041. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  44042. }
  44043. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  44044. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  44045. // When symbol margin is less than 0, margin at both ends will be subtracted
  44046. // to ensure that all of the symbols will not be overflow the given area.
  44047. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  44048. // Both final repeatTimes and final symbolMargin area calculated based on
  44049. // boundingLength.
  44050. var repeatSpecified = isNumeric(symbolRepeat);
  44051. var repeatTimes = repeatSpecified
  44052. ? symbolRepeat
  44053. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  44054. // Adjust calculate margin, to ensure each symbol is displayed
  44055. // entirely in the given layout area.
  44056. var mDiff = absBoundingLength - repeatTimes * unitLength;
  44057. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  44058. uLenWithMargin = unitLength + symbolMargin * 2;
  44059. endFix = hasEndGap ? 0 : symbolMargin * 2;
  44060. // Update repeatTimes when not all symbol will be shown.
  44061. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  44062. repeatTimes = repeatCutLength
  44063. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  44064. : 0;
  44065. }
  44066. pathLen = repeatTimes * uLenWithMargin - endFix;
  44067. output.repeatTimes = repeatTimes;
  44068. output.symbolMargin = symbolMargin;
  44069. }
  44070. var sizeFix = pxSign * (pathLen / 2);
  44071. var pathPosition = output.pathPosition = [];
  44072. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  44073. pathPosition[valueDim.index] = symbolPosition === 'start'
  44074. ? sizeFix
  44075. : symbolPosition === 'end'
  44076. ? boundingLength - sizeFix
  44077. : boundingLength / 2; // 'center'
  44078. if (symbolOffset) {
  44079. pathPosition[0] += symbolOffset[0];
  44080. pathPosition[1] += symbolOffset[1];
  44081. }
  44082. var bundlePosition = output.bundlePosition = [];
  44083. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  44084. bundlePosition[valueDim.index] = layout[valueDim.xy];
  44085. var barRectShape = output.barRectShape = extend({}, layout);
  44086. barRectShape[valueDim.wh] = pxSign * Math.max(
  44087. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  44088. );
  44089. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  44090. var clipShape = output.clipShape = {};
  44091. // Consider that symbol may be overflow layout rect.
  44092. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  44093. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  44094. clipShape[valueDim.xy] = 0;
  44095. clipShape[valueDim.wh] = layout[valueDim.wh];
  44096. }
  44097. function createPath(symbolMeta) {
  44098. var symbolPatternSize = symbolMeta.symbolPatternSize;
  44099. var path = createSymbol(
  44100. // Consider texture img, make a big size.
  44101. symbolMeta.symbolType,
  44102. -symbolPatternSize / 2,
  44103. -symbolPatternSize / 2,
  44104. symbolPatternSize,
  44105. symbolPatternSize,
  44106. symbolMeta.color
  44107. );
  44108. path.attr({
  44109. culling: true
  44110. });
  44111. path.type !== 'image' && path.setStyle({
  44112. strokeNoScale: true
  44113. });
  44114. return path;
  44115. }
  44116. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  44117. var bundle = bar.__pictorialBundle;
  44118. var symbolSize = symbolMeta.symbolSize;
  44119. var valueLineWidth = symbolMeta.valueLineWidth;
  44120. var pathPosition = symbolMeta.pathPosition;
  44121. var valueDim = opt.valueDim;
  44122. var repeatTimes = symbolMeta.repeatTimes || 0;
  44123. var index = 0;
  44124. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  44125. eachPath(bar, function (path) {
  44126. path.__pictorialAnimationIndex = index;
  44127. path.__pictorialRepeatTimes = repeatTimes;
  44128. if (index < repeatTimes) {
  44129. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  44130. }
  44131. else {
  44132. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  44133. bundle.remove(path);
  44134. });
  44135. }
  44136. updateHoverAnimation(path, symbolMeta);
  44137. index++;
  44138. });
  44139. for (; index < repeatTimes; index++) {
  44140. var path = createPath(symbolMeta);
  44141. path.__pictorialAnimationIndex = index;
  44142. path.__pictorialRepeatTimes = repeatTimes;
  44143. bundle.add(path);
  44144. var target = makeTarget(index);
  44145. updateAttr(
  44146. path,
  44147. {
  44148. position: target.position,
  44149. scale: [0, 0]
  44150. },
  44151. {
  44152. scale: target.scale,
  44153. rotation: target.rotation
  44154. },
  44155. symbolMeta,
  44156. isUpdate
  44157. );
  44158. // FIXME
  44159. // If all emphasis/normal through action.
  44160. path
  44161. .on('mouseover', onMouseOver)
  44162. .on('mouseout', onMouseOut);
  44163. updateHoverAnimation(path, symbolMeta);
  44164. }
  44165. function makeTarget(index) {
  44166. var position = pathPosition.slice();
  44167. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  44168. // Otherwise: i = index;
  44169. var pxSign = symbolMeta.pxSign;
  44170. var i = index;
  44171. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  44172. i = repeatTimes - 1 - index;
  44173. }
  44174. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  44175. return {
  44176. position: position,
  44177. scale: symbolMeta.symbolScale.slice(),
  44178. rotation: symbolMeta.rotation
  44179. };
  44180. }
  44181. function onMouseOver() {
  44182. eachPath(bar, function (path) {
  44183. path.trigger('emphasis');
  44184. });
  44185. }
  44186. function onMouseOut() {
  44187. eachPath(bar, function (path) {
  44188. path.trigger('normal');
  44189. });
  44190. }
  44191. }
  44192. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  44193. var bundle = bar.__pictorialBundle;
  44194. var mainPath = bar.__pictorialMainPath;
  44195. if (!mainPath) {
  44196. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  44197. bundle.add(mainPath);
  44198. updateAttr(
  44199. mainPath,
  44200. {
  44201. position: symbolMeta.pathPosition.slice(),
  44202. scale: [0, 0],
  44203. rotation: symbolMeta.rotation
  44204. },
  44205. {
  44206. scale: symbolMeta.symbolScale.slice()
  44207. },
  44208. symbolMeta,
  44209. isUpdate
  44210. );
  44211. mainPath
  44212. .on('mouseover', onMouseOver)
  44213. .on('mouseout', onMouseOut);
  44214. }
  44215. else {
  44216. updateAttr(
  44217. mainPath,
  44218. null,
  44219. {
  44220. position: symbolMeta.pathPosition.slice(),
  44221. scale: symbolMeta.symbolScale.slice(),
  44222. rotation: symbolMeta.rotation
  44223. },
  44224. symbolMeta,
  44225. isUpdate
  44226. );
  44227. }
  44228. updateHoverAnimation(mainPath, symbolMeta);
  44229. function onMouseOver() {
  44230. this.trigger('emphasis');
  44231. }
  44232. function onMouseOut() {
  44233. this.trigger('normal');
  44234. }
  44235. }
  44236. // bar rect is used for label.
  44237. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  44238. var rectShape = extend({}, symbolMeta.barRectShape);
  44239. var barRect = bar.__pictorialBarRect;
  44240. if (!barRect) {
  44241. barRect = bar.__pictorialBarRect = new Rect({
  44242. z2: 2,
  44243. shape: rectShape,
  44244. silent: true,
  44245. style: {
  44246. stroke: 'transparent',
  44247. fill: 'transparent',
  44248. lineWidth: 0
  44249. }
  44250. });
  44251. bar.add(barRect);
  44252. }
  44253. else {
  44254. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  44255. }
  44256. }
  44257. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  44258. // If not clip, symbol will be remove and rebuilt.
  44259. if (symbolMeta.symbolClip) {
  44260. var clipPath = bar.__pictorialClipPath;
  44261. var clipShape = extend({}, symbolMeta.clipShape);
  44262. var valueDim = opt.valueDim;
  44263. var animationModel = symbolMeta.animationModel;
  44264. var dataIndex = symbolMeta.dataIndex;
  44265. if (clipPath) {
  44266. updateProps(
  44267. clipPath, {shape: clipShape}, animationModel, dataIndex
  44268. );
  44269. }
  44270. else {
  44271. clipShape[valueDim.wh] = 0;
  44272. clipPath = new Rect({shape: clipShape});
  44273. bar.__pictorialBundle.setClipPath(clipPath);
  44274. bar.__pictorialClipPath = clipPath;
  44275. var target = {};
  44276. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  44277. graphic[isUpdate ? 'updateProps' : 'initProps'](
  44278. clipPath, {shape: target}, animationModel, dataIndex
  44279. );
  44280. }
  44281. }
  44282. }
  44283. function getItemModel(data, dataIndex) {
  44284. var itemModel = data.getItemModel(dataIndex);
  44285. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  44286. itemModel.isAnimationEnabled = isAnimationEnabled;
  44287. return itemModel;
  44288. }
  44289. function getAnimationDelayParams(path) {
  44290. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  44291. return {
  44292. index: path.__pictorialAnimationIndex,
  44293. count: path.__pictorialRepeatTimes
  44294. };
  44295. }
  44296. function isAnimationEnabled() {
  44297. // `animation` prop can be set on itemModel in pictorial bar chart.
  44298. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  44299. }
  44300. function updateHoverAnimation(path, symbolMeta) {
  44301. path.off('emphasis').off('normal');
  44302. var scale = symbolMeta.symbolScale.slice();
  44303. symbolMeta.hoverAnimation && path
  44304. .on('emphasis', function() {
  44305. this.animateTo({
  44306. scale: [scale[0] * 1.1, scale[1] * 1.1]
  44307. }, 400, 'elasticOut');
  44308. })
  44309. .on('normal', function() {
  44310. this.animateTo({
  44311. scale: scale.slice()
  44312. }, 400, 'elasticOut');
  44313. });
  44314. }
  44315. function createBar(data, opt, symbolMeta, isUpdate) {
  44316. // bar is the main element for each data.
  44317. var bar = new Group();
  44318. // bundle is used for location and clip.
  44319. var bundle = new Group();
  44320. bar.add(bundle);
  44321. bar.__pictorialBundle = bundle;
  44322. bundle.attr('position', symbolMeta.bundlePosition.slice());
  44323. if (symbolMeta.symbolRepeat) {
  44324. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  44325. }
  44326. else {
  44327. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  44328. }
  44329. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  44330. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  44331. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  44332. bar.__pictorialSymbolMeta = symbolMeta;
  44333. return bar;
  44334. }
  44335. function updateBar(bar, opt, symbolMeta) {
  44336. var animationModel = symbolMeta.animationModel;
  44337. var dataIndex = symbolMeta.dataIndex;
  44338. var bundle = bar.__pictorialBundle;
  44339. updateProps(
  44340. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  44341. );
  44342. if (symbolMeta.symbolRepeat) {
  44343. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  44344. }
  44345. else {
  44346. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  44347. }
  44348. createOrUpdateBarRect(bar, symbolMeta, true);
  44349. createOrUpdateClip(bar, opt, symbolMeta, true);
  44350. }
  44351. function removeBar(data, dataIndex, animationModel, bar) {
  44352. // Not show text when animating
  44353. var labelRect = bar.__pictorialBarRect;
  44354. labelRect && (labelRect.style.text = null);
  44355. var pathes = [];
  44356. eachPath(bar, function (path) {
  44357. pathes.push(path);
  44358. });
  44359. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  44360. // I do not find proper remove animation for clip yet.
  44361. bar.__pictorialClipPath && (animationModel = null);
  44362. each$1(pathes, function (path) {
  44363. updateProps(
  44364. path, {scale: [0, 0]}, animationModel, dataIndex,
  44365. function () {
  44366. bar.parent && bar.parent.remove(bar);
  44367. }
  44368. );
  44369. });
  44370. data.setItemGraphicEl(dataIndex, null);
  44371. }
  44372. function getShapeStr(data, symbolMeta) {
  44373. return [
  44374. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  44375. !!symbolMeta.symbolRepeat,
  44376. !!symbolMeta.symbolClip
  44377. ].join(':');
  44378. }
  44379. function eachPath(bar, cb, context) {
  44380. // Do not use Group#eachChild, because it do not support remove.
  44381. each$1(bar.__pictorialBundle.children(), function (el) {
  44382. el !== bar.__pictorialBarRect && cb.call(context, el);
  44383. });
  44384. }
  44385. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  44386. immediateAttrs && el.attr(immediateAttrs);
  44387. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  44388. if (symbolMeta.symbolClip && !isUpdate) {
  44389. animationAttrs && el.attr(animationAttrs);
  44390. }
  44391. else {
  44392. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  44393. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  44394. );
  44395. }
  44396. }
  44397. function updateCommon$1(bar, opt, symbolMeta) {
  44398. var color = symbolMeta.color;
  44399. var dataIndex = symbolMeta.dataIndex;
  44400. var itemModel = symbolMeta.itemModel;
  44401. // Color must be excluded.
  44402. // Because symbol provide setColor individually to set fill and stroke
  44403. var normalStyle = itemModel.getModel('itemStyle.normal').getItemStyle(['color']);
  44404. var hoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  44405. var cursorStyle = itemModel.getShallow('cursor');
  44406. eachPath(bar, function (path) {
  44407. // PENDING setColor should be before setStyle!!!
  44408. path.setColor(color);
  44409. path.setStyle(defaults(
  44410. {
  44411. fill: color,
  44412. opacity: symbolMeta.opacity
  44413. },
  44414. normalStyle
  44415. ));
  44416. setHoverStyle(path, hoverStyle);
  44417. cursorStyle && (path.cursor = cursorStyle);
  44418. path.z2 = symbolMeta.z2;
  44419. });
  44420. var barRectHoverStyle = {};
  44421. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  44422. var barRect = bar.__pictorialBarRect;
  44423. setLabel(
  44424. barRect.style, barRectHoverStyle, itemModel,
  44425. color, opt.seriesModel, dataIndex, barPositionOutside
  44426. );
  44427. setHoverStyle(barRect, barRectHoverStyle);
  44428. }
  44429. function toIntTimes(times) {
  44430. var roundedTimes = Math.round(times);
  44431. // Escapse accurate error
  44432. return Math.abs(times - roundedTimes) < 1e-4
  44433. ? roundedTimes
  44434. : Math.ceil(times);
  44435. }
  44436. // In case developer forget to include grid component
  44437. registerLayout(curry(
  44438. barLayoutGrid, 'pictorialBar'
  44439. ));
  44440. registerVisual(curry(
  44441. visualSymbol, 'pictorialBar', 'roundRect', null
  44442. ));
  44443. /**
  44444. * @constructor module:echarts/coord/single/SingleAxis
  44445. * @extends {module:echarts/coord/Axis}
  44446. * @param {string} dim
  44447. * @param {*} scale
  44448. * @param {Array.<number>} coordExtent
  44449. * @param {string} axisType
  44450. * @param {string} position
  44451. */
  44452. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  44453. Axis.call(this, dim, scale, coordExtent);
  44454. /**
  44455. * Axis type
  44456. * - 'category'
  44457. * - 'value'
  44458. * - 'time'
  44459. * - 'log'
  44460. * @type {string}
  44461. */
  44462. this.type = axisType || 'value';
  44463. /**
  44464. * Axis position
  44465. * - 'top'
  44466. * - 'bottom'
  44467. * - 'left'
  44468. * - 'right'
  44469. * @type {string}
  44470. */
  44471. this.position = position || 'bottom';
  44472. /**
  44473. * Axis orient
  44474. * - 'horizontal'
  44475. * - 'vertical'
  44476. * @type {[type]}
  44477. */
  44478. this.orient = null;
  44479. /**
  44480. * @type {number}
  44481. */
  44482. this._labelInterval = null;
  44483. };
  44484. SingleAxis.prototype = {
  44485. constructor: SingleAxis,
  44486. /**
  44487. * Axis model
  44488. * @type {module:echarts/coord/single/AxisModel}
  44489. */
  44490. model: null,
  44491. /**
  44492. * Judge the orient of the axis.
  44493. * @return {boolean}
  44494. */
  44495. isHorizontal: function () {
  44496. var position = this.position;
  44497. return position === 'top' || position === 'bottom';
  44498. },
  44499. /**
  44500. * @override
  44501. */
  44502. pointToData: function (point, clamp) {
  44503. return this.coordinateSystem.pointToData(point, clamp)[0];
  44504. },
  44505. /**
  44506. * Convert the local coord(processed by dataToCoord())
  44507. * to global coord(concrete pixel coord).
  44508. * designated by module:echarts/coord/single/Single.
  44509. * @type {Function}
  44510. */
  44511. toGlobalCoord: null,
  44512. /**
  44513. * Convert the global coord to local coord.
  44514. * designated by module:echarts/coord/single/Single.
  44515. * @type {Function}
  44516. */
  44517. toLocalCoord: null
  44518. };
  44519. inherits(SingleAxis, Axis);
  44520. /**
  44521. * Single coordinates system.
  44522. */
  44523. /**
  44524. * Create a single coordinates system.
  44525. *
  44526. * @param {module:echarts/coord/single/AxisModel} axisModel
  44527. * @param {module:echarts/model/Global} ecModel
  44528. * @param {module:echarts/ExtensionAPI} api
  44529. */
  44530. function Single(axisModel, ecModel, api) {
  44531. /**
  44532. * @type {string}
  44533. * @readOnly
  44534. */
  44535. this.dimension = 'single';
  44536. /**
  44537. * Add it just for draw tooltip.
  44538. *
  44539. * @type {Array.<string>}
  44540. * @readOnly
  44541. */
  44542. this.dimensions = ['single'];
  44543. /**
  44544. * @private
  44545. * @type {module:echarts/coord/single/SingleAxis}.
  44546. */
  44547. this._axis = null;
  44548. /**
  44549. * @private
  44550. * @type {module:zrender/core/BoundingRect}
  44551. */
  44552. this._rect;
  44553. this._init(axisModel, ecModel, api);
  44554. /**
  44555. * @type {module:echarts/coord/single/AxisModel}
  44556. */
  44557. this.model = axisModel;
  44558. }
  44559. Single.prototype = {
  44560. type: 'singleAxis',
  44561. axisPointerEnabled: true,
  44562. constructor: Single,
  44563. /**
  44564. * Initialize single coordinate system.
  44565. *
  44566. * @param {module:echarts/coord/single/AxisModel} axisModel
  44567. * @param {module:echarts/model/Global} ecModel
  44568. * @param {module:echarts/ExtensionAPI} api
  44569. * @private
  44570. */
  44571. _init: function (axisModel, ecModel, api) {
  44572. var dim = this.dimension;
  44573. var axis = new SingleAxis(
  44574. dim,
  44575. createScaleByModel(axisModel),
  44576. [0, 0],
  44577. axisModel.get('type'),
  44578. axisModel.get('position')
  44579. );
  44580. var isCategory = axis.type === 'category';
  44581. axis.onBand = isCategory && axisModel.get('boundaryGap');
  44582. axis.inverse = axisModel.get('inverse');
  44583. axis.orient = axisModel.get('orient');
  44584. axisModel.axis = axis;
  44585. axis.model = axisModel;
  44586. axis.coordinateSystem = this;
  44587. this._axis = axis;
  44588. },
  44589. /**
  44590. * Update axis scale after data processed
  44591. * @param {module:echarts/model/Global} ecModel
  44592. * @param {module:echarts/ExtensionAPI} api
  44593. */
  44594. update: function (ecModel, api) {
  44595. ecModel.eachSeries(function (seriesModel) {
  44596. if (seriesModel.coordinateSystem === this) {
  44597. var data = seriesModel.getData();
  44598. var dim = this.dimension;
  44599. this._axis.scale.unionExtentFromData(
  44600. data, seriesModel.coordDimToDataDim(dim)
  44601. );
  44602. niceScaleExtent(this._axis.scale, this._axis.model);
  44603. }
  44604. }, this);
  44605. },
  44606. /**
  44607. * Resize the single coordinate system.
  44608. *
  44609. * @param {module:echarts/coord/single/AxisModel} axisModel
  44610. * @param {module:echarts/ExtensionAPI} api
  44611. */
  44612. resize: function (axisModel, api) {
  44613. this._rect = getLayoutRect(
  44614. {
  44615. left: axisModel.get('left'),
  44616. top: axisModel.get('top'),
  44617. right: axisModel.get('right'),
  44618. bottom: axisModel.get('bottom'),
  44619. width: axisModel.get('width'),
  44620. height: axisModel.get('height')
  44621. },
  44622. {
  44623. width: api.getWidth(),
  44624. height: api.getHeight()
  44625. }
  44626. );
  44627. this._adjustAxis();
  44628. },
  44629. /**
  44630. * @return {module:zrender/core/BoundingRect}
  44631. */
  44632. getRect: function () {
  44633. return this._rect;
  44634. },
  44635. /**
  44636. * @private
  44637. */
  44638. _adjustAxis: function () {
  44639. var rect = this._rect;
  44640. var axis = this._axis;
  44641. var isHorizontal = axis.isHorizontal();
  44642. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  44643. var idx = axis.reverse ? 1 : 0;
  44644. axis.setExtent(extent[idx], extent[1 - idx]);
  44645. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  44646. },
  44647. /**
  44648. * @param {module:echarts/coord/single/SingleAxis} axis
  44649. * @param {number} coordBase
  44650. */
  44651. _updateAxisTransform: function (axis, coordBase) {
  44652. var axisExtent = axis.getExtent();
  44653. var extentSum = axisExtent[0] + axisExtent[1];
  44654. var isHorizontal = axis.isHorizontal();
  44655. axis.toGlobalCoord = isHorizontal
  44656. ? function (coord) {
  44657. return coord + coordBase;
  44658. }
  44659. : function (coord) {
  44660. return extentSum - coord + coordBase;
  44661. };
  44662. axis.toLocalCoord = isHorizontal
  44663. ? function (coord) {
  44664. return coord - coordBase;
  44665. }
  44666. : function (coord) {
  44667. return extentSum - coord + coordBase;
  44668. };
  44669. },
  44670. /**
  44671. * Get axis.
  44672. *
  44673. * @return {module:echarts/coord/single/SingleAxis}
  44674. */
  44675. getAxis: function () {
  44676. return this._axis;
  44677. },
  44678. /**
  44679. * Get axis, add it just for draw tooltip.
  44680. *
  44681. * @return {[type]} [description]
  44682. */
  44683. getBaseAxis: function () {
  44684. return this._axis;
  44685. },
  44686. /**
  44687. * @return {Array.<module:echarts/coord/Axis>}
  44688. */
  44689. getAxes: function () {
  44690. return [this._axis];
  44691. },
  44692. /**
  44693. * @return {Object} {baseAxes: [], otherAxes: []}
  44694. */
  44695. getTooltipAxes: function () {
  44696. return {baseAxes: [this.getAxis()]};
  44697. },
  44698. /**
  44699. * If contain point.
  44700. *
  44701. * @param {Array.<number>} point
  44702. * @return {boolean}
  44703. */
  44704. containPoint: function (point) {
  44705. var rect = this.getRect();
  44706. var axis = this.getAxis();
  44707. var orient = axis.orient;
  44708. if (orient === 'horizontal') {
  44709. return axis.contain(axis.toLocalCoord(point[0]))
  44710. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  44711. }
  44712. else {
  44713. return axis.contain(axis.toLocalCoord(point[1]))
  44714. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  44715. }
  44716. },
  44717. /**
  44718. * @param {Array.<number>} point
  44719. * @return {Array.<number>}
  44720. */
  44721. pointToData: function (point) {
  44722. var axis = this.getAxis();
  44723. return [axis.coordToData(axis.toLocalCoord(
  44724. point[axis.orient === 'horizontal' ? 0 : 1]
  44725. ))];
  44726. },
  44727. /**
  44728. * Convert the series data to concrete point.
  44729. *
  44730. * @param {number|Array.<number>} val
  44731. * @return {Array.<number>}
  44732. */
  44733. dataToPoint: function (val) {
  44734. var axis = this.getAxis();
  44735. var rect = this.getRect();
  44736. var pt = [];
  44737. var idx = axis.orient === 'horizontal' ? 0 : 1;
  44738. if (val instanceof Array) {
  44739. val = val[0];
  44740. }
  44741. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  44742. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  44743. return pt;
  44744. }
  44745. };
  44746. /**
  44747. * Single coordinate system creator.
  44748. */
  44749. /**
  44750. * Create single coordinate system and inject it into seriesModel.
  44751. *
  44752. * @param {module:echarts/model/Global} ecModel
  44753. * @param {module:echarts/ExtensionAPI} api
  44754. * @return {Array.<module:echarts/coord/single/Single>}
  44755. */
  44756. function create$3(ecModel, api) {
  44757. var singles = [];
  44758. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  44759. var single = new Single(axisModel, ecModel, api);
  44760. single.name = 'single_' + idx;
  44761. single.resize(axisModel, api);
  44762. axisModel.coordinateSystem = single;
  44763. singles.push(single);
  44764. });
  44765. ecModel.eachSeries(function (seriesModel) {
  44766. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  44767. var singleAxisModel = ecModel.queryComponents({
  44768. mainType: 'singleAxis',
  44769. index: seriesModel.get('singleAxisIndex'),
  44770. id: seriesModel.get('singleAxisId')
  44771. })[0];
  44772. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  44773. }
  44774. });
  44775. return singles;
  44776. }
  44777. CoordinateSystemManager.register('single', {
  44778. create: create$3,
  44779. dimensions: Single.prototype.dimensions
  44780. });
  44781. /**
  44782. * @param {Object} opt {labelInside}
  44783. * @return {Object} {
  44784. * position, rotation, labelDirection, labelOffset,
  44785. * tickDirection, labelRotate, labelInterval, z2
  44786. * }
  44787. */
  44788. function layout$1 (axisModel, opt) {
  44789. opt = opt || {};
  44790. var single = axisModel.coordinateSystem;
  44791. var axis = axisModel.axis;
  44792. var layout = {};
  44793. var axisPosition = axis.position;
  44794. var orient = axis.orient;
  44795. var rect = single.getRect();
  44796. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  44797. var positionMap = {
  44798. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  44799. vertical: {left: rectBound[0], right: rectBound[1]}
  44800. };
  44801. layout.position = [
  44802. orient === 'vertical'
  44803. ? positionMap.vertical[axisPosition]
  44804. : rectBound[0],
  44805. orient === 'horizontal'
  44806. ? positionMap.horizontal[axisPosition]
  44807. : rectBound[3]
  44808. ];
  44809. var r = {horizontal: 0, vertical: 1};
  44810. layout.rotation = Math.PI / 2 * r[orient];
  44811. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  44812. layout.labelDirection = layout.tickDirection
  44813. = layout.nameDirection
  44814. = directionMap[axisPosition];
  44815. if (axisModel.get('axisTick.inside')) {
  44816. layout.tickDirection = -layout.tickDirection;
  44817. }
  44818. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  44819. layout.labelDirection = -layout.labelDirection;
  44820. }
  44821. var labelRotation = opt.rotate;
  44822. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  44823. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  44824. layout.labelInterval = axis.getLabelInterval();
  44825. layout.z2 = 1;
  44826. return layout;
  44827. }
  44828. var getInterval$2 = AxisBuilder.getInterval;
  44829. var ifIgnoreOnTick$2 = AxisBuilder.ifIgnoreOnTick;
  44830. var axisBuilderAttrs$2 = [
  44831. 'axisLine', 'axisTickLabel', 'axisName'
  44832. ];
  44833. var selfBuilderAttr = 'splitLine';
  44834. var SingleAxisView = AxisView.extend({
  44835. type: 'singleAxis',
  44836. axisPointerClass: 'SingleAxisPointer',
  44837. render: function (axisModel, ecModel, api, payload) {
  44838. var group = this.group;
  44839. group.removeAll();
  44840. var layout = layout$1(axisModel);
  44841. var axisBuilder = new AxisBuilder(axisModel, layout);
  44842. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  44843. group.add(axisBuilder.getGroup());
  44844. if (axisModel.get(selfBuilderAttr + '.show')) {
  44845. this['_' + selfBuilderAttr](axisModel, layout.labelInterval);
  44846. }
  44847. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  44848. },
  44849. _splitLine: function(axisModel, labelInterval) {
  44850. var axis = axisModel.axis;
  44851. if (axis.scale.isBlank()) {
  44852. return;
  44853. }
  44854. var splitLineModel = axisModel.getModel('splitLine');
  44855. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44856. var lineWidth = lineStyleModel.get('width');
  44857. var lineColors = lineStyleModel.get('color');
  44858. var lineInterval = getInterval$2(splitLineModel, labelInterval);
  44859. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  44860. var gridRect = axisModel.coordinateSystem.getRect();
  44861. var isHorizontal = axis.isHorizontal();
  44862. var splitLines = [];
  44863. var lineCount = 0;
  44864. var ticksCoords = axis.getTicksCoords();
  44865. var p1 = [];
  44866. var p2 = [];
  44867. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  44868. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  44869. for (var i = 0; i < ticksCoords.length; ++i) {
  44870. if (ifIgnoreOnTick$2(
  44871. axis, i, lineInterval, ticksCoords.length,
  44872. showMinLabel, showMaxLabel
  44873. )) {
  44874. continue;
  44875. }
  44876. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  44877. if (isHorizontal) {
  44878. p1[0] = tickCoord;
  44879. p1[1] = gridRect.y;
  44880. p2[0] = tickCoord;
  44881. p2[1] = gridRect.y + gridRect.height;
  44882. }
  44883. else {
  44884. p1[0] = gridRect.x;
  44885. p1[1] = tickCoord;
  44886. p2[0] = gridRect.x + gridRect.width;
  44887. p2[1] = tickCoord;
  44888. }
  44889. var colorIndex = (lineCount++) % lineColors.length;
  44890. splitLines[colorIndex] = splitLines[colorIndex] || [];
  44891. splitLines[colorIndex].push(new Line(
  44892. subPixelOptimizeLine({
  44893. shape: {
  44894. x1: p1[0],
  44895. y1: p1[1],
  44896. x2: p2[0],
  44897. y2: p2[1]
  44898. },
  44899. style: {
  44900. lineWidth: lineWidth
  44901. },
  44902. silent: true
  44903. })));
  44904. }
  44905. for (var i = 0; i < splitLines.length; ++i) {
  44906. this.group.add(mergePath(splitLines[i], {
  44907. style: {
  44908. stroke: lineColors[i % lineColors.length],
  44909. lineDash: lineStyleModel.getLineDash(lineWidth),
  44910. lineWidth: lineWidth
  44911. },
  44912. silent: true
  44913. }));
  44914. }
  44915. }
  44916. });
  44917. var AxisModel$4 = ComponentModel.extend({
  44918. type: 'singleAxis',
  44919. layoutMode: 'box',
  44920. /**
  44921. * @type {module:echarts/coord/single/SingleAxis}
  44922. */
  44923. axis: null,
  44924. /**
  44925. * @type {module:echarts/coord/single/Single}
  44926. */
  44927. coordinateSystem: null,
  44928. /**
  44929. * @override
  44930. */
  44931. getCoordSysModel: function () {
  44932. return this;
  44933. }
  44934. });
  44935. var defaultOption$2 = {
  44936. left: '5%',
  44937. top: '5%',
  44938. right: '5%',
  44939. bottom: '5%',
  44940. type: 'value',
  44941. position: 'bottom',
  44942. orient: 'horizontal',
  44943. axisLine: {
  44944. show: true,
  44945. lineStyle: {
  44946. width: 2,
  44947. type: 'solid'
  44948. }
  44949. },
  44950. // Single coordinate system and single axis is the,
  44951. // which is used as the parent tooltip model.
  44952. // same model, so we set default tooltip show as true.
  44953. tooltip: {
  44954. show: true
  44955. },
  44956. axisTick: {
  44957. show: true,
  44958. length: 6,
  44959. lineStyle: {
  44960. width: 2
  44961. }
  44962. },
  44963. axisLabel: {
  44964. show: true,
  44965. interval: 'auto'
  44966. },
  44967. splitLine: {
  44968. show: true,
  44969. lineStyle: {
  44970. type: 'dashed',
  44971. opacity: 0.2
  44972. }
  44973. }
  44974. };
  44975. function getAxisType$2(axisName, option) {
  44976. return option.type || (option.data ? 'category' : 'value');
  44977. }
  44978. merge(AxisModel$4.prototype, axisModelCommonMixin);
  44979. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  44980. /**
  44981. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  44982. * @param {module:echarts/model/Global} ecModel
  44983. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  44984. */
  44985. var findPointFromSeries = function (finder, ecModel) {
  44986. var point = [];
  44987. var seriesIndex = finder.seriesIndex;
  44988. var seriesModel;
  44989. if (seriesIndex == null || !(
  44990. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  44991. )) {
  44992. return {point: []};
  44993. }
  44994. var data = seriesModel.getData();
  44995. var dataIndex = queryDataIndex(data, finder);
  44996. if (dataIndex == null || isArray(dataIndex)) {
  44997. return {point: []};
  44998. }
  44999. var el = data.getItemGraphicEl(dataIndex);
  45000. var coordSys = seriesModel.coordinateSystem;
  45001. if (seriesModel.getTooltipPosition) {
  45002. point = seriesModel.getTooltipPosition(dataIndex) || [];
  45003. }
  45004. else if (coordSys && coordSys.dataToPoint) {
  45005. point = coordSys.dataToPoint(
  45006. data.getValues(
  45007. map(coordSys.dimensions, function (dim) {
  45008. return seriesModel.coordDimToDataDim(dim)[0];
  45009. }), dataIndex, true
  45010. )
  45011. ) || [];
  45012. }
  45013. else if (el) {
  45014. // Use graphic bounding rect
  45015. var rect = el.getBoundingRect().clone();
  45016. rect.applyTransform(el.transform);
  45017. point = [
  45018. rect.x + rect.width / 2,
  45019. rect.y + rect.height / 2
  45020. ];
  45021. }
  45022. return {point: point, el: el};
  45023. };
  45024. var each$17 = each$1;
  45025. var curry$3 = curry;
  45026. var get$2 = makeGetter();
  45027. /**
  45028. * Basic logic: check all axis, if they do not demand show/highlight,
  45029. * then hide/downplay them.
  45030. *
  45031. * @param {Object} coordSysAxesInfo
  45032. * @param {Object} payload
  45033. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  45034. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  45035. * trigger axisPointer and tooltip.
  45036. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  45037. * trigger axisPointer and tooltip.
  45038. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  45039. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  45040. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  45041. * [{
  45042. * axisDim: 'x'|'y'|'angle'|...,
  45043. * axisIndex: ...,
  45044. * value: ...
  45045. * }, ...]
  45046. * @param {Function} [payload.dispatchAction]
  45047. * @param {Object} [payload.tooltipOption]
  45048. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  45049. * which can be specified in dispatchAction
  45050. * @param {module:echarts/model/Global} ecModel
  45051. * @param {module:echarts/ExtensionAPI} api
  45052. * @return {Object} content of event obj for echarts.connect.
  45053. */
  45054. var axisTrigger = function (payload, ecModel, api) {
  45055. var currTrigger = payload.currTrigger;
  45056. var point = [payload.x, payload.y];
  45057. var finder = payload;
  45058. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  45059. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  45060. // Pending
  45061. // See #6121. But we are not able to reproduce it yet.
  45062. if (!coordSysAxesInfo) {
  45063. return;
  45064. }
  45065. if (illegalPoint(point)) {
  45066. // Used in the default behavior of `connection`: use the sample seriesIndex
  45067. // and dataIndex. And also used in the tooltipView trigger.
  45068. point = findPointFromSeries({
  45069. seriesIndex: finder.seriesIndex,
  45070. // Do not use dataIndexInside from other ec instance.
  45071. // FIXME: auto detect it?
  45072. dataIndex: finder.dataIndex
  45073. }, ecModel).point;
  45074. }
  45075. var isIllegalPoint = illegalPoint(point);
  45076. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  45077. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  45078. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  45079. // and dataIndex.
  45080. var inputAxesInfo = finder.axesInfo;
  45081. var axesInfo = coordSysAxesInfo.axesInfo;
  45082. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  45083. var outputFinder = {};
  45084. var showValueMap = {};
  45085. var dataByCoordSys = {list: [], map: {}};
  45086. var updaters = {
  45087. showPointer: curry$3(showPointer, showValueMap),
  45088. showTooltip: curry$3(showTooltip, dataByCoordSys)
  45089. };
  45090. // Process for triggered axes.
  45091. each$17(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  45092. // If a point given, it must be contained by the coordinate system.
  45093. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  45094. each$17(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  45095. var axis = axisInfo.axis;
  45096. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  45097. // If no inputAxesInfo, no axis is restricted.
  45098. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  45099. var val = inputAxisInfo && inputAxisInfo.value;
  45100. if (val == null && !isIllegalPoint) {
  45101. val = axis.pointToData(point);
  45102. }
  45103. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  45104. }
  45105. });
  45106. });
  45107. // Process for linked axes.
  45108. var linkTriggers = {};
  45109. each$17(axesInfo, function (tarAxisInfo, tarKey) {
  45110. var linkGroup = tarAxisInfo.linkGroup;
  45111. // If axis has been triggered in the previous stage, it should not be triggered by link.
  45112. if (linkGroup && !showValueMap[tarKey]) {
  45113. each$17(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  45114. var srcValItem = showValueMap[srcKey];
  45115. // If srcValItem exist, source axis is triggered, so link to target axis.
  45116. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  45117. var val = srcValItem.value;
  45118. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  45119. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  45120. )));
  45121. linkTriggers[tarAxisInfo.key] = val;
  45122. }
  45123. });
  45124. }
  45125. });
  45126. each$17(linkTriggers, function (val, tarKey) {
  45127. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  45128. });
  45129. updateModelActually(showValueMap, axesInfo, outputFinder);
  45130. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  45131. dispatchHighDownActually(axesInfo, dispatchAction, api);
  45132. return outputFinder;
  45133. };
  45134. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  45135. var axis = axisInfo.axis;
  45136. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  45137. return;
  45138. }
  45139. if (!axisInfo.involveSeries) {
  45140. updaters.showPointer(axisInfo, newValue);
  45141. return;
  45142. }
  45143. // Heavy calculation. So put it after axis.containData checking.
  45144. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  45145. var payloadBatch = payloadInfo.payloadBatch;
  45146. var snapToValue = payloadInfo.snapToValue;
  45147. // Fill content of event obj for echarts.connect.
  45148. // By defualt use the first involved series data as a sample to connect.
  45149. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  45150. extend(outputFinder, payloadBatch[0]);
  45151. }
  45152. // If no linkSource input, this process is for collecting link
  45153. // target, where snap should not be accepted.
  45154. if (!dontSnap && axisInfo.snap) {
  45155. if (axis.containData(snapToValue) && snapToValue != null) {
  45156. newValue = snapToValue;
  45157. }
  45158. }
  45159. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  45160. // Tooltip should always be snapToValue, otherwise there will be
  45161. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  45162. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  45163. }
  45164. function buildPayloadsBySeries(value, axisInfo) {
  45165. var axis = axisInfo.axis;
  45166. var dim = axis.dim;
  45167. var snapToValue = value;
  45168. var payloadBatch = [];
  45169. var minDist = Number.MAX_VALUE;
  45170. var minDiff = -1;
  45171. each$17(axisInfo.seriesModels, function (series, idx) {
  45172. var dataDim = series.coordDimToDataDim(dim);
  45173. var seriesNestestValue;
  45174. var dataIndices;
  45175. if (series.getAxisTooltipData) {
  45176. var result = series.getAxisTooltipData(dataDim, value, axis);
  45177. dataIndices = result.dataIndices;
  45178. seriesNestestValue = result.nestestValue;
  45179. }
  45180. else {
  45181. dataIndices = series.getData().indicesOfNearest(
  45182. dataDim[0],
  45183. value,
  45184. // Add a threshold to avoid find the wrong dataIndex
  45185. // when data length is not same.
  45186. false, axis.type === 'category' ? 0.5 : null
  45187. );
  45188. if (!dataIndices.length) {
  45189. return;
  45190. }
  45191. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  45192. }
  45193. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  45194. return;
  45195. }
  45196. var diff = value - seriesNestestValue;
  45197. var dist = Math.abs(diff);
  45198. // Consider category case
  45199. if (dist <= minDist) {
  45200. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  45201. minDist = dist;
  45202. minDiff = diff;
  45203. snapToValue = seriesNestestValue;
  45204. payloadBatch.length = 0;
  45205. }
  45206. each$17(dataIndices, function (dataIndex) {
  45207. payloadBatch.push({
  45208. seriesIndex: series.seriesIndex,
  45209. dataIndexInside: dataIndex,
  45210. dataIndex: series.getData().getRawIndex(dataIndex)
  45211. });
  45212. });
  45213. }
  45214. });
  45215. return {
  45216. payloadBatch: payloadBatch,
  45217. snapToValue: snapToValue
  45218. };
  45219. }
  45220. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  45221. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  45222. }
  45223. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  45224. var payloadBatch = payloadInfo.payloadBatch;
  45225. var axis = axisInfo.axis;
  45226. var axisModel = axis.model;
  45227. var axisPointerModel = axisInfo.axisPointerModel;
  45228. // If no data, do not create anything in dataByCoordSys,
  45229. // whose length will be used to judge whether dispatch action.
  45230. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  45231. return;
  45232. }
  45233. var coordSysModel = axisInfo.coordSys.model;
  45234. var coordSysKey = makeKey(coordSysModel);
  45235. var coordSysItem = dataByCoordSys.map[coordSysKey];
  45236. if (!coordSysItem) {
  45237. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  45238. coordSysId: coordSysModel.id,
  45239. coordSysIndex: coordSysModel.componentIndex,
  45240. coordSysType: coordSysModel.type,
  45241. coordSysMainType: coordSysModel.mainType,
  45242. dataByAxis: []
  45243. };
  45244. dataByCoordSys.list.push(coordSysItem);
  45245. }
  45246. coordSysItem.dataByAxis.push({
  45247. axisDim: axis.dim,
  45248. axisIndex: axisModel.componentIndex,
  45249. axisType: axisModel.type,
  45250. axisId: axisModel.id,
  45251. value: value,
  45252. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  45253. // depends that all models have been updated. So it should not be performed
  45254. // here. Considering axisPointerModel used here is volatile, which is hard
  45255. // to be retrieve in TooltipView, we prepare parameters here.
  45256. valueLabelOpt: {
  45257. precision: axisPointerModel.get('label.precision'),
  45258. formatter: axisPointerModel.get('label.formatter')
  45259. },
  45260. seriesDataIndices: payloadBatch.slice()
  45261. });
  45262. }
  45263. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  45264. var outputAxesInfo = outputFinder.axesInfo = [];
  45265. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  45266. each$17(axesInfo, function (axisInfo, key) {
  45267. var option = axisInfo.axisPointerModel.option;
  45268. var valItem = showValueMap[key];
  45269. if (valItem) {
  45270. !axisInfo.useHandle && (option.status = 'show');
  45271. option.value = valItem.value;
  45272. // For label formatter param and highlight.
  45273. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  45274. }
  45275. // When always show (e.g., handle used), remain
  45276. // original value and status.
  45277. else {
  45278. // If hide, value still need to be set, consider
  45279. // click legend to toggle axis blank.
  45280. !axisInfo.useHandle && (option.status = 'hide');
  45281. }
  45282. // If status is 'hide', should be no info in payload.
  45283. option.status === 'show' && outputAxesInfo.push({
  45284. axisDim: axisInfo.axis.dim,
  45285. axisIndex: axisInfo.axis.model.componentIndex,
  45286. value: option.value
  45287. });
  45288. });
  45289. }
  45290. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  45291. // Basic logic: If no showTip required, hideTip will be dispatched.
  45292. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  45293. dispatchAction({type: 'hideTip'});
  45294. return;
  45295. }
  45296. // In most case only one axis (or event one series is used). It is
  45297. // convinient to fetch payload.seriesIndex and payload.dataIndex
  45298. // dirtectly. So put the first seriesIndex and dataIndex of the first
  45299. // axis on the payload.
  45300. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  45301. dispatchAction({
  45302. type: 'showTip',
  45303. escapeConnect: true,
  45304. x: point[0],
  45305. y: point[1],
  45306. tooltipOption: payload.tooltipOption,
  45307. position: payload.position,
  45308. dataIndexInside: sampleItem.dataIndexInside,
  45309. dataIndex: sampleItem.dataIndex,
  45310. seriesIndex: sampleItem.seriesIndex,
  45311. dataByCoordSys: dataByCoordSys.list
  45312. });
  45313. }
  45314. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  45315. // FIXME
  45316. // highlight status modification shoule be a stage of main process?
  45317. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  45318. var zr = api.getZr();
  45319. var highDownKey = 'axisPointerLastHighlights';
  45320. var lastHighlights = get$2(zr)[highDownKey] || {};
  45321. var newHighlights = get$2(zr)[highDownKey] = {};
  45322. // Update highlight/downplay status according to axisPointer model.
  45323. // Build hash map and remove duplicate incidentally.
  45324. each$17(axesInfo, function (axisInfo, key) {
  45325. var option = axisInfo.axisPointerModel.option;
  45326. option.status === 'show' && each$17(option.seriesDataIndices, function (batchItem) {
  45327. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  45328. newHighlights[key] = batchItem;
  45329. });
  45330. });
  45331. // Diff.
  45332. var toHighlight = [];
  45333. var toDownplay = [];
  45334. each$1(lastHighlights, function (batchItem, key) {
  45335. !newHighlights[key] && toDownplay.push(batchItem);
  45336. });
  45337. each$1(newHighlights, function (batchItem, key) {
  45338. !lastHighlights[key] && toHighlight.push(batchItem);
  45339. });
  45340. toDownplay.length && api.dispatchAction({
  45341. type: 'downplay', escapeConnect: true, batch: toDownplay
  45342. });
  45343. toHighlight.length && api.dispatchAction({
  45344. type: 'highlight', escapeConnect: true, batch: toHighlight
  45345. });
  45346. }
  45347. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  45348. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  45349. var inputAxisInfo = inputAxesInfo[i];
  45350. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  45351. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  45352. ) {
  45353. return inputAxisInfo;
  45354. }
  45355. }
  45356. }
  45357. function makeMapperParam(axisInfo) {
  45358. var axisModel = axisInfo.axis.model;
  45359. var item = {};
  45360. var dim = item.axisDim = axisInfo.axis.dim;
  45361. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  45362. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  45363. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  45364. return item;
  45365. }
  45366. function illegalPoint(point) {
  45367. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  45368. }
  45369. var AxisPointerModel = extendComponentModel({
  45370. type: 'axisPointer',
  45371. coordSysAxesInfo: null,
  45372. defaultOption: {
  45373. // 'auto' means that show when triggered by tooltip or handle.
  45374. show: 'auto',
  45375. // 'click' | 'mousemove' | 'none'
  45376. triggerOn: null, // set default in AxisPonterView.js
  45377. zlevel: 0,
  45378. z: 50,
  45379. type: 'line',
  45380. // axispointer triggered by tootip determine snap automatically,
  45381. // see `modelHelper`.
  45382. snap: false,
  45383. triggerTooltip: true,
  45384. value: null,
  45385. status: null, // Init value depends on whether handle is used.
  45386. // [group0, group1, ...]
  45387. // Each group can be: {
  45388. // mapper: function () {},
  45389. // singleTooltip: 'multiple', // 'multiple' or 'single'
  45390. // xAxisId: ...,
  45391. // yAxisName: ...,
  45392. // angleAxisIndex: ...
  45393. // }
  45394. // mapper: can be ignored.
  45395. // input: {axisInfo, value}
  45396. // output: {axisInfo, value}
  45397. link: [],
  45398. // Do not set 'auto' here, otherwise global animation: false
  45399. // will not effect at this axispointer.
  45400. animation: null,
  45401. animationDurationUpdate: 200,
  45402. lineStyle: {
  45403. color: '#aaa',
  45404. width: 1,
  45405. type: 'solid'
  45406. },
  45407. shadowStyle: {
  45408. color: 'rgba(150,150,150,0.3)'
  45409. },
  45410. label: {
  45411. show: true,
  45412. formatter: null, // string | Function
  45413. precision: 'auto', // Or a number like 0, 1, 2 ...
  45414. margin: 3,
  45415. color: '#fff',
  45416. padding: [5, 7, 5, 7],
  45417. backgroundColor: 'auto', // default: axis line color
  45418. borderColor: null,
  45419. borderWidth: 0,
  45420. shadowBlur: 3,
  45421. shadowColor: '#aaa'
  45422. // Considering applicability, common style should
  45423. // better not have shadowOffset.
  45424. // shadowOffsetX: 0,
  45425. // shadowOffsetY: 2
  45426. },
  45427. handle: {
  45428. show: false,
  45429. 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
  45430. size: 45,
  45431. // handle margin is from symbol center to axis, which is stable when circular move.
  45432. margin: 50,
  45433. // color: '#1b8bbd'
  45434. // color: '#2f4554'
  45435. color: '#333',
  45436. shadowBlur: 3,
  45437. shadowColor: '#aaa',
  45438. shadowOffsetX: 0,
  45439. shadowOffsetY: 2,
  45440. // For mobile performance
  45441. throttle: 40
  45442. }
  45443. }
  45444. });
  45445. var get$3 = makeGetter();
  45446. var each$18 = each$1;
  45447. /**
  45448. * @param {string} key
  45449. * @param {module:echarts/ExtensionAPI} api
  45450. * @param {Function} handler
  45451. * param: {string} currTrigger
  45452. * param: {Array.<number>} point
  45453. */
  45454. function register(key, api, handler) {
  45455. if (env$1.node) {
  45456. return;
  45457. }
  45458. var zr = api.getZr();
  45459. get$3(zr).records || (get$3(zr).records = {});
  45460. initGlobalListeners(zr, api);
  45461. var record = get$3(zr).records[key] || (get$3(zr).records[key] = {});
  45462. record.handler = handler;
  45463. }
  45464. function initGlobalListeners(zr, api) {
  45465. if (get$3(zr).initialized) {
  45466. return;
  45467. }
  45468. get$3(zr).initialized = true;
  45469. useHandler('click', curry(doEnter, 'click'));
  45470. useHandler('mousemove', curry(doEnter, 'mousemove'));
  45471. // useHandler('mouseout', onLeave);
  45472. useHandler('globalout', onLeave);
  45473. function useHandler(eventType, cb) {
  45474. zr.on(eventType, function (e) {
  45475. var dis = makeDispatchAction(api);
  45476. each$18(get$3(zr).records, function (record) {
  45477. record && cb(record, e, dis.dispatchAction);
  45478. });
  45479. dispatchTooltipFinally(dis.pendings, api);
  45480. });
  45481. }
  45482. }
  45483. function dispatchTooltipFinally(pendings, api) {
  45484. var showLen = pendings.showTip.length;
  45485. var hideLen = pendings.hideTip.length;
  45486. var actuallyPayload;
  45487. if (showLen) {
  45488. actuallyPayload = pendings.showTip[showLen - 1];
  45489. }
  45490. else if (hideLen) {
  45491. actuallyPayload = pendings.hideTip[hideLen - 1];
  45492. }
  45493. if (actuallyPayload) {
  45494. actuallyPayload.dispatchAction = null;
  45495. api.dispatchAction(actuallyPayload);
  45496. }
  45497. }
  45498. function onLeave(record, e, dispatchAction) {
  45499. record.handler('leave', null, dispatchAction);
  45500. }
  45501. function doEnter(currTrigger, record, e, dispatchAction) {
  45502. record.handler(currTrigger, e, dispatchAction);
  45503. }
  45504. function makeDispatchAction(api) {
  45505. var pendings = {
  45506. showTip: [],
  45507. hideTip: []
  45508. };
  45509. // FIXME
  45510. // better approach?
  45511. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  45512. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  45513. // So we have to add "final stage" to merge those dispatched actions.
  45514. var dispatchAction = function (payload) {
  45515. var pendingList = pendings[payload.type];
  45516. if (pendingList) {
  45517. pendingList.push(payload);
  45518. }
  45519. else {
  45520. payload.dispatchAction = dispatchAction;
  45521. api.dispatchAction(payload);
  45522. }
  45523. };
  45524. return {
  45525. dispatchAction: dispatchAction,
  45526. pendings: pendings
  45527. };
  45528. }
  45529. /**
  45530. * @param {string} key
  45531. * @param {module:echarts/ExtensionAPI} api
  45532. */
  45533. function unregister(key, api) {
  45534. if (env$1.node) {
  45535. return;
  45536. }
  45537. var zr = api.getZr();
  45538. var record = (get$3(zr).records || {})[key];
  45539. if (record) {
  45540. get$3(zr).records[key] = null;
  45541. }
  45542. }
  45543. var AxisPointerView = extendComponentView({
  45544. type: 'axisPointer',
  45545. render: function (globalAxisPointerModel, ecModel, api) {
  45546. var globalTooltipModel = ecModel.getComponent('tooltip');
  45547. var triggerOn = globalAxisPointerModel.get('triggerOn')
  45548. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  45549. // Register global listener in AxisPointerView to enable
  45550. // AxisPointerView to be independent to Tooltip.
  45551. register(
  45552. 'axisPointer',
  45553. api,
  45554. function (currTrigger, e, dispatchAction) {
  45555. // If 'none', it is not controlled by mouse totally.
  45556. if (triggerOn !== 'none'
  45557. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  45558. ) {
  45559. dispatchAction({
  45560. type: 'updateAxisPointer',
  45561. currTrigger: currTrigger,
  45562. x: e && e.offsetX,
  45563. y: e && e.offsetY
  45564. });
  45565. }
  45566. }
  45567. );
  45568. },
  45569. /**
  45570. * @override
  45571. */
  45572. remove: function (ecModel, api) {
  45573. unregister(api.getZr(), 'axisPointer');
  45574. AxisPointerView.superApply(this._model, 'remove', arguments);
  45575. },
  45576. /**
  45577. * @override
  45578. */
  45579. dispose: function (ecModel, api) {
  45580. unregister('axisPointer', api);
  45581. AxisPointerView.superApply(this._model, 'dispose', arguments);
  45582. }
  45583. });
  45584. var get$4 = makeGetter();
  45585. var clone$3 = clone;
  45586. var bind$2 = bind;
  45587. /**
  45588. * Base axis pointer class in 2D.
  45589. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  45590. */
  45591. function BaseAxisPointer () {
  45592. }
  45593. BaseAxisPointer.prototype = {
  45594. /**
  45595. * @private
  45596. */
  45597. _group: null,
  45598. /**
  45599. * @private
  45600. */
  45601. _lastGraphicKey: null,
  45602. /**
  45603. * @private
  45604. */
  45605. _handle: null,
  45606. /**
  45607. * @private
  45608. */
  45609. _dragging: false,
  45610. /**
  45611. * @private
  45612. */
  45613. _lastValue: null,
  45614. /**
  45615. * @private
  45616. */
  45617. _lastStatus: null,
  45618. /**
  45619. * @private
  45620. */
  45621. _payloadInfo: null,
  45622. /**
  45623. * In px, arbitrary value. Do not set too small,
  45624. * no animation is ok for most cases.
  45625. * @protected
  45626. */
  45627. animationThreshold: 15,
  45628. /**
  45629. * @implement
  45630. */
  45631. render: function (axisModel, axisPointerModel, api, forceRender) {
  45632. var value = axisPointerModel.get('value');
  45633. var status = axisPointerModel.get('status');
  45634. // Bind them to `this`, not in closure, otherwise they will not
  45635. // be replaced when user calling setOption in not merge mode.
  45636. this._axisModel = axisModel;
  45637. this._axisPointerModel = axisPointerModel;
  45638. this._api = api;
  45639. // Optimize: `render` will be called repeatly during mouse move.
  45640. // So it is power consuming if performing `render` each time,
  45641. // especially on mobile device.
  45642. if (!forceRender
  45643. && this._lastValue === value
  45644. && this._lastStatus === status
  45645. ) {
  45646. return;
  45647. }
  45648. this._lastValue = value;
  45649. this._lastStatus = status;
  45650. var group = this._group;
  45651. var handle = this._handle;
  45652. if (!status || status === 'hide') {
  45653. // Do not clear here, for animation better.
  45654. group && group.hide();
  45655. handle && handle.hide();
  45656. return;
  45657. }
  45658. group && group.show();
  45659. handle && handle.show();
  45660. // Otherwise status is 'show'
  45661. var elOption = {};
  45662. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  45663. // Enable change axis pointer type.
  45664. var graphicKey = elOption.graphicKey;
  45665. if (graphicKey !== this._lastGraphicKey) {
  45666. this.clear(api);
  45667. }
  45668. this._lastGraphicKey = graphicKey;
  45669. var moveAnimation = this._moveAnimation =
  45670. this.determineAnimation(axisModel, axisPointerModel);
  45671. if (!group) {
  45672. group = this._group = new Group();
  45673. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  45674. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  45675. api.getZr().add(group);
  45676. }
  45677. else {
  45678. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  45679. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  45680. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  45681. }
  45682. updateMandatoryProps(group, axisPointerModel, true);
  45683. this._renderHandle(value);
  45684. },
  45685. /**
  45686. * @implement
  45687. */
  45688. remove: function (api) {
  45689. this.clear(api);
  45690. },
  45691. /**
  45692. * @implement
  45693. */
  45694. dispose: function (api) {
  45695. this.clear(api);
  45696. },
  45697. /**
  45698. * @protected
  45699. */
  45700. determineAnimation: function (axisModel, axisPointerModel) {
  45701. var animation = axisPointerModel.get('animation');
  45702. var axis = axisModel.axis;
  45703. var isCategoryAxis = axis.type === 'category';
  45704. var useSnap = axisPointerModel.get('snap');
  45705. // Value axis without snap always do not snap.
  45706. if (!useSnap && !isCategoryAxis) {
  45707. return false;
  45708. }
  45709. if (animation === 'auto' || animation == null) {
  45710. var animationThreshold = this.animationThreshold;
  45711. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  45712. return true;
  45713. }
  45714. // It is important to auto animation when snap used. Consider if there is
  45715. // a dataZoom, animation will be disabled when too many points exist, while
  45716. // it will be enabled for better visual effect when little points exist.
  45717. if (useSnap) {
  45718. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  45719. var axisExtent = axis.getExtent();
  45720. // Approximate band width
  45721. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  45722. }
  45723. return false;
  45724. }
  45725. return animation === true;
  45726. },
  45727. /**
  45728. * add {pointer, label, graphicKey} to elOption
  45729. * @protected
  45730. */
  45731. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  45732. // Shoule be implemenented by sub-class.
  45733. },
  45734. /**
  45735. * @protected
  45736. */
  45737. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  45738. var pointerOption = elOption.pointer;
  45739. if (pointerOption) {
  45740. var pointerEl = get$4(group).pointerEl = new graphic[pointerOption.type](
  45741. clone$3(elOption.pointer)
  45742. );
  45743. group.add(pointerEl);
  45744. }
  45745. },
  45746. /**
  45747. * @protected
  45748. */
  45749. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  45750. if (elOption.label) {
  45751. var labelEl = get$4(group).labelEl = new Rect(
  45752. clone$3(elOption.label)
  45753. );
  45754. group.add(labelEl);
  45755. updateLabelShowHide(labelEl, axisPointerModel);
  45756. }
  45757. },
  45758. /**
  45759. * @protected
  45760. */
  45761. updatePointerEl: function (group, elOption, updateProps$$1) {
  45762. var pointerEl = get$4(group).pointerEl;
  45763. if (pointerEl) {
  45764. pointerEl.setStyle(elOption.pointer.style);
  45765. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  45766. }
  45767. },
  45768. /**
  45769. * @protected
  45770. */
  45771. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  45772. var labelEl = get$4(group).labelEl;
  45773. if (labelEl) {
  45774. labelEl.setStyle(elOption.label.style);
  45775. updateProps$$1(labelEl, {
  45776. // Consider text length change in vertical axis, animation should
  45777. // be used on shape, otherwise the effect will be weird.
  45778. shape: elOption.label.shape,
  45779. position: elOption.label.position
  45780. });
  45781. updateLabelShowHide(labelEl, axisPointerModel);
  45782. }
  45783. },
  45784. /**
  45785. * @private
  45786. */
  45787. _renderHandle: function (value) {
  45788. if (this._dragging || !this.updateHandleTransform) {
  45789. return;
  45790. }
  45791. var axisPointerModel = this._axisPointerModel;
  45792. var zr = this._api.getZr();
  45793. var handle = this._handle;
  45794. var handleModel = axisPointerModel.getModel('handle');
  45795. var status = axisPointerModel.get('status');
  45796. if (!handleModel.get('show') || !status || status === 'hide') {
  45797. handle && zr.remove(handle);
  45798. this._handle = null;
  45799. return;
  45800. }
  45801. var isInit;
  45802. if (!this._handle) {
  45803. isInit = true;
  45804. handle = this._handle = createIcon(
  45805. handleModel.get('icon'),
  45806. {
  45807. cursor: 'move',
  45808. draggable: true,
  45809. onmousemove: function (e) {
  45810. // Fot mobile devicem, prevent screen slider on the button.
  45811. stop(e.event);
  45812. },
  45813. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  45814. drift: bind$2(this._onHandleDragMove, this),
  45815. ondragend: bind$2(this._onHandleDragEnd, this)
  45816. }
  45817. );
  45818. zr.add(handle);
  45819. }
  45820. updateMandatoryProps(handle, axisPointerModel, false);
  45821. // update style
  45822. var includeStyles = [
  45823. 'color', 'borderColor', 'borderWidth', 'opacity',
  45824. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  45825. ];
  45826. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  45827. // update position
  45828. var handleSize = handleModel.get('size');
  45829. if (!isArray(handleSize)) {
  45830. handleSize = [handleSize, handleSize];
  45831. }
  45832. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  45833. createOrUpdate(
  45834. this,
  45835. '_doDispatchAxisPointer',
  45836. handleModel.get('throttle') || 0,
  45837. 'fixRate'
  45838. );
  45839. this._moveHandleToValue(value, isInit);
  45840. },
  45841. /**
  45842. * @private
  45843. */
  45844. _moveHandleToValue: function (value, isInit) {
  45845. updateProps$1(
  45846. this._axisPointerModel,
  45847. !isInit && this._moveAnimation,
  45848. this._handle,
  45849. getHandleTransProps(this.getHandleTransform(
  45850. value, this._axisModel, this._axisPointerModel
  45851. ))
  45852. );
  45853. },
  45854. /**
  45855. * @private
  45856. */
  45857. _onHandleDragMove: function (dx, dy) {
  45858. var handle = this._handle;
  45859. if (!handle) {
  45860. return;
  45861. }
  45862. this._dragging = true;
  45863. // Persistent for throttle.
  45864. var trans = this.updateHandleTransform(
  45865. getHandleTransProps(handle),
  45866. [dx, dy],
  45867. this._axisModel,
  45868. this._axisPointerModel
  45869. );
  45870. this._payloadInfo = trans;
  45871. handle.stopAnimation();
  45872. handle.attr(getHandleTransProps(trans));
  45873. get$4(handle).lastProp = null;
  45874. this._doDispatchAxisPointer();
  45875. },
  45876. /**
  45877. * Throttled method.
  45878. * @private
  45879. */
  45880. _doDispatchAxisPointer: function () {
  45881. var handle = this._handle;
  45882. if (!handle) {
  45883. return;
  45884. }
  45885. var payloadInfo = this._payloadInfo;
  45886. var axisModel = this._axisModel;
  45887. this._api.dispatchAction({
  45888. type: 'updateAxisPointer',
  45889. x: payloadInfo.cursorPoint[0],
  45890. y: payloadInfo.cursorPoint[1],
  45891. tooltipOption: payloadInfo.tooltipOption,
  45892. axesInfo: [{
  45893. axisDim: axisModel.axis.dim,
  45894. axisIndex: axisModel.componentIndex
  45895. }]
  45896. });
  45897. },
  45898. /**
  45899. * @private
  45900. */
  45901. _onHandleDragEnd: function (moveAnimation) {
  45902. this._dragging = false;
  45903. var handle = this._handle;
  45904. if (!handle) {
  45905. return;
  45906. }
  45907. var value = this._axisPointerModel.get('value');
  45908. // Consider snap or categroy axis, handle may be not consistent with
  45909. // axisPointer. So move handle to align the exact value position when
  45910. // drag ended.
  45911. this._moveHandleToValue(value);
  45912. // For the effect: tooltip will be shown when finger holding on handle
  45913. // button, and will be hidden after finger left handle button.
  45914. this._api.dispatchAction({
  45915. type: 'hideTip'
  45916. });
  45917. },
  45918. /**
  45919. * Should be implemenented by sub-class if support `handle`.
  45920. * @protected
  45921. * @param {number} value
  45922. * @param {module:echarts/model/Model} axisModel
  45923. * @param {module:echarts/model/Model} axisPointerModel
  45924. * @return {Object} {position: [x, y], rotation: 0}
  45925. */
  45926. getHandleTransform: null,
  45927. /**
  45928. * * Should be implemenented by sub-class if support `handle`.
  45929. * @protected
  45930. * @param {Object} transform {position, rotation}
  45931. * @param {Array.<number>} delta [dx, dy]
  45932. * @param {module:echarts/model/Model} axisModel
  45933. * @param {module:echarts/model/Model} axisPointerModel
  45934. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  45935. */
  45936. updateHandleTransform: null,
  45937. /**
  45938. * @private
  45939. */
  45940. clear: function (api) {
  45941. this._lastValue = null;
  45942. this._lastStatus = null;
  45943. var zr = api.getZr();
  45944. var group = this._group;
  45945. var handle = this._handle;
  45946. if (zr && group) {
  45947. this._lastGraphicKey = null;
  45948. group && zr.remove(group);
  45949. handle && zr.remove(handle);
  45950. this._group = null;
  45951. this._handle = null;
  45952. this._payloadInfo = null;
  45953. }
  45954. },
  45955. /**
  45956. * @protected
  45957. */
  45958. doClear: function () {
  45959. // Implemented by sub-class if necessary.
  45960. },
  45961. /**
  45962. * @protected
  45963. * @param {Array.<number>} xy
  45964. * @param {Array.<number>} wh
  45965. * @param {number} [xDimIndex=0] or 1
  45966. */
  45967. buildLabel: function (xy, wh, xDimIndex) {
  45968. xDimIndex = xDimIndex || 0;
  45969. return {
  45970. x: xy[xDimIndex],
  45971. y: xy[1 - xDimIndex],
  45972. width: wh[xDimIndex],
  45973. height: wh[1 - xDimIndex]
  45974. };
  45975. }
  45976. };
  45977. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  45978. function updateProps$1(animationModel, moveAnimation, el, props) {
  45979. // Animation optimize.
  45980. if (!propsEqual(get$4(el).lastProp, props)) {
  45981. get$4(el).lastProp = props;
  45982. moveAnimation
  45983. ? updateProps(el, props, animationModel)
  45984. : (el.stopAnimation(), el.attr(props));
  45985. }
  45986. }
  45987. function propsEqual(lastProps, newProps) {
  45988. if (isObject(lastProps) && isObject(newProps)) {
  45989. var equals = true;
  45990. each$1(newProps, function (item, key) {
  45991. equals = equals && propsEqual(lastProps[key], item);
  45992. });
  45993. return !!equals;
  45994. }
  45995. else {
  45996. return lastProps === newProps;
  45997. }
  45998. }
  45999. function updateLabelShowHide(labelEl, axisPointerModel) {
  46000. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  46001. }
  46002. function getHandleTransProps(trans) {
  46003. return {
  46004. position: trans.position.slice(),
  46005. rotation: trans.rotation || 0
  46006. };
  46007. }
  46008. function updateMandatoryProps(group, axisPointerModel, silent) {
  46009. var z = axisPointerModel.get('z');
  46010. var zlevel = axisPointerModel.get('zlevel');
  46011. group && group.traverse(function (el) {
  46012. if (el.type !== 'group') {
  46013. z != null && (el.z = z);
  46014. zlevel != null && (el.zlevel = zlevel);
  46015. el.silent = silent;
  46016. }
  46017. });
  46018. }
  46019. enableClassExtend(BaseAxisPointer);
  46020. /**
  46021. * @param {module:echarts/model/Model} axisPointerModel
  46022. */
  46023. function buildElStyle(axisPointerModel) {
  46024. var axisPointerType = axisPointerModel.get('type');
  46025. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  46026. var style;
  46027. if (axisPointerType === 'line') {
  46028. style = styleModel.getLineStyle();
  46029. style.fill = null;
  46030. }
  46031. else if (axisPointerType === 'shadow') {
  46032. style = styleModel.getAreaStyle();
  46033. style.stroke = null;
  46034. }
  46035. return style;
  46036. }
  46037. /**
  46038. * @param {Function} labelPos {align, verticalAlign, position}
  46039. */
  46040. function buildLabelElOption(
  46041. elOption, axisModel, axisPointerModel, api, labelPos
  46042. ) {
  46043. var value = axisPointerModel.get('value');
  46044. var text = getValueLabel(
  46045. value, axisModel.axis, axisModel.ecModel,
  46046. axisPointerModel.get('seriesDataIndices'),
  46047. {
  46048. precision: axisPointerModel.get('label.precision'),
  46049. formatter: axisPointerModel.get('label.formatter')
  46050. }
  46051. );
  46052. var labelModel = axisPointerModel.getModel('label');
  46053. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  46054. var font = labelModel.getFont();
  46055. var textRect = getBoundingRect(text, font);
  46056. var position = labelPos.position;
  46057. var width = textRect.width + paddings[1] + paddings[3];
  46058. var height = textRect.height + paddings[0] + paddings[2];
  46059. // Adjust by align.
  46060. var align = labelPos.align;
  46061. align === 'right' && (position[0] -= width);
  46062. align === 'center' && (position[0] -= width / 2);
  46063. var verticalAlign = labelPos.verticalAlign;
  46064. verticalAlign === 'bottom' && (position[1] -= height);
  46065. verticalAlign === 'middle' && (position[1] -= height / 2);
  46066. // Not overflow ec container
  46067. confineInContainer(position, width, height, api);
  46068. var bgColor = labelModel.get('backgroundColor');
  46069. if (!bgColor || bgColor === 'auto') {
  46070. bgColor = axisModel.get('axisLine.lineStyle.color');
  46071. }
  46072. elOption.label = {
  46073. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  46074. position: position.slice(),
  46075. // TODO: rich
  46076. style: {
  46077. text: text,
  46078. textFont: font,
  46079. textFill: labelModel.getTextColor(),
  46080. textPosition: 'inside',
  46081. fill: bgColor,
  46082. stroke: labelModel.get('borderColor') || 'transparent',
  46083. lineWidth: labelModel.get('borderWidth') || 0,
  46084. shadowBlur: labelModel.get('shadowBlur'),
  46085. shadowColor: labelModel.get('shadowColor'),
  46086. shadowOffsetX: labelModel.get('shadowOffsetX'),
  46087. shadowOffsetY: labelModel.get('shadowOffsetY')
  46088. },
  46089. // Lable should be over axisPointer.
  46090. z2: 10
  46091. };
  46092. }
  46093. // Do not overflow ec container
  46094. function confineInContainer(position, width, height, api) {
  46095. var viewWidth = api.getWidth();
  46096. var viewHeight = api.getHeight();
  46097. position[0] = Math.min(position[0] + width, viewWidth) - width;
  46098. position[1] = Math.min(position[1] + height, viewHeight) - height;
  46099. position[0] = Math.max(position[0], 0);
  46100. position[1] = Math.max(position[1], 0);
  46101. }
  46102. /**
  46103. * @param {number} value
  46104. * @param {module:echarts/coord/Axis} axis
  46105. * @param {module:echarts/model/Global} ecModel
  46106. * @param {Object} opt
  46107. * @param {Array.<Object>} seriesDataIndices
  46108. * @param {number|string} opt.precision 'auto' or a number
  46109. * @param {string|Function} opt.formatter label formatter
  46110. */
  46111. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  46112. var text = axis.scale.getLabel(
  46113. // If `precision` is set, width can be fixed (like '12.00500'), which
  46114. // helps to debounce when when moving label.
  46115. value, {precision: opt.precision}
  46116. );
  46117. var formatter = opt.formatter;
  46118. if (formatter) {
  46119. var params = {
  46120. value: getAxisRawValue(axis, value),
  46121. seriesData: []
  46122. };
  46123. each$1(seriesDataIndices, function (idxItem) {
  46124. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  46125. var dataIndex = idxItem.dataIndexInside;
  46126. var dataParams = series && series.getDataParams(dataIndex);
  46127. dataParams && params.seriesData.push(dataParams);
  46128. });
  46129. if (isString(formatter)) {
  46130. text = formatter.replace('{value}', text);
  46131. }
  46132. else if (isFunction(formatter)) {
  46133. text = formatter(params);
  46134. }
  46135. }
  46136. return text;
  46137. }
  46138. /**
  46139. * @param {module:echarts/coord/Axis} axis
  46140. * @param {number} value
  46141. * @param {Object} layoutInfo {
  46142. * rotation, position, labelOffset, labelDirection, labelMargin
  46143. * }
  46144. */
  46145. function getTransformedPosition (axis, value, layoutInfo) {
  46146. var transform = create$1();
  46147. rotate(transform, transform, layoutInfo.rotation);
  46148. translate(transform, transform, layoutInfo.position);
  46149. return applyTransform$1([
  46150. axis.dataToCoord(value),
  46151. (layoutInfo.labelOffset || 0)
  46152. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  46153. ], transform);
  46154. }
  46155. function buildCartesianSingleLabelElOption(
  46156. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46157. ) {
  46158. var textLayout = AxisBuilder.innerTextLayout(
  46159. layoutInfo.rotation, 0, layoutInfo.labelDirection
  46160. );
  46161. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  46162. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  46163. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46164. align: textLayout.textAlign,
  46165. verticalAlign: textLayout.textVerticalAlign
  46166. });
  46167. }
  46168. /**
  46169. * @param {Array.<number>} p1
  46170. * @param {Array.<number>} p2
  46171. * @param {number} [xDimIndex=0] or 1
  46172. */
  46173. function makeLineShape(p1, p2, xDimIndex) {
  46174. xDimIndex = xDimIndex || 0;
  46175. return {
  46176. x1: p1[xDimIndex],
  46177. y1: p1[1 - xDimIndex],
  46178. x2: p2[xDimIndex],
  46179. y2: p2[1 - xDimIndex]
  46180. };
  46181. }
  46182. /**
  46183. * @param {Array.<number>} xy
  46184. * @param {Array.<number>} wh
  46185. * @param {number} [xDimIndex=0] or 1
  46186. */
  46187. function makeRectShape(xy, wh, xDimIndex) {
  46188. xDimIndex = xDimIndex || 0;
  46189. return {
  46190. x: xy[xDimIndex],
  46191. y: xy[1 - xDimIndex],
  46192. width: wh[xDimIndex],
  46193. height: wh[1 - xDimIndex]
  46194. };
  46195. }
  46196. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  46197. return {
  46198. cx: cx,
  46199. cy: cy,
  46200. r0: r0,
  46201. r: r,
  46202. startAngle: startAngle,
  46203. endAngle: endAngle,
  46204. clockwise: true
  46205. };
  46206. }
  46207. var CartesianAxisPointer = BaseAxisPointer.extend({
  46208. /**
  46209. * @override
  46210. */
  46211. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  46212. var axis = axisModel.axis;
  46213. var grid = axis.grid;
  46214. var axisPointerType = axisPointerModel.get('type');
  46215. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  46216. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  46217. if (axisPointerType && axisPointerType !== 'none') {
  46218. var elStyle = buildElStyle(axisPointerModel);
  46219. var pointerOption = pointerShapeBuilder[axisPointerType](
  46220. axis, pixelValue, otherExtent, elStyle
  46221. );
  46222. pointerOption.style = elStyle;
  46223. elOption.graphicKey = pointerOption.type;
  46224. elOption.pointer = pointerOption;
  46225. }
  46226. var layoutInfo = layout(grid.model, axisModel);
  46227. buildCartesianSingleLabelElOption(
  46228. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46229. );
  46230. },
  46231. /**
  46232. * @override
  46233. */
  46234. getHandleTransform: function (value, axisModel, axisPointerModel) {
  46235. var layoutInfo = layout(axisModel.axis.grid.model, axisModel, {
  46236. labelInside: false
  46237. });
  46238. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  46239. return {
  46240. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46241. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  46242. };
  46243. },
  46244. /**
  46245. * @override
  46246. */
  46247. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  46248. var axis = axisModel.axis;
  46249. var grid = axis.grid;
  46250. var axisExtent = axis.getGlobalExtent(true);
  46251. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  46252. var dimIndex = axis.dim === 'x' ? 0 : 1;
  46253. var currPosition = transform.position;
  46254. currPosition[dimIndex] += delta[dimIndex];
  46255. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  46256. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  46257. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  46258. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  46259. cursorPoint[dimIndex] = currPosition[dimIndex];
  46260. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  46261. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  46262. return {
  46263. position: currPosition,
  46264. rotation: transform.rotation,
  46265. cursorPoint: cursorPoint,
  46266. tooltipOption: tooltipOptions[dimIndex]
  46267. };
  46268. }
  46269. });
  46270. function getCartesian(grid, axis) {
  46271. var opt = {};
  46272. opt[axis.dim + 'AxisIndex'] = axis.index;
  46273. return grid.getCartesian(opt);
  46274. }
  46275. var pointerShapeBuilder = {
  46276. line: function (axis, pixelValue, otherExtent, elStyle) {
  46277. var targetShape = makeLineShape(
  46278. [pixelValue, otherExtent[0]],
  46279. [pixelValue, otherExtent[1]],
  46280. getAxisDimIndex(axis)
  46281. );
  46282. subPixelOptimizeLine({
  46283. shape: targetShape,
  46284. style: elStyle
  46285. });
  46286. return {
  46287. type: 'Line',
  46288. shape: targetShape
  46289. };
  46290. },
  46291. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  46292. var bandWidth = axis.getBandWidth();
  46293. var span = otherExtent[1] - otherExtent[0];
  46294. return {
  46295. type: 'Rect',
  46296. shape: makeRectShape(
  46297. [pixelValue - bandWidth / 2, otherExtent[0]],
  46298. [bandWidth, span],
  46299. getAxisDimIndex(axis)
  46300. )
  46301. };
  46302. }
  46303. };
  46304. function getAxisDimIndex(axis) {
  46305. return axis.dim === 'x' ? 0 : 1;
  46306. }
  46307. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  46308. // CartesianAxisPointer is not supposed to be required here. But consider
  46309. // echarts.simple.js and online build tooltip, which only require gridSimple,
  46310. // CartesianAxisPointer should be able to required somewhere.
  46311. registerPreprocessor(function (option) {
  46312. // Always has a global axisPointerModel for default setting.
  46313. if (option) {
  46314. (!option.axisPointer || option.axisPointer.length === 0)
  46315. && (option.axisPointer = {});
  46316. var link = option.axisPointer.link;
  46317. // Normalize to array to avoid object mergin. But if link
  46318. // is not set, remain null/undefined, otherwise it will
  46319. // override existent link setting.
  46320. if (link && !isArray(link)) {
  46321. option.axisPointer.link = [link];
  46322. }
  46323. }
  46324. });
  46325. // This process should proformed after coordinate systems created
  46326. // and series data processed. So put it on statistic processing stage.
  46327. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  46328. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  46329. // allAxesInfo should be updated when setOption performed.
  46330. ecModel.getComponent('axisPointer').coordSysAxesInfo
  46331. = collect(ecModel, api);
  46332. });
  46333. // Broadcast to all views.
  46334. registerAction({
  46335. type: 'updateAxisPointer',
  46336. event: 'updateAxisPointer',
  46337. update: ':updateAxisPointer'
  46338. }, axisTrigger);
  46339. var XY = ['x', 'y'];
  46340. var WH = ['width', 'height'];
  46341. var SingleAxisPointer = BaseAxisPointer.extend({
  46342. /**
  46343. * @override
  46344. */
  46345. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  46346. var axis = axisModel.axis;
  46347. var coordSys = axis.coordinateSystem;
  46348. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  46349. var pixelValue = coordSys.dataToPoint(value)[0];
  46350. var axisPointerType = axisPointerModel.get('type');
  46351. if (axisPointerType && axisPointerType !== 'none') {
  46352. var elStyle = buildElStyle(axisPointerModel);
  46353. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  46354. axis, pixelValue, otherExtent, elStyle
  46355. );
  46356. pointerOption.style = elStyle;
  46357. elOption.graphicKey = pointerOption.type;
  46358. elOption.pointer = pointerOption;
  46359. }
  46360. var layoutInfo = layout$1(axisModel);
  46361. buildCartesianSingleLabelElOption(
  46362. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46363. );
  46364. },
  46365. /**
  46366. * @override
  46367. */
  46368. getHandleTransform: function (value, axisModel, axisPointerModel) {
  46369. var layoutInfo = layout$1(axisModel, {labelInside: false});
  46370. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  46371. return {
  46372. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46373. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  46374. };
  46375. },
  46376. /**
  46377. * @override
  46378. */
  46379. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  46380. var axis = axisModel.axis;
  46381. var coordSys = axis.coordinateSystem;
  46382. var dimIndex = getPointDimIndex(axis);
  46383. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  46384. var currPosition = transform.position;
  46385. currPosition[dimIndex] += delta[dimIndex];
  46386. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  46387. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  46388. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  46389. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  46390. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  46391. cursorPoint[dimIndex] = currPosition[dimIndex];
  46392. return {
  46393. position: currPosition,
  46394. rotation: transform.rotation,
  46395. cursorPoint: cursorPoint,
  46396. tooltipOption: {
  46397. verticalAlign: 'middle'
  46398. }
  46399. };
  46400. }
  46401. });
  46402. var pointerShapeBuilder$1 = {
  46403. line: function (axis, pixelValue, otherExtent, elStyle) {
  46404. var targetShape = makeLineShape(
  46405. [pixelValue, otherExtent[0]],
  46406. [pixelValue, otherExtent[1]],
  46407. getPointDimIndex(axis)
  46408. );
  46409. subPixelOptimizeLine({
  46410. shape: targetShape,
  46411. style: elStyle
  46412. });
  46413. return {
  46414. type: 'Line',
  46415. shape: targetShape
  46416. };
  46417. },
  46418. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  46419. var bandWidth = axis.getBandWidth();
  46420. var span = otherExtent[1] - otherExtent[0];
  46421. return {
  46422. type: 'Rect',
  46423. shape: makeRectShape(
  46424. [pixelValue - bandWidth / 2, otherExtent[0]],
  46425. [bandWidth, span],
  46426. getPointDimIndex(axis)
  46427. )
  46428. };
  46429. }
  46430. };
  46431. function getPointDimIndex(axis) {
  46432. return axis.isHorizontal() ? 0 : 1;
  46433. }
  46434. function getGlobalExtent(coordSys, dimIndex) {
  46435. var rect = coordSys.getRect();
  46436. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  46437. }
  46438. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  46439. extendComponentView({
  46440. type: 'single'
  46441. });
  46442. /**
  46443. * @file Define the themeRiver view's series model
  46444. * @author Deqing Li(annong035@gmail.com)
  46445. */
  46446. var DATA_NAME_INDEX = 2;
  46447. var ThemeRiverSeries = SeriesModel.extend({
  46448. type: 'series.themeRiver',
  46449. dependencies: ['singleAxis'],
  46450. /**
  46451. * @readOnly
  46452. * @type {module:zrender/core/util#HashMap}
  46453. */
  46454. nameMap: null,
  46455. /**
  46456. * @override
  46457. */
  46458. init: function (option) {
  46459. ThemeRiverSeries.superApply(this, 'init', arguments);
  46460. // Put this function here is for the sake of consistency of code style.
  46461. // Enable legend selection for each data item
  46462. // Use a function instead of direct access because data reference may changed
  46463. this.legendDataProvider = function () {
  46464. return this.getRawData();
  46465. };
  46466. },
  46467. /**
  46468. * If there is no value of a certain point in the time for some event,set it value to 0.
  46469. *
  46470. * @param {Array} data initial data in the option
  46471. * @return {Array}
  46472. */
  46473. fixData: function (data) {
  46474. var rawDataLength = data.length;
  46475. // grouped data by name
  46476. var dataByName = nest()
  46477. .key(function (dataItem) {
  46478. return dataItem[2];
  46479. })
  46480. .entries(data);
  46481. // data group in each layer
  46482. var layData = map(dataByName, function (d) {
  46483. return {
  46484. name: d.key,
  46485. dataList: d.values
  46486. };
  46487. });
  46488. var layerNum = layData.length;
  46489. var largestLayer = -1;
  46490. var index = -1;
  46491. for (var i = 0; i < layerNum; ++i) {
  46492. var len = layData[i].dataList.length;
  46493. if (len > largestLayer) {
  46494. largestLayer = len;
  46495. index = i;
  46496. }
  46497. }
  46498. for (var k = 0; k < layerNum; ++k) {
  46499. if (k === index) {
  46500. continue;
  46501. }
  46502. var name = layData[k].name;
  46503. for (var j = 0; j < largestLayer; ++j) {
  46504. var timeValue = layData[index].dataList[j][0];
  46505. var length = layData[k].dataList.length;
  46506. var keyIndex = -1;
  46507. for (var l = 0; l < length; ++l) {
  46508. var value = layData[k].dataList[l][0];
  46509. if (value === timeValue) {
  46510. keyIndex = l;
  46511. break;
  46512. }
  46513. }
  46514. if (keyIndex === -1) {
  46515. data[rawDataLength] = [];
  46516. data[rawDataLength][0] = timeValue;
  46517. data[rawDataLength][1] = 0;
  46518. data[rawDataLength][2] = name;
  46519. rawDataLength++;
  46520. }
  46521. }
  46522. }
  46523. return data;
  46524. },
  46525. /**
  46526. * @override
  46527. * @param {Object} option the initial option that user gived
  46528. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  46529. * @return {module:echarts/data/List}
  46530. */
  46531. getInitialData: function (option, ecModel) {
  46532. var dimensions = [];
  46533. var singleAxisModel = ecModel.queryComponents({
  46534. mainType: 'singleAxis',
  46535. index: this.get('singleAxisIndex'),
  46536. id: this.get('singleAxisId')
  46537. })[0];
  46538. var axisType = singleAxisModel.get('type');
  46539. dimensions = [
  46540. {
  46541. name: 'time',
  46542. // FIXME common?
  46543. type: axisType === 'category'
  46544. ? 'ordinal'
  46545. : axisType === 'time'
  46546. ? 'time'
  46547. : 'float'
  46548. },
  46549. {
  46550. name: 'value',
  46551. type: 'float'
  46552. },
  46553. {
  46554. name: 'name',
  46555. type: 'ordinal'
  46556. }
  46557. ];
  46558. // filter the data item with the value of label is undefined
  46559. var filterData = filter(option.data, function (dataItem) {
  46560. return dataItem[2] !== undefined;
  46561. });
  46562. var data = this.fixData(filterData || []);
  46563. var nameList = [];
  46564. var nameMap = this.nameMap = createHashMap();
  46565. var count = 0;
  46566. for (var i = 0; i < data.length; ++i) {
  46567. nameList.push(data[i][DATA_NAME_INDEX]);
  46568. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  46569. nameMap.set(data[i][DATA_NAME_INDEX], count);
  46570. count++;
  46571. }
  46572. }
  46573. dimensions = completeDimensions(dimensions, data);
  46574. var list = new List(dimensions, this);
  46575. list.initData(data, nameList);
  46576. return list;
  46577. },
  46578. /**
  46579. * Used by single coordinate
  46580. *
  46581. * @param {string} axisDim the dimension for single coordinate
  46582. * @return {Array.<string> } specified dimensions on the axis.
  46583. */
  46584. coordDimToDataDim: function (axisDim) {
  46585. return ['time'];
  46586. },
  46587. /**
  46588. * The raw data is divided into multiple layers and each layer
  46589. * has same name.
  46590. *
  46591. * @return {Array.<Array.<number>>}
  46592. */
  46593. getLayerSeries: function () {
  46594. var data = this.getData();
  46595. var lenCount = data.count();
  46596. var indexArr = [];
  46597. for (var i = 0; i < lenCount; ++i) {
  46598. indexArr[i] = i;
  46599. }
  46600. // data group by name
  46601. var dataByName = nest()
  46602. .key(function (index) {
  46603. return data.get('name', index);
  46604. })
  46605. .entries(indexArr);
  46606. var layerSeries = map(dataByName, function (d) {
  46607. return {
  46608. name: d.key,
  46609. indices: d.values
  46610. };
  46611. });
  46612. for (var j = 0; j < layerSeries.length; ++j) {
  46613. layerSeries[j].indices.sort(comparer);
  46614. }
  46615. function comparer(index1, index2) {
  46616. return data.get('time', index1) - data.get('time', index2);
  46617. }
  46618. return layerSeries;
  46619. },
  46620. /**
  46621. * Get data indices for show tooltip content
  46622. *
  46623. * @param {Array.<string>|string} dim single coordinate dimension
  46624. * @param {number} value axis value
  46625. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  46626. * the themeRiver.
  46627. * @return {Object} {dataIndices, nestestValue}
  46628. */
  46629. getAxisTooltipData: function (dim, value, baseAxis) {
  46630. if (!isArray(dim)) {
  46631. dim = dim ? [dim] : [];
  46632. }
  46633. var data = this.getData();
  46634. var layerSeries = this.getLayerSeries();
  46635. var indices = [];
  46636. var layerNum = layerSeries.length;
  46637. var nestestValue;
  46638. for (var i = 0; i < layerNum; ++i) {
  46639. var minDist = Number.MAX_VALUE;
  46640. var nearestIdx = -1;
  46641. var pointNum = layerSeries[i].indices.length;
  46642. for (var j = 0; j < pointNum; ++j) {
  46643. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  46644. var dist = Math.abs(theValue - value);
  46645. if (dist <= minDist) {
  46646. nestestValue = theValue;
  46647. minDist = dist;
  46648. nearestIdx = layerSeries[i].indices[j];
  46649. }
  46650. }
  46651. indices.push(nearestIdx);
  46652. }
  46653. return {dataIndices: indices, nestestValue: nestestValue};
  46654. },
  46655. /**
  46656. * @override
  46657. * @param {number} dataIndex index of data
  46658. */
  46659. formatTooltip: function (dataIndex) {
  46660. var data = this.getData();
  46661. var htmlName = data.get('name', dataIndex);
  46662. var htmlValue = data.get('value', dataIndex);
  46663. if (isNaN(htmlValue) || htmlValue == null) {
  46664. htmlValue = '-';
  46665. }
  46666. return encodeHTML(htmlName + ' : ' + htmlValue);
  46667. },
  46668. defaultOption: {
  46669. zlevel: 0,
  46670. z: 2,
  46671. coordinateSystem: 'singleAxis',
  46672. // gap in axis's orthogonal orientation
  46673. boundaryGap: ['10%', '10%'],
  46674. // legendHoverLink: true,
  46675. singleAxisIndex: 0,
  46676. animationEasing: 'linear',
  46677. label: {
  46678. normal: {
  46679. margin: 4,
  46680. textAlign: 'right',
  46681. show: true,
  46682. position: 'left',
  46683. color: '#000',
  46684. fontSize: 11
  46685. },
  46686. emphasis: {
  46687. show: true
  46688. }
  46689. }
  46690. }
  46691. });
  46692. /**
  46693. * @file The file used to draw themeRiver view
  46694. * @author Deqing Li(annong035@gmail.com)
  46695. */
  46696. extendChartView({
  46697. type: 'themeRiver',
  46698. init: function () {
  46699. this._layers = [];
  46700. },
  46701. render: function (seriesModel, ecModel, api) {
  46702. var data = seriesModel.getData();
  46703. var group = this.group;
  46704. var layerSeries = seriesModel.getLayerSeries();
  46705. var layoutInfo = data.getLayout('layoutInfo');
  46706. var rect = layoutInfo.rect;
  46707. var boundaryGap = layoutInfo.boundaryGap;
  46708. group.attr('position', [0, rect.y + boundaryGap[0]]);
  46709. function keyGetter(item) {
  46710. return item.name;
  46711. }
  46712. var dataDiffer = new DataDiffer(
  46713. this._layersSeries || [], layerSeries,
  46714. keyGetter, keyGetter
  46715. );
  46716. var newLayersGroups = {};
  46717. dataDiffer
  46718. .add(bind(process, this, 'add'))
  46719. .update(bind(process, this, 'update'))
  46720. .remove(bind(process, this, 'remove'))
  46721. .execute();
  46722. function process(status, idx, oldIdx) {
  46723. var oldLayersGroups = this._layers;
  46724. if (status === 'remove') {
  46725. group.remove(oldLayersGroups[idx]);
  46726. return;
  46727. }
  46728. var points0 = [];
  46729. var points1 = [];
  46730. var color;
  46731. var indices = layerSeries[idx].indices;
  46732. for (var j = 0; j < indices.length; j++) {
  46733. var layout = data.getItemLayout(indices[j]);
  46734. var x = layout.x;
  46735. var y0 = layout.y0;
  46736. var y = layout.y;
  46737. points0.push([x, y0]);
  46738. points1.push([x, y0 + y]);
  46739. color = data.getItemVisual(indices[j], 'color');
  46740. }
  46741. var polygon;
  46742. var text;
  46743. var textLayout = data.getItemLayout(indices[0]);
  46744. var itemModel = data.getItemModel(indices[j - 1]);
  46745. var labelModel = itemModel.getModel('label.normal');
  46746. var margin = labelModel.get('margin');
  46747. if (status === 'add') {
  46748. var layerGroup = newLayersGroups[idx] = new Group();
  46749. polygon = new Polygon$1({
  46750. shape: {
  46751. points: points0,
  46752. stackedOnPoints: points1,
  46753. smooth: 0.4,
  46754. stackedOnSmooth: 0.4,
  46755. smoothConstraint: false
  46756. },
  46757. z2: 0
  46758. });
  46759. text = new Text({
  46760. style: {
  46761. x: textLayout.x - margin,
  46762. y: textLayout.y0 + textLayout.y / 2
  46763. }
  46764. });
  46765. layerGroup.add(polygon);
  46766. layerGroup.add(text);
  46767. group.add(layerGroup);
  46768. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  46769. polygon.removeClipPath();
  46770. }));
  46771. }
  46772. else {
  46773. var layerGroup = oldLayersGroups[oldIdx];
  46774. polygon = layerGroup.childAt(0);
  46775. text = layerGroup.childAt(1);
  46776. group.add(layerGroup);
  46777. newLayersGroups[idx] = layerGroup;
  46778. updateProps(polygon, {
  46779. shape: {
  46780. points: points0,
  46781. stackedOnPoints: points1
  46782. }
  46783. }, seriesModel);
  46784. updateProps(text, {
  46785. style: {
  46786. x: textLayout.x - margin,
  46787. y: textLayout.y0 + textLayout.y / 2
  46788. }
  46789. }, seriesModel);
  46790. }
  46791. var hoverItemStyleModel = itemModel.getModel('itemStyle.emphasis');
  46792. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  46793. setTextStyle(text.style, labelModel, {
  46794. text: labelModel.get('show')
  46795. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  46796. || data.getName(indices[j - 1])
  46797. : null,
  46798. textVerticalAlign: 'middle'
  46799. });
  46800. polygon.setStyle(extend({
  46801. fill: color
  46802. }, itemStyleModel.getItemStyle(['color'])));
  46803. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  46804. }
  46805. this._layersSeries = layerSeries;
  46806. this._layers = newLayersGroups;
  46807. },
  46808. dispose: function () {}
  46809. });
  46810. // add animation to the view
  46811. function createGridClipShape$3(rect, seriesModel, cb) {
  46812. var rectEl = new Rect({
  46813. shape: {
  46814. x: rect.x - 10,
  46815. y: rect.y - 10,
  46816. width: 0,
  46817. height: rect.height + 20
  46818. }
  46819. });
  46820. initProps(rectEl, {
  46821. shape: {
  46822. width: rect.width + 20,
  46823. height: rect.height + 20
  46824. }
  46825. }, seriesModel, cb);
  46826. return rectEl;
  46827. }
  46828. /**
  46829. * @file Using layout algorithm transform the raw data to layout information.
  46830. * @author Deqing Li(annong035@gmail.com)
  46831. */
  46832. var themeRiverLayout = function (ecModel, api) {
  46833. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  46834. var data = seriesModel.getData();
  46835. var single = seriesModel.coordinateSystem;
  46836. var layoutInfo = {};
  46837. // use the axis boundingRect for view
  46838. var rect = single.getRect();
  46839. layoutInfo.rect = rect;
  46840. var boundaryGap = seriesModel.get('boundaryGap');
  46841. var axis = single.getAxis();
  46842. layoutInfo.boundaryGap = boundaryGap;
  46843. if (axis.orient === 'horizontal') {
  46844. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  46845. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  46846. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  46847. themeRiverLayout$1(data, seriesModel, height);
  46848. }
  46849. else {
  46850. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  46851. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  46852. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  46853. themeRiverLayout$1(data, seriesModel, width);
  46854. }
  46855. data.setLayout('layoutInfo', layoutInfo);
  46856. });
  46857. };
  46858. /**
  46859. * The layout information about themeriver
  46860. *
  46861. * @param {module:echarts/data/List} data data in the series
  46862. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  46863. * @param {number} height value used to compute every series height
  46864. */
  46865. function themeRiverLayout$1(data, seriesModel, height) {
  46866. if (!data.count()) {
  46867. return;
  46868. }
  46869. var coordSys = seriesModel.coordinateSystem;
  46870. // the data in each layer are organized into a series.
  46871. var layerSeries = seriesModel.getLayerSeries();
  46872. // the points in each layer.
  46873. var layerPoints = map(layerSeries, function (singleLayer) {
  46874. return map(singleLayer.indices, function (idx) {
  46875. var pt = coordSys.dataToPoint(data.get('time', idx));
  46876. pt[1] = data.get('value', idx);
  46877. return pt;
  46878. });
  46879. });
  46880. var base = computeBaseline(layerPoints);
  46881. var baseLine = base.y0;
  46882. var ky = height / base.max;
  46883. // set layout information for each item.
  46884. var n = layerSeries.length;
  46885. var m = layerSeries[0].indices.length;
  46886. var baseY0;
  46887. for (var j = 0; j < m; ++j) {
  46888. baseY0 = baseLine[j] * ky;
  46889. data.setItemLayout(layerSeries[0].indices[j], {
  46890. layerIndex: 0,
  46891. x: layerPoints[0][j][0],
  46892. y0: baseY0,
  46893. y: layerPoints[0][j][1] * ky
  46894. });
  46895. for (var i = 1; i < n; ++i) {
  46896. baseY0 += layerPoints[i - 1][j][1] * ky;
  46897. data.setItemLayout(layerSeries[i].indices[j], {
  46898. layerIndex: i,
  46899. x: layerPoints[i][j][0],
  46900. y0: baseY0,
  46901. y: layerPoints[i][j][1] * ky
  46902. });
  46903. }
  46904. }
  46905. }
  46906. /**
  46907. * Compute the baseLine of the rawdata
  46908. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  46909. *
  46910. * @param {Array.<Array>} data the points in each layer
  46911. * @return {Object}
  46912. */
  46913. function computeBaseline(data) {
  46914. var layerNum = data.length;
  46915. var pointNum = data[0].length;
  46916. var sums = [];
  46917. var y0 = [];
  46918. var max = 0;
  46919. var temp;
  46920. var base = {};
  46921. for (var i = 0; i < pointNum; ++i) {
  46922. for (var j = 0, temp = 0; j < layerNum; ++j) {
  46923. temp += data[j][i][1];
  46924. }
  46925. if (temp > max) {
  46926. max = temp;
  46927. }
  46928. sums.push(temp);
  46929. }
  46930. for (var k = 0; k < pointNum; ++k) {
  46931. y0[k] = (max - sums[k]) / 2;
  46932. }
  46933. max = 0;
  46934. for (var l = 0; l < pointNum; ++l) {
  46935. var sum = sums[l] + y0[l];
  46936. if (sum > max) {
  46937. max = sum;
  46938. }
  46939. }
  46940. base.y0 = y0;
  46941. base.max = max;
  46942. return base;
  46943. }
  46944. /**
  46945. * @file Visual encoding for themeRiver view
  46946. * @author Deqing Li(annong035@gmail.com)
  46947. */
  46948. var themeRiverVisual = function (ecModel) {
  46949. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  46950. var data = seriesModel.getData();
  46951. var rawData = seriesModel.getRawData();
  46952. var colorList = seriesModel.get('color');
  46953. var idxMap = createHashMap();
  46954. data.each(function (idx) {
  46955. idxMap.set(data.getRawIndex(idx), idx);
  46956. });
  46957. rawData.each(function (rawIndex) {
  46958. var name = rawData.getName(rawIndex);
  46959. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  46960. rawData.setItemVisual(rawIndex, 'color', color);
  46961. var idx = idxMap.get(rawIndex);
  46962. if (idx != null) {
  46963. data.setItemVisual(idx, 'color', color);
  46964. }
  46965. });
  46966. });
  46967. };
  46968. registerLayout(themeRiverLayout);
  46969. registerVisual(themeRiverVisual);
  46970. registerProcessor(curry(dataFilter, 'themeRiver'));
  46971. function dataToCoordSize(dataSize, dataItem) {
  46972. // dataItem is necessary in log axis.
  46973. dataItem = dataItem || [0, 0];
  46974. return map(['x', 'y'], function (dim, dimIdx) {
  46975. var axis = this.getAxis(dim);
  46976. var val = dataItem[dimIdx];
  46977. var halfSize = dataSize[dimIdx] / 2;
  46978. return axis.type === 'category'
  46979. ? axis.getBandWidth()
  46980. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  46981. }, this);
  46982. }
  46983. var prepareCartesian2d = function (coordSys) {
  46984. var rect = coordSys.grid.getRect();
  46985. return {
  46986. coordSys: {
  46987. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  46988. type: 'cartesian2d',
  46989. x: rect.x,
  46990. y: rect.y,
  46991. width: rect.width,
  46992. height: rect.height
  46993. },
  46994. api: {
  46995. coord: bind(coordSys.dataToPoint, coordSys),
  46996. size: bind(dataToCoordSize, coordSys)
  46997. }
  46998. };
  46999. };
  47000. function dataToCoordSize$1(dataSize, dataItem) {
  47001. dataItem = dataItem || [0, 0];
  47002. return map([0, 1], function (dimIdx) {
  47003. var val = dataItem[dimIdx];
  47004. var halfSize = dataSize[dimIdx] / 2;
  47005. var p1 = [];
  47006. var p2 = [];
  47007. p1[dimIdx] = val - halfSize;
  47008. p2[dimIdx] = val + halfSize;
  47009. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  47010. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  47011. }, this);
  47012. }
  47013. var prepareGeo = function (coordSys) {
  47014. var rect = coordSys.getBoundingRect();
  47015. return {
  47016. coordSys: {
  47017. type: 'geo',
  47018. x: rect.x,
  47019. y: rect.y,
  47020. width: rect.width,
  47021. height: rect.height
  47022. },
  47023. api: {
  47024. coord: bind(coordSys.dataToPoint, coordSys),
  47025. size: bind(dataToCoordSize$1, coordSys)
  47026. }
  47027. };
  47028. };
  47029. function dataToCoordSize$2(dataSize, dataItem) {
  47030. // dataItem is necessary in log axis.
  47031. var axis = this.getAxis();
  47032. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  47033. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  47034. return axis.type === 'category'
  47035. ? axis.getBandWidth()
  47036. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  47037. }
  47038. var prepareSingleAxis = function (coordSys) {
  47039. var rect = coordSys.getRect();
  47040. return {
  47041. coordSys: {
  47042. type: 'singleAxis',
  47043. x: rect.x,
  47044. y: rect.y,
  47045. width: rect.width,
  47046. height: rect.height
  47047. },
  47048. api: {
  47049. coord: bind(coordSys.dataToPoint, coordSys),
  47050. size: bind(dataToCoordSize$2, coordSys)
  47051. }
  47052. };
  47053. };
  47054. function dataToCoordSize$3(dataSize, dataItem) {
  47055. // dataItem is necessary in log axis.
  47056. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  47057. var axis = this['get' + dim + 'Axis']();
  47058. var val = dataItem[dimIdx];
  47059. var halfSize = dataSize[dimIdx] / 2;
  47060. var method = 'dataTo' + dim;
  47061. var result = axis.type === 'category'
  47062. ? axis.getBandWidth()
  47063. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  47064. if (dim === 'Angle') {
  47065. result = result * Math.PI / 180;
  47066. }
  47067. return result;
  47068. }, this);
  47069. }
  47070. var preparePolar = function (coordSys) {
  47071. var radiusAxis = coordSys.getRadiusAxis();
  47072. var angleAxis = coordSys.getAngleAxis();
  47073. var radius = radiusAxis.getExtent();
  47074. radius[0] > radius[1] && radius.reverse();
  47075. return {
  47076. coordSys: {
  47077. type: 'polar',
  47078. cx: coordSys.cx,
  47079. cy: coordSys.cy,
  47080. r: radius[1],
  47081. r0: radius[0]
  47082. },
  47083. api: {
  47084. coord: bind(function (data) {
  47085. var radius = radiusAxis.dataToRadius(data[0]);
  47086. var angle = angleAxis.dataToAngle(data[1]);
  47087. var coord = coordSys.coordToPoint([radius, angle]);
  47088. coord.push(radius, angle * Math.PI / 180);
  47089. return coord;
  47090. }),
  47091. size: bind(dataToCoordSize$3, coordSys)
  47092. }
  47093. };
  47094. };
  47095. var prepareCalendar = function (coordSys) {
  47096. var rect = coordSys.getRect();
  47097. var rangeInfo = coordSys.getRangeInfo();
  47098. return {
  47099. coordSys: {
  47100. type: 'calendar',
  47101. x: rect.x,
  47102. y: rect.y,
  47103. width: rect.width,
  47104. height: rect.height,
  47105. cellWidth: coordSys.getCellWidth(),
  47106. cellHeight: coordSys.getCellHeight(),
  47107. rangeInfo: {
  47108. start: rangeInfo.start,
  47109. end: rangeInfo.end,
  47110. weeks: rangeInfo.weeks,
  47111. dayCount: rangeInfo.allDay
  47112. }
  47113. },
  47114. api: {
  47115. coord: bind(coordSys.dataToPoint, coordSys)
  47116. }
  47117. };
  47118. };
  47119. var ITEM_STYLE_NORMAL_PATH = ['itemStyle', 'normal'];
  47120. var ITEM_STYLE_EMPHASIS_PATH = ['itemStyle', 'emphasis'];
  47121. var LABEL_NORMAL = ['label', 'normal'];
  47122. var LABEL_EMPHASIS = ['label', 'emphasis'];
  47123. // Use prefix to avoid index to be the same as el.name,
  47124. // which will cause weird udpate animation.
  47125. var GROUP_DIFF_PREFIX = 'e\0\0';
  47126. /**
  47127. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  47128. * of each coordinate systems are not required by each coordinate systems directly, but
  47129. * required by the module `custom`.
  47130. *
  47131. * prepareInfoForCustomSeries {Function}: optional
  47132. * @return {Object} {coordSys: {...}, api: {
  47133. * coord: function (data, clamp) {}, // return point in global.
  47134. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  47135. * }}
  47136. */
  47137. var prepareCustoms = {
  47138. cartesian2d: prepareCartesian2d,
  47139. geo: prepareGeo,
  47140. singleAxis: prepareSingleAxis,
  47141. polar: preparePolar,
  47142. calendar: prepareCalendar
  47143. };
  47144. // ------
  47145. // Model
  47146. // ------
  47147. extendSeriesModel({
  47148. type: 'series.custom',
  47149. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  47150. defaultOption: {
  47151. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  47152. zlevel: 0,
  47153. z: 2,
  47154. legendHoverLink: true
  47155. // Cartesian coordinate system
  47156. // xAxisIndex: 0,
  47157. // yAxisIndex: 0,
  47158. // Polar coordinate system
  47159. // polarIndex: 0,
  47160. // Geo coordinate system
  47161. // geoIndex: 0,
  47162. // label: {}
  47163. // itemStyle: {}
  47164. },
  47165. getInitialData: function (option, ecModel) {
  47166. return createListFromArray(option.data, this, ecModel);
  47167. }
  47168. });
  47169. // -----
  47170. // View
  47171. // -----
  47172. extendChartView({
  47173. type: 'custom',
  47174. /**
  47175. * @private
  47176. * @type {module:echarts/data/List}
  47177. */
  47178. _data: null,
  47179. /**
  47180. * @override
  47181. */
  47182. render: function (customSeries, ecModel, api) {
  47183. var oldData = this._data;
  47184. var data = customSeries.getData();
  47185. var group = this.group;
  47186. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  47187. data.diff(oldData)
  47188. .add(function (newIdx) {
  47189. data.hasValue(newIdx) && createOrUpdate$1(
  47190. null, newIdx, renderItem(newIdx), customSeries, group, data
  47191. );
  47192. })
  47193. .update(function (newIdx, oldIdx) {
  47194. var el = oldData.getItemGraphicEl(oldIdx);
  47195. data.hasValue(newIdx)
  47196. ? createOrUpdate$1(
  47197. el, newIdx, renderItem(newIdx), customSeries, group, data
  47198. )
  47199. : (el && group.remove(el));
  47200. })
  47201. .remove(function (oldIdx) {
  47202. var el = oldData.getItemGraphicEl(oldIdx);
  47203. el && group.remove(el);
  47204. })
  47205. .execute();
  47206. this._data = data;
  47207. },
  47208. /**
  47209. * @override
  47210. */
  47211. dispose: noop
  47212. });
  47213. function createEl(elOption) {
  47214. var graphicType = elOption.type;
  47215. var el;
  47216. if (graphicType === 'path') {
  47217. var shape = elOption.shape;
  47218. el = makePath(
  47219. shape.pathData,
  47220. null,
  47221. {
  47222. x: shape.x || 0,
  47223. y: shape.y || 0,
  47224. width: shape.width || 0,
  47225. height: shape.height || 0
  47226. },
  47227. 'center'
  47228. );
  47229. el.__customPathData = elOption.pathData;
  47230. }
  47231. else if (graphicType === 'image') {
  47232. el = new ZImage({
  47233. });
  47234. el.__customImagePath = elOption.style.image;
  47235. }
  47236. else if (graphicType === 'text') {
  47237. el = new Text({
  47238. });
  47239. el.__customText = elOption.style.text;
  47240. }
  47241. else {
  47242. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  47243. if (__DEV__) {
  47244. assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
  47245. }
  47246. el = new Clz();
  47247. }
  47248. el.__customGraphicType = graphicType;
  47249. el.name = elOption.name;
  47250. return el;
  47251. }
  47252. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  47253. var targetProps = {};
  47254. var elOptionStyle = elOption.style || {};
  47255. elOption.shape && (targetProps.shape = clone(elOption.shape));
  47256. elOption.position && (targetProps.position = elOption.position.slice());
  47257. elOption.scale && (targetProps.scale = elOption.scale.slice());
  47258. elOption.origin && (targetProps.origin = elOption.origin.slice());
  47259. elOption.rotation && (targetProps.rotation = elOption.rotation);
  47260. if (el.type === 'image' && elOption.style) {
  47261. var targetStyle = targetProps.style = {};
  47262. each$1(['x', 'y', 'width', 'height'], function (prop) {
  47263. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  47264. });
  47265. }
  47266. if (el.type === 'text' && elOption.style) {
  47267. var targetStyle = targetProps.style = {};
  47268. each$1(['x', 'y'], function (prop) {
  47269. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  47270. });
  47271. // Compatible with previous: both support
  47272. // textFill and fill, textStroke and stroke in 'text' element.
  47273. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  47274. elOptionStyle.textFill = elOptionStyle.fill
  47275. );
  47276. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  47277. elOptionStyle.textStroke = elOptionStyle.stroke
  47278. );
  47279. }
  47280. if (el.type !== 'group') {
  47281. el.useStyle(elOptionStyle);
  47282. // Init animation.
  47283. if (isInit) {
  47284. el.style.opacity = 0;
  47285. var targetOpacity = elOptionStyle.opacity;
  47286. targetOpacity == null && (targetOpacity = 1);
  47287. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  47288. }
  47289. }
  47290. if (isInit) {
  47291. el.attr(targetProps);
  47292. }
  47293. else {
  47294. updateProps(el, targetProps, animatableModel, dataIndex);
  47295. }
  47296. // z2 must not be null/undefined, otherwise sort error may occur.
  47297. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  47298. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  47299. }
  47300. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  47301. if (elOptionStyle[prop] != null && !isInit) {
  47302. targetStyle[prop] = elOptionStyle[prop];
  47303. elOptionStyle[prop] = oldElStyle[prop];
  47304. }
  47305. }
  47306. function makeRenderItem(customSeries, data, ecModel, api) {
  47307. var renderItem = customSeries.get('renderItem');
  47308. var coordSys = customSeries.coordinateSystem;
  47309. var prepareResult = {};
  47310. if (coordSys) {
  47311. if (__DEV__) {
  47312. assert(renderItem, 'series.render is required.');
  47313. assert(
  47314. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  47315. 'This coordSys does not support custom series.'
  47316. );
  47317. }
  47318. prepareResult = coordSys.prepareCustoms
  47319. ? coordSys.prepareCustoms()
  47320. : prepareCustoms[coordSys.type](coordSys);
  47321. }
  47322. var userAPI = defaults({
  47323. getWidth: api.getWidth,
  47324. getHeight: api.getHeight,
  47325. getZr: api.getZr,
  47326. getDevicePixelRatio: api.getDevicePixelRatio,
  47327. value: value,
  47328. style: style,
  47329. styleEmphasis: styleEmphasis,
  47330. visual: visual,
  47331. barLayout: barLayout,
  47332. currentSeriesIndices: currentSeriesIndices,
  47333. font: font
  47334. }, prepareResult.api || {});
  47335. var userParams = {
  47336. context: {},
  47337. seriesId: customSeries.id,
  47338. seriesName: customSeries.name,
  47339. seriesIndex: customSeries.seriesIndex,
  47340. coordSys: prepareResult.coordSys,
  47341. dataInsideLength: data.count(),
  47342. encode: wrapEncodeDef(customSeries.getData())
  47343. };
  47344. // Do not support call `api` asynchronously without dataIndexInside input.
  47345. var currDataIndexInside;
  47346. var currDirty = true;
  47347. var currItemModel;
  47348. var currLabelNormalModel;
  47349. var currLabelEmphasisModel;
  47350. var currLabelValueDim;
  47351. var currVisualColor;
  47352. return function (dataIndexInside) {
  47353. currDataIndexInside = dataIndexInside;
  47354. currDirty = true;
  47355. return renderItem && renderItem(
  47356. defaults({
  47357. dataIndexInside: dataIndexInside,
  47358. dataIndex: data.getRawIndex(dataIndexInside)
  47359. }, userParams),
  47360. userAPI
  47361. ) || {};
  47362. };
  47363. // Do not update cache until api called.
  47364. function updateCache(dataIndexInside) {
  47365. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47366. if (currDirty) {
  47367. currItemModel = data.getItemModel(dataIndexInside);
  47368. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  47369. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  47370. currLabelValueDim = findLabelValueDim(data);
  47371. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  47372. currDirty = false;
  47373. }
  47374. }
  47375. /**
  47376. * @public
  47377. * @param {number|string} dim
  47378. * @param {number} [dataIndexInside=currDataIndexInside]
  47379. * @return {number|string} value
  47380. */
  47381. function value(dim, dataIndexInside) {
  47382. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47383. return data.get(data.getDimension(dim || 0), dataIndexInside);
  47384. }
  47385. /**
  47386. * By default, `visual` is applied to style (to support visualMap).
  47387. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  47388. * it can be implemented as:
  47389. * `api.style({stroke: api.visual('color'), fill: null})`;
  47390. * @public
  47391. * @param {Object} [extra]
  47392. * @param {number} [dataIndexInside=currDataIndexInside]
  47393. */
  47394. function style(extra, dataIndexInside) {
  47395. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47396. updateCache(dataIndexInside);
  47397. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  47398. currVisualColor != null && (itemStyle.fill = currVisualColor);
  47399. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  47400. opacity != null && (itemStyle.opacity = opacity);
  47401. if (currLabelValueDim != null) {
  47402. setTextStyle(itemStyle, currLabelNormalModel, null, {
  47403. autoColor: currVisualColor,
  47404. isRectText: true
  47405. });
  47406. itemStyle.text = currLabelNormalModel.getShallow('show')
  47407. ? retrieve2(
  47408. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  47409. data.get(currLabelValueDim, dataIndexInside)
  47410. )
  47411. : null;
  47412. }
  47413. extra && extend(itemStyle, extra);
  47414. return itemStyle;
  47415. }
  47416. /**
  47417. * @public
  47418. * @param {Object} [extra]
  47419. * @param {number} [dataIndexInside=currDataIndexInside]
  47420. */
  47421. function styleEmphasis(extra, dataIndexInside) {
  47422. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47423. updateCache(dataIndexInside);
  47424. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  47425. if (currLabelValueDim != null) {
  47426. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  47427. isRectText: true
  47428. }, true);
  47429. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  47430. ? retrieve3(
  47431. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  47432. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  47433. data.get(currLabelValueDim, dataIndexInside)
  47434. )
  47435. : null;
  47436. }
  47437. extra && extend(itemStyle, extra);
  47438. return itemStyle;
  47439. }
  47440. /**
  47441. * @public
  47442. * @param {string} visualType
  47443. * @param {number} [dataIndexInside=currDataIndexInside]
  47444. */
  47445. function visual(visualType, dataIndexInside) {
  47446. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47447. return data.getItemVisual(dataIndexInside, visualType);
  47448. }
  47449. /**
  47450. * @public
  47451. * @param {number} opt.count Positive interger.
  47452. * @param {number} [opt.barWidth]
  47453. * @param {number} [opt.barMaxWidth]
  47454. * @param {number} [opt.barGap]
  47455. * @param {number} [opt.barCategoryGap]
  47456. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  47457. */
  47458. function barLayout(opt) {
  47459. if (coordSys.getBaseAxis) {
  47460. var baseAxis = coordSys.getBaseAxis();
  47461. return barLayoutGrid.getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  47462. }
  47463. }
  47464. /**
  47465. * @public
  47466. * @return {Array.<number>}
  47467. */
  47468. function currentSeriesIndices() {
  47469. return ecModel.getCurrentSeriesIndices();
  47470. }
  47471. /**
  47472. * @public
  47473. * @param {Object} opt
  47474. * @param {string} [opt.fontStyle]
  47475. * @param {number} [opt.fontWeight]
  47476. * @param {number} [opt.fontSize]
  47477. * @param {string} [opt.fontFamily]
  47478. * @return {string} font string
  47479. */
  47480. function font(opt) {
  47481. return getFont(opt, ecModel);
  47482. }
  47483. }
  47484. function wrapEncodeDef(data) {
  47485. var encodeDef = {};
  47486. each$1(data.dimensions, function (dimName, dataDimIndex) {
  47487. var dimInfo = data.getDimensionInfo(dimName);
  47488. if (!dimInfo.isExtraCoord) {
  47489. var coordDim = dimInfo.coordDim;
  47490. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  47491. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  47492. }
  47493. });
  47494. return encodeDef;
  47495. }
  47496. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  47497. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  47498. el && data.setItemGraphicEl(dataIndex, el);
  47499. }
  47500. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  47501. var elOptionType = elOption.type;
  47502. if (el
  47503. && elOptionType !== el.__customGraphicType
  47504. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  47505. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  47506. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  47507. ) {
  47508. group.remove(el);
  47509. el = null;
  47510. }
  47511. // `elOption.type` is undefined when `renderItem` returns nothing.
  47512. if (elOptionType == null) {
  47513. return;
  47514. }
  47515. var isInit = !el;
  47516. !el && (el = createEl(elOption));
  47517. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  47518. if (elOptionType === 'group') {
  47519. var oldChildren = el.children() || [];
  47520. var newChildren = elOption.children || [];
  47521. if (elOption.diffChildrenByName) {
  47522. // lower performance.
  47523. diffGroupChildren({
  47524. oldChildren: oldChildren,
  47525. newChildren: newChildren,
  47526. dataIndex: dataIndex,
  47527. animatableModel: animatableModel,
  47528. group: el,
  47529. data: data
  47530. });
  47531. }
  47532. else {
  47533. // better performance.
  47534. var index = 0;
  47535. for (; index < newChildren.length; index++) {
  47536. doCreateOrUpdate(
  47537. el.childAt(index),
  47538. dataIndex,
  47539. newChildren[index],
  47540. animatableModel,
  47541. el,
  47542. data
  47543. );
  47544. }
  47545. for (; index < oldChildren.length; index++) {
  47546. oldChildren[index] && el.remove(oldChildren[index]);
  47547. }
  47548. }
  47549. }
  47550. group.add(el);
  47551. return el;
  47552. }
  47553. function diffGroupChildren(context) {
  47554. (new DataDiffer(
  47555. context.oldChildren,
  47556. context.newChildren,
  47557. getKey,
  47558. getKey,
  47559. context
  47560. ))
  47561. .add(processAddUpdate)
  47562. .update(processAddUpdate)
  47563. .remove(processRemove)
  47564. .execute();
  47565. }
  47566. function getKey(item, idx) {
  47567. var name = item && item.name;
  47568. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  47569. }
  47570. function processAddUpdate(newIndex, oldIndex) {
  47571. var context = this.context;
  47572. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  47573. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  47574. doCreateOrUpdate(
  47575. child,
  47576. context.dataIndex,
  47577. childOption,
  47578. context.animatableModel,
  47579. context.group,
  47580. context.data
  47581. );
  47582. }
  47583. function processRemove(oldIndex) {
  47584. var context = this.context;
  47585. var child = context.oldChildren[oldIndex];
  47586. child && context.group.remove(child);
  47587. }
  47588. // -------------
  47589. // Preprocessor
  47590. // -------------
  47591. registerPreprocessor(function (option) {
  47592. var graphicOption = option.graphic;
  47593. // Convert
  47594. // {graphic: [{left: 10, type: 'circle'}, ...]}
  47595. // or
  47596. // {graphic: {left: 10, type: 'circle'}}
  47597. // to
  47598. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  47599. if (isArray(graphicOption)) {
  47600. if (!graphicOption[0] || !graphicOption[0].elements) {
  47601. option.graphic = [{elements: graphicOption}];
  47602. }
  47603. else {
  47604. // Only one graphic instance can be instantiated. (We dont
  47605. // want that too many views are created in echarts._viewMap)
  47606. option.graphic = [option.graphic[0]];
  47607. }
  47608. }
  47609. else if (graphicOption && !graphicOption.elements) {
  47610. option.graphic = [{elements: [graphicOption]}];
  47611. }
  47612. });
  47613. // ------
  47614. // Model
  47615. // ------
  47616. var GraphicModel = extendComponentModel({
  47617. type: 'graphic',
  47618. defaultOption: {
  47619. // Extra properties for each elements:
  47620. //
  47621. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  47622. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  47623. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  47624. // This mechanism is useful when you want to position a group/element
  47625. // against the right side or the center of this container.
  47626. //
  47627. // width/height: (can only be pixel value, default 0)
  47628. // Only be used to specify contianer(group) size, if needed. And
  47629. // can not be percentage value (like '33%'). See the reason in the
  47630. // layout algorithm below.
  47631. //
  47632. // bounding: (enum: 'all' (default) | 'raw')
  47633. // Specify how to calculate boundingRect when locating.
  47634. // 'all': Get uioned and transformed boundingRect
  47635. // from both itself and its descendants.
  47636. // This mode simplies confining a group of elements in the bounding
  47637. // of their ancester container (e.g., using 'right: 0').
  47638. // 'raw': Only use the boundingRect of itself and before transformed.
  47639. // This mode is similar to css behavior, which is useful when you
  47640. // want an element to be able to overflow its container. (Consider
  47641. // a rotated circle needs to be located in a corner.)
  47642. // Note: elements is always behind its ancestors in this elements array.
  47643. elements: [],
  47644. parentId: null
  47645. },
  47646. /**
  47647. * Save el options for the sake of the performance (only update modified graphics).
  47648. * The order is the same as those in option. (ancesters -> descendants)
  47649. *
  47650. * @private
  47651. * @type {Array.<Object>}
  47652. */
  47653. _elOptionsToUpdate: null,
  47654. /**
  47655. * @override
  47656. */
  47657. mergeOption: function (option) {
  47658. // Prevent default merge to elements
  47659. var elements = this.option.elements;
  47660. this.option.elements = null;
  47661. GraphicModel.superApply(this, 'mergeOption', arguments);
  47662. this.option.elements = elements;
  47663. },
  47664. /**
  47665. * @override
  47666. */
  47667. optionUpdated: function (newOption, isInit) {
  47668. var thisOption = this.option;
  47669. var newList = (isInit ? thisOption : newOption).elements;
  47670. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  47671. var flattenedList = [];
  47672. this._flatten(newList, flattenedList);
  47673. var mappingResult = mappingToExists(existList, flattenedList);
  47674. makeIdAndName(mappingResult);
  47675. // Clear elOptionsToUpdate
  47676. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  47677. each$1(mappingResult, function (resultItem, index) {
  47678. var newElOption = resultItem.option;
  47679. if (__DEV__) {
  47680. assert(
  47681. isObject(newElOption) || resultItem.exist,
  47682. 'Empty graphic option definition'
  47683. );
  47684. }
  47685. if (!newElOption) {
  47686. return;
  47687. }
  47688. elOptionsToUpdate.push(newElOption);
  47689. setKeyInfoToNewElOption(resultItem, newElOption);
  47690. mergeNewElOptionToExist(existList, index, newElOption);
  47691. setLayoutInfoToExist(existList[index], newElOption);
  47692. }, this);
  47693. // Clean
  47694. for (var i = existList.length - 1; i >= 0; i--) {
  47695. if (existList[i] == null) {
  47696. existList.splice(i, 1);
  47697. }
  47698. else {
  47699. // $action should be volatile, otherwise option gotten from
  47700. // `getOption` will contain unexpected $action.
  47701. delete existList[i].$action;
  47702. }
  47703. }
  47704. },
  47705. /**
  47706. * Convert
  47707. * [{
  47708. * type: 'group',
  47709. * id: 'xx',
  47710. * children: [{type: 'circle'}, {type: 'polygon'}]
  47711. * }]
  47712. * to
  47713. * [
  47714. * {type: 'group', id: 'xx'},
  47715. * {type: 'circle', parentId: 'xx'},
  47716. * {type: 'polygon', parentId: 'xx'}
  47717. * ]
  47718. *
  47719. * @private
  47720. * @param {Array.<Object>} optionList option list
  47721. * @param {Array.<Object>} result result of flatten
  47722. * @param {Object} parentOption parent option
  47723. */
  47724. _flatten: function (optionList, result, parentOption) {
  47725. each$1(optionList, function (option) {
  47726. if (!option) {
  47727. return;
  47728. }
  47729. if (parentOption) {
  47730. option.parentOption = parentOption;
  47731. }
  47732. result.push(option);
  47733. var children = option.children;
  47734. if (option.type === 'group' && children) {
  47735. this._flatten(children, result, option);
  47736. }
  47737. // Deleting for JSON output, and for not affecting group creation.
  47738. delete option.children;
  47739. }, this);
  47740. },
  47741. // FIXME
  47742. // Pass to view using payload? setOption has a payload?
  47743. useElOptionsToUpdate: function () {
  47744. var els = this._elOptionsToUpdate;
  47745. // Clear to avoid render duplicately when zooming.
  47746. this._elOptionsToUpdate = null;
  47747. return els;
  47748. }
  47749. });
  47750. // -----
  47751. // View
  47752. // -----
  47753. extendComponentView({
  47754. type: 'graphic',
  47755. /**
  47756. * @override
  47757. */
  47758. init: function (ecModel, api) {
  47759. /**
  47760. * @private
  47761. * @type {module:zrender/core/util.HashMap}
  47762. */
  47763. this._elMap = createHashMap();
  47764. /**
  47765. * @private
  47766. * @type {module:echarts/graphic/GraphicModel}
  47767. */
  47768. this._lastGraphicModel;
  47769. },
  47770. /**
  47771. * @override
  47772. */
  47773. render: function (graphicModel, ecModel, api) {
  47774. // Having leveraged between use cases and algorithm complexity, a very
  47775. // simple layout mechanism is used:
  47776. // The size(width/height) can be determined by itself or its parent (not
  47777. // implemented yet), but can not by its children. (Top-down travel)
  47778. // The location(x/y) can be determined by the bounding rect of itself
  47779. // (can including its descendants or not) and the size of its parent.
  47780. // (Bottom-up travel)
  47781. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  47782. // view will be reused.
  47783. if (graphicModel !== this._lastGraphicModel) {
  47784. this._clear();
  47785. }
  47786. this._lastGraphicModel = graphicModel;
  47787. this._updateElements(graphicModel, api);
  47788. this._relocate(graphicModel, api);
  47789. },
  47790. /**
  47791. * Update graphic elements.
  47792. *
  47793. * @private
  47794. * @param {Object} graphicModel graphic model
  47795. * @param {module:echarts/ExtensionAPI} api extension API
  47796. */
  47797. _updateElements: function (graphicModel, api) {
  47798. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  47799. if (!elOptionsToUpdate) {
  47800. return;
  47801. }
  47802. var elMap = this._elMap;
  47803. var rootGroup = this.group;
  47804. // Top-down tranverse to assign graphic settings to each elements.
  47805. each$1(elOptionsToUpdate, function (elOption) {
  47806. var $action = elOption.$action;
  47807. var id = elOption.id;
  47808. var existEl = elMap.get(id);
  47809. var parentId = elOption.parentId;
  47810. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  47811. if (elOption.type === 'text') {
  47812. var elOptionStyle = elOption.style;
  47813. // In top/bottom mode, textVerticalAlign should not be used, which cause
  47814. // inaccurately locating.
  47815. if (elOption.hv && elOption.hv[1]) {
  47816. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  47817. }
  47818. // Compatible with previous setting: both support fill and textFill,
  47819. // stroke and textStroke.
  47820. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  47821. elOptionStyle.textFill = elOptionStyle.fill
  47822. );
  47823. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  47824. elOptionStyle.textStroke = elOptionStyle.stroke
  47825. );
  47826. }
  47827. // Remove unnecessary props to avoid potential problems.
  47828. var elOptionCleaned = getCleanedElOption(elOption);
  47829. // For simple, do not support parent change, otherwise reorder is needed.
  47830. if (__DEV__) {
  47831. existEl && assert(
  47832. targetElParent === existEl.parent,
  47833. 'Changing parent is not supported.'
  47834. );
  47835. }
  47836. if (!$action || $action === 'merge') {
  47837. existEl
  47838. ? existEl.attr(elOptionCleaned)
  47839. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  47840. }
  47841. else if ($action === 'replace') {
  47842. removeEl(existEl, elMap);
  47843. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  47844. }
  47845. else if ($action === 'remove') {
  47846. removeEl(existEl, elMap);
  47847. }
  47848. var el = elMap.get(id);
  47849. if (el) {
  47850. el.__ecGraphicWidth = elOption.width;
  47851. el.__ecGraphicHeight = elOption.height;
  47852. }
  47853. });
  47854. },
  47855. /**
  47856. * Locate graphic elements.
  47857. *
  47858. * @private
  47859. * @param {Object} graphicModel graphic model
  47860. * @param {module:echarts/ExtensionAPI} api extension API
  47861. */
  47862. _relocate: function (graphicModel, api) {
  47863. var elOptions = graphicModel.option.elements;
  47864. var rootGroup = this.group;
  47865. var elMap = this._elMap;
  47866. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  47867. for (var i = elOptions.length - 1; i >= 0; i--) {
  47868. var elOption = elOptions[i];
  47869. var el = elMap.get(elOption.id);
  47870. if (!el) {
  47871. continue;
  47872. }
  47873. var parentEl = el.parent;
  47874. var containerInfo = parentEl === rootGroup
  47875. ? {
  47876. width: api.getWidth(),
  47877. height: api.getHeight()
  47878. }
  47879. : { // Like 'position:absolut' in css, default 0.
  47880. width: parentEl.__ecGraphicWidth || 0,
  47881. height: parentEl.__ecGraphicHeight || 0
  47882. };
  47883. positionElement(
  47884. el, elOption, containerInfo, null,
  47885. {hv: elOption.hv, boundingMode: elOption.bounding}
  47886. );
  47887. }
  47888. },
  47889. /**
  47890. * Clear all elements.
  47891. *
  47892. * @private
  47893. */
  47894. _clear: function () {
  47895. var elMap = this._elMap;
  47896. elMap.each(function (el) {
  47897. removeEl(el, elMap);
  47898. });
  47899. this._elMap = createHashMap();
  47900. },
  47901. /**
  47902. * @override
  47903. */
  47904. dispose: function () {
  47905. this._clear();
  47906. }
  47907. });
  47908. function createEl$1(id, targetElParent, elOption, elMap) {
  47909. var graphicType = elOption.type;
  47910. if (__DEV__) {
  47911. assert(graphicType, 'graphic type MUST be set');
  47912. }
  47913. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  47914. if (__DEV__) {
  47915. assert(Clz, 'graphic type can not be found');
  47916. }
  47917. var el = new Clz(elOption);
  47918. targetElParent.add(el);
  47919. elMap.set(id, el);
  47920. el.__ecGraphicId = id;
  47921. }
  47922. function removeEl(existEl, elMap) {
  47923. var existElParent = existEl && existEl.parent;
  47924. if (existElParent) {
  47925. existEl.type === 'group' && existEl.traverse(function (el) {
  47926. removeEl(el, elMap);
  47927. });
  47928. elMap.removeKey(existEl.__ecGraphicId);
  47929. existElParent.remove(existEl);
  47930. }
  47931. }
  47932. // Remove unnecessary props to avoid potential problems.
  47933. function getCleanedElOption(elOption) {
  47934. elOption = extend({}, elOption);
  47935. each$1(
  47936. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  47937. function (name) {
  47938. delete elOption[name];
  47939. }
  47940. );
  47941. return elOption;
  47942. }
  47943. function isSetLoc(obj, props) {
  47944. var isSet;
  47945. each$1(props, function (prop) {
  47946. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  47947. });
  47948. return isSet;
  47949. }
  47950. function setKeyInfoToNewElOption(resultItem, newElOption) {
  47951. var existElOption = resultItem.exist;
  47952. // Set id and type after id assigned.
  47953. newElOption.id = resultItem.keyInfo.id;
  47954. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  47955. // Set parent id if not specified
  47956. if (newElOption.parentId == null) {
  47957. var newElParentOption = newElOption.parentOption;
  47958. if (newElParentOption) {
  47959. newElOption.parentId = newElParentOption.id;
  47960. }
  47961. else if (existElOption) {
  47962. newElOption.parentId = existElOption.parentId;
  47963. }
  47964. }
  47965. // Clear
  47966. newElOption.parentOption = null;
  47967. }
  47968. function mergeNewElOptionToExist(existList, index, newElOption) {
  47969. // Update existing options, for `getOption` feature.
  47970. var newElOptCopy = extend({}, newElOption);
  47971. var existElOption = existList[index];
  47972. var $action = newElOption.$action || 'merge';
  47973. if ($action === 'merge') {
  47974. if (existElOption) {
  47975. if (__DEV__) {
  47976. var newType = newElOption.type;
  47977. assert(
  47978. !newType || existElOption.type === newType,
  47979. 'Please set $action: "replace" to change `type`'
  47980. );
  47981. }
  47982. // We can ensure that newElOptCopy and existElOption are not
  47983. // the same object, so `merge` will not change newElOptCopy.
  47984. merge(existElOption, newElOptCopy, true);
  47985. // Rigid body, use ignoreSize.
  47986. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  47987. // Will be used in render.
  47988. copyLayoutParams(newElOption, existElOption);
  47989. }
  47990. else {
  47991. existList[index] = newElOptCopy;
  47992. }
  47993. }
  47994. else if ($action === 'replace') {
  47995. existList[index] = newElOptCopy;
  47996. }
  47997. else if ($action === 'remove') {
  47998. // null will be cleaned later.
  47999. existElOption && (existList[index] = null);
  48000. }
  48001. }
  48002. function setLayoutInfoToExist(existItem, newElOption) {
  48003. if (!existItem) {
  48004. return;
  48005. }
  48006. existItem.hv = newElOption.hv = [
  48007. // Rigid body, dont care `width`.
  48008. isSetLoc(newElOption, ['left', 'right']),
  48009. // Rigid body, dont care `height`.
  48010. isSetLoc(newElOption, ['top', 'bottom'])
  48011. ];
  48012. // Give default group size. Otherwise layout error may occur.
  48013. if (existItem.type === 'group') {
  48014. existItem.width == null && (existItem.width = newElOption.width = 0);
  48015. existItem.height == null && (existItem.height = newElOption.height = 0);
  48016. }
  48017. }
  48018. var LegendModel = extendComponentModel({
  48019. type: 'legend.plain',
  48020. dependencies: ['series'],
  48021. layoutMode: {
  48022. type: 'box',
  48023. // legend.width/height are maxWidth/maxHeight actually,
  48024. // whereas realy width/height is calculated by its content.
  48025. // (Setting {left: 10, right: 10} does not make sense).
  48026. // So consider the case:
  48027. // `setOption({legend: {left: 10});`
  48028. // then `setOption({legend: {right: 10});`
  48029. // The previous `left` should be cleared by setting `ignoreSize`.
  48030. ignoreSize: true
  48031. },
  48032. init: function (option, parentModel, ecModel) {
  48033. this.mergeDefaultAndTheme(option, ecModel);
  48034. option.selected = option.selected || {};
  48035. },
  48036. mergeOption: function (option) {
  48037. LegendModel.superCall(this, 'mergeOption', option);
  48038. },
  48039. optionUpdated: function () {
  48040. this._updateData(this.ecModel);
  48041. var legendData = this._data;
  48042. // If selectedMode is single, try to select one
  48043. if (legendData[0] && this.get('selectedMode') === 'single') {
  48044. var hasSelected = false;
  48045. // If has any selected in option.selected
  48046. for (var i = 0; i < legendData.length; i++) {
  48047. var name = legendData[i].get('name');
  48048. if (this.isSelected(name)) {
  48049. // Force to unselect others
  48050. this.select(name);
  48051. hasSelected = true;
  48052. break;
  48053. }
  48054. }
  48055. // Try select the first if selectedMode is single
  48056. !hasSelected && this.select(legendData[0].get('name'));
  48057. }
  48058. },
  48059. _updateData: function (ecModel) {
  48060. var legendData = map(this.get('data') || [], function (dataItem) {
  48061. // Can be string or number
  48062. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  48063. dataItem = {
  48064. name: dataItem
  48065. };
  48066. }
  48067. return new Model(dataItem, this, this.ecModel);
  48068. }, this);
  48069. this._data = legendData;
  48070. var availableNames = map(ecModel.getSeries(), function (series) {
  48071. return series.name;
  48072. });
  48073. ecModel.eachSeries(function (seriesModel) {
  48074. if (seriesModel.legendDataProvider) {
  48075. var data = seriesModel.legendDataProvider();
  48076. availableNames = availableNames.concat(data.mapArray(data.getName));
  48077. }
  48078. });
  48079. /**
  48080. * @type {Array.<string>}
  48081. * @private
  48082. */
  48083. this._availableNames = availableNames;
  48084. },
  48085. /**
  48086. * @return {Array.<module:echarts/model/Model>}
  48087. */
  48088. getData: function () {
  48089. return this._data;
  48090. },
  48091. /**
  48092. * @param {string} name
  48093. */
  48094. select: function (name) {
  48095. var selected = this.option.selected;
  48096. var selectedMode = this.get('selectedMode');
  48097. if (selectedMode === 'single') {
  48098. var data = this._data;
  48099. each$1(data, function (dataItem) {
  48100. selected[dataItem.get('name')] = false;
  48101. });
  48102. }
  48103. selected[name] = true;
  48104. },
  48105. /**
  48106. * @param {string} name
  48107. */
  48108. unSelect: function (name) {
  48109. if (this.get('selectedMode') !== 'single') {
  48110. this.option.selected[name] = false;
  48111. }
  48112. },
  48113. /**
  48114. * @param {string} name
  48115. */
  48116. toggleSelected: function (name) {
  48117. var selected = this.option.selected;
  48118. // Default is true
  48119. if (!selected.hasOwnProperty(name)) {
  48120. selected[name] = true;
  48121. }
  48122. this[selected[name] ? 'unSelect' : 'select'](name);
  48123. },
  48124. /**
  48125. * @param {string} name
  48126. */
  48127. isSelected: function (name) {
  48128. var selected = this.option.selected;
  48129. return !(selected.hasOwnProperty(name) && !selected[name])
  48130. && indexOf(this._availableNames, name) >= 0;
  48131. },
  48132. defaultOption: {
  48133. // 一级层叠
  48134. zlevel: 0,
  48135. // 二级层叠
  48136. z: 4,
  48137. show: true,
  48138. // 布局方式,默认为水平布局,可选为:
  48139. // 'horizontal' | 'vertical'
  48140. orient: 'horizontal',
  48141. left: 'center',
  48142. // right: 'center',
  48143. top: 0,
  48144. // bottom: null,
  48145. // 水平对齐
  48146. // 'auto' | 'left' | 'right'
  48147. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  48148. align: 'auto',
  48149. backgroundColor: 'rgba(0,0,0,0)',
  48150. // 图例边框颜色
  48151. borderColor: '#ccc',
  48152. borderRadius: 0,
  48153. // 图例边框线宽,单位px,默认为0(无边框)
  48154. borderWidth: 0,
  48155. // 图例内边距,单位px,默认各方向内边距为5,
  48156. // 接受数组分别设定上右下左边距,同css
  48157. padding: 5,
  48158. // 各个item之间的间隔,单位px,默认为10,
  48159. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  48160. itemGap: 10,
  48161. // 图例图形宽度
  48162. itemWidth: 25,
  48163. // 图例图形高度
  48164. itemHeight: 14,
  48165. // 图例关闭时候的颜色
  48166. inactiveColor: '#ccc',
  48167. textStyle: {
  48168. // 图例文字颜色
  48169. color: '#333'
  48170. },
  48171. // formatter: '',
  48172. // 选择模式,默认开启图例开关
  48173. selectedMode: true,
  48174. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  48175. // selected: null,
  48176. // 图例内容(详见legend.data,数组中每一项代表一个item
  48177. // data: [],
  48178. // Tooltip 相关配置
  48179. tooltip: {
  48180. show: false
  48181. }
  48182. }
  48183. });
  48184. function legendSelectActionHandler(methodName, payload, ecModel) {
  48185. var selectedMap = {};
  48186. var isToggleSelect = methodName === 'toggleSelected';
  48187. var isSelected;
  48188. // Update all legend components
  48189. ecModel.eachComponent('legend', function (legendModel) {
  48190. if (isToggleSelect && isSelected != null) {
  48191. // Force other legend has same selected status
  48192. // Or the first is toggled to true and other are toggled to false
  48193. // In the case one legend has some item unSelected in option. And if other legend
  48194. // doesn't has the item, they will assume it is selected.
  48195. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  48196. }
  48197. else {
  48198. legendModel[methodName](payload.name);
  48199. isSelected = legendModel.isSelected(payload.name);
  48200. }
  48201. var legendData = legendModel.getData();
  48202. each$1(legendData, function (model) {
  48203. var name = model.get('name');
  48204. // Wrap element
  48205. if (name === '\n' || name === '') {
  48206. return;
  48207. }
  48208. var isItemSelected = legendModel.isSelected(name);
  48209. if (selectedMap.hasOwnProperty(name)) {
  48210. // Unselected if any legend is unselected
  48211. selectedMap[name] = selectedMap[name] && isItemSelected;
  48212. }
  48213. else {
  48214. selectedMap[name] = isItemSelected;
  48215. }
  48216. });
  48217. });
  48218. // Return the event explicitly
  48219. return {
  48220. name: payload.name,
  48221. selected: selectedMap
  48222. };
  48223. }
  48224. /**
  48225. * @event legendToggleSelect
  48226. * @type {Object}
  48227. * @property {string} type 'legendToggleSelect'
  48228. * @property {string} [from]
  48229. * @property {string} name Series name or data item name
  48230. */
  48231. registerAction(
  48232. 'legendToggleSelect', 'legendselectchanged',
  48233. curry(legendSelectActionHandler, 'toggleSelected')
  48234. );
  48235. /**
  48236. * @event legendSelect
  48237. * @type {Object}
  48238. * @property {string} type 'legendSelect'
  48239. * @property {string} name Series name or data item name
  48240. */
  48241. registerAction(
  48242. 'legendSelect', 'legendselected',
  48243. curry(legendSelectActionHandler, 'select')
  48244. );
  48245. /**
  48246. * @event legendUnSelect
  48247. * @type {Object}
  48248. * @property {string} type 'legendUnSelect'
  48249. * @property {string} name Series name or data item name
  48250. */
  48251. registerAction(
  48252. 'legendUnSelect', 'legendunselected',
  48253. curry(legendSelectActionHandler, 'unSelect')
  48254. );
  48255. /**
  48256. * Layout list like component.
  48257. * It will box layout each items in group of component and then position the whole group in the viewport
  48258. * @param {module:zrender/group/Group} group
  48259. * @param {module:echarts/model/Component} componentModel
  48260. * @param {module:echarts/ExtensionAPI}
  48261. */
  48262. function layout$2(group, componentModel, api) {
  48263. var boxLayoutParams = componentModel.getBoxLayoutParams();
  48264. var padding = componentModel.get('padding');
  48265. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  48266. var rect = getLayoutRect(
  48267. boxLayoutParams,
  48268. viewportSize,
  48269. padding
  48270. );
  48271. box(
  48272. componentModel.get('orient'),
  48273. group,
  48274. componentModel.get('itemGap'),
  48275. rect.width,
  48276. rect.height
  48277. );
  48278. positionElement(
  48279. group,
  48280. boxLayoutParams,
  48281. viewportSize,
  48282. padding
  48283. );
  48284. }
  48285. function makeBackground(rect, componentModel) {
  48286. var padding = normalizeCssArray$1(
  48287. componentModel.get('padding')
  48288. );
  48289. var style = componentModel.getItemStyle(['color', 'opacity']);
  48290. style.fill = componentModel.get('backgroundColor');
  48291. var rect = new Rect({
  48292. shape: {
  48293. x: rect.x - padding[3],
  48294. y: rect.y - padding[0],
  48295. width: rect.width + padding[1] + padding[3],
  48296. height: rect.height + padding[0] + padding[2],
  48297. r: componentModel.get('borderRadius')
  48298. },
  48299. style: style,
  48300. silent: true,
  48301. z2: -1
  48302. });
  48303. // FIXME
  48304. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  48305. // and background rect when setting like `left: 0`, `top: 0`.
  48306. // graphic.subPixelOptimizeRect(rect);
  48307. return rect;
  48308. }
  48309. var curry$4 = curry;
  48310. var each$19 = each$1;
  48311. var Group$3 = Group;
  48312. var LegendView = extendComponentView({
  48313. type: 'legend.plain',
  48314. newlineDisabled: false,
  48315. /**
  48316. * @override
  48317. */
  48318. init: function () {
  48319. /**
  48320. * @private
  48321. * @type {module:zrender/container/Group}
  48322. */
  48323. this.group.add(this._contentGroup = new Group$3());
  48324. /**
  48325. * @private
  48326. * @type {module:zrender/Element}
  48327. */
  48328. this._backgroundEl;
  48329. },
  48330. /**
  48331. * @protected
  48332. */
  48333. getContentGroup: function () {
  48334. return this._contentGroup;
  48335. },
  48336. /**
  48337. * @override
  48338. */
  48339. render: function (legendModel, ecModel, api) {
  48340. this.resetInner();
  48341. if (!legendModel.get('show', true)) {
  48342. return;
  48343. }
  48344. var itemAlign = legendModel.get('align');
  48345. if (!itemAlign || itemAlign === 'auto') {
  48346. itemAlign = (
  48347. legendModel.get('left') === 'right'
  48348. && legendModel.get('orient') === 'vertical'
  48349. ) ? 'right' : 'left';
  48350. }
  48351. this.renderInner(itemAlign, legendModel, ecModel, api);
  48352. // Perform layout.
  48353. var positionInfo = legendModel.getBoxLayoutParams();
  48354. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  48355. var padding = legendModel.get('padding');
  48356. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  48357. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  48358. // Place mainGroup, based on the calculated `mainRect`.
  48359. var layoutRect = getLayoutRect(
  48360. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  48361. viewportSize,
  48362. padding
  48363. );
  48364. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  48365. // Render background after group is layout.
  48366. this.group.add(
  48367. this._backgroundEl = makeBackground(mainRect, legendModel)
  48368. );
  48369. },
  48370. /**
  48371. * @protected
  48372. */
  48373. resetInner: function () {
  48374. this.getContentGroup().removeAll();
  48375. this._backgroundEl && this.group.remove(this._backgroundEl);
  48376. },
  48377. /**
  48378. * @protected
  48379. */
  48380. renderInner: function (itemAlign, legendModel, ecModel, api) {
  48381. var contentGroup = this.getContentGroup();
  48382. var legendDrawnMap = createHashMap();
  48383. var selectMode = legendModel.get('selectedMode');
  48384. each$19(legendModel.getData(), function (itemModel, dataIndex) {
  48385. var name = itemModel.get('name');
  48386. // Use empty string or \n as a newline string
  48387. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  48388. contentGroup.add(new Group$3({
  48389. newline: true
  48390. }));
  48391. return;
  48392. }
  48393. var seriesModel = ecModel.getSeriesByName(name)[0];
  48394. if (legendDrawnMap.get(name)) {
  48395. // Have been drawed
  48396. return;
  48397. }
  48398. // Series legend
  48399. if (seriesModel) {
  48400. var data = seriesModel.getData();
  48401. var color = data.getVisual('color');
  48402. // If color is a callback function
  48403. if (typeof color === 'function') {
  48404. // Use the first data
  48405. color = color(seriesModel.getDataParams(0));
  48406. }
  48407. // Using rect symbol defaultly
  48408. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  48409. var symbolType = data.getVisual('symbol');
  48410. var itemGroup = this._createItem(
  48411. name, dataIndex, itemModel, legendModel,
  48412. legendSymbolType, symbolType,
  48413. itemAlign, color,
  48414. selectMode
  48415. );
  48416. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  48417. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api))
  48418. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api));
  48419. legendDrawnMap.set(name, true);
  48420. }
  48421. else {
  48422. // Data legend of pie, funnel
  48423. ecModel.eachRawSeries(function (seriesModel) {
  48424. // In case multiple series has same data name
  48425. if (legendDrawnMap.get(name)) {
  48426. return;
  48427. }
  48428. if (seriesModel.legendDataProvider) {
  48429. var data = seriesModel.legendDataProvider();
  48430. var idx = data.indexOfName(name);
  48431. if (idx < 0) {
  48432. return;
  48433. }
  48434. var color = data.getItemVisual(idx, 'color');
  48435. var legendSymbolType = 'roundRect';
  48436. var itemGroup = this._createItem(
  48437. name, dataIndex, itemModel, legendModel,
  48438. legendSymbolType, null,
  48439. itemAlign, color,
  48440. selectMode
  48441. );
  48442. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  48443. // FIXME Should not specify the series name
  48444. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api))
  48445. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api));
  48446. legendDrawnMap.set(name, true);
  48447. }
  48448. }, this);
  48449. }
  48450. if (__DEV__) {
  48451. if (!legendDrawnMap.get(name)) {
  48452. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  48453. }
  48454. }
  48455. }, this);
  48456. },
  48457. _createItem: function (
  48458. name, dataIndex, itemModel, legendModel,
  48459. legendSymbolType, symbolType,
  48460. itemAlign, color, selectMode
  48461. ) {
  48462. var itemWidth = legendModel.get('itemWidth');
  48463. var itemHeight = legendModel.get('itemHeight');
  48464. var inactiveColor = legendModel.get('inactiveColor');
  48465. var isSelected = legendModel.isSelected(name);
  48466. var itemGroup = new Group$3();
  48467. var textStyleModel = itemModel.getModel('textStyle');
  48468. var itemIcon = itemModel.get('icon');
  48469. var tooltipModel = itemModel.getModel('tooltip');
  48470. var legendGlobalTooltipModel = tooltipModel.parentModel;
  48471. // Use user given icon first
  48472. legendSymbolType = itemIcon || legendSymbolType;
  48473. itemGroup.add(createSymbol(
  48474. legendSymbolType,
  48475. 0,
  48476. 0,
  48477. itemWidth,
  48478. itemHeight,
  48479. isSelected ? color : inactiveColor,
  48480. true
  48481. ));
  48482. // Compose symbols
  48483. // PENDING
  48484. if (!itemIcon && symbolType
  48485. // At least show one symbol, can't be all none
  48486. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  48487. ) {
  48488. var size = itemHeight * 0.8;
  48489. if (symbolType === 'none') {
  48490. symbolType = 'circle';
  48491. }
  48492. // Put symbol in the center
  48493. itemGroup.add(createSymbol(
  48494. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  48495. isSelected ? color : inactiveColor
  48496. ));
  48497. }
  48498. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  48499. var textAlign = itemAlign;
  48500. var formatter = legendModel.get('formatter');
  48501. var content = name;
  48502. if (typeof formatter === 'string' && formatter) {
  48503. content = formatter.replace('{name}', name != null ? name : '');
  48504. }
  48505. else if (typeof formatter === 'function') {
  48506. content = formatter(name);
  48507. }
  48508. itemGroup.add(new Text({
  48509. style: setTextStyle({}, textStyleModel, {
  48510. text: content,
  48511. x: textX,
  48512. y: itemHeight / 2,
  48513. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  48514. textAlign: textAlign,
  48515. textVerticalAlign: 'middle'
  48516. })
  48517. }));
  48518. // Add a invisible rect to increase the area of mouse hover
  48519. var hitRect = new Rect({
  48520. shape: itemGroup.getBoundingRect(),
  48521. invisible: true,
  48522. tooltip: tooltipModel.get('show') ? extend({
  48523. content: name,
  48524. // Defaul formatter
  48525. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  48526. return name;
  48527. },
  48528. formatterParams: {
  48529. componentType: 'legend',
  48530. legendIndex: legendModel.componentIndex,
  48531. name: name,
  48532. $vars: ['name']
  48533. }
  48534. }, tooltipModel.option) : null
  48535. });
  48536. itemGroup.add(hitRect);
  48537. itemGroup.eachChild(function (child) {
  48538. child.silent = true;
  48539. });
  48540. hitRect.silent = !selectMode;
  48541. this.getContentGroup().add(itemGroup);
  48542. setHoverStyle(itemGroup);
  48543. itemGroup.__legendDataIndex = dataIndex;
  48544. return itemGroup;
  48545. },
  48546. /**
  48547. * @protected
  48548. */
  48549. layoutInner: function (legendModel, itemAlign, maxSize) {
  48550. var contentGroup = this.getContentGroup();
  48551. // Place items in contentGroup.
  48552. box(
  48553. legendModel.get('orient'),
  48554. contentGroup,
  48555. legendModel.get('itemGap'),
  48556. maxSize.width,
  48557. maxSize.height
  48558. );
  48559. var contentRect = contentGroup.getBoundingRect();
  48560. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  48561. return this.group.getBoundingRect();
  48562. }
  48563. });
  48564. function dispatchSelectAction(name, api) {
  48565. api.dispatchAction({
  48566. type: 'legendToggleSelect',
  48567. name: name
  48568. });
  48569. }
  48570. function dispatchHighlightAction(seriesModel, dataName, api) {
  48571. // If element hover will move to a hoverLayer.
  48572. var el = api.getZr().storage.getDisplayList()[0];
  48573. if (!(el && el.useHoverLayer)) {
  48574. seriesModel.get('legendHoverLink') && api.dispatchAction({
  48575. type: 'highlight',
  48576. seriesName: seriesModel.name,
  48577. name: dataName
  48578. });
  48579. }
  48580. }
  48581. function dispatchDownplayAction(seriesModel, dataName, api) {
  48582. // If element hover will move to a hoverLayer.
  48583. var el = api.getZr().storage.getDisplayList()[0];
  48584. if (!(el && el.useHoverLayer)) {
  48585. seriesModel.get('legendHoverLink') && api.dispatchAction({
  48586. type: 'downplay',
  48587. seriesName: seriesModel.name,
  48588. name: dataName
  48589. });
  48590. }
  48591. }
  48592. var legendFilter = function (ecModel) {
  48593. var legendModels = ecModel.findComponents({
  48594. mainType: 'legend'
  48595. });
  48596. if (legendModels && legendModels.length) {
  48597. ecModel.filterSeries(function (series) {
  48598. // If in any legend component the status is not selected.
  48599. // Because in legend series is assumed selected when it is not in the legend data.
  48600. for (var i = 0; i < legendModels.length; i++) {
  48601. if (!legendModels[i].isSelected(series.name)) {
  48602. return false;
  48603. }
  48604. }
  48605. return true;
  48606. });
  48607. }
  48608. };
  48609. // Do not contain scrollable legend, for sake of file size.
  48610. // Series Filter
  48611. registerProcessor(legendFilter);
  48612. ComponentModel.registerSubTypeDefaulter('legend', function () {
  48613. // Default 'plain' when no type specified.
  48614. return 'plain';
  48615. });
  48616. var ScrollableLegendModel = LegendModel.extend({
  48617. type: 'legend.scroll',
  48618. /**
  48619. * @param {number} scrollDataIndex
  48620. */
  48621. setScrollDataIndex: function (scrollDataIndex) {
  48622. this.option.scrollDataIndex = scrollDataIndex;
  48623. },
  48624. defaultOption: {
  48625. scrollDataIndex: 0,
  48626. pageButtonItemGap: 5,
  48627. pageButtonGap: null,
  48628. pageButtonPosition: 'end', // 'start' or 'end'
  48629. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  48630. pageIcons: {
  48631. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  48632. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  48633. },
  48634. pageIconColor: '#2f4554',
  48635. pageIconInactiveColor: '#aaa',
  48636. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  48637. pageTextStyle: {
  48638. color: '#333'
  48639. },
  48640. animationDurationUpdate: 800
  48641. },
  48642. /**
  48643. * @override
  48644. */
  48645. init: function (option, parentModel, ecModel, extraOpt) {
  48646. var inputPositionParams = getLayoutParams(option);
  48647. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  48648. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  48649. },
  48650. /**
  48651. * @override
  48652. */
  48653. mergeOption: function (option, extraOpt) {
  48654. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  48655. mergeAndNormalizeLayoutParams(this, this.option, option);
  48656. },
  48657. getOrient: function () {
  48658. return this.get('orient') === 'vertical'
  48659. ? {index: 1, name: 'vertical'}
  48660. : {index: 0, name: 'horizontal'};
  48661. }
  48662. });
  48663. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  48664. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  48665. var orient = legendModel.getOrient();
  48666. var ignoreSize = [1, 1];
  48667. ignoreSize[orient.index] = 0;
  48668. mergeLayoutParam(target, raw, {
  48669. type: 'box', ignoreSize: ignoreSize
  48670. });
  48671. }
  48672. /**
  48673. * Separate legend and scrollable legend to reduce package size.
  48674. */
  48675. var Group$4 = Group;
  48676. var WH$1 = ['width', 'height'];
  48677. var XY$1 = ['x', 'y'];
  48678. var ScrollableLegendView = LegendView.extend({
  48679. type: 'legend.scroll',
  48680. newlineDisabled: true,
  48681. init: function () {
  48682. ScrollableLegendView.superCall(this, 'init');
  48683. /**
  48684. * @private
  48685. * @type {number} For `scroll`.
  48686. */
  48687. this._currentIndex = 0;
  48688. /**
  48689. * @private
  48690. * @type {module:zrender/container/Group}
  48691. */
  48692. this.group.add(this._containerGroup = new Group$4());
  48693. this._containerGroup.add(this.getContentGroup());
  48694. /**
  48695. * @private
  48696. * @type {module:zrender/container/Group}
  48697. */
  48698. this.group.add(this._controllerGroup = new Group$4());
  48699. /**
  48700. *
  48701. * @private
  48702. */
  48703. this._showController;
  48704. },
  48705. /**
  48706. * @override
  48707. */
  48708. resetInner: function () {
  48709. ScrollableLegendView.superCall(this, 'resetInner');
  48710. this._controllerGroup.removeAll();
  48711. this._containerGroup.removeClipPath();
  48712. this._containerGroup.__rectSize = null;
  48713. },
  48714. /**
  48715. * @override
  48716. */
  48717. renderInner: function (itemAlign, legendModel, ecModel, api) {
  48718. var me = this;
  48719. // Render content items.
  48720. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  48721. var controllerGroup = this._controllerGroup;
  48722. var pageIconSize = legendModel.get('pageIconSize', true);
  48723. if (!isArray(pageIconSize)) {
  48724. pageIconSize = [pageIconSize, pageIconSize];
  48725. }
  48726. createPageButton('pagePrev', 0);
  48727. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  48728. controllerGroup.add(new Text({
  48729. name: 'pageText',
  48730. style: {
  48731. textFill: pageTextStyleModel.getTextColor(),
  48732. font: pageTextStyleModel.getFont(),
  48733. textVerticalAlign: 'middle',
  48734. textAlign: 'center'
  48735. },
  48736. silent: true
  48737. }));
  48738. createPageButton('pageNext', 1);
  48739. function createPageButton(name, iconIdx) {
  48740. var pageDataIndexName = name + 'DataIndex';
  48741. var icon = createIcon(
  48742. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  48743. {
  48744. // Buttons will be created in each render, so we do not need
  48745. // to worry about avoiding using legendModel kept in scope.
  48746. onclick: bind(
  48747. me._pageGo, me, pageDataIndexName, legendModel, api
  48748. )
  48749. },
  48750. {
  48751. x: -pageIconSize[0] / 2,
  48752. y: -pageIconSize[1] / 2,
  48753. width: pageIconSize[0],
  48754. height: pageIconSize[1]
  48755. }
  48756. );
  48757. icon.name = name;
  48758. controllerGroup.add(icon);
  48759. }
  48760. },
  48761. /**
  48762. * @override
  48763. */
  48764. layoutInner: function (legendModel, itemAlign, maxSize) {
  48765. var contentGroup = this.getContentGroup();
  48766. var containerGroup = this._containerGroup;
  48767. var controllerGroup = this._controllerGroup;
  48768. var orientIdx = legendModel.getOrient().index;
  48769. var wh = WH$1[orientIdx];
  48770. var hw = WH$1[1 - orientIdx];
  48771. var yx = XY$1[1 - orientIdx];
  48772. // Place items in contentGroup.
  48773. box(
  48774. legendModel.get('orient'),
  48775. contentGroup,
  48776. legendModel.get('itemGap'),
  48777. !orientIdx ? null : maxSize.width,
  48778. orientIdx ? null : maxSize.height
  48779. );
  48780. box(
  48781. // Buttons in controller are layout always horizontally.
  48782. 'horizontal',
  48783. controllerGroup,
  48784. legendModel.get('pageButtonItemGap', true)
  48785. );
  48786. var contentRect = contentGroup.getBoundingRect();
  48787. var controllerRect = controllerGroup.getBoundingRect();
  48788. var showController = this._showController = contentRect[wh] > maxSize[wh];
  48789. var contentPos = [-contentRect.x, -contentRect.y];
  48790. // Remain contentPos when scroll animation perfroming.
  48791. contentPos[orientIdx] = contentGroup.position[orientIdx];
  48792. // Layout container group based on 0.
  48793. var containerPos = [0, 0];
  48794. var controllerPos = [-controllerRect.x, -controllerRect.y];
  48795. var pageButtonGap = retrieve2(
  48796. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  48797. );
  48798. // Place containerGroup and controllerGroup and contentGroup.
  48799. if (showController) {
  48800. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  48801. // controller is on the right / bottom.
  48802. if (pageButtonPosition === 'end') {
  48803. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  48804. }
  48805. // controller is on the left / top.
  48806. else {
  48807. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  48808. }
  48809. }
  48810. // Always align controller to content as 'middle'.
  48811. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  48812. contentGroup.attr('position', contentPos);
  48813. containerGroup.attr('position', containerPos);
  48814. controllerGroup.attr('position', controllerPos);
  48815. // Calculate `mainRect` and set `clipPath`.
  48816. // mainRect should not be calculated by `this.group.getBoundingRect()`
  48817. // for sake of the overflow.
  48818. var mainRect = this.group.getBoundingRect();
  48819. var mainRect = {x: 0, y: 0};
  48820. // Consider content may be overflow (should be clipped).
  48821. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  48822. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  48823. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  48824. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  48825. containerGroup.__rectSize = maxSize[wh];
  48826. if (showController) {
  48827. var clipShape = {x: 0, y: 0};
  48828. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  48829. clipShape[hw] = mainRect[hw];
  48830. containerGroup.setClipPath(new Rect({shape: clipShape}));
  48831. // Consider content may be larger than container, container rect
  48832. // can not be obtained from `containerGroup.getBoundingRect()`.
  48833. containerGroup.__rectSize = clipShape[wh];
  48834. }
  48835. else {
  48836. // Do not remove or ignore controller. Keep them set as place holders.
  48837. controllerGroup.eachChild(function (child) {
  48838. child.attr({invisible: true, silent: true});
  48839. });
  48840. }
  48841. // Content translate animation.
  48842. var pageInfo = this._getPageInfo(legendModel);
  48843. pageInfo.pageIndex != null && updateProps(
  48844. contentGroup,
  48845. {position: pageInfo.contentPosition},
  48846. // When switch from "show controller" to "not show controller", view should be
  48847. // updated immediately without animation, otherwise causes weird efffect.
  48848. showController ? legendModel : false
  48849. );
  48850. this._updatePageInfoView(legendModel, pageInfo);
  48851. return mainRect;
  48852. },
  48853. _pageGo: function (to, legendModel, api) {
  48854. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  48855. scrollDataIndex != null && api.dispatchAction({
  48856. type: 'legendScroll',
  48857. scrollDataIndex: scrollDataIndex,
  48858. legendId: legendModel.id
  48859. });
  48860. },
  48861. _updatePageInfoView: function (legendModel, pageInfo) {
  48862. var controllerGroup = this._controllerGroup;
  48863. each$1(['pagePrev', 'pageNext'], function (name) {
  48864. var canJump = pageInfo[name + 'DataIndex'] != null;
  48865. var icon = controllerGroup.childOfName(name);
  48866. if (icon) {
  48867. icon.setStyle(
  48868. 'fill',
  48869. canJump
  48870. ? legendModel.get('pageIconColor', true)
  48871. : legendModel.get('pageIconInactiveColor', true)
  48872. );
  48873. icon.cursor = canJump ? 'pointer' : 'default';
  48874. }
  48875. });
  48876. var pageText = controllerGroup.childOfName('pageText');
  48877. var pageFormatter = legendModel.get('pageFormatter');
  48878. var pageIndex = pageInfo.pageIndex;
  48879. var current = pageIndex != null ? pageIndex + 1 : 0;
  48880. var total = pageInfo.pageCount;
  48881. pageText && pageFormatter && pageText.setStyle(
  48882. 'text',
  48883. isString(pageFormatter)
  48884. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  48885. : pageFormatter({current: current, total: total})
  48886. );
  48887. },
  48888. /**
  48889. * @param {module:echarts/model/Model} legendModel
  48890. * @return {Object} {
  48891. * contentPosition: Array.<number>, null when data item not found.
  48892. * pageIndex: number, null when data item not found.
  48893. * pageCount: number, always be a number, can be 0.
  48894. * pagePrevDataIndex: number, null when no next page.
  48895. * pageNextDataIndex: number, null when no previous page.
  48896. * }
  48897. */
  48898. _getPageInfo: function (legendModel) {
  48899. // Align left or top by the current dataIndex.
  48900. var currDataIndex = legendModel.get('scrollDataIndex', true);
  48901. var contentGroup = this.getContentGroup();
  48902. var contentRect = contentGroup.getBoundingRect();
  48903. var containerRectSize = this._containerGroup.__rectSize;
  48904. var orientIdx = legendModel.getOrient().index;
  48905. var wh = WH$1[orientIdx];
  48906. var hw = WH$1[1 - orientIdx];
  48907. var xy = XY$1[orientIdx];
  48908. var contentPos = contentGroup.position.slice();
  48909. var pageIndex;
  48910. var pagePrevDataIndex;
  48911. var pageNextDataIndex;
  48912. var targetItemGroup;
  48913. if (this._showController) {
  48914. contentGroup.eachChild(function (child) {
  48915. if (child.__legendDataIndex === currDataIndex) {
  48916. targetItemGroup = child;
  48917. }
  48918. });
  48919. }
  48920. else {
  48921. targetItemGroup = contentGroup.childAt(0);
  48922. }
  48923. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  48924. if (targetItemGroup) {
  48925. var itemRect = targetItemGroup.getBoundingRect();
  48926. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  48927. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  48928. pageIndex = Math.floor(
  48929. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  48930. );
  48931. pageIndex = (contentRect[wh] && pageCount)
  48932. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  48933. : -1;
  48934. var winRect = {x: 0, y: 0};
  48935. winRect[wh] = containerRectSize;
  48936. winRect[hw] = contentRect[hw];
  48937. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  48938. var startIdx;
  48939. var children = contentGroup.children();
  48940. contentGroup.eachChild(function (child, index) {
  48941. var itemRect = getItemRect(child);
  48942. if (itemRect.intersect(winRect)) {
  48943. startIdx == null && (startIdx = index);
  48944. // It is user-friendly that the last item shown in the
  48945. // current window is shown at the begining of next window.
  48946. pageNextDataIndex = child.__legendDataIndex;
  48947. }
  48948. // If the last item is shown entirely, no next page.
  48949. if (index === children.length - 1
  48950. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  48951. ) {
  48952. pageNextDataIndex = null;
  48953. }
  48954. });
  48955. // Always align based on the left/top most item, so the left/top most
  48956. // item in the previous window is needed to be found here.
  48957. if (startIdx != null) {
  48958. var startItem = children[startIdx];
  48959. var startRect = getItemRect(startItem);
  48960. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  48961. // If the first item is shown entirely, no previous page.
  48962. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  48963. pagePrevDataIndex = null;
  48964. }
  48965. else {
  48966. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  48967. startIdx--;
  48968. }
  48969. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  48970. }
  48971. }
  48972. }
  48973. return {
  48974. contentPosition: contentPos,
  48975. pageIndex: pageIndex,
  48976. pageCount: pageCount,
  48977. pagePrevDataIndex: pagePrevDataIndex,
  48978. pageNextDataIndex: pageNextDataIndex
  48979. };
  48980. function getItemRect(el) {
  48981. var itemRect = el.getBoundingRect().clone();
  48982. itemRect[xy] += el.position[orientIdx];
  48983. return itemRect;
  48984. }
  48985. }
  48986. });
  48987. /**
  48988. * @event legendScroll
  48989. * @type {Object}
  48990. * @property {string} type 'legendScroll'
  48991. * @property {string} scrollDataIndex
  48992. */
  48993. registerAction(
  48994. 'legendScroll', 'legendscroll',
  48995. function (payload, ecModel) {
  48996. var scrollDataIndex = payload.scrollDataIndex;
  48997. scrollDataIndex != null && ecModel.eachComponent(
  48998. {mainType: 'legend', subType: 'scroll', query: payload},
  48999. function (legendModel) {
  49000. legendModel.setScrollDataIndex(scrollDataIndex);
  49001. }
  49002. );
  49003. }
  49004. );
  49005. /**
  49006. * Legend component entry file8
  49007. */
  49008. extendComponentModel({
  49009. type: 'tooltip',
  49010. dependencies: ['axisPointer'],
  49011. defaultOption: {
  49012. zlevel: 0,
  49013. z: 8,
  49014. show: true,
  49015. // tooltip主体内容
  49016. showContent: true,
  49017. // 'trigger' only works on coordinate system.
  49018. // 'item' | 'axis' | 'none'
  49019. trigger: 'item',
  49020. // 'click' | 'mousemove' | 'none'
  49021. triggerOn: 'mousemove|click',
  49022. alwaysShowContent: false,
  49023. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  49024. // 位置 {Array} | {Function}
  49025. // position: null
  49026. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  49027. // align: null,
  49028. // verticalAlign: null,
  49029. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  49030. confine: false,
  49031. // 内容格式器:{string}(Template) ¦ {Function}
  49032. // formatter: null
  49033. showDelay: 0,
  49034. // 隐藏延迟,单位ms
  49035. hideDelay: 100,
  49036. // 动画变换时间,单位s
  49037. transitionDuration: 0.4,
  49038. enterable: false,
  49039. // 提示背景颜色,默认为透明度为0.7的黑色
  49040. backgroundColor: 'rgba(50,50,50,0.7)',
  49041. // 提示边框颜色
  49042. borderColor: '#333',
  49043. // 提示边框圆角,单位px,默认为4
  49044. borderRadius: 4,
  49045. // 提示边框线宽,单位px,默认为0(无边框)
  49046. borderWidth: 0,
  49047. // 提示内边距,单位px,默认各方向内边距为5,
  49048. // 接受数组分别设定上右下左边距,同css
  49049. padding: 5,
  49050. // Extra css text
  49051. extraCssText: '',
  49052. // 坐标轴指示器,坐标轴触发有效
  49053. axisPointer: {
  49054. // 默认为直线
  49055. // 可选为:'line' | 'shadow' | 'cross'
  49056. type: 'line',
  49057. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  49058. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  49059. // 默认 'auto',会选择类型为 cateogry 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  49060. // 极坐标系会默认选择 angle 轴
  49061. axis: 'auto',
  49062. animation: 'auto',
  49063. animationDurationUpdate: 200,
  49064. animationEasingUpdate: 'exponentialOut',
  49065. crossStyle: {
  49066. color: '#999',
  49067. width: 1,
  49068. type: 'dashed',
  49069. // TODO formatter
  49070. textStyle: {}
  49071. }
  49072. // lineStyle and shadowStyle should not be specified here,
  49073. // otherwise it will always override those styles on option.axisPointer.
  49074. },
  49075. textStyle: {
  49076. color: '#fff',
  49077. fontSize: 14
  49078. }
  49079. }
  49080. });
  49081. var each$21 = each$1;
  49082. var toCamelCase$1 = toCamelCase;
  49083. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  49084. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  49085. /**
  49086. * @param {number} duration
  49087. * @return {string}
  49088. * @inner
  49089. */
  49090. function assembleTransition(duration) {
  49091. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  49092. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  49093. + 'top ' + duration + 's ' + transitionCurve;
  49094. return map(vendors, function (vendorPrefix) {
  49095. return vendorPrefix + 'transition:' + transitionText;
  49096. }).join(';');
  49097. }
  49098. /**
  49099. * @param {Object} textStyle
  49100. * @return {string}
  49101. * @inner
  49102. */
  49103. function assembleFont(textStyleModel) {
  49104. var cssText = [];
  49105. var fontSize = textStyleModel.get('fontSize');
  49106. var color = textStyleModel.getTextColor();
  49107. color && cssText.push('color:' + color);
  49108. cssText.push('font:' + textStyleModel.getFont());
  49109. fontSize &&
  49110. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  49111. each$21(['decoration', 'align'], function (name) {
  49112. var val = textStyleModel.get(name);
  49113. val && cssText.push('text-' + name + ':' + val);
  49114. });
  49115. return cssText.join(';');
  49116. }
  49117. /**
  49118. * @param {Object} tooltipModel
  49119. * @return {string}
  49120. * @inner
  49121. */
  49122. function assembleCssText(tooltipModel) {
  49123. var cssText = [];
  49124. var transitionDuration = tooltipModel.get('transitionDuration');
  49125. var backgroundColor = tooltipModel.get('backgroundColor');
  49126. var textStyleModel = tooltipModel.getModel('textStyle');
  49127. var padding = tooltipModel.get('padding');
  49128. // Animation transition. Do not animate when transitionDuration is 0.
  49129. transitionDuration &&
  49130. cssText.push(assembleTransition(transitionDuration));
  49131. if (backgroundColor) {
  49132. if (env$1.canvasSupported) {
  49133. cssText.push('background-Color:' + backgroundColor);
  49134. }
  49135. else {
  49136. // for ie
  49137. cssText.push(
  49138. 'background-Color:#' + toHex(backgroundColor)
  49139. );
  49140. cssText.push('filter:alpha(opacity=70)');
  49141. }
  49142. }
  49143. // Border style
  49144. each$21(['width', 'color', 'radius'], function (name) {
  49145. var borderName = 'border-' + name;
  49146. var camelCase = toCamelCase$1(borderName);
  49147. var val = tooltipModel.get(camelCase);
  49148. val != null &&
  49149. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  49150. });
  49151. // Text style
  49152. cssText.push(assembleFont(textStyleModel));
  49153. // Padding
  49154. if (padding != null) {
  49155. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  49156. }
  49157. return cssText.join(';') + ';';
  49158. }
  49159. /**
  49160. * @alias module:echarts/component/tooltip/TooltipContent
  49161. * @constructor
  49162. */
  49163. function TooltipContent(container, api) {
  49164. var el = document.createElement('div');
  49165. var zr = this._zr = api.getZr();
  49166. this.el = el;
  49167. this._x = api.getWidth() / 2;
  49168. this._y = api.getHeight() / 2;
  49169. container.appendChild(el);
  49170. this._container = container;
  49171. this._show = false;
  49172. /**
  49173. * @private
  49174. */
  49175. this._hideTimeout;
  49176. var self = this;
  49177. el.onmouseenter = function () {
  49178. // clear the timeout in hideLater and keep showing tooltip
  49179. if (self._enterable) {
  49180. clearTimeout(self._hideTimeout);
  49181. self._show = true;
  49182. }
  49183. self._inContent = true;
  49184. };
  49185. el.onmousemove = function (e) {
  49186. e = e || window.event;
  49187. if (!self._enterable) {
  49188. // Try trigger zrender event to avoid mouse
  49189. // in and out shape too frequently
  49190. var handler = zr.handler;
  49191. normalizeEvent(container, e, true);
  49192. handler.dispatch('mousemove', e);
  49193. }
  49194. };
  49195. el.onmouseleave = function () {
  49196. if (self._enterable) {
  49197. if (self._show) {
  49198. self.hideLater(self._hideDelay);
  49199. }
  49200. }
  49201. self._inContent = false;
  49202. };
  49203. }
  49204. TooltipContent.prototype = {
  49205. constructor: TooltipContent,
  49206. /**
  49207. * @private
  49208. * @type {boolean}
  49209. */
  49210. _enterable: true,
  49211. /**
  49212. * Update when tooltip is rendered
  49213. */
  49214. update: function () {
  49215. // FIXME
  49216. // Move this logic to ec main?
  49217. var container = this._container;
  49218. var stl = container.currentStyle
  49219. || document.defaultView.getComputedStyle(container);
  49220. var domStyle = container.style;
  49221. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  49222. domStyle.position = 'relative';
  49223. }
  49224. // Hide the tooltip
  49225. // PENDING
  49226. // this.hide();
  49227. },
  49228. show: function (tooltipModel) {
  49229. clearTimeout(this._hideTimeout);
  49230. var el = this.el;
  49231. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  49232. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  49233. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  49234. + (tooltipModel.get('extraCssText') || '');
  49235. el.style.display = el.innerHTML ? 'block' : 'none';
  49236. this._show = true;
  49237. },
  49238. setContent: function (content) {
  49239. this.el.innerHTML = content == null ? '' : content;
  49240. },
  49241. setEnterable: function (enterable) {
  49242. this._enterable = enterable;
  49243. },
  49244. getSize: function () {
  49245. var el = this.el;
  49246. return [el.clientWidth, el.clientHeight];
  49247. },
  49248. moveTo: function (x, y) {
  49249. // xy should be based on canvas root. But tooltipContent is
  49250. // the sibling of canvas root. So padding of ec container
  49251. // should be considered here.
  49252. var zr = this._zr;
  49253. var viewportRootOffset;
  49254. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  49255. x += viewportRootOffset.offsetLeft;
  49256. y += viewportRootOffset.offsetTop;
  49257. }
  49258. var style = this.el.style;
  49259. style.left = x + 'px';
  49260. style.top = y + 'px';
  49261. this._x = x;
  49262. this._y = y;
  49263. },
  49264. hide: function () {
  49265. this.el.style.display = 'none';
  49266. this._show = false;
  49267. },
  49268. hideLater: function (time) {
  49269. if (this._show && !(this._inContent && this._enterable)) {
  49270. if (time) {
  49271. this._hideDelay = time;
  49272. // Set show false to avoid invoke hideLater mutiple times
  49273. this._show = false;
  49274. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  49275. }
  49276. else {
  49277. this.hide();
  49278. }
  49279. }
  49280. },
  49281. isShow: function () {
  49282. return this._show;
  49283. }
  49284. };
  49285. var bind$3 = bind;
  49286. var each$20 = each$1;
  49287. var parsePercent$2 = parsePercent$1;
  49288. var proxyRect = new Rect({
  49289. shape: {x: -1, y: -1, width: 2, height: 2}
  49290. });
  49291. extendComponentView({
  49292. type: 'tooltip',
  49293. init: function (ecModel, api) {
  49294. if (env$1.node) {
  49295. return;
  49296. }
  49297. var tooltipContent = new TooltipContent(api.getDom(), api);
  49298. this._tooltipContent = tooltipContent;
  49299. },
  49300. render: function (tooltipModel, ecModel, api) {
  49301. if (env$1.node) {
  49302. return;
  49303. }
  49304. // Reset
  49305. this.group.removeAll();
  49306. /**
  49307. * @private
  49308. * @type {module:echarts/component/tooltip/TooltipModel}
  49309. */
  49310. this._tooltipModel = tooltipModel;
  49311. /**
  49312. * @private
  49313. * @type {module:echarts/model/Global}
  49314. */
  49315. this._ecModel = ecModel;
  49316. /**
  49317. * @private
  49318. * @type {module:echarts/ExtensionAPI}
  49319. */
  49320. this._api = api;
  49321. /**
  49322. * Should be cleaned when render.
  49323. * @private
  49324. * @type {Array.<Array.<Object>>}
  49325. */
  49326. this._lastDataByCoordSys = null;
  49327. /**
  49328. * @private
  49329. * @type {boolean}
  49330. */
  49331. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  49332. var tooltipContent = this._tooltipContent;
  49333. tooltipContent.update();
  49334. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  49335. this._initGlobalListener();
  49336. this._keepShow();
  49337. },
  49338. _initGlobalListener: function () {
  49339. var tooltipModel = this._tooltipModel;
  49340. var triggerOn = tooltipModel.get('triggerOn');
  49341. register(
  49342. 'itemTooltip',
  49343. this._api,
  49344. bind$3(function (currTrigger, e, dispatchAction) {
  49345. // If 'none', it is not controlled by mouse totally.
  49346. if (triggerOn !== 'none') {
  49347. if (triggerOn.indexOf(currTrigger) >= 0) {
  49348. this._tryShow(e, dispatchAction);
  49349. }
  49350. else if (currTrigger === 'leave') {
  49351. this._hide(dispatchAction);
  49352. }
  49353. }
  49354. }, this)
  49355. );
  49356. },
  49357. _keepShow: function () {
  49358. var tooltipModel = this._tooltipModel;
  49359. var ecModel = this._ecModel;
  49360. var api = this._api;
  49361. // Try to keep the tooltip show when refreshing
  49362. if (this._lastX != null
  49363. && this._lastY != null
  49364. // When user is willing to control tooltip totally using API,
  49365. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  49366. // which is not expected.
  49367. && tooltipModel.get('triggerOn') !== 'none'
  49368. ) {
  49369. var self = this;
  49370. clearTimeout(this._refreshUpdateTimeout);
  49371. this._refreshUpdateTimeout = setTimeout(function () {
  49372. // Show tip next tick after other charts are rendered
  49373. // In case highlight action has wrong result
  49374. // FIXME
  49375. self.manuallyShowTip(tooltipModel, ecModel, api, {
  49376. x: self._lastX,
  49377. y: self._lastY
  49378. });
  49379. });
  49380. }
  49381. },
  49382. /**
  49383. * Show tip manually by
  49384. * dispatchAction({
  49385. * type: 'showTip',
  49386. * x: 10,
  49387. * y: 10
  49388. * });
  49389. * Or
  49390. * dispatchAction({
  49391. * type: 'showTip',
  49392. * seriesIndex: 0,
  49393. * dataIndex or dataIndexInside or name
  49394. * });
  49395. *
  49396. * TODO Batch
  49397. */
  49398. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  49399. if (payload.from === this.uid || env$1.node) {
  49400. return;
  49401. }
  49402. var dispatchAction = makeDispatchAction$1(payload, api);
  49403. // Reset ticket
  49404. this._ticket = '';
  49405. // When triggered from axisPointer.
  49406. var dataByCoordSys = payload.dataByCoordSys;
  49407. if (payload.tooltip && payload.x != null && payload.y != null) {
  49408. var el = proxyRect;
  49409. el.position = [payload.x, payload.y];
  49410. el.update();
  49411. el.tooltip = payload.tooltip;
  49412. // Manually show tooltip while view is not using zrender elements.
  49413. this._tryShow({
  49414. offsetX: payload.x,
  49415. offsetY: payload.y,
  49416. target: el
  49417. }, dispatchAction);
  49418. }
  49419. else if (dataByCoordSys) {
  49420. this._tryShow({
  49421. offsetX: payload.x,
  49422. offsetY: payload.y,
  49423. position: payload.position,
  49424. event: {},
  49425. dataByCoordSys: payload.dataByCoordSys,
  49426. tooltipOption: payload.tooltipOption
  49427. }, dispatchAction);
  49428. }
  49429. else if (payload.seriesIndex != null) {
  49430. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  49431. return;
  49432. }
  49433. var pointInfo = findPointFromSeries(payload, ecModel);
  49434. var cx = pointInfo.point[0];
  49435. var cy = pointInfo.point[1];
  49436. if (cx != null && cy != null) {
  49437. this._tryShow({
  49438. offsetX: cx,
  49439. offsetY: cy,
  49440. position: payload.position,
  49441. target: pointInfo.el,
  49442. event: {}
  49443. }, dispatchAction);
  49444. }
  49445. }
  49446. else if (payload.x != null && payload.y != null) {
  49447. // FIXME
  49448. // should wrap dispatchAction like `axisPointer/globalListener` ?
  49449. api.dispatchAction({
  49450. type: 'updateAxisPointer',
  49451. x: payload.x,
  49452. y: payload.y
  49453. });
  49454. this._tryShow({
  49455. offsetX: payload.x,
  49456. offsetY: payload.y,
  49457. position: payload.position,
  49458. target: api.getZr().findHover(payload.x, payload.y).target,
  49459. event: {}
  49460. }, dispatchAction);
  49461. }
  49462. },
  49463. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  49464. var tooltipContent = this._tooltipContent;
  49465. if (!this._alwaysShowContent) {
  49466. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  49467. }
  49468. this._lastX = this._lastY = null;
  49469. if (payload.from !== this.uid) {
  49470. this._hide(makeDispatchAction$1(payload, api));
  49471. }
  49472. },
  49473. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  49474. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  49475. // and tooltip.
  49476. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  49477. var seriesIndex = payload.seriesIndex;
  49478. var dataIndex = payload.dataIndex;
  49479. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  49480. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  49481. return;
  49482. }
  49483. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  49484. if (!seriesModel) {
  49485. return;
  49486. }
  49487. var data = seriesModel.getData();
  49488. var tooltipModel = buildTooltipModel([
  49489. data.getItemModel(dataIndex),
  49490. seriesModel,
  49491. (seriesModel.coordinateSystem || {}).model,
  49492. tooltipModel
  49493. ]);
  49494. if (tooltipModel.get('trigger') !== 'axis') {
  49495. return;
  49496. }
  49497. api.dispatchAction({
  49498. type: 'updateAxisPointer',
  49499. seriesIndex: seriesIndex,
  49500. dataIndex: dataIndex,
  49501. position: payload.position
  49502. });
  49503. return true;
  49504. },
  49505. _tryShow: function (e, dispatchAction) {
  49506. var el = e.target;
  49507. var tooltipModel = this._tooltipModel;
  49508. if (!tooltipModel) {
  49509. return;
  49510. }
  49511. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  49512. this._lastX = e.offsetX;
  49513. this._lastY = e.offsetY;
  49514. var dataByCoordSys = e.dataByCoordSys;
  49515. if (dataByCoordSys && dataByCoordSys.length) {
  49516. this._showAxisTooltip(dataByCoordSys, e);
  49517. }
  49518. // Always show item tooltip if mouse is on the element with dataIndex
  49519. else if (el && el.dataIndex != null) {
  49520. this._lastDataByCoordSys = null;
  49521. this._showSeriesItemTooltip(e, el, dispatchAction);
  49522. }
  49523. // Tooltip provided directly. Like legend.
  49524. else if (el && el.tooltip) {
  49525. this._lastDataByCoordSys = null;
  49526. this._showComponentItemTooltip(e, el, dispatchAction);
  49527. }
  49528. else {
  49529. this._lastDataByCoordSys = null;
  49530. this._hide(dispatchAction);
  49531. }
  49532. },
  49533. _showOrMove: function (tooltipModel, cb) {
  49534. // showDelay is used in this case: tooltip.enterable is set
  49535. // as true. User intent to move mouse into tooltip and click
  49536. // something. `showDelay` makes it easyer to enter the content
  49537. // but tooltip do not move immediately.
  49538. var delay = tooltipModel.get('showDelay');
  49539. cb = bind(cb, this);
  49540. clearTimeout(this._showTimout);
  49541. delay > 0
  49542. ? (this._showTimout = setTimeout(cb, delay))
  49543. : cb();
  49544. },
  49545. _showAxisTooltip: function (dataByCoordSys, e) {
  49546. var ecModel = this._ecModel;
  49547. var globalTooltipModel = this._tooltipModel;
  49548. var point = [e.offsetX, e.offsetY];
  49549. var singleDefaultHTML = [];
  49550. var singleParamsList = [];
  49551. var singleTooltipModel = buildTooltipModel([
  49552. e.tooltipOption,
  49553. globalTooltipModel
  49554. ]);
  49555. each$20(dataByCoordSys, function (itemCoordSys) {
  49556. // var coordParamList = [];
  49557. // var coordDefaultHTML = [];
  49558. // var coordTooltipModel = buildTooltipModel([
  49559. // e.tooltipOption,
  49560. // itemCoordSys.tooltipOption,
  49561. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  49562. // globalTooltipModel
  49563. // ]);
  49564. // var displayMode = coordTooltipModel.get('displayMode');
  49565. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  49566. each$20(itemCoordSys.dataByAxis, function (item) {
  49567. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  49568. var axisValue = item.value;
  49569. var seriesDefaultHTML = [];
  49570. if (!axisModel || axisValue == null) {
  49571. return;
  49572. }
  49573. var valueLabel = getValueLabel(
  49574. axisValue, axisModel.axis, ecModel,
  49575. item.seriesDataIndices,
  49576. item.valueLabelOpt
  49577. );
  49578. each$1(item.seriesDataIndices, function (idxItem) {
  49579. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  49580. var dataIndex = idxItem.dataIndexInside;
  49581. var dataParams = series && series.getDataParams(dataIndex);
  49582. dataParams.axisDim = item.axisDim;
  49583. dataParams.axisIndex = item.axisIndex;
  49584. dataParams.axisType = item.axisType;
  49585. dataParams.axisId = item.axisId;
  49586. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  49587. dataParams.axisValueLabel = valueLabel;
  49588. if (dataParams) {
  49589. singleParamsList.push(dataParams);
  49590. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  49591. }
  49592. });
  49593. // Default tooltip content
  49594. // FIXME
  49595. // (1) shold be the first data which has name?
  49596. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  49597. var firstLine = valueLabel;
  49598. singleDefaultHTML.push(
  49599. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  49600. + seriesDefaultHTML.join('<br />')
  49601. );
  49602. });
  49603. }, this);
  49604. // In most case, the second axis is shown upper than the first one.
  49605. singleDefaultHTML.reverse();
  49606. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  49607. var positionExpr = e.position;
  49608. this._showOrMove(singleTooltipModel, function () {
  49609. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  49610. this._updatePosition(
  49611. singleTooltipModel,
  49612. positionExpr,
  49613. point[0], point[1],
  49614. this._tooltipContent,
  49615. singleParamsList
  49616. );
  49617. }
  49618. else {
  49619. this._showTooltipContent(
  49620. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  49621. point[0], point[1], positionExpr
  49622. );
  49623. }
  49624. });
  49625. // Do not trigger events here, because this branch only be entered
  49626. // from dispatchAction.
  49627. },
  49628. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  49629. var ecModel = this._ecModel;
  49630. // Use dataModel in element if possible
  49631. // Used when mouseover on a element like markPoint or edge
  49632. // In which case, the data is not main data in series.
  49633. var seriesIndex = el.seriesIndex;
  49634. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  49635. // For example, graph link.
  49636. var dataModel = el.dataModel || seriesModel;
  49637. var dataIndex = el.dataIndex;
  49638. var dataType = el.dataType;
  49639. var data = dataModel.getData();
  49640. var tooltipModel = buildTooltipModel([
  49641. data.getItemModel(dataIndex),
  49642. dataModel,
  49643. seriesModel && (seriesModel.coordinateSystem || {}).model,
  49644. this._tooltipModel
  49645. ]);
  49646. var tooltipTrigger = tooltipModel.get('trigger');
  49647. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  49648. return;
  49649. }
  49650. var params = dataModel.getDataParams(dataIndex, dataType);
  49651. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  49652. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  49653. this._showOrMove(tooltipModel, function () {
  49654. this._showTooltipContent(
  49655. tooltipModel, defaultHtml, params, asyncTicket,
  49656. e.offsetX, e.offsetY, e.position, e.target
  49657. );
  49658. });
  49659. // FIXME
  49660. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  49661. dispatchAction({
  49662. type: 'showTip',
  49663. dataIndexInside: dataIndex,
  49664. dataIndex: data.getRawIndex(dataIndex),
  49665. seriesIndex: seriesIndex,
  49666. from: this.uid
  49667. });
  49668. },
  49669. _showComponentItemTooltip: function (e, el, dispatchAction) {
  49670. var tooltipOpt = el.tooltip;
  49671. if (typeof tooltipOpt === 'string') {
  49672. var content = tooltipOpt;
  49673. tooltipOpt = {
  49674. content: content,
  49675. // Fixed formatter
  49676. formatter: content
  49677. };
  49678. }
  49679. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  49680. var defaultHtml = subTooltipModel.get('content');
  49681. var asyncTicket = Math.random();
  49682. // Do not check whether `trigger` is 'none' here, because `trigger`
  49683. // only works on cooridinate system. In fact, we have not found case
  49684. // that requires setting `trigger` nothing on component yet.
  49685. this._showOrMove(subTooltipModel, function () {
  49686. this._showTooltipContent(
  49687. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  49688. asyncTicket, e.offsetX, e.offsetY, e.position, el
  49689. );
  49690. });
  49691. // If not dispatch showTip, tip may be hide triggered by axis.
  49692. dispatchAction({
  49693. type: 'showTip',
  49694. from: this.uid
  49695. });
  49696. },
  49697. _showTooltipContent: function (
  49698. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  49699. ) {
  49700. // Reset ticket
  49701. this._ticket = '';
  49702. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  49703. return;
  49704. }
  49705. var tooltipContent = this._tooltipContent;
  49706. var formatter = tooltipModel.get('formatter');
  49707. positionExpr = positionExpr || tooltipModel.get('position');
  49708. var html = defaultHtml;
  49709. if (formatter && typeof formatter === 'string') {
  49710. html = formatTpl(formatter, params, true);
  49711. }
  49712. else if (typeof formatter === 'function') {
  49713. var callback = bind$3(function (cbTicket, html) {
  49714. if (cbTicket === this._ticket) {
  49715. tooltipContent.setContent(html);
  49716. this._updatePosition(
  49717. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  49718. );
  49719. }
  49720. }, this);
  49721. this._ticket = asyncTicket;
  49722. html = formatter(params, asyncTicket, callback);
  49723. }
  49724. tooltipContent.setContent(html);
  49725. tooltipContent.show(tooltipModel);
  49726. this._updatePosition(
  49727. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  49728. );
  49729. },
  49730. /**
  49731. * @param {string|Function|Array.<number>|Object} positionExpr
  49732. * @param {number} x Mouse x
  49733. * @param {number} y Mouse y
  49734. * @param {boolean} confine Whether confine tooltip content in view rect.
  49735. * @param {Object|<Array.<Object>} params
  49736. * @param {module:zrender/Element} el target element
  49737. * @param {module:echarts/ExtensionAPI} api
  49738. * @return {Array.<number>}
  49739. */
  49740. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  49741. var viewWidth = this._api.getWidth();
  49742. var viewHeight = this._api.getHeight();
  49743. positionExpr = positionExpr || tooltipModel.get('position');
  49744. var contentSize = content.getSize();
  49745. var align = tooltipModel.get('align');
  49746. var vAlign = tooltipModel.get('verticalAlign');
  49747. var rect = el && el.getBoundingRect().clone();
  49748. el && rect.applyTransform(el.transform);
  49749. if (typeof positionExpr === 'function') {
  49750. // Callback of position can be an array or a string specify the position
  49751. positionExpr = positionExpr([x, y], params, content.el, rect, {
  49752. viewSize: [viewWidth, viewHeight],
  49753. contentSize: contentSize.slice()
  49754. });
  49755. }
  49756. if (isArray(positionExpr)) {
  49757. x = parsePercent$2(positionExpr[0], viewWidth);
  49758. y = parsePercent$2(positionExpr[1], viewHeight);
  49759. }
  49760. else if (isObject(positionExpr)) {
  49761. positionExpr.width = contentSize[0];
  49762. positionExpr.height = contentSize[1];
  49763. var layoutRect = getLayoutRect(
  49764. positionExpr, {width: viewWidth, height: viewHeight}
  49765. );
  49766. x = layoutRect.x;
  49767. y = layoutRect.y;
  49768. align = null;
  49769. // When positionExpr is left/top/right/bottom,
  49770. // align and verticalAlign will not work.
  49771. vAlign = null;
  49772. }
  49773. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  49774. else if (typeof positionExpr === 'string' && el) {
  49775. var pos = calcTooltipPosition(
  49776. positionExpr, rect, contentSize
  49777. );
  49778. x = pos[0];
  49779. y = pos[1];
  49780. }
  49781. else {
  49782. var pos = refixTooltipPosition(
  49783. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  49784. );
  49785. x = pos[0];
  49786. y = pos[1];
  49787. }
  49788. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  49789. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  49790. if (tooltipModel.get('confine')) {
  49791. var pos = confineTooltipPosition(
  49792. x, y, content.el, viewWidth, viewHeight
  49793. );
  49794. x = pos[0];
  49795. y = pos[1];
  49796. }
  49797. content.moveTo(x, y);
  49798. },
  49799. // FIXME
  49800. // Should we remove this but leave this to user?
  49801. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  49802. var lastCoordSys = this._lastDataByCoordSys;
  49803. var contentNotChanged = !!lastCoordSys
  49804. && lastCoordSys.length === dataByCoordSys.length;
  49805. contentNotChanged && each$20(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  49806. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  49807. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  49808. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  49809. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  49810. contentNotChanged && each$20(lastDataByAxis, function (lastItem, indexAxis) {
  49811. var thisItem = thisDataByAxis[indexAxis] || {};
  49812. var lastIndices = lastItem.seriesDataIndices || [];
  49813. var newIndices = thisItem.seriesDataIndices || [];
  49814. contentNotChanged &=
  49815. lastItem.value === thisItem.value
  49816. && lastItem.axisType === thisItem.axisType
  49817. && lastItem.axisId === thisItem.axisId
  49818. && lastIndices.length === newIndices.length;
  49819. contentNotChanged && each$20(lastIndices, function (lastIdxItem, j) {
  49820. var newIdxItem = newIndices[j];
  49821. contentNotChanged &=
  49822. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  49823. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  49824. });
  49825. });
  49826. });
  49827. this._lastDataByCoordSys = dataByCoordSys;
  49828. return !!contentNotChanged;
  49829. },
  49830. _hide: function (dispatchAction) {
  49831. // Do not directly hideLater here, because this behavior may be prevented
  49832. // in dispatchAction when showTip is dispatched.
  49833. // FIXME
  49834. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  49835. this._lastDataByCoordSys = null;
  49836. dispatchAction({
  49837. type: 'hideTip',
  49838. from: this.uid
  49839. });
  49840. },
  49841. dispose: function (ecModel, api) {
  49842. if (env$1.node) {
  49843. return;
  49844. }
  49845. this._tooltipContent.hide();
  49846. unregister('itemTooltip', api);
  49847. }
  49848. });
  49849. /**
  49850. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  49851. * From top to bottom. (the last one should be globalTooltipModel);
  49852. */
  49853. function buildTooltipModel(modelCascade) {
  49854. var resultModel = modelCascade.pop();
  49855. while (modelCascade.length) {
  49856. var tooltipOpt = modelCascade.pop();
  49857. if (tooltipOpt) {
  49858. if (tooltipOpt instanceof Model) {
  49859. tooltipOpt = tooltipOpt.get('tooltip', true);
  49860. }
  49861. // In each data item tooltip can be simply write:
  49862. // {
  49863. // value: 10,
  49864. // tooltip: 'Something you need to know'
  49865. // }
  49866. if (typeof tooltipOpt === 'string') {
  49867. tooltipOpt = {formatter: tooltipOpt};
  49868. }
  49869. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  49870. }
  49871. }
  49872. return resultModel;
  49873. }
  49874. function makeDispatchAction$1(payload, api) {
  49875. return payload.dispatchAction || bind(api.dispatchAction, api);
  49876. }
  49877. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  49878. var size = getOuterSize(el);
  49879. var width = size.width;
  49880. var height = size.height;
  49881. if (gapH != null) {
  49882. if (x + width + gapH > viewWidth) {
  49883. x -= width + gapH;
  49884. }
  49885. else {
  49886. x += gapH;
  49887. }
  49888. }
  49889. if (gapV != null) {
  49890. if (y + height + gapV > viewHeight) {
  49891. y -= height + gapV;
  49892. }
  49893. else {
  49894. y += gapV;
  49895. }
  49896. }
  49897. return [x, y];
  49898. }
  49899. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  49900. var size = getOuterSize(el);
  49901. var width = size.width;
  49902. var height = size.height;
  49903. x = Math.min(x + width, viewWidth) - width;
  49904. y = Math.min(y + height, viewHeight) - height;
  49905. x = Math.max(x, 0);
  49906. y = Math.max(y, 0);
  49907. return [x, y];
  49908. }
  49909. function getOuterSize(el) {
  49910. var width = el.clientWidth;
  49911. var height = el.clientHeight;
  49912. // Consider browser compatibility.
  49913. // IE8 does not support getComputedStyle.
  49914. if (document.defaultView && document.defaultView.getComputedStyle) {
  49915. var stl = document.defaultView.getComputedStyle(el);
  49916. if (stl) {
  49917. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  49918. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  49919. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  49920. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  49921. }
  49922. }
  49923. return {width: width, height: height};
  49924. }
  49925. function calcTooltipPosition(position, rect, contentSize) {
  49926. var domWidth = contentSize[0];
  49927. var domHeight = contentSize[1];
  49928. var gap = 5;
  49929. var x = 0;
  49930. var y = 0;
  49931. var rectWidth = rect.width;
  49932. var rectHeight = rect.height;
  49933. switch (position) {
  49934. case 'inside':
  49935. x = rect.x + rectWidth / 2 - domWidth / 2;
  49936. y = rect.y + rectHeight / 2 - domHeight / 2;
  49937. break;
  49938. case 'top':
  49939. x = rect.x + rectWidth / 2 - domWidth / 2;
  49940. y = rect.y - domHeight - gap;
  49941. break;
  49942. case 'bottom':
  49943. x = rect.x + rectWidth / 2 - domWidth / 2;
  49944. y = rect.y + rectHeight + gap;
  49945. break;
  49946. case 'left':
  49947. x = rect.x - domWidth - gap;
  49948. y = rect.y + rectHeight / 2 - domHeight / 2;
  49949. break;
  49950. case 'right':
  49951. x = rect.x + rectWidth + gap;
  49952. y = rect.y + rectHeight / 2 - domHeight / 2;
  49953. }
  49954. return [x, y];
  49955. }
  49956. function isCenterAlign(align) {
  49957. return align === 'center' || align === 'middle';
  49958. }
  49959. // FIXME Better way to pack data in graphic element
  49960. /**
  49961. * @action
  49962. * @property {string} type
  49963. * @property {number} seriesIndex
  49964. * @property {number} dataIndex
  49965. * @property {number} [x]
  49966. * @property {number} [y]
  49967. */
  49968. registerAction(
  49969. {
  49970. type: 'showTip',
  49971. event: 'showTip',
  49972. update: 'tooltip:manuallyShowTip'
  49973. },
  49974. // noop
  49975. function () {}
  49976. );
  49977. registerAction(
  49978. {
  49979. type: 'hideTip',
  49980. event: 'hideTip',
  49981. update: 'tooltip:manuallyHideTip'
  49982. },
  49983. // noop
  49984. function () {}
  49985. );
  49986. function getSeriesStackId$1(seriesModel) {
  49987. return seriesModel.get('stack')
  49988. || '__ec_stack_' + seriesModel.seriesIndex;
  49989. }
  49990. function getAxisKey$1(axis) {
  49991. return axis.dim;
  49992. }
  49993. /**
  49994. * @param {string} seriesType
  49995. * @param {module:echarts/model/Global} ecModel
  49996. * @param {module:echarts/ExtensionAPI} api
  49997. */
  49998. function barLayoutPolar(seriesType, ecModel, api) {
  49999. var width = api.getWidth();
  50000. var height = api.getHeight();
  50001. var lastStackCoords = {};
  50002. var lastStackCoordsOrigin = {};
  50003. var barWidthAndOffset = calRadialBar(
  50004. filter(
  50005. ecModel.getSeriesByType(seriesType),
  50006. function (seriesModel) {
  50007. return !ecModel.isSeriesFiltered(seriesModel)
  50008. && seriesModel.coordinateSystem
  50009. && seriesModel.coordinateSystem.type === 'polar';
  50010. }
  50011. )
  50012. );
  50013. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  50014. // Check series coordinate, do layout for polar only
  50015. if (seriesModel.coordinateSystem.type !== 'polar') {
  50016. return;
  50017. }
  50018. var data = seriesModel.getData();
  50019. var polar = seriesModel.coordinateSystem;
  50020. var angleAxis = polar.getAngleAxis();
  50021. var baseAxis = polar.getBaseAxis();
  50022. var stackId = getSeriesStackId$1(seriesModel);
  50023. var columnLayoutInfo
  50024. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  50025. var columnOffset = columnLayoutInfo.offset;
  50026. var columnWidth = columnLayoutInfo.width;
  50027. var valueAxis = polar.getOtherAxis(baseAxis);
  50028. var center = seriesModel.get('center') || ['50%', '50%'];
  50029. var cx = parsePercent$1(center[0], width);
  50030. var cy = parsePercent$1(center[1], height);
  50031. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  50032. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  50033. var valueAxisStart = valueAxis.getExtent()[0];
  50034. var valueMax = valueAxis.model.get('max');
  50035. var valueMin = valueAxis.model.get('min');
  50036. var coordDims = [
  50037. seriesModel.coordDimToDataDim('radius')[0],
  50038. seriesModel.coordDimToDataDim('angle')[0]
  50039. ];
  50040. var coords = data.mapArray(coordDims, function (radius, angle) {
  50041. return polar.dataToPoint([radius, angle]);
  50042. }, true);
  50043. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  50044. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  50045. data.each(seriesModel.coordDimToDataDim(valueAxis.dim)[0], function (value, idx) {
  50046. if (isNaN(value)) {
  50047. return;
  50048. }
  50049. if (!lastStackCoords[stackId][idx]) {
  50050. lastStackCoords[stackId][idx] = {
  50051. p: valueAxisStart, // Positive stack
  50052. n: valueAxisStart // Negative stack
  50053. };
  50054. lastStackCoordsOrigin[stackId][idx] = {
  50055. p: valueAxisStart, // Positive stack
  50056. n: valueAxisStart // Negative stack
  50057. };
  50058. }
  50059. var sign = value >= 0 ? 'p' : 'n';
  50060. var coord = polar.pointToCoord(coords[idx]);
  50061. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  50062. var r0;
  50063. var r;
  50064. var startAngle;
  50065. var endAngle;
  50066. if (valueAxis.dim === 'radius') {
  50067. // radial sector
  50068. r0 = lastCoordOrigin;
  50069. r = coord[0];
  50070. startAngle = (-coord[1] + columnOffset) * Math.PI / 180;
  50071. endAngle = startAngle + columnWidth * Math.PI / 180;
  50072. if (Math.abs(r) < barMinHeight) {
  50073. r = r0 + (r < 0 ? -1 : 1) * barMinHeight;
  50074. }
  50075. lastStackCoordsOrigin[stackId][idx][sign] = r;
  50076. }
  50077. else {
  50078. // tangential sector
  50079. r0 = coord[0] + columnOffset;
  50080. r = r0 + columnWidth;
  50081. // clamp data if min or max is defined for valueAxis
  50082. if (valueMax != null) {
  50083. value = Math.min(value, valueMax);
  50084. }
  50085. if (valueMin != null) {
  50086. value = Math.max(value, valueMin);
  50087. }
  50088. var angle = angleAxis.dataToAngle(value);
  50089. if (Math.abs(angle - lastCoordOrigin) < barMinAngle) {
  50090. angle = lastCoordOrigin - (value < 0 ? -1 : 1)
  50091. * barMinAngle;
  50092. }
  50093. startAngle = -lastCoordOrigin * Math.PI / 180;
  50094. endAngle = -angle * Math.PI / 180;
  50095. // if the previous stack is at the end of the ring,
  50096. // add a round to differentiate it from origin
  50097. var extent = angleAxis.getExtent();
  50098. var stackCoord = angle;
  50099. if (stackCoord === extent[0] && value > 0) {
  50100. stackCoord = extent[1];
  50101. }
  50102. else if (stackCoord === extent[1] && value < 0) {
  50103. stackCoord = extent[0];
  50104. }
  50105. lastStackCoordsOrigin[stackId][idx][sign] = stackCoord;
  50106. }
  50107. data.setItemLayout(idx, {
  50108. cx: cx,
  50109. cy: cy,
  50110. r0: r0,
  50111. r: r,
  50112. startAngle: startAngle,
  50113. endAngle: endAngle
  50114. });
  50115. }, true);
  50116. }, this);
  50117. }
  50118. /**
  50119. * Calculate bar width and offset for radial bar charts
  50120. */
  50121. function calRadialBar(barSeries, api) {
  50122. // Columns info on each category axis. Key is polar name
  50123. var columnsMap = {};
  50124. each$1(barSeries, function (seriesModel, idx) {
  50125. var data = seriesModel.getData();
  50126. var polar = seriesModel.coordinateSystem;
  50127. var baseAxis = polar.getBaseAxis();
  50128. var axisExtent = baseAxis.getExtent();
  50129. var bandWidth = baseAxis.type === 'category'
  50130. ? baseAxis.getBandWidth()
  50131. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  50132. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  50133. bandWidth: bandWidth,
  50134. remainedWidth: bandWidth,
  50135. autoWidthCount: 0,
  50136. categoryGap: '20%',
  50137. gap: '30%',
  50138. stacks: {}
  50139. };
  50140. var stacks = columnsOnAxis.stacks;
  50141. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  50142. var stackId = getSeriesStackId$1(seriesModel);
  50143. if (!stacks[stackId]) {
  50144. columnsOnAxis.autoWidthCount++;
  50145. }
  50146. stacks[stackId] = stacks[stackId] || {
  50147. width: 0,
  50148. maxWidth: 0
  50149. };
  50150. var barWidth = parsePercent$1(
  50151. seriesModel.get('barWidth'),
  50152. bandWidth
  50153. );
  50154. var barMaxWidth = parsePercent$1(
  50155. seriesModel.get('barMaxWidth'),
  50156. bandWidth
  50157. );
  50158. var barGap = seriesModel.get('barGap');
  50159. var barCategoryGap = seriesModel.get('barCategoryGap');
  50160. if (barWidth && !stacks[stackId].width) {
  50161. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  50162. stacks[stackId].width = barWidth;
  50163. columnsOnAxis.remainedWidth -= barWidth;
  50164. }
  50165. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  50166. (barGap != null) && (columnsOnAxis.gap = barGap);
  50167. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  50168. });
  50169. var result = {};
  50170. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  50171. result[coordSysName] = {};
  50172. var stacks = columnsOnAxis.stacks;
  50173. var bandWidth = columnsOnAxis.bandWidth;
  50174. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  50175. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  50176. var remainedWidth = columnsOnAxis.remainedWidth;
  50177. var autoWidthCount = columnsOnAxis.autoWidthCount;
  50178. var autoWidth = (remainedWidth - categoryGap)
  50179. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  50180. autoWidth = Math.max(autoWidth, 0);
  50181. // Find if any auto calculated bar exceeded maxBarWidth
  50182. each$1(stacks, function (column, stack) {
  50183. var maxWidth = column.maxWidth;
  50184. if (maxWidth && maxWidth < autoWidth) {
  50185. maxWidth = Math.min(maxWidth, remainedWidth);
  50186. if (column.width) {
  50187. maxWidth = Math.min(maxWidth, column.width);
  50188. }
  50189. remainedWidth -= maxWidth;
  50190. column.width = maxWidth;
  50191. autoWidthCount--;
  50192. }
  50193. });
  50194. // Recalculate width again
  50195. autoWidth = (remainedWidth - categoryGap)
  50196. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  50197. autoWidth = Math.max(autoWidth, 0);
  50198. var widthSum = 0;
  50199. var lastColumn;
  50200. each$1(stacks, function (column, idx) {
  50201. if (!column.width) {
  50202. column.width = autoWidth;
  50203. }
  50204. lastColumn = column;
  50205. widthSum += column.width * (1 + barGapPercent);
  50206. });
  50207. if (lastColumn) {
  50208. widthSum -= lastColumn.width * barGapPercent;
  50209. }
  50210. var offset = -widthSum / 2;
  50211. each$1(stacks, function (column, stackId) {
  50212. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  50213. offset: offset,
  50214. width: column.width
  50215. };
  50216. offset += column.width * (1 + barGapPercent);
  50217. });
  50218. });
  50219. return result;
  50220. }
  50221. function RadiusAxis(scale, radiusExtent) {
  50222. Axis.call(this, 'radius', scale, radiusExtent);
  50223. /**
  50224. * Axis type
  50225. * - 'category'
  50226. * - 'value'
  50227. * - 'time'
  50228. * - 'log'
  50229. * @type {string}
  50230. */
  50231. this.type = 'category';
  50232. }
  50233. RadiusAxis.prototype = {
  50234. constructor: RadiusAxis,
  50235. /**
  50236. * @override
  50237. */
  50238. pointToData: function (point, clamp) {
  50239. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  50240. },
  50241. dataToRadius: Axis.prototype.dataToCoord,
  50242. radiusToData: Axis.prototype.coordToData
  50243. };
  50244. inherits(RadiusAxis, Axis);
  50245. function AngleAxis(scale, angleExtent) {
  50246. angleExtent = angleExtent || [0, 360];
  50247. Axis.call(this, 'angle', scale, angleExtent);
  50248. /**
  50249. * Axis type
  50250. * - 'category'
  50251. * - 'value'
  50252. * - 'time'
  50253. * - 'log'
  50254. * @type {string}
  50255. */
  50256. this.type = 'category';
  50257. }
  50258. AngleAxis.prototype = {
  50259. constructor: AngleAxis,
  50260. /**
  50261. * @override
  50262. */
  50263. pointToData: function (point, clamp) {
  50264. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  50265. },
  50266. dataToAngle: Axis.prototype.dataToCoord,
  50267. angleToData: Axis.prototype.coordToData
  50268. };
  50269. inherits(AngleAxis, Axis);
  50270. /**
  50271. * @module echarts/coord/polar/Polar
  50272. */
  50273. /**
  50274. * @alias {module:echarts/coord/polar/Polar}
  50275. * @constructor
  50276. * @param {string} name
  50277. */
  50278. var Polar = function (name) {
  50279. /**
  50280. * @type {string}
  50281. */
  50282. this.name = name || '';
  50283. /**
  50284. * x of polar center
  50285. * @type {number}
  50286. */
  50287. this.cx = 0;
  50288. /**
  50289. * y of polar center
  50290. * @type {number}
  50291. */
  50292. this.cy = 0;
  50293. /**
  50294. * @type {module:echarts/coord/polar/RadiusAxis}
  50295. * @private
  50296. */
  50297. this._radiusAxis = new RadiusAxis();
  50298. /**
  50299. * @type {module:echarts/coord/polar/AngleAxis}
  50300. * @private
  50301. */
  50302. this._angleAxis = new AngleAxis();
  50303. this._radiusAxis.polar = this._angleAxis.polar = this;
  50304. };
  50305. Polar.prototype = {
  50306. type: 'polar',
  50307. axisPointerEnabled: true,
  50308. constructor: Polar,
  50309. /**
  50310. * @param {Array.<string>}
  50311. * @readOnly
  50312. */
  50313. dimensions: ['radius', 'angle'],
  50314. /**
  50315. * @type {module:echarts/coord/PolarModel}
  50316. */
  50317. model: null,
  50318. /**
  50319. * If contain coord
  50320. * @param {Array.<number>} point
  50321. * @return {boolean}
  50322. */
  50323. containPoint: function (point) {
  50324. var coord = this.pointToCoord(point);
  50325. return this._radiusAxis.contain(coord[0])
  50326. && this._angleAxis.contain(coord[1]);
  50327. },
  50328. /**
  50329. * If contain data
  50330. * @param {Array.<number>} data
  50331. * @return {boolean}
  50332. */
  50333. containData: function (data) {
  50334. return this._radiusAxis.containData(data[0])
  50335. && this._angleAxis.containData(data[1]);
  50336. },
  50337. /**
  50338. * @param {string} dim
  50339. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50340. */
  50341. getAxis: function (dim) {
  50342. return this['_' + dim + 'Axis'];
  50343. },
  50344. /**
  50345. * @return {Array.<module:echarts/coord/Axis>}
  50346. */
  50347. getAxes: function () {
  50348. return [this._radiusAxis, this._angleAxis];
  50349. },
  50350. /**
  50351. * Get axes by type of scale
  50352. * @param {string} scaleType
  50353. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50354. */
  50355. getAxesByScale: function (scaleType) {
  50356. var axes = [];
  50357. var angleAxis = this._angleAxis;
  50358. var radiusAxis = this._radiusAxis;
  50359. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  50360. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  50361. return axes;
  50362. },
  50363. /**
  50364. * @return {module:echarts/coord/polar/AngleAxis}
  50365. */
  50366. getAngleAxis: function () {
  50367. return this._angleAxis;
  50368. },
  50369. /**
  50370. * @return {module:echarts/coord/polar/RadiusAxis}
  50371. */
  50372. getRadiusAxis: function () {
  50373. return this._radiusAxis;
  50374. },
  50375. /**
  50376. * @param {module:echarts/coord/polar/Axis}
  50377. * @return {module:echarts/coord/polar/Axis}
  50378. */
  50379. getOtherAxis: function (axis) {
  50380. var angleAxis = this._angleAxis;
  50381. return axis === angleAxis ? this._radiusAxis : angleAxis;
  50382. },
  50383. /**
  50384. * Base axis will be used on stacking.
  50385. *
  50386. * @return {module:echarts/coord/polar/Axis}
  50387. */
  50388. getBaseAxis: function () {
  50389. return this.getAxesByScale('ordinal')[0]
  50390. || this.getAxesByScale('time')[0]
  50391. || this.getAngleAxis();
  50392. },
  50393. /**
  50394. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  50395. * @return {Object} {baseAxes: [], otherAxes: []}
  50396. */
  50397. getTooltipAxes: function (dim) {
  50398. var baseAxis = (dim != null && dim !== 'auto')
  50399. ? this.getAxis(dim) : this.getBaseAxis();
  50400. return {
  50401. baseAxes: [baseAxis],
  50402. otherAxes: [this.getOtherAxis(baseAxis)]
  50403. };
  50404. },
  50405. /**
  50406. * Convert a single data item to (x, y) point.
  50407. * Parameter data is an array which the first element is radius and the second is angle
  50408. * @param {Array.<number>} data
  50409. * @param {boolean} [clamp=false]
  50410. * @return {Array.<number>}
  50411. */
  50412. dataToPoint: function (data, clamp) {
  50413. return this.coordToPoint([
  50414. this._radiusAxis.dataToRadius(data[0], clamp),
  50415. this._angleAxis.dataToAngle(data[1], clamp)
  50416. ]);
  50417. },
  50418. /**
  50419. * Convert a (x, y) point to data
  50420. * @param {Array.<number>} point
  50421. * @param {boolean} [clamp=false]
  50422. * @return {Array.<number>}
  50423. */
  50424. pointToData: function (point, clamp) {
  50425. var coord = this.pointToCoord(point);
  50426. return [
  50427. this._radiusAxis.radiusToData(coord[0], clamp),
  50428. this._angleAxis.angleToData(coord[1], clamp)
  50429. ];
  50430. },
  50431. /**
  50432. * Convert a (x, y) point to (radius, angle) coord
  50433. * @param {Array.<number>} point
  50434. * @return {Array.<number>}
  50435. */
  50436. pointToCoord: function (point) {
  50437. var dx = point[0] - this.cx;
  50438. var dy = point[1] - this.cy;
  50439. var angleAxis = this.getAngleAxis();
  50440. var extent = angleAxis.getExtent();
  50441. var minAngle = Math.min(extent[0], extent[1]);
  50442. var maxAngle = Math.max(extent[0], extent[1]);
  50443. // Fix fixed extent in polarCreator
  50444. // FIXME
  50445. angleAxis.inverse
  50446. ? (minAngle = maxAngle - 360)
  50447. : (maxAngle = minAngle + 360);
  50448. var radius = Math.sqrt(dx * dx + dy * dy);
  50449. dx /= radius;
  50450. dy /= radius;
  50451. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  50452. // move to angleExtent
  50453. var dir = radian < minAngle ? 1 : -1;
  50454. while (radian < minAngle || radian > maxAngle) {
  50455. radian += dir * 360;
  50456. }
  50457. return [radius, radian];
  50458. },
  50459. /**
  50460. * Convert a (radius, angle) coord to (x, y) point
  50461. * @param {Array.<number>} coord
  50462. * @return {Array.<number>}
  50463. */
  50464. coordToPoint: function (coord) {
  50465. var radius = coord[0];
  50466. var radian = coord[1] / 180 * Math.PI;
  50467. var x = Math.cos(radian) * radius + this.cx;
  50468. // Inverse the y
  50469. var y = -Math.sin(radian) * radius + this.cy;
  50470. return [x, y];
  50471. }
  50472. };
  50473. var PolarAxisModel = ComponentModel.extend({
  50474. type: 'polarAxis',
  50475. /**
  50476. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50477. */
  50478. axis: null,
  50479. /**
  50480. * @override
  50481. */
  50482. getCoordSysModel: function () {
  50483. return this.ecModel.queryComponents({
  50484. mainType: 'polar',
  50485. index: this.option.polarIndex,
  50486. id: this.option.polarId
  50487. })[0];
  50488. }
  50489. });
  50490. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  50491. var polarAxisDefaultExtendedOption = {
  50492. angle: {
  50493. // polarIndex: 0,
  50494. // polarId: '',
  50495. startAngle: 90,
  50496. clockwise: true,
  50497. splitNumber: 12,
  50498. axisLabel: {
  50499. rotate: false
  50500. }
  50501. },
  50502. radius: {
  50503. // polarIndex: 0,
  50504. // polarId: '',
  50505. splitNumber: 5
  50506. }
  50507. };
  50508. function getAxisType$3(axisDim, option) {
  50509. // Default axis with data is category axis
  50510. return option.type || (option.data ? 'category' : 'value');
  50511. }
  50512. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  50513. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  50514. extendComponentModel({
  50515. type: 'polar',
  50516. dependencies: ['polarAxis', 'angleAxis'],
  50517. /**
  50518. * @type {module:echarts/coord/polar/Polar}
  50519. */
  50520. coordinateSystem: null,
  50521. /**
  50522. * @param {string} axisType
  50523. * @return {module:echarts/coord/polar/AxisModel}
  50524. */
  50525. findAxisModel: function (axisType) {
  50526. var foundAxisModel;
  50527. var ecModel = this.ecModel;
  50528. ecModel.eachComponent(axisType, function (axisModel) {
  50529. if (axisModel.getCoordSysModel() === this) {
  50530. foundAxisModel = axisModel;
  50531. }
  50532. }, this);
  50533. return foundAxisModel;
  50534. },
  50535. defaultOption: {
  50536. zlevel: 0,
  50537. z: 0,
  50538. center: ['50%', '50%'],
  50539. radius: '80%'
  50540. }
  50541. });
  50542. // TODO Axis scale
  50543. // 依赖 PolarModel 做预处理
  50544. /**
  50545. * Resize method bound to the polar
  50546. * @param {module:echarts/coord/polar/PolarModel} polarModel
  50547. * @param {module:echarts/ExtensionAPI} api
  50548. */
  50549. function resizePolar(polar, polarModel, api) {
  50550. var center = polarModel.get('center');
  50551. var width = api.getWidth();
  50552. var height = api.getHeight();
  50553. polar.cx = parsePercent$1(center[0], width);
  50554. polar.cy = parsePercent$1(center[1], height);
  50555. var radiusAxis = polar.getRadiusAxis();
  50556. var size = Math.min(width, height) / 2;
  50557. var radius = parsePercent$1(polarModel.get('radius'), size);
  50558. radiusAxis.inverse
  50559. ? radiusAxis.setExtent(radius, 0)
  50560. : radiusAxis.setExtent(0, radius);
  50561. }
  50562. /**
  50563. * Update polar
  50564. */
  50565. function updatePolarScale(ecModel, api) {
  50566. var polar = this;
  50567. var angleAxis = polar.getAngleAxis();
  50568. var radiusAxis = polar.getRadiusAxis();
  50569. // Reset scale
  50570. angleAxis.scale.setExtent(Infinity, -Infinity);
  50571. radiusAxis.scale.setExtent(Infinity, -Infinity);
  50572. ecModel.eachSeries(function (seriesModel) {
  50573. if (seriesModel.coordinateSystem === polar) {
  50574. var data = seriesModel.getData();
  50575. radiusAxis.scale.unionExtentFromData(data, 'radius');
  50576. angleAxis.scale.unionExtentFromData(data, 'angle');
  50577. }
  50578. });
  50579. niceScaleExtent(angleAxis.scale, angleAxis.model);
  50580. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  50581. // Fix extent of category angle axis
  50582. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  50583. var extent = angleAxis.getExtent();
  50584. var diff = 360 / angleAxis.scale.count();
  50585. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  50586. angleAxis.setExtent(extent[0], extent[1]);
  50587. }
  50588. }
  50589. /**
  50590. * Set common axis properties
  50591. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50592. * @param {module:echarts/coord/polar/AxisModel}
  50593. * @inner
  50594. */
  50595. function setAxis(axis, axisModel) {
  50596. axis.type = axisModel.get('type');
  50597. axis.scale = createScaleByModel(axisModel);
  50598. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  50599. axis.inverse = axisModel.get('inverse');
  50600. if (axisModel.mainType === 'angleAxis') {
  50601. axis.inverse ^= axisModel.get('clockwise');
  50602. var startAngle = axisModel.get('startAngle');
  50603. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  50604. }
  50605. // Inject axis instance
  50606. axisModel.axis = axis;
  50607. axis.model = axisModel;
  50608. }
  50609. var polarCreator = {
  50610. dimensions: Polar.prototype.dimensions,
  50611. create: function (ecModel, api) {
  50612. var polarList = [];
  50613. ecModel.eachComponent('polar', function (polarModel, idx) {
  50614. var polar = new Polar(idx);
  50615. // Inject resize and update method
  50616. polar.update = updatePolarScale;
  50617. var radiusAxis = polar.getRadiusAxis();
  50618. var angleAxis = polar.getAngleAxis();
  50619. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  50620. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  50621. setAxis(radiusAxis, radiusAxisModel);
  50622. setAxis(angleAxis, angleAxisModel);
  50623. resizePolar(polar, polarModel, api);
  50624. polarList.push(polar);
  50625. polarModel.coordinateSystem = polar;
  50626. polar.model = polarModel;
  50627. });
  50628. // Inject coordinateSystem to series
  50629. ecModel.eachSeries(function (seriesModel) {
  50630. if (seriesModel.get('coordinateSystem') === 'polar') {
  50631. var polarModel = ecModel.queryComponents({
  50632. mainType: 'polar',
  50633. index: seriesModel.get('polarIndex'),
  50634. id: seriesModel.get('polarId')
  50635. })[0];
  50636. if (__DEV__) {
  50637. if (!polarModel) {
  50638. throw new Error(
  50639. 'Polar "' + retrieve(
  50640. seriesModel.get('polarIndex'),
  50641. seriesModel.get('polarId'),
  50642. 0
  50643. ) + '" not found'
  50644. );
  50645. }
  50646. }
  50647. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  50648. }
  50649. });
  50650. return polarList;
  50651. }
  50652. };
  50653. CoordinateSystemManager.register('polar', polarCreator);
  50654. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  50655. function getAxisLineShape(polar, rExtent, angle) {
  50656. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  50657. var start = polar.coordToPoint([rExtent[0], angle]);
  50658. var end = polar.coordToPoint([rExtent[1], angle]);
  50659. return {
  50660. x1: start[0],
  50661. y1: start[1],
  50662. x2: end[0],
  50663. y2: end[1]
  50664. };
  50665. }
  50666. function getRadiusIdx(polar) {
  50667. var radiusAxis = polar.getRadiusAxis();
  50668. return radiusAxis.inverse ? 0 : 1;
  50669. }
  50670. AxisView.extend({
  50671. type: 'angleAxis',
  50672. axisPointerClass: 'PolarAxisPointer',
  50673. render: function (angleAxisModel, ecModel) {
  50674. this.group.removeAll();
  50675. if (!angleAxisModel.get('show')) {
  50676. return;
  50677. }
  50678. var angleAxis = angleAxisModel.axis;
  50679. var polar = angleAxis.polar;
  50680. var radiusExtent = polar.getRadiusAxis().getExtent();
  50681. var ticksAngles = angleAxis.getTicksCoords();
  50682. if (angleAxis.type !== 'category') {
  50683. // Remove the last tick which will overlap the first tick
  50684. ticksAngles.pop();
  50685. }
  50686. each$1(elementList$1, function (name) {
  50687. if (angleAxisModel.get(name +'.show')
  50688. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  50689. ) {
  50690. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent);
  50691. }
  50692. }, this);
  50693. },
  50694. /**
  50695. * @private
  50696. */
  50697. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50698. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  50699. var circle = new Circle({
  50700. shape: {
  50701. cx: polar.cx,
  50702. cy: polar.cy,
  50703. r: radiusExtent[getRadiusIdx(polar)]
  50704. },
  50705. style: lineStyleModel.getLineStyle(),
  50706. z2: 1,
  50707. silent: true
  50708. });
  50709. circle.style.fill = null;
  50710. this.group.add(circle);
  50711. },
  50712. /**
  50713. * @private
  50714. */
  50715. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50716. var tickModel = angleAxisModel.getModel('axisTick');
  50717. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  50718. var radius = radiusExtent[getRadiusIdx(polar)];
  50719. var lines = map(ticksAngles, function (tickAngle) {
  50720. return new Line({
  50721. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngle)
  50722. });
  50723. });
  50724. this.group.add(mergePath(
  50725. lines, {
  50726. style: defaults(
  50727. tickModel.getModel('lineStyle').getLineStyle(),
  50728. {
  50729. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  50730. }
  50731. )
  50732. }
  50733. ));
  50734. },
  50735. /**
  50736. * @private
  50737. */
  50738. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50739. var axis = angleAxisModel.axis;
  50740. var categoryData = angleAxisModel.get('data');
  50741. var labelModel = angleAxisModel.getModel('axisLabel');
  50742. var labels = angleAxisModel.getFormattedLabels();
  50743. var labelMargin = labelModel.get('margin');
  50744. var labelsAngles = axis.getLabelsCoords();
  50745. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  50746. for (var i = 0; i < ticksAngles.length; i++) {
  50747. var r = radiusExtent[getRadiusIdx(polar)];
  50748. var p = polar.coordToPoint([r + labelMargin, labelsAngles[i]]);
  50749. var cx = polar.cx;
  50750. var cy = polar.cy;
  50751. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  50752. ? 'center' : (p[0] > cx ? 'left' : 'right');
  50753. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  50754. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  50755. if (categoryData && categoryData[i] && categoryData[i].textStyle) {
  50756. labelModel = new Model(categoryData[i].textStyle, labelModel, labelModel.ecModel);
  50757. }
  50758. var textEl = new Text({silent: true});
  50759. this.group.add(textEl);
  50760. setTextStyle(textEl.style, labelModel, {
  50761. x: p[0],
  50762. y: p[1],
  50763. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  50764. text: labels[i],
  50765. textAlign: labelTextAlign,
  50766. textVerticalAlign: labelTextVerticalAlign
  50767. });
  50768. }
  50769. },
  50770. /**
  50771. * @private
  50772. */
  50773. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50774. var splitLineModel = angleAxisModel.getModel('splitLine');
  50775. var lineStyleModel = splitLineModel.getModel('lineStyle');
  50776. var lineColors = lineStyleModel.get('color');
  50777. var lineCount = 0;
  50778. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  50779. var splitLines = [];
  50780. for (var i = 0; i < ticksAngles.length; i++) {
  50781. var colorIndex = (lineCount++) % lineColors.length;
  50782. splitLines[colorIndex] = splitLines[colorIndex] || [];
  50783. splitLines[colorIndex].push(new Line({
  50784. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i])
  50785. }));
  50786. }
  50787. // Simple optimization
  50788. // Batching the lines if color are the same
  50789. for (var i = 0; i < splitLines.length; i++) {
  50790. this.group.add(mergePath(splitLines[i], {
  50791. style: defaults({
  50792. stroke: lineColors[i % lineColors.length]
  50793. }, lineStyleModel.getLineStyle()),
  50794. silent: true,
  50795. z: angleAxisModel.get('z')
  50796. }));
  50797. }
  50798. },
  50799. /**
  50800. * @private
  50801. */
  50802. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50803. var splitAreaModel = angleAxisModel.getModel('splitArea');
  50804. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  50805. var areaColors = areaStyleModel.get('color');
  50806. var lineCount = 0;
  50807. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  50808. var splitAreas = [];
  50809. var RADIAN = Math.PI / 180;
  50810. var prevAngle = -ticksAngles[0] * RADIAN;
  50811. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  50812. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  50813. var clockwise = angleAxisModel.get('clockwise');
  50814. for (var i = 1; i < ticksAngles.length; i++) {
  50815. var colorIndex = (lineCount++) % areaColors.length;
  50816. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  50817. splitAreas[colorIndex].push(new Sector({
  50818. shape: {
  50819. cx: polar.cx,
  50820. cy: polar.cy,
  50821. r0: r0,
  50822. r: r1,
  50823. startAngle: prevAngle,
  50824. endAngle: -ticksAngles[i] * RADIAN,
  50825. clockwise: clockwise
  50826. },
  50827. silent: true
  50828. }));
  50829. prevAngle = -ticksAngles[i] * RADIAN;
  50830. }
  50831. // Simple optimization
  50832. // Batching the lines if color are the same
  50833. for (var i = 0; i < splitAreas.length; i++) {
  50834. this.group.add(mergePath(splitAreas[i], {
  50835. style: defaults({
  50836. fill: areaColors[i % areaColors.length]
  50837. }, areaStyleModel.getAreaStyle()),
  50838. silent: true
  50839. }));
  50840. }
  50841. }
  50842. });
  50843. var axisBuilderAttrs$3 = [
  50844. 'axisLine', 'axisTickLabel', 'axisName'
  50845. ];
  50846. var selfBuilderAttrs$1 = [
  50847. 'splitLine', 'splitArea'
  50848. ];
  50849. AxisView.extend({
  50850. type: 'radiusAxis',
  50851. axisPointerClass: 'PolarAxisPointer',
  50852. render: function (radiusAxisModel, ecModel) {
  50853. this.group.removeAll();
  50854. if (!radiusAxisModel.get('show')) {
  50855. return;
  50856. }
  50857. var radiusAxis = radiusAxisModel.axis;
  50858. var polar = radiusAxis.polar;
  50859. var angleAxis = polar.getAngleAxis();
  50860. var ticksCoords = radiusAxis.getTicksCoords();
  50861. var axisAngle = angleAxis.getExtent()[0];
  50862. var radiusExtent = radiusAxis.getExtent();
  50863. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  50864. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  50865. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  50866. this.group.add(axisBuilder.getGroup());
  50867. each$1(selfBuilderAttrs$1, function (name) {
  50868. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  50869. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  50870. }
  50871. }, this);
  50872. },
  50873. /**
  50874. * @private
  50875. */
  50876. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  50877. var splitLineModel = radiusAxisModel.getModel('splitLine');
  50878. var lineStyleModel = splitLineModel.getModel('lineStyle');
  50879. var lineColors = lineStyleModel.get('color');
  50880. var lineCount = 0;
  50881. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  50882. var splitLines = [];
  50883. for (var i = 0; i < ticksCoords.length; i++) {
  50884. var colorIndex = (lineCount++) % lineColors.length;
  50885. splitLines[colorIndex] = splitLines[colorIndex] || [];
  50886. splitLines[colorIndex].push(new Circle({
  50887. shape: {
  50888. cx: polar.cx,
  50889. cy: polar.cy,
  50890. r: ticksCoords[i]
  50891. },
  50892. silent: true
  50893. }));
  50894. }
  50895. // Simple optimization
  50896. // Batching the lines if color are the same
  50897. for (var i = 0; i < splitLines.length; i++) {
  50898. this.group.add(mergePath(splitLines[i], {
  50899. style: defaults({
  50900. stroke: lineColors[i % lineColors.length],
  50901. fill: null
  50902. }, lineStyleModel.getLineStyle()),
  50903. silent: true
  50904. }));
  50905. }
  50906. },
  50907. /**
  50908. * @private
  50909. */
  50910. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  50911. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  50912. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  50913. var areaColors = areaStyleModel.get('color');
  50914. var lineCount = 0;
  50915. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  50916. var splitAreas = [];
  50917. var prevRadius = ticksCoords[0];
  50918. for (var i = 1; i < ticksCoords.length; i++) {
  50919. var colorIndex = (lineCount++) % areaColors.length;
  50920. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  50921. splitAreas[colorIndex].push(new Sector({
  50922. shape: {
  50923. cx: polar.cx,
  50924. cy: polar.cy,
  50925. r0: prevRadius,
  50926. r: ticksCoords[i],
  50927. startAngle: 0,
  50928. endAngle: Math.PI * 2
  50929. },
  50930. silent: true
  50931. }));
  50932. prevRadius = ticksCoords[i];
  50933. }
  50934. // Simple optimization
  50935. // Batching the lines if color are the same
  50936. for (var i = 0; i < splitAreas.length; i++) {
  50937. this.group.add(mergePath(splitAreas[i], {
  50938. style: defaults({
  50939. fill: areaColors[i % areaColors.length]
  50940. }, areaStyleModel.getAreaStyle()),
  50941. silent: true
  50942. }));
  50943. }
  50944. }
  50945. });
  50946. /**
  50947. * @inner
  50948. */
  50949. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  50950. return {
  50951. position: [polar.cx, polar.cy],
  50952. rotation: axisAngle / 180 * Math.PI,
  50953. labelDirection: -1,
  50954. tickDirection: -1,
  50955. nameDirection: 1,
  50956. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  50957. // Over splitLine and splitArea
  50958. z2: 1
  50959. };
  50960. }
  50961. var PolarAxisPointer = BaseAxisPointer.extend({
  50962. /**
  50963. * @override
  50964. */
  50965. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50966. var axis = axisModel.axis;
  50967. if (axis.dim === 'angle') {
  50968. this.animationThreshold = Math.PI / 18;
  50969. }
  50970. var polar = axis.polar;
  50971. var otherAxis = polar.getOtherAxis(axis);
  50972. var otherExtent = otherAxis.getExtent();
  50973. var coordValue;
  50974. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  50975. var axisPointerType = axisPointerModel.get('type');
  50976. if (axisPointerType && axisPointerType !== 'none') {
  50977. var elStyle = buildElStyle(axisPointerModel);
  50978. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  50979. axis, polar, coordValue, otherExtent, elStyle
  50980. );
  50981. pointerOption.style = elStyle;
  50982. elOption.graphicKey = pointerOption.type;
  50983. elOption.pointer = pointerOption;
  50984. }
  50985. var labelMargin = axisPointerModel.get('label.margin');
  50986. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  50987. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  50988. }
  50989. // Do not support handle, utill any user requires it.
  50990. });
  50991. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  50992. var axis = axisModel.axis;
  50993. var coord = axis.dataToCoord(value);
  50994. var axisAngle = polar.getAngleAxis().getExtent()[0];
  50995. axisAngle = axisAngle / 180 * Math.PI;
  50996. var radiusExtent = polar.getRadiusAxis().getExtent();
  50997. var position;
  50998. var align;
  50999. var verticalAlign;
  51000. if (axis.dim === 'radius') {
  51001. var transform = create$1();
  51002. rotate(transform, transform, axisAngle);
  51003. translate(transform, transform, [polar.cx, polar.cy]);
  51004. position = applyTransform$1([coord, -labelMargin], transform);
  51005. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  51006. var labelLayout = AxisBuilder.innerTextLayout(
  51007. axisAngle, labelRotation * Math.PI / 180, -1
  51008. );
  51009. align = labelLayout.textAlign;
  51010. verticalAlign = labelLayout.textVerticalAlign;
  51011. }
  51012. else { // angle axis
  51013. var r = radiusExtent[1];
  51014. position = polar.coordToPoint([r + labelMargin, coord]);
  51015. var cx = polar.cx;
  51016. var cy = polar.cy;
  51017. align = Math.abs(position[0] - cx) / r < 0.3
  51018. ? 'center' : (position[0] > cx ? 'left' : 'right');
  51019. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  51020. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  51021. }
  51022. return {
  51023. position: position,
  51024. align: align,
  51025. verticalAlign: verticalAlign
  51026. };
  51027. }
  51028. var pointerShapeBuilder$2 = {
  51029. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  51030. return axis.dim === 'angle'
  51031. ? {
  51032. type: 'Line',
  51033. shape: makeLineShape(
  51034. polar.coordToPoint([otherExtent[0], coordValue]),
  51035. polar.coordToPoint([otherExtent[1], coordValue])
  51036. )
  51037. }
  51038. : {
  51039. type: 'Circle',
  51040. shape: {
  51041. cx: polar.cx,
  51042. cy: polar.cy,
  51043. r: coordValue
  51044. }
  51045. };
  51046. },
  51047. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  51048. var bandWidth = axis.getBandWidth();
  51049. var radian = Math.PI / 180;
  51050. return axis.dim === 'angle'
  51051. ? {
  51052. type: 'Sector',
  51053. shape: makeSectorShape(
  51054. polar.cx, polar.cy,
  51055. otherExtent[0], otherExtent[1],
  51056. // In ECharts y is negative if angle is positive
  51057. (-coordValue - bandWidth / 2) * radian,
  51058. (-coordValue + bandWidth / 2) * radian
  51059. )
  51060. }
  51061. : {
  51062. type: 'Sector',
  51063. shape: makeSectorShape(
  51064. polar.cx, polar.cy,
  51065. coordValue - bandWidth / 2,
  51066. coordValue + bandWidth / 2,
  51067. 0, Math.PI * 2
  51068. )
  51069. };
  51070. }
  51071. };
  51072. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  51073. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  51074. registerLayout(curry(barLayoutPolar, 'bar'));
  51075. // Polar view
  51076. extendComponentView({
  51077. type: 'polar'
  51078. });
  51079. var GeoModel = ComponentModel.extend({
  51080. type: 'geo',
  51081. /**
  51082. * @type {module:echarts/coord/geo/Geo}
  51083. */
  51084. coordinateSystem: null,
  51085. layoutMode: 'box',
  51086. init: function (option) {
  51087. ComponentModel.prototype.init.apply(this, arguments);
  51088. // Default label emphasis `show`
  51089. defaultEmphasis(option.label, ['show']);
  51090. },
  51091. optionUpdated: function () {
  51092. var option = this.option;
  51093. var self = this;
  51094. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  51095. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  51096. if (regionOpt.name) {
  51097. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  51098. }
  51099. return optionModelMap;
  51100. }, createHashMap());
  51101. this.updateSelectedMap(option.regions);
  51102. },
  51103. defaultOption: {
  51104. zlevel: 0,
  51105. z: 0,
  51106. show: true,
  51107. left: 'center',
  51108. top: 'center',
  51109. // width:,
  51110. // height:,
  51111. // right
  51112. // bottom
  51113. // Aspect is width / height. Inited to be geoJson bbox aspect
  51114. // This parameter is used for scale this aspect
  51115. aspectScale: 0.75,
  51116. ///// Layout with center and size
  51117. // If you wan't to put map in a fixed size box with right aspect ratio
  51118. // This two properties may more conveninet
  51119. // layoutCenter: [50%, 50%]
  51120. // layoutSize: 100
  51121. silent: false,
  51122. // Map type
  51123. map: '',
  51124. // Define left-top, right-bottom coords to control view
  51125. // For example, [ [180, 90], [-180, -90] ]
  51126. boundingCoords: null,
  51127. // Default on center of map
  51128. center: null,
  51129. zoom: 1,
  51130. scaleLimit: null,
  51131. // selectedMode: false
  51132. label: {
  51133. normal: {
  51134. show: false,
  51135. color: '#000'
  51136. },
  51137. emphasis: {
  51138. show: true,
  51139. color: 'rgb(100,0,0)'
  51140. }
  51141. },
  51142. itemStyle: {
  51143. normal: {
  51144. // color: 各异,
  51145. borderWidth: 0.5,
  51146. borderColor: '#444',
  51147. color: '#eee'
  51148. },
  51149. emphasis: { // 也是选中样式
  51150. color: 'rgba(255,215,0,0.8)'
  51151. }
  51152. },
  51153. regions: []
  51154. },
  51155. /**
  51156. * Get model of region
  51157. * @param {string} name
  51158. * @return {module:echarts/model/Model}
  51159. */
  51160. getRegionModel: function (name) {
  51161. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  51162. },
  51163. /**
  51164. * Format label
  51165. * @param {string} name Region name
  51166. * @param {string} [status='normal'] 'normal' or 'emphasis'
  51167. * @return {string}
  51168. */
  51169. getFormattedLabel: function (name, status) {
  51170. var regionModel = this.getRegionModel(name);
  51171. var formatter = regionModel.get('label.' + status + '.formatter');
  51172. var params = {
  51173. name: name
  51174. };
  51175. if (typeof formatter === 'function') {
  51176. params.status = status;
  51177. return formatter(params);
  51178. }
  51179. else if (typeof formatter === 'string') {
  51180. return formatter.replace('{a}', name != null ? name : '');
  51181. }
  51182. },
  51183. setZoom: function (zoom) {
  51184. this.option.zoom = zoom;
  51185. },
  51186. setCenter: function (center) {
  51187. this.option.center = center;
  51188. }
  51189. });
  51190. mixin(GeoModel, selectableMixin);
  51191. extendComponentView({
  51192. type: 'geo',
  51193. init: function (ecModel, api) {
  51194. var mapDraw = new MapDraw(api, true);
  51195. this._mapDraw = mapDraw;
  51196. this.group.add(mapDraw.group);
  51197. },
  51198. render: function (geoModel, ecModel, api, payload) {
  51199. // Not render if it is an toggleSelect action from self
  51200. if (payload && payload.type === 'geoToggleSelect'
  51201. && payload.from === this.uid
  51202. ) {
  51203. return;
  51204. }
  51205. var mapDraw = this._mapDraw;
  51206. if (geoModel.get('show')) {
  51207. mapDraw.draw(geoModel, ecModel, api, this, payload);
  51208. }
  51209. else {
  51210. this._mapDraw.group.removeAll();
  51211. }
  51212. this.group.silent = geoModel.get('silent');
  51213. },
  51214. dispose: function () {
  51215. this._mapDraw && this._mapDraw.remove();
  51216. }
  51217. });
  51218. function makeAction(method, actionInfo) {
  51219. actionInfo.update = 'updateView';
  51220. registerAction(actionInfo, function (payload, ecModel) {
  51221. var selected = {};
  51222. ecModel.eachComponent(
  51223. { mainType: 'geo', query: payload},
  51224. function (geoModel) {
  51225. geoModel[method](payload.name);
  51226. var geo = geoModel.coordinateSystem;
  51227. each$1(geo.regions, function (region) {
  51228. selected[region.name] = geoModel.isSelected(region.name) || false;
  51229. });
  51230. }
  51231. );
  51232. return {
  51233. selected: selected,
  51234. name: payload.name
  51235. };
  51236. });
  51237. }
  51238. makeAction('toggleSelected', {
  51239. type: 'geoToggleSelect',
  51240. event: 'geoselectchanged'
  51241. });
  51242. makeAction('select', {
  51243. type: 'geoSelect',
  51244. event: 'geoselected'
  51245. });
  51246. makeAction('unSelect', {
  51247. type: 'geoUnSelect',
  51248. event: 'geounselected'
  51249. });
  51250. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  51251. var preprocessor$1 = function (option, isNew) {
  51252. var brushComponents = option && option.brush;
  51253. if (!isArray(brushComponents)) {
  51254. brushComponents = brushComponents ? [brushComponents] : [];
  51255. }
  51256. if (!brushComponents.length) {
  51257. return;
  51258. }
  51259. var brushComponentSpecifiedBtns = [];
  51260. each$1(brushComponents, function (brushOpt) {
  51261. var tbs = brushOpt.hasOwnProperty('toolbox')
  51262. ? brushOpt.toolbox : [];
  51263. if (tbs instanceof Array) {
  51264. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  51265. }
  51266. });
  51267. var toolbox = option && option.toolbox;
  51268. if (isArray(toolbox)) {
  51269. toolbox = toolbox[0];
  51270. }
  51271. if (!toolbox) {
  51272. toolbox = {feature: {}};
  51273. option.toolbox = [toolbox];
  51274. }
  51275. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  51276. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  51277. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  51278. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  51279. removeDuplicate(brushTypes);
  51280. if (isNew && !brushTypes.length) {
  51281. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  51282. }
  51283. };
  51284. function removeDuplicate(arr) {
  51285. var map$$1 = {};
  51286. each$1(arr, function (val) {
  51287. map$$1[val] = 1;
  51288. });
  51289. arr.length = 0;
  51290. each$1(map$$1, function (flag, val) {
  51291. arr.push(val);
  51292. });
  51293. }
  51294. /**
  51295. * @file Visual solution, for consistent option specification.
  51296. */
  51297. var each$22 = each$1;
  51298. function hasKeys(obj) {
  51299. if (obj) {
  51300. for (var name in obj){
  51301. if (obj.hasOwnProperty(name)) {
  51302. return true;
  51303. }
  51304. }
  51305. }
  51306. }
  51307. /**
  51308. * @param {Object} option
  51309. * @param {Array.<string>} stateList
  51310. * @param {Function} [supplementVisualOption]
  51311. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  51312. */
  51313. function createVisualMappings(option, stateList, supplementVisualOption) {
  51314. var visualMappings = {};
  51315. each$22(stateList, function (state) {
  51316. var mappings = visualMappings[state] = createMappings();
  51317. each$22(option[state], function (visualData, visualType) {
  51318. if (!VisualMapping.isValidType(visualType)) {
  51319. return;
  51320. }
  51321. var mappingOption = {
  51322. type: visualType,
  51323. visual: visualData
  51324. };
  51325. supplementVisualOption && supplementVisualOption(mappingOption, state);
  51326. mappings[visualType] = new VisualMapping(mappingOption);
  51327. // Prepare a alpha for opacity, for some case that opacity
  51328. // is not supported, such as rendering using gradient color.
  51329. if (visualType === 'opacity') {
  51330. mappingOption = clone(mappingOption);
  51331. mappingOption.type = 'colorAlpha';
  51332. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  51333. }
  51334. });
  51335. });
  51336. return visualMappings;
  51337. function createMappings() {
  51338. var Creater = function () {};
  51339. // Make sure hidden fields will not be visited by
  51340. // object iteration (with hasOwnProperty checking).
  51341. Creater.prototype.__hidden = Creater.prototype;
  51342. var obj = new Creater();
  51343. return obj;
  51344. }
  51345. }
  51346. /**
  51347. * @param {Object} thisOption
  51348. * @param {Object} newOption
  51349. * @param {Array.<string>} keys
  51350. */
  51351. function replaceVisualOption(thisOption, newOption, keys) {
  51352. // Visual attributes merge is not supported, otherwise it
  51353. // brings overcomplicated merge logic. See #2853. So if
  51354. // newOption has anyone of these keys, all of these keys
  51355. // will be reset. Otherwise, all keys remain.
  51356. var has;
  51357. each$1(keys, function (key) {
  51358. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  51359. has = true;
  51360. }
  51361. });
  51362. has && each$1(keys, function (key) {
  51363. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  51364. thisOption[key] = clone(newOption[key]);
  51365. }
  51366. else {
  51367. delete thisOption[key];
  51368. }
  51369. });
  51370. }
  51371. /**
  51372. * @param {Array.<string>} stateList
  51373. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  51374. * @param {module:echarts/data/List} list
  51375. * @param {Function} getValueState param: valueOrIndex, return: state.
  51376. * @param {object} [scope] Scope for getValueState
  51377. * @param {string} [dimension] Concrete dimension, if used.
  51378. */
  51379. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  51380. var visualTypesMap = {};
  51381. each$1(stateList, function (state) {
  51382. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  51383. visualTypesMap[state] = visualTypes;
  51384. });
  51385. var dataIndex;
  51386. function getVisual(key) {
  51387. return data.getItemVisual(dataIndex, key);
  51388. }
  51389. function setVisual(key, value) {
  51390. data.setItemVisual(dataIndex, key, value);
  51391. }
  51392. if (dimension == null) {
  51393. data.each(eachItem, true);
  51394. }
  51395. else {
  51396. data.each([dimension], eachItem, true);
  51397. }
  51398. function eachItem(valueOrIndex, index) {
  51399. dataIndex = dimension == null ? valueOrIndex : index;
  51400. var rawDataItem = data.getRawDataItem(dataIndex);
  51401. // Consider performance
  51402. if (rawDataItem && rawDataItem.visualMap === false) {
  51403. return;
  51404. }
  51405. var valueState = getValueState.call(scope, valueOrIndex);
  51406. var mappings = visualMappings[valueState];
  51407. var visualTypes = visualTypesMap[valueState];
  51408. for (var i = 0, len = visualTypes.length; i < len; i++) {
  51409. var type = visualTypes[i];
  51410. mappings[type] && mappings[type].applyVisual(
  51411. valueOrIndex, getVisual, setVisual
  51412. );
  51413. }
  51414. }
  51415. }
  51416. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  51417. // Key of the second level is chart element type: `point`, `rect`.
  51418. // See moudule:echarts/component/helper/BrushController
  51419. // function param:
  51420. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  51421. // {Object} selectors {point: selector, rect: selector, ...}
  51422. // {Object} area {range: [[], [], ..], boudingRect}
  51423. // function return:
  51424. // {boolean} Whether in the given brush.
  51425. var selector = {
  51426. lineX: getLineSelectors(0),
  51427. lineY: getLineSelectors(1),
  51428. rect: {
  51429. point: function (itemLayout, selectors, area) {
  51430. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  51431. },
  51432. rect: function (itemLayout, selectors, area) {
  51433. return itemLayout && area.boundingRect.intersect(itemLayout);
  51434. }
  51435. },
  51436. polygon: {
  51437. point: function (itemLayout, selectors, area) {
  51438. return itemLayout
  51439. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  51440. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  51441. },
  51442. rect: function (itemLayout, selectors, area) {
  51443. var points = area.range;
  51444. if (!itemLayout || points.length <= 1) {
  51445. return false;
  51446. }
  51447. var x = itemLayout.x;
  51448. var y = itemLayout.y;
  51449. var width = itemLayout.width;
  51450. var height = itemLayout.height;
  51451. var p = points[0];
  51452. if (contain$1(points, x, y)
  51453. || contain$1(points, x + width, y)
  51454. || contain$1(points, x, y + height)
  51455. || contain$1(points, x + width, y + height)
  51456. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  51457. || lineIntersectPolygon(x, y, x + width, y, points)
  51458. || lineIntersectPolygon(x, y, x, y + height, points)
  51459. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  51460. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  51461. ) {
  51462. return true;
  51463. }
  51464. }
  51465. }
  51466. };
  51467. function getLineSelectors(xyIndex) {
  51468. var xy = ['x', 'y'];
  51469. var wh = ['width', 'height'];
  51470. return {
  51471. point: function (itemLayout, selectors, area) {
  51472. if (itemLayout) {
  51473. var range = area.range;
  51474. var p = itemLayout[xyIndex];
  51475. return inLineRange(p, range);
  51476. }
  51477. },
  51478. rect: function (itemLayout, selectors, area) {
  51479. if (itemLayout) {
  51480. var range = area.range;
  51481. var layoutRange = [
  51482. itemLayout[xy[xyIndex]],
  51483. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  51484. ];
  51485. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  51486. return inLineRange(layoutRange[0], range)
  51487. || inLineRange(layoutRange[1], range)
  51488. || inLineRange(range[0], layoutRange)
  51489. || inLineRange(range[1], layoutRange);
  51490. }
  51491. }
  51492. };
  51493. }
  51494. function inLineRange(p, range) {
  51495. return range[0] <= p && p <= range[1];
  51496. }
  51497. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  51498. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  51499. var p = points[i];
  51500. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  51501. return true;
  51502. }
  51503. p2 = p;
  51504. }
  51505. }
  51506. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  51507. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  51508. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  51509. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  51510. if (nearZero(delta)) { // parallel
  51511. return false;
  51512. }
  51513. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  51514. if (namenda < 0 || namenda > 1) {
  51515. return false;
  51516. }
  51517. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  51518. if (miu < 0 || miu > 1) {
  51519. return false;
  51520. }
  51521. return true;
  51522. }
  51523. function nearZero(val) {
  51524. return val <= (1e-6) && val >= -(1e-6);
  51525. }
  51526. function determinant(v1, v2, v3, v4) {
  51527. return v1 * v4 - v2 * v3;
  51528. }
  51529. var each$23 = each$1;
  51530. var indexOf$2 = indexOf;
  51531. var curry$5 = curry;
  51532. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  51533. // FIXME
  51534. // how to genarialize to more coordinate systems.
  51535. var INCLUDE_FINDER_MAIN_TYPES = [
  51536. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  51537. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  51538. ];
  51539. /**
  51540. * [option in constructor]:
  51541. * {
  51542. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51543. * }
  51544. *
  51545. *
  51546. * [targetInfo]:
  51547. *
  51548. * There can be multiple axes in a single targetInfo. Consider the case
  51549. * of `grid` component, a targetInfo represents a grid which contains one or more
  51550. * cartesian and one or more axes. And consider the case of parallel system,
  51551. * which has multiple axes in a coordinate system.
  51552. * Can be {
  51553. * panelId: ...,
  51554. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  51555. * coordSyses: all cartesians.
  51556. * gridModel: <grid component>
  51557. * xAxes: correspond to coordSyses on index
  51558. * yAxes: correspond to coordSyses on index
  51559. * }
  51560. * or {
  51561. * panelId: ...,
  51562. * coordSys: <geo coord sys>
  51563. * coordSyses: [<geo coord sys>]
  51564. * geoModel: <geo component>
  51565. * }
  51566. *
  51567. *
  51568. * [panelOpt]:
  51569. *
  51570. * Make from targetInfo. Input to BrushController.
  51571. * {
  51572. * panelId: ...,
  51573. * rect: ...
  51574. * }
  51575. *
  51576. *
  51577. * [area]:
  51578. *
  51579. * Generated by BrushController or user input.
  51580. * {
  51581. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  51582. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  51583. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51584. * range: pixel range.
  51585. * coordRange: representitive coord range (the first one of coordRanges).
  51586. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  51587. * }
  51588. */
  51589. /**
  51590. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  51591. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  51592. * @param {module:echarts/model/Global} ecModel
  51593. * @param {Object} [opt]
  51594. * @param {Array.<string>} [opt.include] include coordinate system types.
  51595. */
  51596. function BrushTargetManager(option, ecModel, opt) {
  51597. /**
  51598. * @private
  51599. * @type {Array.<Object>}
  51600. */
  51601. var targetInfoList = this._targetInfoList = [];
  51602. var info = {};
  51603. var foundCpts = parseFinder$1(ecModel, option);
  51604. each$23(targetInfoBuilders, function (builder, type) {
  51605. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  51606. builder(foundCpts, targetInfoList, info);
  51607. }
  51608. });
  51609. }
  51610. var proto = BrushTargetManager.prototype;
  51611. proto.setOutputRanges = function (areas, ecModel) {
  51612. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  51613. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  51614. // area.coordRange is the first of area.coordRanges
  51615. if (!area.coordRange) {
  51616. area.coordRange = coordRange;
  51617. // In 'category' axis, coord to pixel is not reversible, so we can not
  51618. // rebuild range by coordRange accrately, which may bring trouble when
  51619. // brushing only one item. So we use __rangeOffset to rebuilding range
  51620. // by coordRange. And this it only used in brush component so it is no
  51621. // need to be adapted to coordRanges.
  51622. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  51623. area.__rangeOffset = {
  51624. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  51625. xyMinMax: result.xyMinMax
  51626. };
  51627. }
  51628. });
  51629. };
  51630. proto.matchOutputRanges = function (areas, ecModel, cb) {
  51631. each$23(areas, function (area) {
  51632. var targetInfo = this.findTargetInfo(area, ecModel);
  51633. if (targetInfo && targetInfo !== true) {
  51634. each$1(
  51635. targetInfo.coordSyses,
  51636. function (coordSys) {
  51637. var result = coordConvert[area.brushType](1, coordSys, area.range);
  51638. cb(area, result.values, coordSys, ecModel);
  51639. }
  51640. );
  51641. }
  51642. }, this);
  51643. };
  51644. proto.setInputRanges = function (areas, ecModel) {
  51645. each$23(areas, function (area) {
  51646. var targetInfo = this.findTargetInfo(area, ecModel);
  51647. if (__DEV__) {
  51648. assert(
  51649. !targetInfo || targetInfo === true || area.coordRange,
  51650. 'coordRange must be specified when coord index specified.'
  51651. );
  51652. assert(
  51653. !targetInfo || targetInfo !== true || area.range,
  51654. 'range must be specified in global brush.'
  51655. );
  51656. }
  51657. area.range = area.range || [];
  51658. // convert coordRange to global range and set panelId.
  51659. if (targetInfo && targetInfo !== true) {
  51660. area.panelId = targetInfo.panelId;
  51661. // (1) area.range shoule always be calculate from coordRange but does
  51662. // not keep its original value, for the sake of the dataZoom scenario,
  51663. // where area.coordRange remains unchanged but area.range may be changed.
  51664. // (2) Only support converting one coordRange to pixel range in brush
  51665. // component. So do not consider `coordRanges`.
  51666. // (3) About __rangeOffset, see comment above.
  51667. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  51668. var rangeOffset = area.__rangeOffset;
  51669. area.range = rangeOffset
  51670. ? diffProcessor[area.brushType](
  51671. result.values,
  51672. rangeOffset.offset,
  51673. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  51674. )
  51675. : result.values;
  51676. }
  51677. }, this);
  51678. };
  51679. proto.makePanelOpts = function (api, getDefaultBrushType) {
  51680. return map(this._targetInfoList, function (targetInfo) {
  51681. var rect = targetInfo.getPanelRect();
  51682. return {
  51683. panelId: targetInfo.panelId,
  51684. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  51685. clipPath: makeRectPanelClipPath(rect),
  51686. isTargetByCursor: makeRectIsTargetByCursor(
  51687. rect, api, targetInfo.coordSysModel
  51688. ),
  51689. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  51690. };
  51691. });
  51692. };
  51693. proto.controlSeries = function (area, seriesModel, ecModel) {
  51694. // Check whether area is bound in coord, and series do not belong to that coord.
  51695. // If do not do this check, some brush (like lineX) will controll all axes.
  51696. var targetInfo = this.findTargetInfo(area, ecModel);
  51697. return targetInfo === true || (
  51698. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  51699. );
  51700. };
  51701. /**
  51702. * If return Object, a coord found.
  51703. * If reutrn true, global found.
  51704. * Otherwise nothing found.
  51705. *
  51706. * @param {Object} area
  51707. * @param {Array} targetInfoList
  51708. * @return {Object|boolean}
  51709. */
  51710. proto.findTargetInfo = function (area, ecModel) {
  51711. var targetInfoList = this._targetInfoList;
  51712. var foundCpts = parseFinder$1(ecModel, area);
  51713. for (var i = 0; i < targetInfoList.length; i++) {
  51714. var targetInfo = targetInfoList[i];
  51715. var areaPanelId = area.panelId;
  51716. if (areaPanelId) {
  51717. if (targetInfo.panelId === areaPanelId) {
  51718. return targetInfo;
  51719. }
  51720. }
  51721. else {
  51722. for (var i = 0; i < targetInfoMatchers.length; i++) {
  51723. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  51724. return targetInfo;
  51725. }
  51726. }
  51727. }
  51728. }
  51729. return true;
  51730. };
  51731. function formatMinMax(minMax) {
  51732. minMax[0] > minMax[1] && minMax.reverse();
  51733. return minMax;
  51734. }
  51735. function parseFinder$1(ecModel, option) {
  51736. return parseFinder(
  51737. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  51738. );
  51739. }
  51740. var targetInfoBuilders = {
  51741. grid: function (foundCpts, targetInfoList) {
  51742. var xAxisModels = foundCpts.xAxisModels;
  51743. var yAxisModels = foundCpts.yAxisModels;
  51744. var gridModels = foundCpts.gridModels;
  51745. // Remove duplicated.
  51746. var gridModelMap = createHashMap();
  51747. var xAxesHas = {};
  51748. var yAxesHas = {};
  51749. if (!xAxisModels && !yAxisModels && !gridModels) {
  51750. return;
  51751. }
  51752. each$23(xAxisModels, function (axisModel) {
  51753. var gridModel = axisModel.axis.grid.model;
  51754. gridModelMap.set(gridModel.id, gridModel);
  51755. xAxesHas[gridModel.id] = true;
  51756. });
  51757. each$23(yAxisModels, function (axisModel) {
  51758. var gridModel = axisModel.axis.grid.model;
  51759. gridModelMap.set(gridModel.id, gridModel);
  51760. yAxesHas[gridModel.id] = true;
  51761. });
  51762. each$23(gridModels, function (gridModel) {
  51763. gridModelMap.set(gridModel.id, gridModel);
  51764. xAxesHas[gridModel.id] = true;
  51765. yAxesHas[gridModel.id] = true;
  51766. });
  51767. gridModelMap.each(function (gridModel) {
  51768. var grid = gridModel.coordinateSystem;
  51769. var cartesians = [];
  51770. each$23(grid.getCartesians(), function (cartesian, index) {
  51771. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  51772. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  51773. ) {
  51774. cartesians.push(cartesian);
  51775. }
  51776. });
  51777. targetInfoList.push({
  51778. panelId: 'grid--' + gridModel.id,
  51779. gridModel: gridModel,
  51780. coordSysModel: gridModel,
  51781. // Use the first one as the representitive coordSys.
  51782. coordSys: cartesians[0],
  51783. coordSyses: cartesians,
  51784. getPanelRect: panelRectBuilder.grid,
  51785. xAxisDeclared: xAxesHas[gridModel.id],
  51786. yAxisDeclared: yAxesHas[gridModel.id]
  51787. });
  51788. });
  51789. },
  51790. geo: function (foundCpts, targetInfoList) {
  51791. each$23(foundCpts.geoModels, function (geoModel) {
  51792. var coordSys = geoModel.coordinateSystem;
  51793. targetInfoList.push({
  51794. panelId: 'geo--' + geoModel.id,
  51795. geoModel: geoModel,
  51796. coordSysModel: geoModel,
  51797. coordSys: coordSys,
  51798. coordSyses: [coordSys],
  51799. getPanelRect: panelRectBuilder.geo
  51800. });
  51801. });
  51802. }
  51803. };
  51804. var targetInfoMatchers = [
  51805. // grid
  51806. function (foundCpts, targetInfo) {
  51807. var xAxisModel = foundCpts.xAxisModel;
  51808. var yAxisModel = foundCpts.yAxisModel;
  51809. var gridModel = foundCpts.gridModel;
  51810. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  51811. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  51812. return gridModel && gridModel === targetInfo.gridModel;
  51813. },
  51814. // geo
  51815. function (foundCpts, targetInfo) {
  51816. var geoModel = foundCpts.geoModel;
  51817. return geoModel && geoModel === targetInfo.geoModel;
  51818. }
  51819. ];
  51820. var panelRectBuilder = {
  51821. grid: function () {
  51822. // grid is not Transformable.
  51823. return this.coordSys.grid.getRect().clone();
  51824. },
  51825. geo: function () {
  51826. var coordSys = this.coordSys;
  51827. var rect = coordSys.getBoundingRect().clone();
  51828. // geo roam and zoom transform
  51829. rect.applyTransform(getTransform(coordSys));
  51830. return rect;
  51831. }
  51832. };
  51833. var coordConvert = {
  51834. lineX: curry$5(axisConvert, 0),
  51835. lineY: curry$5(axisConvert, 1),
  51836. rect: function (to, coordSys, rangeOrCoordRange) {
  51837. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  51838. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  51839. var values = [
  51840. formatMinMax([xminymin[0], xmaxymax[0]]),
  51841. formatMinMax([xminymin[1], xmaxymax[1]])
  51842. ];
  51843. return {values: values, xyMinMax: values};
  51844. },
  51845. polygon: function (to, coordSys, rangeOrCoordRange) {
  51846. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  51847. var values = map(rangeOrCoordRange, function (item) {
  51848. var p = coordSys[COORD_CONVERTS[to]](item);
  51849. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  51850. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  51851. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  51852. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  51853. return p;
  51854. });
  51855. return {values: values, xyMinMax: xyMinMax};
  51856. }
  51857. };
  51858. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  51859. if (__DEV__) {
  51860. assert(
  51861. coordSys.type === 'cartesian2d',
  51862. 'lineX/lineY brush is available only in cartesian2d.'
  51863. );
  51864. }
  51865. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  51866. var values = formatMinMax(map([0, 1], function (i) {
  51867. return to
  51868. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  51869. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  51870. }));
  51871. var xyMinMax = [];
  51872. xyMinMax[axisNameIndex] = values;
  51873. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  51874. return {values: values, xyMinMax: xyMinMax};
  51875. }
  51876. var diffProcessor = {
  51877. lineX: curry$5(axisDiffProcessor, 0),
  51878. lineY: curry$5(axisDiffProcessor, 1),
  51879. rect: function (values, refer, scales) {
  51880. return [
  51881. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  51882. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  51883. ];
  51884. },
  51885. polygon: function (values, refer, scales) {
  51886. return map(values, function (item, idx) {
  51887. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  51888. });
  51889. }
  51890. };
  51891. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  51892. return [
  51893. values[0] - scales[axisNameIndex] * refer[0],
  51894. values[1] - scales[axisNameIndex] * refer[1]
  51895. ];
  51896. }
  51897. // We have to process scale caused by dataZoom manually,
  51898. // although it might be not accurate.
  51899. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  51900. var sizeCurr = getSize(xyMinMaxCurr);
  51901. var sizeOrigin = getSize(xyMinMaxOrigin);
  51902. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  51903. isNaN(scales[0]) && (scales[0] = 1);
  51904. isNaN(scales[1]) && (scales[1] = 1);
  51905. return scales;
  51906. }
  51907. function getSize(xyMinMax) {
  51908. return xyMinMax
  51909. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  51910. : [NaN, NaN];
  51911. }
  51912. var STATE_LIST = ['inBrush', 'outOfBrush'];
  51913. var DISPATCH_METHOD = '__ecBrushSelect';
  51914. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  51915. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  51916. /**
  51917. * Layout for visual, the priority higher than other layout, and before brush visual.
  51918. */
  51919. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  51920. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  51921. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  51922. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  51923. );
  51924. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  51925. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  51926. });
  51927. });
  51928. /**
  51929. * Register the visual encoding if this modules required.
  51930. */
  51931. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  51932. var brushSelected = [];
  51933. var throttleType;
  51934. var throttleDelay;
  51935. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  51936. var thisBrushSelected = {
  51937. brushId: brushModel.id,
  51938. brushIndex: brushIndex,
  51939. brushName: brushModel.name,
  51940. areas: clone(brushModel.areas),
  51941. selected: []
  51942. };
  51943. // Every brush component exists in event params, convenient
  51944. // for user to find by index.
  51945. brushSelected.push(thisBrushSelected);
  51946. var brushOption = brushModel.option;
  51947. var brushLink = brushOption.brushLink;
  51948. var linkedSeriesMap = [];
  51949. var selectedDataIndexForLink = [];
  51950. var rangeInfoBySeries = [];
  51951. var hasBrushExists = 0;
  51952. if (!brushIndex) { // Only the first throttle setting works.
  51953. throttleType = brushOption.throttleType;
  51954. throttleDelay = brushOption.throttleDelay;
  51955. }
  51956. // Add boundingRect and selectors to range.
  51957. var areas = map(brushModel.areas, function (area) {
  51958. return bindSelector(
  51959. defaults(
  51960. {boundingRect: boundingRectBuilders[area.brushType](area)},
  51961. area
  51962. )
  51963. );
  51964. });
  51965. var visualMappings = createVisualMappings(
  51966. brushModel.option, STATE_LIST, function (mappingOption) {
  51967. mappingOption.mappingMethod = 'fixed';
  51968. }
  51969. );
  51970. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  51971. linkedSeriesMap[seriesIndex] = 1;
  51972. });
  51973. function linkOthers(seriesIndex) {
  51974. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  51975. }
  51976. // If no supported brush or no brush on the series,
  51977. // all visuals should be in original state.
  51978. function brushed(rangeInfoList) {
  51979. return !!rangeInfoList.length;
  51980. }
  51981. /**
  51982. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  51983. *
  51984. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  51985. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  51986. * └!hasBrushExist┘ └nothing.
  51987. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  51988. * └!hasBrushExist┘ └nothing.
  51989. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  51990. * !brushed┘ └nothing.
  51991. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  51992. */
  51993. // Step A
  51994. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  51995. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  51996. seriesModel.subType === 'parallel'
  51997. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  51998. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  51999. });
  52000. function stepAParallel(seriesModel, seriesIndex) {
  52001. var coordSys = seriesModel.coordinateSystem;
  52002. hasBrushExists |= coordSys.hasAxisBrushed();
  52003. linkOthers(seriesIndex) && coordSys.eachActiveState(
  52004. seriesModel.getData(),
  52005. function (activeState, dataIndex) {
  52006. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  52007. }
  52008. );
  52009. }
  52010. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  52011. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  52012. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  52013. return;
  52014. }
  52015. each$1(areas, function (area) {
  52016. selectorsByBrushType[area.brushType]
  52017. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  52018. && rangeInfoList.push(area);
  52019. hasBrushExists |= brushed(rangeInfoList);
  52020. });
  52021. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  52022. var data = seriesModel.getData();
  52023. data.each(function (dataIndex) {
  52024. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  52025. selectedDataIndexForLink[dataIndex] = 1;
  52026. }
  52027. });
  52028. }
  52029. }
  52030. // Step B
  52031. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  52032. var seriesBrushSelected = {
  52033. seriesId: seriesModel.id,
  52034. seriesIndex: seriesIndex,
  52035. seriesName: seriesModel.name,
  52036. dataIndex: []
  52037. };
  52038. // Every series exists in event params, convenient
  52039. // for user to find series by seriesIndex.
  52040. thisBrushSelected.selected.push(seriesBrushSelected);
  52041. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  52042. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  52043. var data = seriesModel.getData();
  52044. var getValueState = linkOthers(seriesIndex)
  52045. ? function (dataIndex) {
  52046. return selectedDataIndexForLink[dataIndex]
  52047. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  52048. : 'outOfBrush';
  52049. }
  52050. : function (dataIndex) {
  52051. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  52052. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  52053. : 'outOfBrush';
  52054. };
  52055. // If no supported brush or no brush, all visuals are in original state.
  52056. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  52057. && applyVisual(
  52058. STATE_LIST, visualMappings, data, getValueState
  52059. );
  52060. });
  52061. });
  52062. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  52063. });
  52064. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  52065. // This event will not be triggered when `setOpion`, otherwise dead lock may
  52066. // triggered when do `setOption` in event listener, which we do not find
  52067. // satisfactory way to solve yet. Some considered resolutions:
  52068. // (a) Diff with prevoius selected data ant only trigger event when changed.
  52069. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  52070. // also detect value changes in selected data) might bring complexity or fragility.
  52071. // (b) Use spectial param like `silent` to suppress event triggering.
  52072. // But such kind of volatile param may be weird in `setOption`.
  52073. if (!payload) {
  52074. return;
  52075. }
  52076. var zr = api.getZr();
  52077. if (zr[DISPATCH_FLAG]) {
  52078. return;
  52079. }
  52080. if (!zr[DISPATCH_METHOD]) {
  52081. zr[DISPATCH_METHOD] = doDispatch;
  52082. }
  52083. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  52084. fn(api, brushSelected);
  52085. }
  52086. function doDispatch(api, brushSelected) {
  52087. if (!api.isDisposed()) {
  52088. var zr = api.getZr();
  52089. zr[DISPATCH_FLAG] = true;
  52090. api.dispatchAction({
  52091. type: 'brushSelect',
  52092. batch: brushSelected
  52093. });
  52094. zr[DISPATCH_FLAG] = false;
  52095. }
  52096. }
  52097. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  52098. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  52099. var area = rangeInfoList[i];
  52100. if (selectorsByBrushType[area.brushType](
  52101. dataIndex, data, area.selectors, area
  52102. )) {
  52103. return true;
  52104. }
  52105. }
  52106. }
  52107. function getSelectorsByBrushType(seriesModel) {
  52108. var brushSelector = seriesModel.brushSelector;
  52109. if (isString(brushSelector)) {
  52110. var sels = [];
  52111. each$1(selector, function (selectorsByElementType, brushType) {
  52112. sels[brushType] = function (dataIndex, data, selectors, area) {
  52113. var itemLayout = data.getItemLayout(dataIndex);
  52114. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  52115. };
  52116. });
  52117. return sels;
  52118. }
  52119. else if (isFunction(brushSelector)) {
  52120. var bSelector = {};
  52121. each$1(selector, function (sel, brushType) {
  52122. bSelector[brushType] = brushSelector;
  52123. });
  52124. return bSelector;
  52125. }
  52126. return brushSelector;
  52127. }
  52128. function brushModelNotControll(brushModel, seriesIndex) {
  52129. var seriesIndices = brushModel.option.seriesIndex;
  52130. return seriesIndices != null
  52131. && seriesIndices !== 'all'
  52132. && (
  52133. isArray(seriesIndices)
  52134. ? indexOf(seriesIndices, seriesIndex) < 0
  52135. : seriesIndex !== seriesIndices
  52136. );
  52137. }
  52138. function bindSelector(area) {
  52139. var selectors = area.selectors = {};
  52140. each$1(selector[area.brushType], function (selFn, elType) {
  52141. // Do not use function binding or curry for performance.
  52142. selectors[elType] = function (itemLayout) {
  52143. return selFn(itemLayout, selectors, area);
  52144. };
  52145. });
  52146. return area;
  52147. }
  52148. var boundingRectBuilders = {
  52149. lineX: noop,
  52150. lineY: noop,
  52151. rect: function (area) {
  52152. return getBoundingRectFromMinMax(area.range);
  52153. },
  52154. polygon: function (area) {
  52155. var minMax;
  52156. var range = area.range;
  52157. for (var i = 0, len = range.length; i < len; i++) {
  52158. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  52159. var rg = range[i];
  52160. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  52161. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  52162. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  52163. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  52164. }
  52165. return minMax && getBoundingRectFromMinMax(minMax);
  52166. }
  52167. };
  52168. function getBoundingRectFromMinMax(minMax) {
  52169. return new BoundingRect(
  52170. minMax[0][0],
  52171. minMax[1][0],
  52172. minMax[0][1] - minMax[0][0],
  52173. minMax[1][1] - minMax[1][0]
  52174. );
  52175. }
  52176. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  52177. var BrushModel = extendComponentModel({
  52178. type: 'brush',
  52179. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  52180. /**
  52181. * @protected
  52182. */
  52183. defaultOption: {
  52184. // inBrush: null,
  52185. // outOfBrush: null,
  52186. toolbox: null, // Default value see preprocessor.
  52187. brushLink: null, // Series indices array, broadcast using dataIndex.
  52188. // or 'all', which means all series. 'none' or null means no series.
  52189. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  52190. geoIndex: null, //
  52191. xAxisIndex: null,
  52192. yAxisIndex: null,
  52193. brushType: 'rect', // Default brushType, see BrushController.
  52194. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  52195. transformable: true, // Default transformable.
  52196. brushStyle: { // Default brushStyle
  52197. borderWidth: 1,
  52198. color: 'rgba(120,140,180,0.3)',
  52199. borderColor: 'rgba(120,140,180,0.8)'
  52200. },
  52201. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  52202. // If null, no throttle. Valid only in the first brush component
  52203. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  52204. // FIXME
  52205. // 试验效果
  52206. removeOnClick: true,
  52207. z: 10000
  52208. },
  52209. /**
  52210. * @readOnly
  52211. * @type {Array.<Object>}
  52212. */
  52213. areas: [],
  52214. /**
  52215. * Current activated brush type.
  52216. * If null, brush is inactived.
  52217. * see module:echarts/component/helper/BrushController
  52218. * @readOnly
  52219. * @type {string}
  52220. */
  52221. brushType: null,
  52222. /**
  52223. * Current brush opt.
  52224. * see module:echarts/component/helper/BrushController
  52225. * @readOnly
  52226. * @type {Object}
  52227. */
  52228. brushOption: {},
  52229. /**
  52230. * @readOnly
  52231. * @type {Array.<Object>}
  52232. */
  52233. coordInfoList: [],
  52234. optionUpdated: function (newOption, isInit) {
  52235. var thisOption = this.option;
  52236. !isInit && replaceVisualOption(
  52237. thisOption, newOption, ['inBrush', 'outOfBrush']
  52238. );
  52239. thisOption.inBrush = thisOption.inBrush || {};
  52240. // Always give default visual, consider setOption at the second time.
  52241. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  52242. },
  52243. /**
  52244. * If ranges is null/undefined, range state remain.
  52245. *
  52246. * @param {Array.<Object>} [ranges]
  52247. */
  52248. setAreas: function (areas) {
  52249. if (__DEV__) {
  52250. assert(isArray(areas));
  52251. each$1(areas, function (area) {
  52252. assert(area.brushType, 'Illegal areas');
  52253. });
  52254. }
  52255. // If ranges is null/undefined, range state remain.
  52256. // This helps user to dispatchAction({type: 'brush'}) with no areas
  52257. // set but just want to get the current brush select info from a `brush` event.
  52258. if (!areas) {
  52259. return;
  52260. }
  52261. this.areas = map(areas, function (area) {
  52262. return generateBrushOption(this.option, area);
  52263. }, this);
  52264. },
  52265. /**
  52266. * see module:echarts/component/helper/BrushController
  52267. * @param {Object} brushOption
  52268. */
  52269. setBrushOption: function (brushOption) {
  52270. this.brushOption = generateBrushOption(this.option, brushOption);
  52271. this.brushType = this.brushOption.brushType;
  52272. }
  52273. });
  52274. function generateBrushOption(option, brushOption) {
  52275. return merge(
  52276. {
  52277. brushType: option.brushType,
  52278. brushMode: option.brushMode,
  52279. transformable: option.transformable,
  52280. brushStyle: new Model(option.brushStyle).getItemStyle(),
  52281. removeOnClick: option.removeOnClick,
  52282. z: option.z
  52283. },
  52284. brushOption,
  52285. true
  52286. );
  52287. }
  52288. extendComponentView({
  52289. type: 'brush',
  52290. init: function (ecModel, api) {
  52291. /**
  52292. * @readOnly
  52293. * @type {module:echarts/model/Global}
  52294. */
  52295. this.ecModel = ecModel;
  52296. /**
  52297. * @readOnly
  52298. * @type {module:echarts/ExtensionAPI}
  52299. */
  52300. this.api = api;
  52301. /**
  52302. * @readOnly
  52303. * @type {module:echarts/component/brush/BrushModel}
  52304. */
  52305. this.model;
  52306. /**
  52307. * @private
  52308. * @type {module:echarts/component/helper/BrushController}
  52309. */
  52310. (this._brushController = new BrushController(api.getZr()))
  52311. .on('brush', bind(this._onBrush, this))
  52312. .mount();
  52313. },
  52314. /**
  52315. * @override
  52316. */
  52317. render: function (brushModel) {
  52318. this.model = brushModel;
  52319. return updateController.apply(this, arguments);
  52320. },
  52321. /**
  52322. * @override
  52323. */
  52324. updateView: updateController,
  52325. /**
  52326. * @override
  52327. */
  52328. updateLayout: updateController,
  52329. /**
  52330. * @override
  52331. */
  52332. updateVisual: updateController,
  52333. /**
  52334. * @override
  52335. */
  52336. dispose: function () {
  52337. this._brushController.dispose();
  52338. },
  52339. /**
  52340. * @private
  52341. */
  52342. _onBrush: function (areas, opt) {
  52343. var modelId = this.model.id;
  52344. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  52345. // Action is not dispatched on drag end, because the drag end
  52346. // emits the same params with the last drag move event, and
  52347. // may have some delay when using touch pad, which makes
  52348. // animation not smooth (when using debounce).
  52349. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  52350. type: 'brush',
  52351. brushId: modelId,
  52352. areas: clone(areas),
  52353. $from: modelId
  52354. });
  52355. }
  52356. });
  52357. function updateController(brushModel, ecModel, api, payload) {
  52358. // Do not update controller when drawing.
  52359. (!payload || payload.$from !== brushModel.id) && this._brushController
  52360. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  52361. .enableBrush(brushModel.brushOption)
  52362. .updateCovers(brushModel.areas.slice());
  52363. }
  52364. /**
  52365. * payload: {
  52366. * brushIndex: number, or,
  52367. * brushId: string, or,
  52368. * brushName: string,
  52369. * globalRanges: Array
  52370. * }
  52371. */
  52372. registerAction(
  52373. {type: 'brush', event: 'brush', update: 'updateView'},
  52374. function (payload, ecModel) {
  52375. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  52376. brushModel.setAreas(payload.areas);
  52377. });
  52378. }
  52379. );
  52380. /**
  52381. * payload: {
  52382. * brushComponents: [
  52383. * {
  52384. * brushId,
  52385. * brushIndex,
  52386. * brushName,
  52387. * series: [
  52388. * {
  52389. * seriesId,
  52390. * seriesIndex,
  52391. * seriesName,
  52392. * rawIndices: [21, 34, ...]
  52393. * },
  52394. * ...
  52395. * ]
  52396. * },
  52397. * ...
  52398. * ]
  52399. * }
  52400. */
  52401. registerAction(
  52402. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  52403. function () {}
  52404. );
  52405. var features = {};
  52406. function register$1(name, ctor) {
  52407. features[name] = ctor;
  52408. }
  52409. function get$5(name) {
  52410. return features[name];
  52411. }
  52412. var lang = {
  52413. toolbox: {
  52414. brush: {
  52415. title: {
  52416. rect: '矩形选择',
  52417. polygon: '圈选',
  52418. lineX: '横向选择',
  52419. lineY: '纵向选择',
  52420. keep: '保持选择',
  52421. clear: '清除选择'
  52422. }
  52423. },
  52424. dataView: {
  52425. title: '数据视图',
  52426. lang: ['数据视图', '关闭', '刷新']
  52427. },
  52428. dataZoom: {
  52429. title: {
  52430. zoom: '区域缩放',
  52431. back: '区域缩放还原'
  52432. }
  52433. },
  52434. magicType: {
  52435. title: {
  52436. line: '切换为折线图',
  52437. bar: '切换为柱状图',
  52438. stack: '切换为堆叠',
  52439. tiled: '切换为平铺'
  52440. }
  52441. },
  52442. restore: {
  52443. title: '还原'
  52444. },
  52445. saveAsImage: {
  52446. title: '保存为图片',
  52447. lang: ['右键另存为图片']
  52448. }
  52449. }
  52450. };
  52451. var brushLang = lang.toolbox.brush;
  52452. function Brush(model, ecModel, api) {
  52453. this.model = model;
  52454. this.ecModel = ecModel;
  52455. this.api = api;
  52456. /**
  52457. * @private
  52458. * @type {string}
  52459. */
  52460. this._brushType;
  52461. /**
  52462. * @private
  52463. * @type {string}
  52464. */
  52465. this._brushMode;
  52466. }
  52467. Brush.defaultOption = {
  52468. show: true,
  52469. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  52470. icon: {
  52471. 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
  52472. 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
  52473. 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
  52474. 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
  52475. 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
  52476. 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
  52477. },
  52478. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  52479. title: clone(brushLang.title)
  52480. };
  52481. var proto$1 = Brush.prototype;
  52482. proto$1.render =
  52483. proto$1.updateView =
  52484. proto$1.updateLayout = function (featureModel, ecModel, api) {
  52485. var brushType;
  52486. var brushMode;
  52487. var isBrushed;
  52488. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  52489. brushType = brushModel.brushType;
  52490. brushMode = brushModel.brushOption.brushMode || 'single';
  52491. isBrushed |= brushModel.areas.length;
  52492. });
  52493. this._brushType = brushType;
  52494. this._brushMode = brushMode;
  52495. each$1(featureModel.get('type', true), function (type) {
  52496. featureModel.setIconStatus(
  52497. type,
  52498. (
  52499. type === 'keep'
  52500. ? brushMode === 'multiple'
  52501. : type === 'clear'
  52502. ? isBrushed
  52503. : type === brushType
  52504. ) ? 'emphasis' : 'normal'
  52505. );
  52506. });
  52507. };
  52508. proto$1.getIcons = function () {
  52509. var model = this.model;
  52510. var availableIcons = model.get('icon', true);
  52511. var icons = {};
  52512. each$1(model.get('type', true), function (type) {
  52513. if (availableIcons[type]) {
  52514. icons[type] = availableIcons[type];
  52515. }
  52516. });
  52517. return icons;
  52518. };
  52519. proto$1.onclick = function (ecModel, api, type) {
  52520. var brushType = this._brushType;
  52521. var brushMode = this._brushMode;
  52522. if (type === 'clear') {
  52523. // Trigger parallel action firstly
  52524. api.dispatchAction({
  52525. type: 'axisAreaSelect',
  52526. intervals: []
  52527. });
  52528. api.dispatchAction({
  52529. type: 'brush',
  52530. command: 'clear',
  52531. // Clear all areas of all brush components.
  52532. areas: []
  52533. });
  52534. }
  52535. else {
  52536. api.dispatchAction({
  52537. type: 'takeGlobalCursor',
  52538. key: 'brush',
  52539. brushOption: {
  52540. brushType: type === 'keep'
  52541. ? brushType
  52542. : (brushType === type ? false : type),
  52543. brushMode: type === 'keep'
  52544. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  52545. : brushMode
  52546. }
  52547. });
  52548. }
  52549. };
  52550. register$1('brush', Brush);
  52551. /**
  52552. * Brush component entry
  52553. */
  52554. registerPreprocessor(preprocessor$1);
  52555. // (24*60*60*1000)
  52556. var PROXIMATE_ONE_DAY = 86400000;
  52557. /**
  52558. * Calendar
  52559. *
  52560. * @constructor
  52561. *
  52562. * @param {Object} calendarModel calendarModel
  52563. * @param {Object} ecModel ecModel
  52564. * @param {Object} api api
  52565. */
  52566. function Calendar(calendarModel, ecModel, api) {
  52567. this._model = calendarModel;
  52568. }
  52569. Calendar.prototype = {
  52570. constructor: Calendar,
  52571. type: 'calendar',
  52572. dimensions: ['time', 'value'],
  52573. // Required in createListFromData
  52574. getDimensionsInfo: function () {
  52575. return [{name: 'time', type: 'time'}];
  52576. },
  52577. getRangeInfo: function () {
  52578. return this._rangeInfo;
  52579. },
  52580. getModel: function () {
  52581. return this._model;
  52582. },
  52583. getRect: function () {
  52584. return this._rect;
  52585. },
  52586. getCellWidth: function () {
  52587. return this._sw;
  52588. },
  52589. getCellHeight: function () {
  52590. return this._sh;
  52591. },
  52592. getOrient: function () {
  52593. return this._orient;
  52594. },
  52595. /**
  52596. * getFirstDayOfWeek
  52597. *
  52598. * @example
  52599. * 0 : start at Sunday
  52600. * 1 : start at Monday
  52601. *
  52602. * @return {number}
  52603. */
  52604. getFirstDayOfWeek: function () {
  52605. return this._firstDayOfWeek;
  52606. },
  52607. /**
  52608. * get date info
  52609. *
  52610. * @param {string|number} date date
  52611. * @return {Object}
  52612. * {
  52613. * y: string, local full year, eg., '1940',
  52614. * m: string, local month, from '01' ot '12',
  52615. * d: string, local date, from '01' to '31' (if exists),
  52616. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  52617. * time: timestamp,
  52618. * formatedDate: string, yyyy-MM-dd,
  52619. * date: original date object.
  52620. * }
  52621. */
  52622. getDateInfo: function (date) {
  52623. date = parseDate(date);
  52624. var y = date.getFullYear();
  52625. var m = date.getMonth() + 1;
  52626. m = m < 10 ? '0' + m : m;
  52627. var d = date.getDate();
  52628. d = d < 10 ? '0' + d : d;
  52629. var day = date.getDay();
  52630. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  52631. return {
  52632. y: y,
  52633. m: m,
  52634. d: d,
  52635. day: day,
  52636. time: date.getTime(),
  52637. formatedDate: y + '-' + m + '-' + d,
  52638. date: date
  52639. };
  52640. },
  52641. getNextNDay: function (date, n) {
  52642. n = n || 0;
  52643. if (n === 0) {
  52644. return this.getDateInfo(date);
  52645. }
  52646. date = new Date(this.getDateInfo(date).time);
  52647. date.setDate(date.getDate() + n);
  52648. return this.getDateInfo(date);
  52649. },
  52650. update: function (ecModel, api) {
  52651. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  52652. this._orient = this._model.get('orient');
  52653. this._lineWidth = this._model.getModel('itemStyle.normal').getItemStyle().lineWidth || 0;
  52654. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  52655. var weeks = this._rangeInfo.weeks || 1;
  52656. var whNames = ['width', 'height'];
  52657. var cellSize = this._model.get('cellSize').slice();
  52658. var layoutParams = this._model.getBoxLayoutParams();
  52659. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  52660. each$1([0, 1], function (idx) {
  52661. if (cellSizeSpecified(cellSize, idx)) {
  52662. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  52663. }
  52664. });
  52665. var whGlobal = {
  52666. width: api.getWidth(),
  52667. height: api.getHeight()
  52668. };
  52669. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  52670. each$1([0, 1], function (idx) {
  52671. if (!cellSizeSpecified(cellSize, idx)) {
  52672. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  52673. }
  52674. });
  52675. function cellSizeSpecified(cellSize, idx) {
  52676. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  52677. }
  52678. this._sw = cellSize[0];
  52679. this._sh = cellSize[1];
  52680. },
  52681. /**
  52682. * Convert a time data(time, value) item to (x, y) point.
  52683. *
  52684. * @override
  52685. * @param {Array|number} data data
  52686. * @param {boolean} [clamp=true] out of range
  52687. * @return {Array} point
  52688. */
  52689. dataToPoint: function (data, clamp) {
  52690. isArray(data) && (data = data[0]);
  52691. clamp == null && (clamp = true);
  52692. var dayInfo = this.getDateInfo(data);
  52693. var range = this._rangeInfo;
  52694. var date = dayInfo.formatedDate;
  52695. // if not in range return [NaN, NaN]
  52696. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) {
  52697. return [NaN, NaN];
  52698. }
  52699. var week = dayInfo.day;
  52700. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  52701. if (this._orient === 'vertical') {
  52702. return [
  52703. this._rect.x + week * this._sw + this._sw / 2,
  52704. this._rect.y + nthWeek * this._sh + this._sh / 2
  52705. ];
  52706. }
  52707. return [
  52708. this._rect.x + nthWeek * this._sw + this._sw / 2,
  52709. this._rect.y + week * this._sh + this._sh / 2
  52710. ];
  52711. },
  52712. /**
  52713. * Convert a (x, y) point to time data
  52714. *
  52715. * @override
  52716. * @param {string} point point
  52717. * @return {string} data
  52718. */
  52719. pointToData: function (point) {
  52720. var date = this.pointToDate(point);
  52721. return date && date.time;
  52722. },
  52723. /**
  52724. * Convert a time date item to (x, y) four point.
  52725. *
  52726. * @param {Array} data date[0] is date
  52727. * @param {boolean} [clamp=true] out of range
  52728. * @return {Object} point
  52729. */
  52730. dataToRect: function (data, clamp) {
  52731. var point = this.dataToPoint(data, clamp);
  52732. return {
  52733. contentShape: {
  52734. x: point[0] - (this._sw - this._lineWidth) / 2,
  52735. y: point[1] - (this._sh - this._lineWidth) / 2,
  52736. width: this._sw - this._lineWidth,
  52737. height: this._sh - this._lineWidth
  52738. },
  52739. center: point,
  52740. tl: [
  52741. point[0] - this._sw / 2,
  52742. point[1] - this._sh / 2
  52743. ],
  52744. tr: [
  52745. point[0] + this._sw / 2,
  52746. point[1] - this._sh / 2
  52747. ],
  52748. br: [
  52749. point[0] + this._sw / 2,
  52750. point[1] + this._sh / 2
  52751. ],
  52752. bl: [
  52753. point[0] - this._sw / 2,
  52754. point[1] + this._sh / 2
  52755. ]
  52756. };
  52757. },
  52758. /**
  52759. * Convert a (x, y) point to time date
  52760. *
  52761. * @param {Array} point point
  52762. * @return {Object} date
  52763. */
  52764. pointToDate: function (point) {
  52765. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  52766. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  52767. var range = this._rangeInfo.range;
  52768. if (this._orient === 'vertical') {
  52769. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  52770. }
  52771. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  52772. },
  52773. /**
  52774. * @inheritDoc
  52775. */
  52776. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  52777. /**
  52778. * @inheritDoc
  52779. */
  52780. convertFromPixel: curry(doConvert$2, 'pointToData'),
  52781. /**
  52782. * initRange
  52783. *
  52784. * @private
  52785. * @return {Array} [start, end]
  52786. */
  52787. _initRangeOption: function () {
  52788. var range = this._model.get('range');
  52789. var rg = range;
  52790. if (isArray(rg) && rg.length === 1) {
  52791. rg = rg[0];
  52792. }
  52793. if (/^\d{4}$/.test(rg)) {
  52794. range = [rg + '-01-01', rg + '-12-31'];
  52795. }
  52796. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  52797. var start = this.getDateInfo(rg);
  52798. var firstDay = start.date;
  52799. firstDay.setMonth(firstDay.getMonth() + 1);
  52800. var end = this.getNextNDay(firstDay, -1);
  52801. range = [start.formatedDate, end.formatedDate];
  52802. }
  52803. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  52804. range = [rg, rg];
  52805. }
  52806. var tmp = this._getRangeInfo(range);
  52807. if (tmp.start.time > tmp.end.time) {
  52808. range.reverse();
  52809. }
  52810. return range;
  52811. },
  52812. /**
  52813. * range info
  52814. *
  52815. * @private
  52816. * @param {Array} range range ['2017-01-01', '2017-07-08']
  52817. * If range[0] > range[1], they will not be reversed.
  52818. * @return {Object} obj
  52819. */
  52820. _getRangeInfo: function (range) {
  52821. range = [
  52822. this.getDateInfo(range[0]),
  52823. this.getDateInfo(range[1])
  52824. ];
  52825. var reversed;
  52826. if (range[0].time > range[1].time) {
  52827. reversed = true;
  52828. range.reverse();
  52829. }
  52830. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  52831. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  52832. // Consider case:
  52833. // Firstly set system timezone as "Time Zone: America/Toronto",
  52834. // ```
  52835. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  52836. // var second = new Date(1478412000000);
  52837. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  52838. // ```
  52839. // will get wrong result because of DST. So we should fix it.
  52840. var date = new Date(range[0].time);
  52841. var startDateNum = date.getDate();
  52842. var endDateNum = range[1].date.getDate();
  52843. date.setDate(startDateNum + allDay - 1);
  52844. // The bias can not over a month, so just compare date.
  52845. if (date.getDate() !== endDateNum) {
  52846. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  52847. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  52848. allDay -= sign;
  52849. date.setDate(startDateNum + allDay - 1);
  52850. }
  52851. }
  52852. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  52853. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  52854. reversed && range.reverse();
  52855. return {
  52856. range: [range[0].formatedDate, range[1].formatedDate],
  52857. start: range[0],
  52858. end: range[1],
  52859. allDay: allDay,
  52860. weeks: weeks,
  52861. // From 0.
  52862. nthWeek: nthWeek,
  52863. fweek: range[0].day,
  52864. lweek: range[1].day
  52865. };
  52866. },
  52867. /**
  52868. * get date by nthWeeks and week day in range
  52869. *
  52870. * @private
  52871. * @param {number} nthWeek the week
  52872. * @param {number} day the week day
  52873. * @param {Array} range [d1, d2]
  52874. * @return {Object}
  52875. */
  52876. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  52877. var rangeInfo = this._getRangeInfo(range);
  52878. if (nthWeek > rangeInfo.weeks
  52879. || (nthWeek === 0 && day < rangeInfo.fweek)
  52880. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  52881. ) {
  52882. return false;
  52883. }
  52884. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  52885. var date = new Date(rangeInfo.start.time);
  52886. date.setDate(rangeInfo.start.d + nthDay);
  52887. return this.getDateInfo(date);
  52888. }
  52889. };
  52890. Calendar.dimensions = Calendar.prototype.dimensions;
  52891. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  52892. Calendar.create = function (ecModel, api) {
  52893. var calendarList = [];
  52894. ecModel.eachComponent('calendar', function (calendarModel) {
  52895. var calendar = new Calendar(calendarModel, ecModel, api);
  52896. calendarList.push(calendar);
  52897. calendarModel.coordinateSystem = calendar;
  52898. });
  52899. ecModel.eachSeries(function (calendarSeries) {
  52900. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  52901. // Inject coordinate system
  52902. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  52903. }
  52904. });
  52905. return calendarList;
  52906. };
  52907. function doConvert$2(methodName, ecModel, finder, value) {
  52908. var calendarModel = finder.calendarModel;
  52909. var seriesModel = finder.seriesModel;
  52910. var coordSys = calendarModel
  52911. ? calendarModel.coordinateSystem
  52912. : seriesModel
  52913. ? seriesModel.coordinateSystem
  52914. : null;
  52915. return coordSys === this ? coordSys[methodName](value) : null;
  52916. }
  52917. CoordinateSystemManager.register('calendar', Calendar);
  52918. var CalendarModel = ComponentModel.extend({
  52919. type: 'calendar',
  52920. /**
  52921. * @type {module:echarts/coord/calendar/Calendar}
  52922. */
  52923. coordinateSystem: null,
  52924. defaultOption: {
  52925. zlevel: 0,
  52926. z: 2,
  52927. left: 80,
  52928. top: 60,
  52929. cellSize: 20,
  52930. // horizontal vertical
  52931. orient: 'horizontal',
  52932. // month separate line style
  52933. splitLine: {
  52934. show: true,
  52935. lineStyle: {
  52936. color: '#000',
  52937. width: 1,
  52938. type: 'solid'
  52939. }
  52940. },
  52941. // rect style temporarily unused emphasis
  52942. itemStyle: {
  52943. normal: {
  52944. color: '#fff',
  52945. borderWidth: 1,
  52946. borderColor: '#ccc'
  52947. }
  52948. },
  52949. // week text style
  52950. dayLabel: {
  52951. show: true,
  52952. // a week first day
  52953. firstDay: 0,
  52954. // start end
  52955. position: 'start',
  52956. margin: '50%', // 50% of cellSize
  52957. nameMap: 'en',
  52958. color: '#000'
  52959. },
  52960. // month text style
  52961. monthLabel: {
  52962. show: true,
  52963. // start end
  52964. position: 'start',
  52965. margin: 5,
  52966. // center or left
  52967. align: 'center',
  52968. // cn en []
  52969. nameMap: 'en',
  52970. formatter: null,
  52971. color: '#000'
  52972. },
  52973. // year text style
  52974. yearLabel: {
  52975. show: true,
  52976. // top bottom left right
  52977. position: null,
  52978. margin: 30,
  52979. formatter: null,
  52980. color: '#ccc',
  52981. fontFamily: 'sans-serif',
  52982. fontWeight: 'bolder',
  52983. fontSize: 20
  52984. }
  52985. },
  52986. /**
  52987. * @override
  52988. */
  52989. init: function (option, parentModel, ecModel, extraOpt) {
  52990. var inputPositionParams = getLayoutParams(option);
  52991. CalendarModel.superApply(this, 'init', arguments);
  52992. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  52993. },
  52994. /**
  52995. * @override
  52996. */
  52997. mergeOption: function (option, extraOpt) {
  52998. CalendarModel.superApply(this, 'mergeOption', arguments);
  52999. mergeAndNormalizeLayoutParams$1(this.option, option);
  53000. }
  53001. });
  53002. function mergeAndNormalizeLayoutParams$1(target, raw) {
  53003. // Normalize cellSize
  53004. var cellSize = target.cellSize;
  53005. if (!isArray(cellSize)) {
  53006. cellSize = target.cellSize = [cellSize, cellSize];
  53007. }
  53008. else if (cellSize.length === 1) {
  53009. cellSize[1] = cellSize[0];
  53010. }
  53011. var ignoreSize = map([0, 1], function (hvIdx) {
  53012. // If user have set `width` or both `left` and `right`, cellSize
  53013. // will be automatically set to 'auto', otherwise the default
  53014. // setting of cellSize will make `width` setting not work.
  53015. if (sizeCalculable(raw, hvIdx)) {
  53016. cellSize[hvIdx] = 'auto';
  53017. }
  53018. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  53019. });
  53020. mergeLayoutParam(target, raw, {
  53021. type: 'box', ignoreSize: ignoreSize
  53022. });
  53023. }
  53024. var MONTH_TEXT = {
  53025. EN: [
  53026. 'Jan', 'Feb', 'Mar',
  53027. 'Apr', 'May', 'Jun',
  53028. 'Jul', 'Aug', 'Sep',
  53029. 'Oct', 'Nov', 'Dec'
  53030. ],
  53031. CN: [
  53032. '一月', '二月', '三月',
  53033. '四月', '五月', '六月',
  53034. '七月', '八月', '九月',
  53035. '十月', '十一月', '十二月'
  53036. ]
  53037. };
  53038. var WEEK_TEXT = {
  53039. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  53040. CN: ['日', '一', '二', '三', '四', '五', '六']
  53041. };
  53042. extendComponentView({
  53043. type: 'calendar',
  53044. /**
  53045. * top/left line points
  53046. * @private
  53047. */
  53048. _tlpoints: null,
  53049. /**
  53050. * bottom/right line points
  53051. * @private
  53052. */
  53053. _blpoints: null,
  53054. /**
  53055. * first day of month
  53056. * @private
  53057. */
  53058. _firstDayOfMonth: null,
  53059. /**
  53060. * first day point of month
  53061. * @private
  53062. */
  53063. _firstDayPoints: null,
  53064. render: function (calendarModel, ecModel, api) {
  53065. var group = this.group;
  53066. group.removeAll();
  53067. var coordSys = calendarModel.coordinateSystem;
  53068. // range info
  53069. var rangeData = coordSys.getRangeInfo();
  53070. var orient = coordSys.getOrient();
  53071. this._renderDayRect(calendarModel, rangeData, group);
  53072. // _renderLines must be called prior to following function
  53073. this._renderLines(calendarModel, rangeData, orient, group);
  53074. this._renderYearText(calendarModel, rangeData, orient, group);
  53075. this._renderMonthText(calendarModel, orient, group);
  53076. this._renderWeekText(calendarModel, rangeData, orient, group);
  53077. },
  53078. // render day rect
  53079. _renderDayRect: function (calendarModel, rangeData, group) {
  53080. var coordSys = calendarModel.coordinateSystem;
  53081. var itemRectStyleModel = calendarModel.getModel('itemStyle.normal').getItemStyle();
  53082. var sw = coordSys.getCellWidth();
  53083. var sh = coordSys.getCellHeight();
  53084. for (var i = rangeData.start.time;
  53085. i <= rangeData.end.time;
  53086. i = coordSys.getNextNDay(i, 1).time
  53087. ) {
  53088. var point = coordSys.dataToRect([i], false).tl;
  53089. // every rect
  53090. var rect = new Rect({
  53091. shape: {
  53092. x: point[0],
  53093. y: point[1],
  53094. width: sw,
  53095. height: sh
  53096. },
  53097. cursor: 'default',
  53098. style: itemRectStyleModel
  53099. });
  53100. group.add(rect);
  53101. }
  53102. },
  53103. // render separate line
  53104. _renderLines: function (calendarModel, rangeData, orient, group) {
  53105. var self = this;
  53106. var coordSys = calendarModel.coordinateSystem;
  53107. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  53108. var show = calendarModel.get('splitLine.show');
  53109. var lineWidth = lineStyleModel.lineWidth;
  53110. this._tlpoints = [];
  53111. this._blpoints = [];
  53112. this._firstDayOfMonth = [];
  53113. this._firstDayPoints = [];
  53114. var firstDay = rangeData.start;
  53115. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  53116. addPoints(firstDay.formatedDate);
  53117. if (i === 0) {
  53118. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  53119. }
  53120. var date = firstDay.date;
  53121. date.setMonth(date.getMonth() + 1);
  53122. firstDay = coordSys.getDateInfo(date);
  53123. }
  53124. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  53125. function addPoints(date) {
  53126. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  53127. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  53128. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  53129. self._tlpoints.push(points[0]);
  53130. self._blpoints.push(points[points.length - 1]);
  53131. show && self._drawSplitline(points, lineStyleModel, group);
  53132. }
  53133. // render top/left line
  53134. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  53135. // render bottom/right line
  53136. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  53137. },
  53138. // get points at both ends
  53139. _getEdgesPoints: function (points, lineWidth, orient) {
  53140. var rs = [points[0].slice(), points[points.length - 1].slice()];
  53141. var idx = orient === 'horizontal' ? 0 : 1;
  53142. // both ends of the line are extend half lineWidth
  53143. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  53144. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  53145. return rs;
  53146. },
  53147. // render split line
  53148. _drawSplitline: function (points, lineStyleModel, group) {
  53149. var poyline = new Polyline({
  53150. z2: 20,
  53151. shape: {
  53152. points: points
  53153. },
  53154. style: lineStyleModel
  53155. });
  53156. group.add(poyline);
  53157. },
  53158. // render month line of one week points
  53159. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  53160. var coordSys = calendarModel.coordinateSystem;
  53161. date = coordSys.getDateInfo(date);
  53162. var points = [];
  53163. for (var i = 0; i < 7; i++) {
  53164. var tmpD = coordSys.getNextNDay(date.time, i);
  53165. var point = coordSys.dataToRect([tmpD.time], false);
  53166. points[2 * tmpD.day] = point.tl;
  53167. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  53168. }
  53169. return points;
  53170. },
  53171. _formatterLabel: function (formatter, params) {
  53172. if (typeof formatter === 'string' && formatter) {
  53173. return formatTplSimple(formatter, params);
  53174. }
  53175. if (typeof formatter === 'function') {
  53176. return formatter(params);
  53177. }
  53178. return params.nameMap;
  53179. },
  53180. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  53181. point = point.slice();
  53182. var aligns = ['center', 'bottom'];
  53183. if (position === 'bottom') {
  53184. point[1] += margin;
  53185. aligns = ['center', 'top'];
  53186. }
  53187. else if (position === 'left') {
  53188. point[0] -= margin;
  53189. }
  53190. else if (position === 'right') {
  53191. point[0] += margin;
  53192. aligns = ['center', 'top'];
  53193. }
  53194. else { // top
  53195. point[1] -= margin;
  53196. }
  53197. var rotate = 0;
  53198. if (position === 'left' || position === 'right') {
  53199. rotate = Math.PI / 2;
  53200. }
  53201. return {
  53202. rotation: rotate,
  53203. position: point,
  53204. style: {
  53205. textAlign: aligns[0],
  53206. textVerticalAlign: aligns[1]
  53207. }
  53208. };
  53209. },
  53210. // render year
  53211. _renderYearText: function (calendarModel, rangeData, orient, group) {
  53212. var yearLabel = calendarModel.getModel('yearLabel');
  53213. if (!yearLabel.get('show')) {
  53214. return;
  53215. }
  53216. var margin = yearLabel.get('margin');
  53217. var pos = yearLabel.get('position');
  53218. if (!pos) {
  53219. pos = orient !== 'horizontal' ? 'top' : 'left';
  53220. }
  53221. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  53222. var xc = (points[0][0] + points[1][0]) / 2;
  53223. var yc = (points[0][1] + points[1][1]) / 2;
  53224. var idx = orient === 'horizontal' ? 0 : 1;
  53225. var posPoints = {
  53226. top: [xc, points[idx][1]],
  53227. bottom: [xc, points[1 - idx][1]],
  53228. left: [points[1 - idx][0], yc],
  53229. right: [points[idx][0], yc]
  53230. };
  53231. var name = rangeData.start.y;
  53232. if (+rangeData.end.y > +rangeData.start.y) {
  53233. name = name + '-' + rangeData.end.y;
  53234. }
  53235. var formatter = yearLabel.get('formatter');
  53236. var params = {
  53237. start: rangeData.start.y,
  53238. end: rangeData.end.y,
  53239. nameMap: name
  53240. };
  53241. var content = this._formatterLabel(formatter, params);
  53242. var yearText = new Text({z2: 30});
  53243. setTextStyle(yearText.style, yearLabel, {text: content}),
  53244. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  53245. group.add(yearText);
  53246. },
  53247. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  53248. var align = 'left';
  53249. var vAlign = 'top';
  53250. var x = point[0];
  53251. var y = point[1];
  53252. if (orient === 'horizontal') {
  53253. y = y + margin;
  53254. if (isCenter) {
  53255. align = 'center';
  53256. }
  53257. if (position === 'start') {
  53258. vAlign = 'bottom';
  53259. }
  53260. }
  53261. else {
  53262. x = x + margin;
  53263. if (isCenter) {
  53264. vAlign = 'middle';
  53265. }
  53266. if (position === 'start') {
  53267. align = 'right';
  53268. }
  53269. }
  53270. return {
  53271. x: x,
  53272. y: y,
  53273. textAlign: align,
  53274. textVerticalAlign: vAlign
  53275. };
  53276. },
  53277. // render month and year text
  53278. _renderMonthText: function (calendarModel, orient, group) {
  53279. var monthLabel = calendarModel.getModel('monthLabel');
  53280. if (!monthLabel.get('show')) {
  53281. return;
  53282. }
  53283. var nameMap = monthLabel.get('nameMap');
  53284. var margin = monthLabel.get('margin');
  53285. var pos = monthLabel.get('position');
  53286. var align = monthLabel.get('align');
  53287. var termPoints = [this._tlpoints, this._blpoints];
  53288. if (isString(nameMap)) {
  53289. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  53290. }
  53291. var idx = pos === 'start' ? 0 : 1;
  53292. var axis = orient === 'horizontal' ? 0 : 1;
  53293. margin = pos === 'start' ? -margin : margin;
  53294. var isCenter = (align === 'center');
  53295. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  53296. var tmp = termPoints[idx][i].slice();
  53297. var firstDay = this._firstDayOfMonth[i];
  53298. if (isCenter) {
  53299. var firstDayPoints = this._firstDayPoints[i];
  53300. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  53301. }
  53302. var formatter = monthLabel.get('formatter');
  53303. var name = nameMap[+firstDay.m - 1];
  53304. var params = {
  53305. yyyy: firstDay.y,
  53306. yy: (firstDay.y + '').slice(2),
  53307. MM: firstDay.m,
  53308. M: +firstDay.m,
  53309. nameMap: name
  53310. };
  53311. var content = this._formatterLabel(formatter, params);
  53312. var monthText = new Text({z2: 30});
  53313. extend(
  53314. setTextStyle(monthText.style, monthLabel, {text: content}),
  53315. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  53316. );
  53317. group.add(monthText);
  53318. }
  53319. },
  53320. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  53321. var align = 'center';
  53322. var vAlign = 'middle';
  53323. var x = point[0];
  53324. var y = point[1];
  53325. var isStart = position === 'start';
  53326. if (orient === 'horizontal') {
  53327. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  53328. align = isStart ? 'right' : 'left';
  53329. }
  53330. else {
  53331. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  53332. vAlign = isStart ? 'bottom' : 'top';
  53333. }
  53334. return {
  53335. x: x,
  53336. y: y,
  53337. textAlign: align,
  53338. textVerticalAlign: vAlign
  53339. };
  53340. },
  53341. // render weeks
  53342. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  53343. var dayLabel = calendarModel.getModel('dayLabel');
  53344. if (!dayLabel.get('show')) {
  53345. return;
  53346. }
  53347. var coordSys = calendarModel.coordinateSystem;
  53348. var pos = dayLabel.get('position');
  53349. var nameMap = dayLabel.get('nameMap');
  53350. var margin = dayLabel.get('margin');
  53351. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  53352. if (isString(nameMap)) {
  53353. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  53354. }
  53355. var start = coordSys.getNextNDay(
  53356. rangeData.end.time, (7 - rangeData.lweek)
  53357. ).time;
  53358. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  53359. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  53360. if (pos === 'start') {
  53361. start = coordSys.getNextNDay(
  53362. rangeData.start.time, -(7 + rangeData.fweek)
  53363. ).time;
  53364. margin = -margin;
  53365. }
  53366. for (var i = 0; i < 7; i++) {
  53367. var tmpD = coordSys.getNextNDay(start, i);
  53368. var point = coordSys.dataToRect([tmpD.time], false).center;
  53369. var day = i;
  53370. day = Math.abs((i + firstDayOfWeek) % 7);
  53371. var weekText = new Text({z2: 30});
  53372. extend(
  53373. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  53374. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  53375. );
  53376. group.add(weekText);
  53377. }
  53378. }
  53379. });
  53380. /**
  53381. * @file calendar.js
  53382. * @author dxh
  53383. */
  53384. // Model
  53385. extendComponentModel({
  53386. type: 'title',
  53387. layoutMode: {type: 'box', ignoreSize: true},
  53388. defaultOption: {
  53389. // 一级层叠
  53390. zlevel: 0,
  53391. // 二级层叠
  53392. z: 6,
  53393. show: true,
  53394. text: '',
  53395. // 超链接跳转
  53396. // link: null,
  53397. // 仅支持self | blank
  53398. target: 'blank',
  53399. subtext: '',
  53400. // 超链接跳转
  53401. // sublink: null,
  53402. // 仅支持self | blank
  53403. subtarget: 'blank',
  53404. // 'center' ¦ 'left' ¦ 'right'
  53405. // ¦ {number}(x坐标,单位px)
  53406. left: 0,
  53407. // 'top' ¦ 'bottom' ¦ 'center'
  53408. // ¦ {number}(y坐标,单位px)
  53409. top: 0,
  53410. // 水平对齐
  53411. // 'auto' | 'left' | 'right' | 'center'
  53412. // 默认根据 left 的位置判断是左对齐还是右对齐
  53413. // textAlign: null
  53414. //
  53415. // 垂直对齐
  53416. // 'auto' | 'top' | 'bottom' | 'middle'
  53417. // 默认根据 top 位置判断是上对齐还是下对齐
  53418. // textBaseline: null
  53419. backgroundColor: 'rgba(0,0,0,0)',
  53420. // 标题边框颜色
  53421. borderColor: '#ccc',
  53422. // 标题边框线宽,单位px,默认为0(无边框)
  53423. borderWidth: 0,
  53424. // 标题内边距,单位px,默认各方向内边距为5,
  53425. // 接受数组分别设定上右下左边距,同css
  53426. padding: 5,
  53427. // 主副标题纵向间隔,单位px,默认为10,
  53428. itemGap: 10,
  53429. textStyle: {
  53430. fontSize: 18,
  53431. fontWeight: 'bolder',
  53432. color: '#333'
  53433. },
  53434. subtextStyle: {
  53435. color: '#aaa'
  53436. }
  53437. }
  53438. });
  53439. // View
  53440. extendComponentView({
  53441. type: 'title',
  53442. render: function (titleModel, ecModel, api) {
  53443. this.group.removeAll();
  53444. if (!titleModel.get('show')) {
  53445. return;
  53446. }
  53447. var group = this.group;
  53448. var textStyleModel = titleModel.getModel('textStyle');
  53449. var subtextStyleModel = titleModel.getModel('subtextStyle');
  53450. var textAlign = titleModel.get('textAlign');
  53451. var textBaseline = titleModel.get('textBaseline');
  53452. var textEl = new Text({
  53453. style: setTextStyle({}, textStyleModel, {
  53454. text: titleModel.get('text'),
  53455. textFill: textStyleModel.getTextColor()
  53456. }, {disableBox: true}),
  53457. z2: 10
  53458. });
  53459. var textRect = textEl.getBoundingRect();
  53460. var subText = titleModel.get('subtext');
  53461. var subTextEl = new Text({
  53462. style: setTextStyle({}, subtextStyleModel, {
  53463. text: subText,
  53464. textFill: subtextStyleModel.getTextColor(),
  53465. y: textRect.height + titleModel.get('itemGap'),
  53466. textVerticalAlign: 'top'
  53467. }, {disableBox: true}),
  53468. z2: 10
  53469. });
  53470. var link = titleModel.get('link');
  53471. var sublink = titleModel.get('sublink');
  53472. textEl.silent = !link;
  53473. subTextEl.silent = !sublink;
  53474. if (link) {
  53475. textEl.on('click', function () {
  53476. window.open(link, '_' + titleModel.get('target'));
  53477. });
  53478. }
  53479. if (sublink) {
  53480. subTextEl.on('click', function () {
  53481. window.open(sublink, '_' + titleModel.get('subtarget'));
  53482. });
  53483. }
  53484. group.add(textEl);
  53485. subText && group.add(subTextEl);
  53486. // If no subText, but add subTextEl, there will be an empty line.
  53487. var groupRect = group.getBoundingRect();
  53488. var layoutOption = titleModel.getBoxLayoutParams();
  53489. layoutOption.width = groupRect.width;
  53490. layoutOption.height = groupRect.height;
  53491. var layoutRect = getLayoutRect(
  53492. layoutOption, {
  53493. width: api.getWidth(),
  53494. height: api.getHeight()
  53495. }, titleModel.get('padding')
  53496. );
  53497. // Adjust text align based on position
  53498. if (!textAlign) {
  53499. // Align left if title is on the left. center and right is same
  53500. textAlign = titleModel.get('left') || titleModel.get('right');
  53501. if (textAlign === 'middle') {
  53502. textAlign = 'center';
  53503. }
  53504. // Adjust layout by text align
  53505. if (textAlign === 'right') {
  53506. layoutRect.x += layoutRect.width;
  53507. }
  53508. else if (textAlign === 'center') {
  53509. layoutRect.x += layoutRect.width / 2;
  53510. }
  53511. }
  53512. if (!textBaseline) {
  53513. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  53514. if (textBaseline === 'center') {
  53515. textBaseline = 'middle';
  53516. }
  53517. if (textBaseline === 'bottom') {
  53518. layoutRect.y += layoutRect.height;
  53519. }
  53520. else if (textBaseline === 'middle') {
  53521. layoutRect.y += layoutRect.height / 2;
  53522. }
  53523. textBaseline = textBaseline || 'top';
  53524. }
  53525. group.attr('position', [layoutRect.x, layoutRect.y]);
  53526. var alignStyle = {
  53527. textAlign: textAlign,
  53528. textVerticalAlign: textBaseline
  53529. };
  53530. textEl.setStyle(alignStyle);
  53531. subTextEl.setStyle(alignStyle);
  53532. // Render background
  53533. // Get groupRect again because textAlign has been changed
  53534. groupRect = group.getBoundingRect();
  53535. var padding = layoutRect.margin;
  53536. var style = titleModel.getItemStyle(['color', 'opacity']);
  53537. style.fill = titleModel.get('backgroundColor');
  53538. var rect = new Rect({
  53539. shape: {
  53540. x: groupRect.x - padding[3],
  53541. y: groupRect.y - padding[0],
  53542. width: groupRect.width + padding[1] + padding[3],
  53543. height: groupRect.height + padding[0] + padding[2],
  53544. r: titleModel.get('borderRadius')
  53545. },
  53546. style: style,
  53547. silent: true
  53548. });
  53549. subPixelOptimizeRect(rect);
  53550. group.add(rect);
  53551. }
  53552. });
  53553. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  53554. // Default 'slider' when no type specified.
  53555. return 'slider';
  53556. });
  53557. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  53558. // Supported coords.
  53559. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  53560. /**
  53561. * @param {string} coordType
  53562. * @return {boolean}
  53563. */
  53564. function isCoordSupported(coordType) {
  53565. return indexOf(COORDS, coordType) >= 0;
  53566. }
  53567. /**
  53568. * Create "each" method to iterate names.
  53569. *
  53570. * @pubilc
  53571. * @param {Array.<string>} names
  53572. * @param {Array.<string>=} attrs
  53573. * @return {Function}
  53574. */
  53575. function createNameEach(names, attrs) {
  53576. names = names.slice();
  53577. var capitalNames = map(names, capitalFirst);
  53578. attrs = (attrs || []).slice();
  53579. var capitalAttrs = map(attrs, capitalFirst);
  53580. return function (callback, context) {
  53581. each$1(names, function (name, index) {
  53582. var nameObj = {name: name, capital: capitalNames[index]};
  53583. for (var j = 0; j < attrs.length; j++) {
  53584. nameObj[attrs[j]] = name + capitalAttrs[j];
  53585. }
  53586. callback.call(context, nameObj);
  53587. });
  53588. };
  53589. }
  53590. /**
  53591. * Iterate each dimension name.
  53592. *
  53593. * @public
  53594. * @param {Function} callback The parameter is like:
  53595. * {
  53596. * name: 'angle',
  53597. * capital: 'Angle',
  53598. * axis: 'angleAxis',
  53599. * axisIndex: 'angleAixs',
  53600. * index: 'angleIndex'
  53601. * }
  53602. * @param {Object} context
  53603. */
  53604. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  53605. /**
  53606. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  53607. * dataZoomModels and 'links' make up one or more graphics.
  53608. * This function finds the graphic where the source dataZoomModel is in.
  53609. *
  53610. * @public
  53611. * @param {Function} forEachNode Node iterator.
  53612. * @param {Function} forEachEdgeType edgeType iterator
  53613. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  53614. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  53615. */
  53616. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  53617. return function (sourceNode) {
  53618. var result = {
  53619. nodes: [],
  53620. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  53621. };
  53622. forEachEdgeType(function (edgeType) {
  53623. result.records[edgeType.name] = {};
  53624. });
  53625. if (!sourceNode) {
  53626. return result;
  53627. }
  53628. absorb(sourceNode, result);
  53629. var existsLink;
  53630. do {
  53631. existsLink = false;
  53632. forEachNode(processSingleNode);
  53633. }
  53634. while (existsLink);
  53635. function processSingleNode(node) {
  53636. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  53637. absorb(node, result);
  53638. existsLink = true;
  53639. }
  53640. }
  53641. return result;
  53642. };
  53643. function isNodeAbsorded(node, result) {
  53644. return indexOf(result.nodes, node) >= 0;
  53645. }
  53646. function isLinked(node, result) {
  53647. var hasLink = false;
  53648. forEachEdgeType(function (edgeType) {
  53649. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  53650. result.records[edgeType.name][edgeId] && (hasLink = true);
  53651. });
  53652. });
  53653. return hasLink;
  53654. }
  53655. function absorb(node, result) {
  53656. result.nodes.push(node);
  53657. forEachEdgeType(function (edgeType) {
  53658. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  53659. result.records[edgeType.name][edgeId] = true;
  53660. });
  53661. });
  53662. }
  53663. }
  53664. var each$25 = each$1;
  53665. var asc$1 = asc;
  53666. /**
  53667. * Operate single axis.
  53668. * One axis can only operated by one axis operator.
  53669. * Different dataZoomModels may be defined to operate the same axis.
  53670. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  53671. * So dataZoomModels share one axisProxy in that case.
  53672. *
  53673. * @class
  53674. */
  53675. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  53676. /**
  53677. * @private
  53678. * @type {string}
  53679. */
  53680. this._dimName = dimName;
  53681. /**
  53682. * @private
  53683. */
  53684. this._axisIndex = axisIndex;
  53685. /**
  53686. * @private
  53687. * @type {Array.<number>}
  53688. */
  53689. this._valueWindow;
  53690. /**
  53691. * @private
  53692. * @type {Array.<number>}
  53693. */
  53694. this._percentWindow;
  53695. /**
  53696. * @private
  53697. * @type {Array.<number>}
  53698. */
  53699. this._dataExtent;
  53700. /**
  53701. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  53702. * @private
  53703. * @type {Object}
  53704. */
  53705. this._minMaxSpan;
  53706. /**
  53707. * @readOnly
  53708. * @type {module: echarts/model/Global}
  53709. */
  53710. this.ecModel = ecModel;
  53711. /**
  53712. * @private
  53713. * @type {module: echarts/component/dataZoom/DataZoomModel}
  53714. */
  53715. this._dataZoomModel = dataZoomModel;
  53716. };
  53717. AxisProxy.prototype = {
  53718. constructor: AxisProxy,
  53719. /**
  53720. * Whether the axisProxy is hosted by dataZoomModel.
  53721. *
  53722. * @public
  53723. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53724. * @return {boolean}
  53725. */
  53726. hostedBy: function (dataZoomModel) {
  53727. return this._dataZoomModel === dataZoomModel;
  53728. },
  53729. /**
  53730. * @return {Array.<number>} Value can only be NaN or finite value.
  53731. */
  53732. getDataValueWindow: function () {
  53733. return this._valueWindow.slice();
  53734. },
  53735. /**
  53736. * @return {Array.<number>}
  53737. */
  53738. getDataPercentWindow: function () {
  53739. return this._percentWindow.slice();
  53740. },
  53741. /**
  53742. * @public
  53743. * @param {number} axisIndex
  53744. * @return {Array} seriesModels
  53745. */
  53746. getTargetSeriesModels: function () {
  53747. var seriesModels = [];
  53748. var ecModel = this.ecModel;
  53749. ecModel.eachSeries(function (seriesModel) {
  53750. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  53751. var dimName = this._dimName;
  53752. var axisModel = ecModel.queryComponents({
  53753. mainType: dimName + 'Axis',
  53754. index: seriesModel.get(dimName + 'AxisIndex'),
  53755. id: seriesModel.get(dimName + 'AxisId')
  53756. })[0];
  53757. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  53758. seriesModels.push(seriesModel);
  53759. }
  53760. }
  53761. }, this);
  53762. return seriesModels;
  53763. },
  53764. getAxisModel: function () {
  53765. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  53766. },
  53767. getOtherAxisModel: function () {
  53768. var axisDim = this._dimName;
  53769. var ecModel = this.ecModel;
  53770. var axisModel = this.getAxisModel();
  53771. var isCartesian = axisDim === 'x' || axisDim === 'y';
  53772. var otherAxisDim;
  53773. var coordSysIndexName;
  53774. if (isCartesian) {
  53775. coordSysIndexName = 'gridIndex';
  53776. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  53777. }
  53778. else {
  53779. coordSysIndexName = 'polarIndex';
  53780. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  53781. }
  53782. var foundOtherAxisModel;
  53783. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  53784. if ((otherAxisModel.get(coordSysIndexName) || 0)
  53785. === (axisModel.get(coordSysIndexName) || 0)
  53786. ) {
  53787. foundOtherAxisModel = otherAxisModel;
  53788. }
  53789. });
  53790. return foundOtherAxisModel;
  53791. },
  53792. getMinMaxSpan: function () {
  53793. return clone(this._minMaxSpan);
  53794. },
  53795. /**
  53796. * Only calculate by given range and this._dataExtent, do not change anything.
  53797. *
  53798. * @param {Object} opt
  53799. * @param {number} [opt.start]
  53800. * @param {number} [opt.end]
  53801. * @param {number} [opt.startValue]
  53802. * @param {number} [opt.endValue]
  53803. */
  53804. calculateDataWindow: function (opt) {
  53805. var dataExtent = this._dataExtent;
  53806. var axisModel = this.getAxisModel();
  53807. var scale = axisModel.axis.scale;
  53808. var rangePropMode = this._dataZoomModel.getRangePropMode();
  53809. var percentExtent = [0, 100];
  53810. var percentWindow = [
  53811. opt.start,
  53812. opt.end
  53813. ];
  53814. var valueWindow = [];
  53815. each$25(['startValue', 'endValue'], function (prop) {
  53816. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  53817. });
  53818. // Normalize bound.
  53819. each$25([0, 1], function (idx) {
  53820. var boundValue = valueWindow[idx];
  53821. var boundPercent = percentWindow[idx];
  53822. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  53823. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  53824. // for cases that a dataZoom component controls multiple axes with different
  53825. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  53826. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  53827. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  53828. // accurately (because all of values that are overflow the `dataExtent` will
  53829. // be calculated to percent '100%'). So we have to use
  53830. // `dataZoom.getRangePropMode()` to mark which prop is used.
  53831. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  53832. // it remains its original value.
  53833. if (rangePropMode[idx] === 'percent') {
  53834. if (boundPercent == null) {
  53835. boundPercent = percentExtent[idx];
  53836. }
  53837. // Use scale.parse to math round for category or time axis.
  53838. boundValue = scale.parse(linearMap(
  53839. boundPercent, percentExtent, dataExtent, true
  53840. ));
  53841. }
  53842. else {
  53843. // Calculating `percent` from `value` may be not accurate, because
  53844. // This calculation can not be inversed, because all of values that
  53845. // are overflow the `dataExtent` will be calculated to percent '100%'
  53846. boundPercent = linearMap(
  53847. boundValue, dataExtent, percentExtent, true
  53848. );
  53849. }
  53850. // valueWindow[idx] = round(boundValue);
  53851. // percentWindow[idx] = round(boundPercent);
  53852. valueWindow[idx] = boundValue;
  53853. percentWindow[idx] = boundPercent;
  53854. });
  53855. return {
  53856. valueWindow: asc$1(valueWindow),
  53857. percentWindow: asc$1(percentWindow)
  53858. };
  53859. },
  53860. /**
  53861. * Notice: reset should not be called before series.restoreData() called,
  53862. * so it is recommanded to be called in "process stage" but not "model init
  53863. * stage".
  53864. *
  53865. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53866. */
  53867. reset: function (dataZoomModel) {
  53868. if (dataZoomModel !== this._dataZoomModel) {
  53869. return;
  53870. }
  53871. // Culculate data window and data extent, and record them.
  53872. this._dataExtent = calculateDataExtent(
  53873. this, this._dimName, this.getTargetSeriesModels()
  53874. );
  53875. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  53876. this._valueWindow = dataWindow.valueWindow;
  53877. this._percentWindow = dataWindow.percentWindow;
  53878. setMinMaxSpan(this);
  53879. // Update axis setting then.
  53880. setAxisModel(this);
  53881. },
  53882. /**
  53883. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53884. */
  53885. restore: function (dataZoomModel) {
  53886. if (dataZoomModel !== this._dataZoomModel) {
  53887. return;
  53888. }
  53889. this._valueWindow = this._percentWindow = null;
  53890. setAxisModel(this, true);
  53891. },
  53892. /**
  53893. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53894. */
  53895. filterData: function (dataZoomModel) {
  53896. if (dataZoomModel !== this._dataZoomModel) {
  53897. return;
  53898. }
  53899. var axisDim = this._dimName;
  53900. var seriesModels = this.getTargetSeriesModels();
  53901. var filterMode = dataZoomModel.get('filterMode');
  53902. var valueWindow = this._valueWindow;
  53903. if (filterMode === 'none') {
  53904. return;
  53905. }
  53906. // FIXME
  53907. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  53908. // with NaN data, NaN will be filtered and stack will be wrong.
  53909. // So we need to force the mode to be set empty.
  53910. // In fect, it is not a big deal that do not support filterMode-'filter'
  53911. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  53912. // selection" some day, which might need "adapt to data extent on the
  53913. // otherAxis", which is disabled by filterMode-'empty'.
  53914. var otherAxisModel = this.getOtherAxisModel();
  53915. if (dataZoomModel.get('$fromToolbox')
  53916. && otherAxisModel
  53917. && otherAxisModel.get('type') === 'category'
  53918. ) {
  53919. filterMode = 'empty';
  53920. }
  53921. // Process series data
  53922. each$25(seriesModels, function (seriesModel) {
  53923. var seriesData = seriesModel.getData();
  53924. var dataDims = seriesModel.coordDimToDataDim(axisDim);
  53925. if (filterMode === 'weakFilter') {
  53926. seriesData && seriesData.filterSelf(function (dataIndex) {
  53927. var leftOut;
  53928. var rightOut;
  53929. var hasValue;
  53930. for (var i = 0; i < dataDims.length; i++) {
  53931. var value = seriesData.get(dataDims[i], dataIndex);
  53932. var thisHasValue = !isNaN(value);
  53933. var thisLeftOut = value < valueWindow[0];
  53934. var thisRightOut = value > valueWindow[1];
  53935. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  53936. return true;
  53937. }
  53938. thisHasValue && (hasValue = true);
  53939. thisLeftOut && (leftOut = true);
  53940. thisRightOut && (rightOut = true);
  53941. }
  53942. // If both left out and right out, do not filter.
  53943. return hasValue && leftOut && rightOut;
  53944. });
  53945. }
  53946. else {
  53947. seriesData && each$25(dataDims, function (dim) {
  53948. if (filterMode === 'empty') {
  53949. seriesModel.setData(
  53950. seriesData.map(dim, function (value) {
  53951. return !isInWindow(value) ? NaN : value;
  53952. })
  53953. );
  53954. }
  53955. else {
  53956. seriesData.filterSelf(dim, isInWindow);
  53957. }
  53958. });
  53959. }
  53960. });
  53961. function isInWindow(value) {
  53962. return value >= valueWindow[0] && value <= valueWindow[1];
  53963. }
  53964. }
  53965. };
  53966. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  53967. var dataExtent = [Infinity, -Infinity];
  53968. each$25(seriesModels, function (seriesModel) {
  53969. var seriesData = seriesModel.getData();
  53970. if (seriesData) {
  53971. each$25(seriesModel.coordDimToDataDim(axisDim), function (dim) {
  53972. var seriesExtent = seriesData.getDataExtent(dim);
  53973. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  53974. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  53975. });
  53976. }
  53977. });
  53978. if (dataExtent[1] < dataExtent[0]) {
  53979. dataExtent = [NaN, NaN];
  53980. }
  53981. // It is important to get "consistent" extent when more then one axes is
  53982. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  53983. // when zooming. But it is difficult to know what is "consistent", considering
  53984. // axes have different type or even different meanings (For example, two
  53985. // time axes are used to compare data of the same date in different years).
  53986. // So basically dataZoom just obtains extent by series.data (in category axis
  53987. // extent can be obtained from axis.data).
  53988. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  53989. // consistent.
  53990. fixExtentByAxis(axisProxy, dataExtent);
  53991. return dataExtent;
  53992. }
  53993. function fixExtentByAxis(axisProxy, dataExtent) {
  53994. var axisModel = axisProxy.getAxisModel();
  53995. var min = axisModel.getMin(true);
  53996. // For category axis, if min/max/scale are not set, extent is determined
  53997. // by axis.data by default.
  53998. var isCategoryAxis = axisModel.get('type') === 'category';
  53999. var axisDataLen = isCategoryAxis && (axisModel.get('data') || []).length;
  54000. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  54001. dataExtent[0] = min;
  54002. }
  54003. else if (isCategoryAxis) {
  54004. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  54005. }
  54006. var max = axisModel.getMax(true);
  54007. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  54008. dataExtent[1] = max;
  54009. }
  54010. else if (isCategoryAxis) {
  54011. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  54012. }
  54013. if (!axisModel.get('scale', true)) {
  54014. dataExtent[0] > 0 && (dataExtent[0] = 0);
  54015. dataExtent[1] < 0 && (dataExtent[1] = 0);
  54016. }
  54017. // For value axis, if min/max/scale are not set, we just use the extent obtained
  54018. // by series data, which may be a little different from the extent calculated by
  54019. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  54020. // little when zooming. So it will not be fixed until some users require it strongly.
  54021. return dataExtent;
  54022. }
  54023. function setAxisModel(axisProxy, isRestore) {
  54024. var axisModel = axisProxy.getAxisModel();
  54025. var percentWindow = axisProxy._percentWindow;
  54026. var valueWindow = axisProxy._valueWindow;
  54027. if (!percentWindow) {
  54028. return;
  54029. }
  54030. // [0, 500]: arbitrary value, guess axis extent.
  54031. var precision = getPixelPrecision(valueWindow, [0, 500]);
  54032. precision = Math.min(precision, 20);
  54033. // isRestore or isFull
  54034. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  54035. axisModel.setRange(
  54036. useOrigin ? null : +valueWindow[0].toFixed(precision),
  54037. useOrigin ? null : +valueWindow[1].toFixed(precision)
  54038. );
  54039. }
  54040. function setMinMaxSpan(axisProxy) {
  54041. var minMaxSpan = axisProxy._minMaxSpan = {};
  54042. var dataZoomModel = axisProxy._dataZoomModel;
  54043. each$25(['min', 'max'], function (minMax) {
  54044. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  54045. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  54046. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  54047. if (valueSpan != null) {
  54048. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  54049. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  54050. if (valueSpan != null) {
  54051. var dataExtent = axisProxy._dataExtent;
  54052. minMaxSpan[minMax + 'Span'] = linearMap(
  54053. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  54054. );
  54055. }
  54056. }
  54057. });
  54058. }
  54059. var each$24 = each$1;
  54060. var eachAxisDim = eachAxisDim$1;
  54061. var DataZoomModel = extendComponentModel({
  54062. type: 'dataZoom',
  54063. dependencies: [
  54064. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  54065. ],
  54066. /**
  54067. * @protected
  54068. */
  54069. defaultOption: {
  54070. zlevel: 0,
  54071. z: 4, // Higher than normal component (z: 2).
  54072. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  54073. xAxisIndex: null, // Default the first horizontal category axis.
  54074. yAxisIndex: null, // Default the first vertical category axis.
  54075. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  54076. // 'filter': data items which are out of window will be removed. This option is
  54077. // applicable when filtering outliers. For each data item, it will be
  54078. // filtered if one of the relevant dimensions is out of the window.
  54079. // 'weakFilter': data items which are out of window will be removed. This option
  54080. // is applicable when filtering outliers. For each data item, it will be
  54081. // filtered only if all of the relevant dimensions are out of the same
  54082. // side of the window.
  54083. // 'empty': data items which are out of window will be set to empty.
  54084. // This option is applicable when user should not neglect
  54085. // that there are some data items out of window.
  54086. // 'none': Do not filter.
  54087. // Taking line chart as an example, line will be broken in
  54088. // the filtered points when filterModel is set to 'empty', but
  54089. // be connected when set to 'filter'.
  54090. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  54091. // default 100. Do not throttle when use null/undefined.
  54092. // If animation === true and animationDurationUpdate > 0,
  54093. // default value is 100, otherwise 20.
  54094. start: 0, // Start percent. 0 ~ 100
  54095. end: 100, // End percent. 0 ~ 100
  54096. startValue: null, // Start value. If startValue specified, start is ignored.
  54097. endValue: null, // End value. If endValue specified, end is ignored.
  54098. minSpan: null, // 0 ~ 100
  54099. maxSpan: null, // 0 ~ 100
  54100. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  54101. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  54102. rangeMode: null // Array, can be 'value' or 'percent'.
  54103. },
  54104. /**
  54105. * @override
  54106. */
  54107. init: function (option, parentModel, ecModel) {
  54108. /**
  54109. * key like x_0, y_1
  54110. * @private
  54111. * @type {Object}
  54112. */
  54113. this._dataIntervalByAxis = {};
  54114. /**
  54115. * @private
  54116. */
  54117. this._dataInfo = {};
  54118. /**
  54119. * key like x_0, y_1
  54120. * @private
  54121. */
  54122. this._axisProxies = {};
  54123. /**
  54124. * @readOnly
  54125. */
  54126. this.textStyleModel;
  54127. /**
  54128. * @private
  54129. */
  54130. this._autoThrottle = true;
  54131. /**
  54132. * 'percent' or 'value'
  54133. * @private
  54134. */
  54135. this._rangePropMode = ['percent', 'percent'];
  54136. var rawOption = retrieveRaw(option);
  54137. this.mergeDefaultAndTheme(option, ecModel);
  54138. this.doInit(rawOption);
  54139. },
  54140. /**
  54141. * @override
  54142. */
  54143. mergeOption: function (newOption) {
  54144. var rawOption = retrieveRaw(newOption);
  54145. //FIX #2591
  54146. merge(this.option, newOption, true);
  54147. this.doInit(rawOption);
  54148. },
  54149. /**
  54150. * @protected
  54151. */
  54152. doInit: function (rawOption) {
  54153. var thisOption = this.option;
  54154. // Disable realtime view update if canvas is not supported.
  54155. if (!env$1.canvasSupported) {
  54156. thisOption.realtime = false;
  54157. }
  54158. this._setDefaultThrottle(rawOption);
  54159. updateRangeUse(this, rawOption);
  54160. each$24([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  54161. // start/end has higher priority over startValue/endValue if they
  54162. // both set, but we should make chart.setOption({endValue: 1000})
  54163. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  54164. if (this._rangePropMode[index] === 'value') {
  54165. thisOption[names[0]] = null;
  54166. }
  54167. // Otherwise do nothing and use the merge result.
  54168. }, this);
  54169. this.textStyleModel = this.getModel('textStyle');
  54170. this._resetTarget();
  54171. this._giveAxisProxies();
  54172. },
  54173. /**
  54174. * @private
  54175. */
  54176. _giveAxisProxies: function () {
  54177. var axisProxies = this._axisProxies;
  54178. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  54179. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  54180. // If exists, share axisProxy with other dataZoomModels.
  54181. var axisProxy = axisModel.__dzAxisProxy || (
  54182. // Use the first dataZoomModel as the main model of axisProxy.
  54183. axisModel.__dzAxisProxy = new AxisProxy(
  54184. dimNames.name, axisIndex, this, ecModel
  54185. )
  54186. );
  54187. // FIXME
  54188. // dispose __dzAxisProxy
  54189. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  54190. }, this);
  54191. },
  54192. /**
  54193. * @private
  54194. */
  54195. _resetTarget: function () {
  54196. var thisOption = this.option;
  54197. var autoMode = this._judgeAutoMode();
  54198. eachAxisDim(function (dimNames) {
  54199. var axisIndexName = dimNames.axisIndex;
  54200. thisOption[axisIndexName] = normalizeToArray(
  54201. thisOption[axisIndexName]
  54202. );
  54203. }, this);
  54204. if (autoMode === 'axisIndex') {
  54205. this._autoSetAxisIndex();
  54206. }
  54207. else if (autoMode === 'orient') {
  54208. this._autoSetOrient();
  54209. }
  54210. },
  54211. /**
  54212. * @private
  54213. */
  54214. _judgeAutoMode: function () {
  54215. // Auto set only works for setOption at the first time.
  54216. // The following is user's reponsibility. So using merged
  54217. // option is OK.
  54218. var thisOption = this.option;
  54219. var hasIndexSpecified = false;
  54220. eachAxisDim(function (dimNames) {
  54221. // When user set axisIndex as a empty array, we think that user specify axisIndex
  54222. // but do not want use auto mode. Because empty array may be encountered when
  54223. // some error occured.
  54224. if (thisOption[dimNames.axisIndex] != null) {
  54225. hasIndexSpecified = true;
  54226. }
  54227. }, this);
  54228. var orient = thisOption.orient;
  54229. if (orient == null && hasIndexSpecified) {
  54230. return 'orient';
  54231. }
  54232. else if (!hasIndexSpecified) {
  54233. if (orient == null) {
  54234. thisOption.orient = 'horizontal';
  54235. }
  54236. return 'axisIndex';
  54237. }
  54238. },
  54239. /**
  54240. * @private
  54241. */
  54242. _autoSetAxisIndex: function () {
  54243. var autoAxisIndex = true;
  54244. var orient = this.get('orient', true);
  54245. var thisOption = this.option;
  54246. var dependentModels = this.dependentModels;
  54247. if (autoAxisIndex) {
  54248. // Find axis that parallel to dataZoom as default.
  54249. var dimName = orient === 'vertical' ? 'y' : 'x';
  54250. if (dependentModels[dimName + 'Axis'].length) {
  54251. thisOption[dimName + 'AxisIndex'] = [0];
  54252. autoAxisIndex = false;
  54253. }
  54254. else {
  54255. each$24(dependentModels.singleAxis, function (singleAxisModel) {
  54256. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  54257. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  54258. autoAxisIndex = false;
  54259. }
  54260. });
  54261. }
  54262. }
  54263. if (autoAxisIndex) {
  54264. // Find the first category axis as default. (consider polar)
  54265. eachAxisDim(function (dimNames) {
  54266. if (!autoAxisIndex) {
  54267. return;
  54268. }
  54269. var axisIndices = [];
  54270. var axisModels = this.dependentModels[dimNames.axis];
  54271. if (axisModels.length && !axisIndices.length) {
  54272. for (var i = 0, len = axisModels.length; i < len; i++) {
  54273. if (axisModels[i].get('type') === 'category') {
  54274. axisIndices.push(i);
  54275. }
  54276. }
  54277. }
  54278. thisOption[dimNames.axisIndex] = axisIndices;
  54279. if (axisIndices.length) {
  54280. autoAxisIndex = false;
  54281. }
  54282. }, this);
  54283. }
  54284. if (autoAxisIndex) {
  54285. // FIXME
  54286. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  54287. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  54288. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  54289. // dataZoom component auto adopts series that reference to
  54290. // both xAxis and yAxis which type is 'value'.
  54291. this.ecModel.eachSeries(function (seriesModel) {
  54292. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  54293. eachAxisDim(function (dimNames) {
  54294. var axisIndices = thisOption[dimNames.axisIndex];
  54295. var axisIndex = seriesModel.get(dimNames.axisIndex);
  54296. var axisId = seriesModel.get(dimNames.axisId);
  54297. var axisModel = seriesModel.ecModel.queryComponents({
  54298. mainType: dimNames.axis,
  54299. index: axisIndex,
  54300. id: axisId
  54301. })[0];
  54302. if (__DEV__) {
  54303. if (!axisModel) {
  54304. throw new Error(
  54305. dimNames.axis + ' "' + retrieve(
  54306. axisIndex,
  54307. axisId,
  54308. 0
  54309. ) + '" not found'
  54310. );
  54311. }
  54312. }
  54313. axisIndex = axisModel.componentIndex;
  54314. if (indexOf(axisIndices, axisIndex) < 0) {
  54315. axisIndices.push(axisIndex);
  54316. }
  54317. });
  54318. }
  54319. }, this);
  54320. }
  54321. },
  54322. /**
  54323. * @private
  54324. */
  54325. _autoSetOrient: function () {
  54326. var dim;
  54327. // Find the first axis
  54328. this.eachTargetAxis(function (dimNames) {
  54329. !dim && (dim = dimNames.name);
  54330. }, this);
  54331. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  54332. },
  54333. /**
  54334. * @private
  54335. */
  54336. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  54337. // FIXME
  54338. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  54339. // 例如series.type === scatter时。
  54340. var is = true;
  54341. eachAxisDim(function (dimNames) {
  54342. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  54343. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  54344. if (!axisModel || axisModel.get('type') !== axisType) {
  54345. is = false;
  54346. }
  54347. }, this);
  54348. return is;
  54349. },
  54350. /**
  54351. * @private
  54352. */
  54353. _setDefaultThrottle: function (rawOption) {
  54354. // When first time user set throttle, auto throttle ends.
  54355. if (rawOption.hasOwnProperty('throttle')) {
  54356. this._autoThrottle = false;
  54357. }
  54358. if (this._autoThrottle) {
  54359. var globalOption = this.ecModel.option;
  54360. this.option.throttle =
  54361. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  54362. ? 100 : 20;
  54363. }
  54364. },
  54365. /**
  54366. * @public
  54367. */
  54368. getFirstTargetAxisModel: function () {
  54369. var firstAxisModel;
  54370. eachAxisDim(function (dimNames) {
  54371. if (firstAxisModel == null) {
  54372. var indices = this.get(dimNames.axisIndex);
  54373. if (indices.length) {
  54374. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  54375. }
  54376. }
  54377. }, this);
  54378. return firstAxisModel;
  54379. },
  54380. /**
  54381. * @public
  54382. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  54383. */
  54384. eachTargetAxis: function (callback, context) {
  54385. var ecModel = this.ecModel;
  54386. eachAxisDim(function (dimNames) {
  54387. each$24(
  54388. this.get(dimNames.axisIndex),
  54389. function (axisIndex) {
  54390. callback.call(context, dimNames, axisIndex, this, ecModel);
  54391. },
  54392. this
  54393. );
  54394. }, this);
  54395. },
  54396. /**
  54397. * @param {string} dimName
  54398. * @param {number} axisIndex
  54399. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  54400. */
  54401. getAxisProxy: function (dimName, axisIndex) {
  54402. return this._axisProxies[dimName + '_' + axisIndex];
  54403. },
  54404. /**
  54405. * @param {string} dimName
  54406. * @param {number} axisIndex
  54407. * @return {module:echarts/model/Model} If not found, return null/undefined.
  54408. */
  54409. getAxisModel: function (dimName, axisIndex) {
  54410. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  54411. return axisProxy && axisProxy.getAxisModel();
  54412. },
  54413. /**
  54414. * If not specified, set to undefined.
  54415. *
  54416. * @public
  54417. * @param {Object} opt
  54418. * @param {number} [opt.start]
  54419. * @param {number} [opt.end]
  54420. * @param {number} [opt.startValue]
  54421. * @param {number} [opt.endValue]
  54422. * @param {boolean} [ignoreUpdateRangeUsg=false]
  54423. */
  54424. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  54425. var option = this.option;
  54426. each$24([['start', 'startValue'], ['end', 'endValue']], function (names) {
  54427. // If only one of 'start' and 'startValue' is not null/undefined, the other
  54428. // should be cleared, which enable clear the option.
  54429. // If both of them are not set, keep option with the original value, which
  54430. // enable use only set start but not set end when calling `dispatchAction`.
  54431. // The same as 'end' and 'endValue'.
  54432. if (opt[names[0]] != null || opt[names[1]] != null) {
  54433. option[names[0]] = opt[names[0]];
  54434. option[names[1]] = opt[names[1]];
  54435. }
  54436. }, this);
  54437. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  54438. },
  54439. /**
  54440. * @public
  54441. * @return {Array.<number>} [startPercent, endPercent]
  54442. */
  54443. getPercentRange: function () {
  54444. var axisProxy = this.findRepresentativeAxisProxy();
  54445. if (axisProxy) {
  54446. return axisProxy.getDataPercentWindow();
  54447. }
  54448. },
  54449. /**
  54450. * @public
  54451. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  54452. *
  54453. * @param {string} [axisDimName]
  54454. * @param {number} [axisIndex]
  54455. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  54456. */
  54457. getValueRange: function (axisDimName, axisIndex) {
  54458. if (axisDimName == null && axisIndex == null) {
  54459. var axisProxy = this.findRepresentativeAxisProxy();
  54460. if (axisProxy) {
  54461. return axisProxy.getDataValueWindow();
  54462. }
  54463. }
  54464. else {
  54465. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  54466. }
  54467. },
  54468. /**
  54469. * @public
  54470. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  54471. * corresponding to the axisModel
  54472. * @return {module:echarts/component/dataZoom/AxisProxy}
  54473. */
  54474. findRepresentativeAxisProxy: function (axisModel) {
  54475. if (axisModel) {
  54476. return axisModel.__dzAxisProxy;
  54477. }
  54478. // Find the first hosted axisProxy
  54479. var axisProxies = this._axisProxies;
  54480. for (var key in axisProxies) {
  54481. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  54482. return axisProxies[key];
  54483. }
  54484. }
  54485. // If no hosted axis find not hosted axisProxy.
  54486. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  54487. // and the option.start or option.end settings are different. The percentRange
  54488. // should follow axisProxy.
  54489. // (We encounter this problem in toolbox data zoom.)
  54490. for (var key in axisProxies) {
  54491. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  54492. return axisProxies[key];
  54493. }
  54494. }
  54495. },
  54496. /**
  54497. * @return {Array.<string>}
  54498. */
  54499. getRangePropMode: function () {
  54500. return this._rangePropMode.slice();
  54501. }
  54502. });
  54503. function retrieveRaw(option) {
  54504. var ret = {};
  54505. each$24(
  54506. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  54507. function (name) {
  54508. option.hasOwnProperty(name) && (ret[name] = option[name]);
  54509. }
  54510. );
  54511. return ret;
  54512. }
  54513. function updateRangeUse(dataZoomModel, rawOption) {
  54514. var rangePropMode = dataZoomModel._rangePropMode;
  54515. var rangeModeInOption = dataZoomModel.get('rangeMode');
  54516. each$24([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  54517. var percentSpecified = rawOption[names[0]] != null;
  54518. var valueSpecified = rawOption[names[1]] != null;
  54519. if (percentSpecified && !valueSpecified) {
  54520. rangePropMode[index] = 'percent';
  54521. }
  54522. else if (!percentSpecified && valueSpecified) {
  54523. rangePropMode[index] = 'value';
  54524. }
  54525. else if (rangeModeInOption) {
  54526. rangePropMode[index] = rangeModeInOption[index];
  54527. }
  54528. else if (percentSpecified) { // percentSpecified && valueSpecified
  54529. rangePropMode[index] = 'percent';
  54530. }
  54531. // else remain its original setting.
  54532. });
  54533. }
  54534. var DataZoomView = Component.extend({
  54535. type: 'dataZoom',
  54536. render: function (dataZoomModel, ecModel, api, payload) {
  54537. this.dataZoomModel = dataZoomModel;
  54538. this.ecModel = ecModel;
  54539. this.api = api;
  54540. },
  54541. /**
  54542. * Find the first target coordinate system.
  54543. *
  54544. * @protected
  54545. * @return {Object} {
  54546. * grid: [
  54547. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  54548. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  54549. * ...
  54550. * ], // cartesians must not be null/undefined.
  54551. * polar: [
  54552. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  54553. * ...
  54554. * ], // polars must not be null/undefined.
  54555. * singleAxis: [
  54556. * {model: coord0, axisModels: [], coordIndex: 0}
  54557. * ]
  54558. */
  54559. getTargetCoordInfo: function () {
  54560. var dataZoomModel = this.dataZoomModel;
  54561. var ecModel = this.ecModel;
  54562. var coordSysLists = {};
  54563. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  54564. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  54565. if (axisModel) {
  54566. var coordModel = axisModel.getCoordSysModel();
  54567. coordModel && save(
  54568. coordModel,
  54569. axisModel,
  54570. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  54571. coordModel.componentIndex
  54572. );
  54573. }
  54574. }, this);
  54575. function save(coordModel, axisModel, store, coordIndex) {
  54576. var item;
  54577. for (var i = 0; i < store.length; i++) {
  54578. if (store[i].model === coordModel) {
  54579. item = store[i];
  54580. break;
  54581. }
  54582. }
  54583. if (!item) {
  54584. store.push(item = {
  54585. model: coordModel, axisModels: [], coordIndex: coordIndex
  54586. });
  54587. }
  54588. item.axisModels.push(axisModel);
  54589. }
  54590. return coordSysLists;
  54591. }
  54592. });
  54593. var SliderZoomModel = DataZoomModel.extend({
  54594. type: 'dataZoom.slider',
  54595. layoutMode: 'box',
  54596. /**
  54597. * @protected
  54598. */
  54599. defaultOption: {
  54600. show: true,
  54601. // ph => placeholder. Using placehoder here because
  54602. // deault value can only be drived in view stage.
  54603. right: 'ph', // Default align to grid rect.
  54604. top: 'ph', // Default align to grid rect.
  54605. width: 'ph', // Default align to grid rect.
  54606. height: 'ph', // Default align to grid rect.
  54607. left: null, // Default align to grid rect.
  54608. bottom: null, // Default align to grid rect.
  54609. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  54610. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  54611. // highest priority, remain for compatibility of
  54612. // previous version, but not recommended any more.
  54613. dataBackground: {
  54614. lineStyle: {
  54615. color: '#2f4554',
  54616. width: 0.5,
  54617. opacity: 0.3
  54618. },
  54619. areaStyle: {
  54620. color: 'rgba(47,69,84,0.3)',
  54621. opacity: 0.3
  54622. }
  54623. },
  54624. borderColor: '#ddd', // border color of the box. For compatibility,
  54625. // if dataBackgroundColor is set, borderColor
  54626. // is ignored.
  54627. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  54628. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  54629. // 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',
  54630. 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',
  54631. // Percent of the slider height
  54632. handleSize: '100%',
  54633. handleStyle: {
  54634. color: '#a7b7cc'
  54635. },
  54636. labelPrecision: null,
  54637. labelFormatter: null,
  54638. showDetail: true,
  54639. showDataShadow: 'auto', // Default auto decision.
  54640. realtime: true,
  54641. zoomLock: false, // Whether disable zoom.
  54642. textStyle: {
  54643. color: '#333'
  54644. }
  54645. }
  54646. });
  54647. var Rect$2 = Rect;
  54648. var linearMap$2 = linearMap;
  54649. var asc$2 = asc;
  54650. var bind$4 = bind;
  54651. var each$26 = each$1;
  54652. // Constants
  54653. var DEFAULT_LOCATION_EDGE_GAP = 7;
  54654. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  54655. var DEFAULT_FILLER_SIZE = 30;
  54656. var HORIZONTAL = 'horizontal';
  54657. var VERTICAL = 'vertical';
  54658. var LABEL_GAP = 5;
  54659. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  54660. var SliderZoomView = DataZoomView.extend({
  54661. type: 'dataZoom.slider',
  54662. init: function (ecModel, api) {
  54663. /**
  54664. * @private
  54665. * @type {Object}
  54666. */
  54667. this._displayables = {};
  54668. /**
  54669. * @private
  54670. * @type {string}
  54671. */
  54672. this._orient;
  54673. /**
  54674. * [0, 100]
  54675. * @private
  54676. */
  54677. this._range;
  54678. /**
  54679. * [coord of the first handle, coord of the second handle]
  54680. * @private
  54681. */
  54682. this._handleEnds;
  54683. /**
  54684. * [length, thick]
  54685. * @private
  54686. * @type {Array.<number>}
  54687. */
  54688. this._size;
  54689. /**
  54690. * @private
  54691. * @type {number}
  54692. */
  54693. this._handleWidth;
  54694. /**
  54695. * @private
  54696. * @type {number}
  54697. */
  54698. this._handleHeight;
  54699. /**
  54700. * @private
  54701. */
  54702. this._location;
  54703. /**
  54704. * @private
  54705. */
  54706. this._dragging;
  54707. /**
  54708. * @private
  54709. */
  54710. this._dataShadowInfo;
  54711. this.api = api;
  54712. },
  54713. /**
  54714. * @override
  54715. */
  54716. render: function (dataZoomModel, ecModel, api, payload) {
  54717. SliderZoomView.superApply(this, 'render', arguments);
  54718. createOrUpdate(
  54719. this,
  54720. '_dispatchZoomAction',
  54721. this.dataZoomModel.get('throttle'),
  54722. 'fixRate'
  54723. );
  54724. this._orient = dataZoomModel.get('orient');
  54725. if (this.dataZoomModel.get('show') === false) {
  54726. this.group.removeAll();
  54727. return;
  54728. }
  54729. // Notice: this._resetInterval() should not be executed when payload.type
  54730. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  54731. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  54732. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  54733. this._buildView();
  54734. }
  54735. this._updateView();
  54736. },
  54737. /**
  54738. * @override
  54739. */
  54740. remove: function () {
  54741. SliderZoomView.superApply(this, 'remove', arguments);
  54742. clear(this, '_dispatchZoomAction');
  54743. },
  54744. /**
  54745. * @override
  54746. */
  54747. dispose: function () {
  54748. SliderZoomView.superApply(this, 'dispose', arguments);
  54749. clear(this, '_dispatchZoomAction');
  54750. },
  54751. _buildView: function () {
  54752. var thisGroup = this.group;
  54753. thisGroup.removeAll();
  54754. this._resetLocation();
  54755. this._resetInterval();
  54756. var barGroup = this._displayables.barGroup = new Group();
  54757. this._renderBackground();
  54758. this._renderHandle();
  54759. this._renderDataShadow();
  54760. thisGroup.add(barGroup);
  54761. this._positionGroup();
  54762. },
  54763. /**
  54764. * @private
  54765. */
  54766. _resetLocation: function () {
  54767. var dataZoomModel = this.dataZoomModel;
  54768. var api = this.api;
  54769. // If some of x/y/width/height are not specified,
  54770. // auto-adapt according to target grid.
  54771. var coordRect = this._findCoordRect();
  54772. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  54773. // Default align by coordinate system rect.
  54774. var positionInfo = this._orient === HORIZONTAL
  54775. ? {
  54776. // Why using 'right', because right should be used in vertical,
  54777. // and it is better to be consistent for dealing with position param merge.
  54778. right: ecSize.width - coordRect.x - coordRect.width,
  54779. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  54780. width: coordRect.width,
  54781. height: DEFAULT_FILLER_SIZE
  54782. }
  54783. : { // vertical
  54784. right: DEFAULT_LOCATION_EDGE_GAP,
  54785. top: coordRect.y,
  54786. width: DEFAULT_FILLER_SIZE,
  54787. height: coordRect.height
  54788. };
  54789. // Do not write back to option and replace value 'ph', because
  54790. // the 'ph' value should be recalculated when resize.
  54791. var layoutParams = getLayoutParams(dataZoomModel.option);
  54792. // Replace the placeholder value.
  54793. each$1(['right', 'top', 'width', 'height'], function (name) {
  54794. if (layoutParams[name] === 'ph') {
  54795. layoutParams[name] = positionInfo[name];
  54796. }
  54797. });
  54798. var layoutRect = getLayoutRect(
  54799. layoutParams,
  54800. ecSize,
  54801. dataZoomModel.padding
  54802. );
  54803. this._location = {x: layoutRect.x, y: layoutRect.y};
  54804. this._size = [layoutRect.width, layoutRect.height];
  54805. this._orient === VERTICAL && this._size.reverse();
  54806. },
  54807. /**
  54808. * @private
  54809. */
  54810. _positionGroup: function () {
  54811. var thisGroup = this.group;
  54812. var location = this._location;
  54813. var orient = this._orient;
  54814. // Just use the first axis to determine mapping.
  54815. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  54816. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  54817. var barGroup = this._displayables.barGroup;
  54818. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  54819. // Transform barGroup.
  54820. barGroup.attr(
  54821. (orient === HORIZONTAL && !inverse)
  54822. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  54823. : (orient === HORIZONTAL && inverse)
  54824. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  54825. : (orient === VERTICAL && !inverse)
  54826. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  54827. // Dont use Math.PI, considering shadow direction.
  54828. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  54829. );
  54830. // Position barGroup
  54831. var rect = thisGroup.getBoundingRect([barGroup]);
  54832. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  54833. },
  54834. /**
  54835. * @private
  54836. */
  54837. _getViewExtent: function () {
  54838. return [0, this._size[0]];
  54839. },
  54840. _renderBackground: function () {
  54841. var dataZoomModel = this.dataZoomModel;
  54842. var size = this._size;
  54843. var barGroup = this._displayables.barGroup;
  54844. barGroup.add(new Rect$2({
  54845. silent: true,
  54846. shape: {
  54847. x: 0, y: 0, width: size[0], height: size[1]
  54848. },
  54849. style: {
  54850. fill: dataZoomModel.get('backgroundColor')
  54851. },
  54852. z2: -40
  54853. }));
  54854. // Click panel, over shadow, below handles.
  54855. barGroup.add(new Rect$2({
  54856. shape: {
  54857. x: 0, y: 0, width: size[0], height: size[1]
  54858. },
  54859. style: {
  54860. fill: 'transparent'
  54861. },
  54862. z2: 0,
  54863. onclick: bind(this._onClickPanelClick, this)
  54864. }));
  54865. },
  54866. _renderDataShadow: function () {
  54867. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  54868. if (!info) {
  54869. return;
  54870. }
  54871. var size = this._size;
  54872. var seriesModel = info.series;
  54873. var data = seriesModel.getRawData();
  54874. var otherDim = seriesModel.getShadowDim
  54875. ? seriesModel.getShadowDim() // @see candlestick
  54876. : info.otherDim;
  54877. if (otherDim == null) {
  54878. return;
  54879. }
  54880. var otherDataExtent = data.getDataExtent(otherDim);
  54881. // Nice extent.
  54882. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  54883. otherDataExtent = [
  54884. otherDataExtent[0] - otherOffset,
  54885. otherDataExtent[1] + otherOffset
  54886. ];
  54887. var otherShadowExtent = [0, size[1]];
  54888. var thisShadowExtent = [0, size[0]];
  54889. var areaPoints = [[size[0], 0], [0, 0]];
  54890. var linePoints = [];
  54891. var step = thisShadowExtent[1] / (data.count() - 1);
  54892. var thisCoord = 0;
  54893. // Optimize for large data shadow
  54894. var stride = Math.round(data.count() / size[0]);
  54895. var lastIsEmpty;
  54896. data.each([otherDim], function (value, index) {
  54897. if (stride > 0 && (index % stride)) {
  54898. thisCoord += step;
  54899. return;
  54900. }
  54901. // FIXME
  54902. // Should consider axis.min/axis.max when drawing dataShadow.
  54903. // FIXME
  54904. // 应该使用统一的空判断?还是在list里进行空判断?
  54905. var isEmpty = value == null || isNaN(value) || value === '';
  54906. // See #4235.
  54907. var otherCoord = isEmpty
  54908. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  54909. // Attempt to draw data shadow precisely when there are empty value.
  54910. if (isEmpty && !lastIsEmpty && index) {
  54911. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  54912. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  54913. }
  54914. else if (!isEmpty && lastIsEmpty) {
  54915. areaPoints.push([thisCoord, 0]);
  54916. linePoints.push([thisCoord, 0]);
  54917. }
  54918. areaPoints.push([thisCoord, otherCoord]);
  54919. linePoints.push([thisCoord, otherCoord]);
  54920. thisCoord += step;
  54921. lastIsEmpty = isEmpty;
  54922. });
  54923. var dataZoomModel = this.dataZoomModel;
  54924. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  54925. this._displayables.barGroup.add(new Polygon({
  54926. shape: {points: areaPoints},
  54927. style: defaults(
  54928. {fill: dataZoomModel.get('dataBackgroundColor')},
  54929. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  54930. ),
  54931. silent: true,
  54932. z2: -20
  54933. }));
  54934. this._displayables.barGroup.add(new Polyline({
  54935. shape: {points: linePoints},
  54936. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  54937. silent: true,
  54938. z2: -19
  54939. }));
  54940. },
  54941. _prepareDataShadowInfo: function () {
  54942. var dataZoomModel = this.dataZoomModel;
  54943. var showDataShadow = dataZoomModel.get('showDataShadow');
  54944. if (showDataShadow === false) {
  54945. return;
  54946. }
  54947. // Find a representative series.
  54948. var result;
  54949. var ecModel = this.ecModel;
  54950. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  54951. var seriesModels = dataZoomModel
  54952. .getAxisProxy(dimNames.name, axisIndex)
  54953. .getTargetSeriesModels();
  54954. each$1(seriesModels, function (seriesModel) {
  54955. if (result) {
  54956. return;
  54957. }
  54958. if (showDataShadow !== true && indexOf(
  54959. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  54960. ) < 0
  54961. ) {
  54962. return;
  54963. }
  54964. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  54965. var otherDim = getOtherDim(dimNames.name);
  54966. var otherAxisInverse;
  54967. var coordSys = seriesModel.coordinateSystem;
  54968. if (otherDim != null && coordSys.getOtherAxis) {
  54969. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  54970. }
  54971. result = {
  54972. thisAxis: thisAxis,
  54973. series: seriesModel,
  54974. thisDim: dimNames.name,
  54975. otherDim: otherDim,
  54976. otherAxisInverse: otherAxisInverse
  54977. };
  54978. }, this);
  54979. }, this);
  54980. return result;
  54981. },
  54982. _renderHandle: function () {
  54983. var displaybles = this._displayables;
  54984. var handles = displaybles.handles = [];
  54985. var handleLabels = displaybles.handleLabels = [];
  54986. var barGroup = this._displayables.barGroup;
  54987. var size = this._size;
  54988. var dataZoomModel = this.dataZoomModel;
  54989. barGroup.add(displaybles.filler = new Rect$2({
  54990. draggable: true,
  54991. cursor: getCursor(this._orient),
  54992. drift: bind$4(this._onDragMove, this, 'all'),
  54993. onmousemove: function (e) {
  54994. // Fot mobile devicem, prevent screen slider on the button.
  54995. stop(e.event);
  54996. },
  54997. ondragstart: bind$4(this._showDataInfo, this, true),
  54998. ondragend: bind$4(this._onDragEnd, this),
  54999. onmouseover: bind$4(this._showDataInfo, this, true),
  55000. onmouseout: bind$4(this._showDataInfo, this, false),
  55001. style: {
  55002. fill: dataZoomModel.get('fillerColor'),
  55003. textPosition : 'inside'
  55004. }
  55005. }));
  55006. // Frame border.
  55007. barGroup.add(new Rect$2(subPixelOptimizeRect({
  55008. silent: true,
  55009. shape: {
  55010. x: 0,
  55011. y: 0,
  55012. width: size[0],
  55013. height: size[1]
  55014. },
  55015. style: {
  55016. stroke: dataZoomModel.get('dataBackgroundColor')
  55017. || dataZoomModel.get('borderColor'),
  55018. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  55019. fill: 'rgba(0,0,0,0)'
  55020. }
  55021. })));
  55022. each$26([0, 1], function (handleIndex) {
  55023. var path = createIcon(
  55024. dataZoomModel.get('handleIcon'),
  55025. {
  55026. cursor: getCursor(this._orient),
  55027. draggable: true,
  55028. drift: bind$4(this._onDragMove, this, handleIndex),
  55029. onmousemove: function (e) {
  55030. // Fot mobile devicem, prevent screen slider on the button.
  55031. stop(e.event);
  55032. },
  55033. ondragend: bind$4(this._onDragEnd, this),
  55034. onmouseover: bind$4(this._showDataInfo, this, true),
  55035. onmouseout: bind$4(this._showDataInfo, this, false)
  55036. },
  55037. {x: -1, y: 0, width: 2, height: 2}
  55038. );
  55039. var bRect = path.getBoundingRect();
  55040. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  55041. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  55042. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  55043. var handleColor = dataZoomModel.get('handleColor');
  55044. // Compatitable with previous version
  55045. if (handleColor != null) {
  55046. path.style.fill = handleColor;
  55047. }
  55048. barGroup.add(handles[handleIndex] = path);
  55049. var textStyleModel = dataZoomModel.textStyleModel;
  55050. this.group.add(
  55051. handleLabels[handleIndex] = new Text({
  55052. silent: true,
  55053. invisible: true,
  55054. style: {
  55055. x: 0, y: 0, text: '',
  55056. textVerticalAlign: 'middle',
  55057. textAlign: 'center',
  55058. textFill: textStyleModel.getTextColor(),
  55059. textFont: textStyleModel.getFont()
  55060. },
  55061. z2: 10
  55062. }));
  55063. }, this);
  55064. },
  55065. /**
  55066. * @private
  55067. */
  55068. _resetInterval: function () {
  55069. var range = this._range = this.dataZoomModel.getPercentRange();
  55070. var viewExtent = this._getViewExtent();
  55071. this._handleEnds = [
  55072. linearMap$2(range[0], [0, 100], viewExtent, true),
  55073. linearMap$2(range[1], [0, 100], viewExtent, true)
  55074. ];
  55075. },
  55076. /**
  55077. * @private
  55078. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  55079. * @param {number} delta
  55080. */
  55081. _updateInterval: function (handleIndex, delta) {
  55082. var dataZoomModel = this.dataZoomModel;
  55083. var handleEnds = this._handleEnds;
  55084. var viewExtend = this._getViewExtent();
  55085. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55086. var percentExtent = [0, 100];
  55087. sliderMove(
  55088. delta,
  55089. handleEnds,
  55090. viewExtend,
  55091. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  55092. minMaxSpan.minSpan != null
  55093. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  55094. minMaxSpan.maxSpan != null
  55095. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  55096. );
  55097. this._range = asc$2([
  55098. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  55099. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  55100. ]);
  55101. },
  55102. /**
  55103. * @private
  55104. */
  55105. _updateView: function (nonRealtime) {
  55106. var displaybles = this._displayables;
  55107. var handleEnds = this._handleEnds;
  55108. var handleInterval = asc$2(handleEnds.slice());
  55109. var size = this._size;
  55110. each$26([0, 1], function (handleIndex) {
  55111. // Handles
  55112. var handle = displaybles.handles[handleIndex];
  55113. var handleHeight = this._handleHeight;
  55114. handle.attr({
  55115. scale: [handleHeight / 2, handleHeight / 2],
  55116. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  55117. });
  55118. }, this);
  55119. // Filler
  55120. displaybles.filler.setShape({
  55121. x: handleInterval[0],
  55122. y: 0,
  55123. width: handleInterval[1] - handleInterval[0],
  55124. height: size[1]
  55125. });
  55126. this._updateDataInfo(nonRealtime);
  55127. },
  55128. /**
  55129. * @private
  55130. */
  55131. _updateDataInfo: function (nonRealtime) {
  55132. var dataZoomModel = this.dataZoomModel;
  55133. var displaybles = this._displayables;
  55134. var handleLabels = displaybles.handleLabels;
  55135. var orient = this._orient;
  55136. var labelTexts = ['', ''];
  55137. // FIXME
  55138. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  55139. if (dataZoomModel.get('showDetail')) {
  55140. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55141. if (axisProxy) {
  55142. var axis = axisProxy.getAxisModel().axis;
  55143. var range = this._range;
  55144. var dataInterval = nonRealtime
  55145. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  55146. ? axisProxy.calculateDataWindow({
  55147. start: range[0], end: range[1]
  55148. }).valueWindow
  55149. : axisProxy.getDataValueWindow();
  55150. labelTexts = [
  55151. this._formatLabel(dataInterval[0], axis),
  55152. this._formatLabel(dataInterval[1], axis)
  55153. ];
  55154. }
  55155. }
  55156. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  55157. setLabel.call(this, 0);
  55158. setLabel.call(this, 1);
  55159. function setLabel(handleIndex) {
  55160. // Label
  55161. // Text should not transform by barGroup.
  55162. // Ignore handlers transform
  55163. var barTransform = getTransform(
  55164. displaybles.handles[handleIndex].parent, this.group
  55165. );
  55166. var direction = transformDirection(
  55167. handleIndex === 0 ? 'right' : 'left', barTransform
  55168. );
  55169. var offset = this._handleWidth / 2 + LABEL_GAP;
  55170. var textPoint = applyTransform$1(
  55171. [
  55172. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  55173. this._size[1] / 2
  55174. ],
  55175. barTransform
  55176. );
  55177. handleLabels[handleIndex].setStyle({
  55178. x: textPoint[0],
  55179. y: textPoint[1],
  55180. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  55181. textAlign: orient === HORIZONTAL ? direction : 'center',
  55182. text: labelTexts[handleIndex]
  55183. });
  55184. }
  55185. },
  55186. /**
  55187. * @private
  55188. */
  55189. _formatLabel: function (value, axis) {
  55190. var dataZoomModel = this.dataZoomModel;
  55191. var labelFormatter = dataZoomModel.get('labelFormatter');
  55192. var labelPrecision = dataZoomModel.get('labelPrecision');
  55193. if (labelPrecision == null || labelPrecision === 'auto') {
  55194. labelPrecision = axis.getPixelPrecision();
  55195. }
  55196. var valueStr = (value == null || isNaN(value))
  55197. ? ''
  55198. // FIXME Glue code
  55199. : (axis.type === 'category' || axis.type === 'time')
  55200. ? axis.scale.getLabel(Math.round(value))
  55201. // param of toFixed should less then 20.
  55202. : value.toFixed(Math.min(labelPrecision, 20));
  55203. return isFunction(labelFormatter)
  55204. ? labelFormatter(value, valueStr)
  55205. : isString(labelFormatter)
  55206. ? labelFormatter.replace('{value}', valueStr)
  55207. : valueStr;
  55208. },
  55209. /**
  55210. * @private
  55211. * @param {boolean} showOrHide true: show, false: hide
  55212. */
  55213. _showDataInfo: function (showOrHide) {
  55214. // Always show when drgging.
  55215. showOrHide = this._dragging || showOrHide;
  55216. var handleLabels = this._displayables.handleLabels;
  55217. handleLabels[0].attr('invisible', !showOrHide);
  55218. handleLabels[1].attr('invisible', !showOrHide);
  55219. },
  55220. _onDragMove: function (handleIndex, dx, dy) {
  55221. this._dragging = true;
  55222. // Transform dx, dy to bar coordination.
  55223. var barTransform = this._displayables.barGroup.getLocalTransform();
  55224. var vertex = applyTransform$1([dx, dy], barTransform, true);
  55225. this._updateInterval(handleIndex, vertex[0]);
  55226. var realtime = this.dataZoomModel.get('realtime');
  55227. this._updateView(!realtime);
  55228. if (realtime) {
  55229. realtime && this._dispatchZoomAction();
  55230. }
  55231. },
  55232. _onDragEnd: function () {
  55233. this._dragging = false;
  55234. this._showDataInfo(false);
  55235. this._dispatchZoomAction();
  55236. },
  55237. _onClickPanelClick: function (e) {
  55238. var size = this._size;
  55239. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  55240. if (localPoint[0] < 0 || localPoint[0] > size[0]
  55241. || localPoint[1] < 0 || localPoint[1] > size[1]
  55242. ) {
  55243. return;
  55244. }
  55245. var handleEnds = this._handleEnds;
  55246. var center = (handleEnds[0] + handleEnds[1]) / 2;
  55247. this._updateInterval('all', localPoint[0] - center);
  55248. this._updateView();
  55249. this._dispatchZoomAction();
  55250. },
  55251. /**
  55252. * This action will be throttled.
  55253. * @private
  55254. */
  55255. _dispatchZoomAction: function () {
  55256. var range = this._range;
  55257. this.api.dispatchAction({
  55258. type: 'dataZoom',
  55259. from: this.uid,
  55260. dataZoomId: this.dataZoomModel.id,
  55261. start: range[0],
  55262. end: range[1]
  55263. });
  55264. },
  55265. /**
  55266. * @private
  55267. */
  55268. _findCoordRect: function () {
  55269. // Find the grid coresponding to the first axis referred by dataZoom.
  55270. var rect;
  55271. each$26(this.getTargetCoordInfo(), function (coordInfoList) {
  55272. if (!rect && coordInfoList.length) {
  55273. var coordSys = coordInfoList[0].model.coordinateSystem;
  55274. rect = coordSys.getRect && coordSys.getRect();
  55275. }
  55276. });
  55277. if (!rect) {
  55278. var width = this.api.getWidth();
  55279. var height = this.api.getHeight();
  55280. rect = {
  55281. x: width * 0.2,
  55282. y: height * 0.2,
  55283. width: width * 0.6,
  55284. height: height * 0.6
  55285. };
  55286. }
  55287. return rect;
  55288. }
  55289. });
  55290. function getOtherDim(thisDim) {
  55291. // FIXME
  55292. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  55293. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  55294. return map$$1[thisDim];
  55295. }
  55296. function getCursor(orient) {
  55297. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  55298. }
  55299. DataZoomModel.extend({
  55300. type: 'dataZoom.inside',
  55301. /**
  55302. * @protected
  55303. */
  55304. defaultOption: {
  55305. disabled: false, // Whether disable this inside zoom.
  55306. zoomLock: false, // Whether disable zoom but only pan.
  55307. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  55308. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  55309. preventDefaultMouseMove: true
  55310. }
  55311. });
  55312. // Only create one roam controller for each coordinate system.
  55313. // one roam controller might be refered by two inside data zoom
  55314. // components (for example, one for x and one for y). When user
  55315. // pan or zoom, only dispatch one action for those data zoom
  55316. // components.
  55317. var curry$6 = curry;
  55318. var ATTR$1 = '\0_ec_dataZoom_roams';
  55319. /**
  55320. * @public
  55321. * @param {module:echarts/ExtensionAPI} api
  55322. * @param {Object} dataZoomInfo
  55323. * @param {string} dataZoomInfo.coordId
  55324. * @param {Function} dataZoomInfo.containsPoint
  55325. * @param {Array.<string>} dataZoomInfo.allCoordIds
  55326. * @param {string} dataZoomInfo.dataZoomId
  55327. * @param {number} dataZoomInfo.throttleRate
  55328. * @param {Function} dataZoomInfo.panGetRange
  55329. * @param {Function} dataZoomInfo.zoomGetRange
  55330. * @param {boolean} [dataZoomInfo.zoomLock]
  55331. * @param {boolean} [dataZoomInfo.disabled]
  55332. */
  55333. function register$2(api, dataZoomInfo) {
  55334. var store = giveStore(api);
  55335. var theDataZoomId = dataZoomInfo.dataZoomId;
  55336. var theCoordId = dataZoomInfo.coordId;
  55337. // Do clean when a dataZoom changes its target coordnate system.
  55338. // Avoid memory leak, dispose all not-used-registered.
  55339. each$1(store, function (record, coordId) {
  55340. var dataZoomInfos = record.dataZoomInfos;
  55341. if (dataZoomInfos[theDataZoomId]
  55342. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  55343. ) {
  55344. delete dataZoomInfos[theDataZoomId];
  55345. record.count--;
  55346. }
  55347. });
  55348. cleanStore(store);
  55349. var record = store[theCoordId];
  55350. // Create if needed.
  55351. if (!record) {
  55352. record = store[theCoordId] = {
  55353. coordId: theCoordId,
  55354. dataZoomInfos: {},
  55355. count: 0
  55356. };
  55357. record.controller = createController(api, record);
  55358. record.dispatchAction = curry(dispatchAction$1, api);
  55359. }
  55360. // Update reference of dataZoom.
  55361. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  55362. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  55363. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  55364. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  55365. // Consider resize, area should be always updated.
  55366. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  55367. // Update throttle.
  55368. createOrUpdate(
  55369. record,
  55370. 'dispatchAction',
  55371. dataZoomInfo.throttleRate,
  55372. 'fixRate'
  55373. );
  55374. }
  55375. /**
  55376. * @public
  55377. * @param {module:echarts/ExtensionAPI} api
  55378. * @param {string} dataZoomId
  55379. */
  55380. function unregister$1(api, dataZoomId) {
  55381. var store = giveStore(api);
  55382. each$1(store, function (record) {
  55383. record.controller.dispose();
  55384. var dataZoomInfos = record.dataZoomInfos;
  55385. if (dataZoomInfos[dataZoomId]) {
  55386. delete dataZoomInfos[dataZoomId];
  55387. record.count--;
  55388. }
  55389. });
  55390. cleanStore(store);
  55391. }
  55392. /**
  55393. * @public
  55394. */
  55395. function shouldRecordRange(payload, dataZoomId) {
  55396. if (payload && payload.type === 'dataZoom' && payload.batch) {
  55397. for (var i = 0, len = payload.batch.length; i < len; i++) {
  55398. if (payload.batch[i].dataZoomId === dataZoomId) {
  55399. return false;
  55400. }
  55401. }
  55402. }
  55403. return true;
  55404. }
  55405. /**
  55406. * @public
  55407. */
  55408. function generateCoordId(coordModel) {
  55409. return coordModel.type + '\0_' + coordModel.id;
  55410. }
  55411. /**
  55412. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  55413. * @type {Array.<Object>}
  55414. */
  55415. function giveStore(api) {
  55416. // Mount store on zrender instance, so that we do not
  55417. // need to worry about dispose.
  55418. var zr = api.getZr();
  55419. return zr[ATTR$1] || (zr[ATTR$1] = {});
  55420. }
  55421. function createController(api, newRecord) {
  55422. var controller = new RoamController(api.getZr());
  55423. controller.on('pan', curry$6(onPan, newRecord));
  55424. controller.on('zoom', curry$6(onZoom, newRecord));
  55425. return controller;
  55426. }
  55427. function cleanStore(store) {
  55428. each$1(store, function (record, coordId) {
  55429. if (!record.count) {
  55430. record.controller.dispose();
  55431. delete store[coordId];
  55432. }
  55433. });
  55434. }
  55435. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  55436. wrapAndDispatch(record, function (info) {
  55437. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  55438. });
  55439. }
  55440. function onZoom(record, scale, mouseX, mouseY) {
  55441. wrapAndDispatch(record, function (info) {
  55442. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  55443. });
  55444. }
  55445. function wrapAndDispatch(record, getRange) {
  55446. var batch = [];
  55447. each$1(record.dataZoomInfos, function (info) {
  55448. var range = getRange(info);
  55449. !info.disabled && range && batch.push({
  55450. dataZoomId: info.dataZoomId,
  55451. start: range[0],
  55452. end: range[1]
  55453. });
  55454. });
  55455. record.dispatchAction(batch);
  55456. }
  55457. /**
  55458. * This action will be throttled.
  55459. */
  55460. function dispatchAction$1(api, batch) {
  55461. api.dispatchAction({
  55462. type: 'dataZoom',
  55463. batch: batch
  55464. });
  55465. }
  55466. /**
  55467. * Merge roamController settings when multiple dataZooms share one roamController.
  55468. */
  55469. function mergeControllerParams(dataZoomInfos) {
  55470. var controlType;
  55471. var opt = {};
  55472. var typePriority = {
  55473. 'true': 2,
  55474. 'move': 1,
  55475. 'false': 0,
  55476. 'undefined': -1
  55477. };
  55478. each$1(dataZoomInfos, function (dataZoomInfo) {
  55479. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  55480. typePriority[oneType] > typePriority[controlType] && (controlType = oneType);
  55481. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  55482. extend(opt, dataZoomInfo.roamControllerOpt);
  55483. });
  55484. return {
  55485. controlType: controlType,
  55486. opt: opt
  55487. };
  55488. }
  55489. var bind$5 = bind;
  55490. var InsideZoomView = DataZoomView.extend({
  55491. type: 'dataZoom.inside',
  55492. /**
  55493. * @override
  55494. */
  55495. init: function (ecModel, api) {
  55496. /**
  55497. * 'throttle' is used in this.dispatchAction, so we save range
  55498. * to avoid missing some 'pan' info.
  55499. * @private
  55500. * @type {Array.<number>}
  55501. */
  55502. this._range;
  55503. },
  55504. /**
  55505. * @override
  55506. */
  55507. render: function (dataZoomModel, ecModel, api, payload) {
  55508. InsideZoomView.superApply(this, 'render', arguments);
  55509. // Notice: origin this._range should be maintained, and should not be re-fetched
  55510. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  55511. // info will be missed because of 'throttle' of this.dispatchAction.
  55512. if (shouldRecordRange(payload, dataZoomModel.id)) {
  55513. this._range = dataZoomModel.getPercentRange();
  55514. }
  55515. // Reset controllers.
  55516. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  55517. var allCoordIds = map(coordInfoList, function (coordInfo) {
  55518. return generateCoordId(coordInfo.model);
  55519. });
  55520. each$1(coordInfoList, function (coordInfo) {
  55521. var coordModel = coordInfo.model;
  55522. var dataZoomOption = dataZoomModel.option;
  55523. register$2(
  55524. api,
  55525. {
  55526. coordId: generateCoordId(coordModel),
  55527. allCoordIds: allCoordIds,
  55528. containsPoint: function (e, x, y) {
  55529. return coordModel.coordinateSystem.containPoint([x, y]);
  55530. },
  55531. dataZoomId: dataZoomModel.id,
  55532. throttleRate: dataZoomModel.get('throttle', true),
  55533. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  55534. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  55535. zoomLock: dataZoomOption.zoomLock,
  55536. disabled: dataZoomOption.disabled,
  55537. roamControllerOpt: {
  55538. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  55539. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  55540. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  55541. }
  55542. }
  55543. );
  55544. }, this);
  55545. }, this);
  55546. },
  55547. /**
  55548. * @override
  55549. */
  55550. dispose: function () {
  55551. unregister$1(this.api, this.dataZoomModel.id);
  55552. InsideZoomView.superApply(this, 'dispose', arguments);
  55553. this._range = null;
  55554. },
  55555. /**
  55556. * @private
  55557. */
  55558. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  55559. var range = this._range.slice();
  55560. // Calculate transform by the first axis.
  55561. var axisModel = coordInfo.axisModels[0];
  55562. if (!axisModel) {
  55563. return;
  55564. }
  55565. var directionInfo = getDirectionInfo[coordSysName](
  55566. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  55567. );
  55568. var percentDelta = directionInfo.signal
  55569. * (range[1] - range[0])
  55570. * directionInfo.pixel / directionInfo.pixelLength;
  55571. sliderMove(percentDelta, range, [0, 100], 'all');
  55572. return (this._range = range);
  55573. },
  55574. /**
  55575. * @private
  55576. */
  55577. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  55578. var range = this._range.slice();
  55579. // Calculate transform by the first axis.
  55580. var axisModel = coordInfo.axisModels[0];
  55581. if (!axisModel) {
  55582. return;
  55583. }
  55584. var directionInfo = getDirectionInfo[coordSysName](
  55585. null, [mouseX, mouseY], axisModel, controller, coordInfo
  55586. );
  55587. var percentPoint = (
  55588. directionInfo.signal > 0
  55589. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  55590. : (directionInfo.pixel - directionInfo.pixelStart)
  55591. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  55592. scale = Math.max(1 / scale, 0);
  55593. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  55594. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  55595. // Restrict range.
  55596. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55597. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  55598. return (this._range = range);
  55599. }
  55600. });
  55601. var getDirectionInfo = {
  55602. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55603. var axis = axisModel.axis;
  55604. var ret = {};
  55605. var rect = coordInfo.model.coordinateSystem.getRect();
  55606. oldPoint = oldPoint || [0, 0];
  55607. if (axis.dim === 'x') {
  55608. ret.pixel = newPoint[0] - oldPoint[0];
  55609. ret.pixelLength = rect.width;
  55610. ret.pixelStart = rect.x;
  55611. ret.signal = axis.inverse ? 1 : -1;
  55612. }
  55613. else { // axis.dim === 'y'
  55614. ret.pixel = newPoint[1] - oldPoint[1];
  55615. ret.pixelLength = rect.height;
  55616. ret.pixelStart = rect.y;
  55617. ret.signal = axis.inverse ? -1 : 1;
  55618. }
  55619. return ret;
  55620. },
  55621. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55622. var axis = axisModel.axis;
  55623. var ret = {};
  55624. var polar = coordInfo.model.coordinateSystem;
  55625. var radiusExtent = polar.getRadiusAxis().getExtent();
  55626. var angleExtent = polar.getAngleAxis().getExtent();
  55627. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  55628. newPoint = polar.pointToCoord(newPoint);
  55629. if (axisModel.mainType === 'radiusAxis') {
  55630. ret.pixel = newPoint[0] - oldPoint[0];
  55631. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  55632. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  55633. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  55634. ret.pixelStart = radiusExtent[0];
  55635. ret.signal = axis.inverse ? 1 : -1;
  55636. }
  55637. else { // 'angleAxis'
  55638. ret.pixel = newPoint[1] - oldPoint[1];
  55639. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  55640. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  55641. ret.pixelLength = angleExtent[1] - angleExtent[0];
  55642. ret.pixelStart = angleExtent[0];
  55643. ret.signal = axis.inverse ? -1 : 1;
  55644. }
  55645. return ret;
  55646. },
  55647. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55648. var axis = axisModel.axis;
  55649. var rect = coordInfo.model.coordinateSystem.getRect();
  55650. var ret = {};
  55651. oldPoint = oldPoint || [0, 0];
  55652. if (axis.orient === 'horizontal') {
  55653. ret.pixel = newPoint[0] - oldPoint[0];
  55654. ret.pixelLength = rect.width;
  55655. ret.pixelStart = rect.x;
  55656. ret.signal = axis.inverse ? 1 : -1;
  55657. }
  55658. else { // 'vertical'
  55659. ret.pixel = newPoint[1] - oldPoint[1];
  55660. ret.pixelLength = rect.height;
  55661. ret.pixelStart = rect.y;
  55662. ret.signal = axis.inverse ? -1 : 1;
  55663. }
  55664. return ret;
  55665. }
  55666. };
  55667. registerProcessor(function (ecModel, api) {
  55668. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  55669. // We calculate window and reset axis here but not in model
  55670. // init stage and not after action dispatch handler, because
  55671. // reset should be called after seriesData.restoreData.
  55672. dataZoomModel.eachTargetAxis(resetSingleAxis);
  55673. // Caution: data zoom filtering is order sensitive when using
  55674. // percent range and no min/max/scale set on axis.
  55675. // For example, we have dataZoom definition:
  55676. // [
  55677. // {xAxisIndex: 0, start: 30, end: 70},
  55678. // {yAxisIndex: 0, start: 20, end: 80}
  55679. // ]
  55680. // In this case, [20, 80] of y-dataZoom should be based on data
  55681. // that have filtered by x-dataZoom using range of [30, 70],
  55682. // but should not be based on full raw data. Thus sliding
  55683. // x-dataZoom will change both ranges of xAxis and yAxis,
  55684. // while sliding y-dataZoom will only change the range of yAxis.
  55685. // So we should filter x-axis after reset x-axis immediately,
  55686. // and then reset y-axis and filter y-axis.
  55687. dataZoomModel.eachTargetAxis(filterSingleAxis);
  55688. });
  55689. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  55690. // Fullfill all of the range props so that user
  55691. // is able to get them from chart.getOption().
  55692. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55693. var percentRange = axisProxy.getDataPercentWindow();
  55694. var valueRange = axisProxy.getDataValueWindow();
  55695. dataZoomModel.setRawRange({
  55696. start: percentRange[0],
  55697. end: percentRange[1],
  55698. startValue: valueRange[0],
  55699. endValue: valueRange[1]
  55700. }, true);
  55701. });
  55702. });
  55703. function resetSingleAxis(dimNames, axisIndex, dataZoomModel) {
  55704. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel);
  55705. }
  55706. function filterSingleAxis(dimNames, axisIndex, dataZoomModel) {
  55707. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel);
  55708. }
  55709. registerAction('dataZoom', function (payload, ecModel) {
  55710. var linkedNodesFinder = createLinkedNodesFinder(
  55711. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  55712. eachAxisDim$1,
  55713. function (model, dimNames) {
  55714. return model.get(dimNames.axisIndex);
  55715. }
  55716. );
  55717. var effectedModels = [];
  55718. ecModel.eachComponent(
  55719. {mainType: 'dataZoom', query: payload},
  55720. function (model, index) {
  55721. effectedModels.push.apply(
  55722. effectedModels, linkedNodesFinder(model).nodes
  55723. );
  55724. }
  55725. );
  55726. each$1(effectedModels, function (dataZoomModel, index) {
  55727. dataZoomModel.setRawRange({
  55728. start: payload.start,
  55729. end: payload.end,
  55730. startValue: payload.startValue,
  55731. endValue: payload.endValue
  55732. });
  55733. });
  55734. });
  55735. /**
  55736. * DataZoom component entry
  55737. */
  55738. var each$27 = each$1;
  55739. var preprocessor$2 = function (option) {
  55740. var visualMap = option && option.visualMap;
  55741. if (!isArray(visualMap)) {
  55742. visualMap = visualMap ? [visualMap] : [];
  55743. }
  55744. each$27(visualMap, function (opt) {
  55745. if (!opt) {
  55746. return;
  55747. }
  55748. // rename splitList to pieces
  55749. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  55750. opt.pieces = opt.splitList;
  55751. delete opt.splitList;
  55752. }
  55753. var pieces = opt.pieces;
  55754. if (pieces && isArray(pieces)) {
  55755. each$27(pieces, function (piece) {
  55756. if (isObject(piece)) {
  55757. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  55758. piece.min = piece.start;
  55759. }
  55760. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  55761. piece.max = piece.end;
  55762. }
  55763. }
  55764. });
  55765. }
  55766. });
  55767. };
  55768. function has$1(obj, name) {
  55769. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  55770. }
  55771. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  55772. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  55773. return (
  55774. !option.categories
  55775. && (
  55776. !(
  55777. option.pieces
  55778. ? option.pieces.length > 0
  55779. : option.splitNumber > 0
  55780. )
  55781. || option.calculable
  55782. )
  55783. )
  55784. ? 'continuous' : 'piecewise';
  55785. });
  55786. registerVisual(PRIORITY.VISUAL.COMPONENT, function (ecModel) {
  55787. ecModel.eachComponent('visualMap', function (visualMapModel) {
  55788. processSingleVisualMap(visualMapModel, ecModel);
  55789. });
  55790. prepareVisualMeta(ecModel);
  55791. });
  55792. function processSingleVisualMap(visualMapModel, ecModel) {
  55793. visualMapModel.eachTargetSeries(function (seriesModel) {
  55794. var data = seriesModel.getData();
  55795. applyVisual(
  55796. visualMapModel.stateList,
  55797. visualMapModel.targetVisuals,
  55798. data,
  55799. visualMapModel.getValueState,
  55800. visualMapModel,
  55801. visualMapModel.getDataDimension(data)
  55802. );
  55803. });
  55804. }
  55805. // Only support color.
  55806. function prepareVisualMeta(ecModel) {
  55807. ecModel.eachSeries(function (seriesModel) {
  55808. var data = seriesModel.getData();
  55809. var visualMetaList = [];
  55810. ecModel.eachComponent('visualMap', function (visualMapModel) {
  55811. if (visualMapModel.isTargetSeries(seriesModel)) {
  55812. var visualMeta = visualMapModel.getVisualMeta(
  55813. bind(getColorVisual, null, seriesModel, visualMapModel)
  55814. ) || {stops: [], outerColors: []};
  55815. visualMeta.dimension = visualMapModel.getDataDimension(data);
  55816. visualMetaList.push(visualMeta);
  55817. }
  55818. });
  55819. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  55820. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  55821. });
  55822. }
  55823. // FIXME
  55824. // performance and export for heatmap?
  55825. // value can be Infinity or -Infinity
  55826. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  55827. var mappings = visualMapModel.targetVisuals[valueState];
  55828. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  55829. var resultVisual = {
  55830. color: seriesModel.getData().getVisual('color') // default color.
  55831. };
  55832. for (var i = 0, len = visualTypes.length; i < len; i++) {
  55833. var type = visualTypes[i];
  55834. var mapping = mappings[
  55835. type === 'opacity' ? '__alphaForOpacity' : type
  55836. ];
  55837. mapping && mapping.applyVisual(value, getVisual, setVisual);
  55838. }
  55839. return resultVisual.color;
  55840. function getVisual(key) {
  55841. return resultVisual[key];
  55842. }
  55843. function setVisual(key, value) {
  55844. resultVisual[key] = value;
  55845. }
  55846. }
  55847. /**
  55848. * @file Visual mapping.
  55849. */
  55850. var visualDefault = {
  55851. /**
  55852. * @public
  55853. */
  55854. get: function (visualType, key, isCategory) {
  55855. var value = clone(
  55856. (defaultOption$3[visualType] || {})[key]
  55857. );
  55858. return isCategory
  55859. ? (isArray(value) ? value[value.length - 1] : value)
  55860. : value;
  55861. }
  55862. };
  55863. var defaultOption$3 = {
  55864. color: {
  55865. active: ['#006edd', '#e0ffff'],
  55866. inactive: ['rgba(0,0,0,0)']
  55867. },
  55868. colorHue: {
  55869. active: [0, 360],
  55870. inactive: [0, 0]
  55871. },
  55872. colorSaturation: {
  55873. active: [0.3, 1],
  55874. inactive: [0, 0]
  55875. },
  55876. colorLightness: {
  55877. active: [0.9, 0.5],
  55878. inactive: [0, 0]
  55879. },
  55880. colorAlpha: {
  55881. active: [0.3, 1],
  55882. inactive: [0, 0]
  55883. },
  55884. opacity: {
  55885. active: [0.3, 1],
  55886. inactive: [0, 0]
  55887. },
  55888. symbol: {
  55889. active: ['circle', 'roundRect', 'diamond'],
  55890. inactive: ['none']
  55891. },
  55892. symbolSize: {
  55893. active: [10, 50],
  55894. inactive: [0, 0]
  55895. }
  55896. };
  55897. var mapVisual$2 = VisualMapping.mapVisual;
  55898. var eachVisual = VisualMapping.eachVisual;
  55899. var isArray$3 = isArray;
  55900. var each$28 = each$1;
  55901. var asc$3 = asc;
  55902. var linearMap$3 = linearMap;
  55903. var noop$2 = noop;
  55904. var DEFAULT_COLOR = ['#f6efa6', '#d88273', '#bf444c'];
  55905. var VisualMapModel = extendComponentModel({
  55906. type: 'visualMap',
  55907. dependencies: ['series'],
  55908. /**
  55909. * @readOnly
  55910. * @type {Array.<string>}
  55911. */
  55912. stateList: ['inRange', 'outOfRange'],
  55913. /**
  55914. * @readOnly
  55915. * @type {Array.<string>}
  55916. */
  55917. replacableOptionKeys: [
  55918. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  55919. ],
  55920. /**
  55921. * [lowerBound, upperBound]
  55922. *
  55923. * @readOnly
  55924. * @type {Array.<number>}
  55925. */
  55926. dataBound: [-Infinity, Infinity],
  55927. /**
  55928. * @readOnly
  55929. * @type {string|Object}
  55930. */
  55931. layoutMode: {type: 'box', ignoreSize: true},
  55932. /**
  55933. * @protected
  55934. */
  55935. defaultOption: {
  55936. show: true,
  55937. zlevel: 0,
  55938. z: 4,
  55939. seriesIndex: 'all', // 'all' or null/undefined: all series.
  55940. // A number or an array of number: the specified series.
  55941. // set min: 0, max: 200, only for campatible with ec2.
  55942. // In fact min max should not have default value.
  55943. min: 0, // min value, must specified if pieces is not specified.
  55944. max: 200, // max value, must specified if pieces is not specified.
  55945. dimension: null,
  55946. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  55947. // 'symbol', 'symbolSize'
  55948. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  55949. // 'colorLightness', 'colorAlpha',
  55950. // 'symbol', 'symbolSize'
  55951. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  55952. right: null, // The same as left.
  55953. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  55954. bottom: 0, // The same as top.
  55955. itemWidth: null,
  55956. itemHeight: null,
  55957. inverse: false,
  55958. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  55959. backgroundColor: 'rgba(0,0,0,0)',
  55960. borderColor: '#ccc', // 值域边框颜色
  55961. contentColor: '#5793f3',
  55962. inactiveColor: '#aaa',
  55963. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  55964. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  55965. // 接受数组分别设定上右下左边距,同css
  55966. textGap: 10, //
  55967. precision: 0, // 小数精度,默认为0,无小数点
  55968. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  55969. formatter: null,
  55970. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  55971. textStyle: {
  55972. color: '#333' // 值域文字颜色
  55973. }
  55974. },
  55975. /**
  55976. * @protected
  55977. */
  55978. init: function (option, parentModel, ecModel) {
  55979. /**
  55980. * @private
  55981. * @type {Array.<number>}
  55982. */
  55983. this._dataExtent;
  55984. /**
  55985. * @readOnly
  55986. */
  55987. this.targetVisuals = {};
  55988. /**
  55989. * @readOnly
  55990. */
  55991. this.controllerVisuals = {};
  55992. /**
  55993. * @readOnly
  55994. */
  55995. this.textStyleModel;
  55996. /**
  55997. * [width, height]
  55998. * @readOnly
  55999. * @type {Array.<number>}
  56000. */
  56001. this.itemSize;
  56002. this.mergeDefaultAndTheme(option, ecModel);
  56003. },
  56004. /**
  56005. * @protected
  56006. */
  56007. optionUpdated: function (newOption, isInit) {
  56008. var thisOption = this.option;
  56009. // FIXME
  56010. // necessary?
  56011. // Disable realtime view update if canvas is not supported.
  56012. if (!env$1.canvasSupported) {
  56013. thisOption.realtime = false;
  56014. }
  56015. !isInit && replaceVisualOption(
  56016. thisOption, newOption, this.replacableOptionKeys
  56017. );
  56018. this.textStyleModel = this.getModel('textStyle');
  56019. this.resetItemSize();
  56020. this.completeVisualOption();
  56021. },
  56022. /**
  56023. * @protected
  56024. */
  56025. resetVisual: function (supplementVisualOption) {
  56026. var stateList = this.stateList;
  56027. supplementVisualOption = bind(supplementVisualOption, this);
  56028. this.controllerVisuals = createVisualMappings(
  56029. this.option.controller, stateList, supplementVisualOption
  56030. );
  56031. this.targetVisuals = createVisualMappings(
  56032. this.option.target, stateList, supplementVisualOption
  56033. );
  56034. },
  56035. /**
  56036. * @protected
  56037. * @return {Array.<number>} An array of series indices.
  56038. */
  56039. getTargetSeriesIndices: function () {
  56040. var optionSeriesIndex = this.option.seriesIndex;
  56041. var seriesIndices = [];
  56042. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  56043. this.ecModel.eachSeries(function (seriesModel, index) {
  56044. seriesIndices.push(index);
  56045. });
  56046. }
  56047. else {
  56048. seriesIndices = normalizeToArray(optionSeriesIndex);
  56049. }
  56050. return seriesIndices;
  56051. },
  56052. /**
  56053. * @public
  56054. */
  56055. eachTargetSeries: function (callback, context) {
  56056. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  56057. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  56058. }, this);
  56059. },
  56060. /**
  56061. * @pubilc
  56062. */
  56063. isTargetSeries: function (seriesModel) {
  56064. var is = false;
  56065. this.eachTargetSeries(function (model) {
  56066. model === seriesModel && (is = true);
  56067. });
  56068. return is;
  56069. },
  56070. /**
  56071. * @example
  56072. * this.formatValueText(someVal); // format single numeric value to text.
  56073. * this.formatValueText(someVal, true); // format single category value to text.
  56074. * this.formatValueText([min, max]); // format numeric min-max to text.
  56075. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  56076. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  56077. *
  56078. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  56079. * @param {boolean} [isCategory=false] Only available when value is number.
  56080. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  56081. * @return {string}
  56082. * @protected
  56083. */
  56084. formatValueText: function(value, isCategory, edgeSymbols) {
  56085. var option = this.option;
  56086. var precision = option.precision;
  56087. var dataBound = this.dataBound;
  56088. var formatter = option.formatter;
  56089. var isMinMax;
  56090. var textValue;
  56091. edgeSymbols = edgeSymbols || ['<', '>'];
  56092. if (isArray(value)) {
  56093. value = value.slice();
  56094. isMinMax = true;
  56095. }
  56096. textValue = isCategory
  56097. ? value
  56098. : (isMinMax
  56099. ? [toFixed(value[0]), toFixed(value[1])]
  56100. : toFixed(value)
  56101. );
  56102. if (isString(formatter)) {
  56103. return formatter
  56104. .replace('{value}', isMinMax ? textValue[0] : textValue)
  56105. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  56106. }
  56107. else if (isFunction(formatter)) {
  56108. return isMinMax
  56109. ? formatter(value[0], value[1])
  56110. : formatter(value);
  56111. }
  56112. if (isMinMax) {
  56113. if (value[0] === dataBound[0]) {
  56114. return edgeSymbols[0] + ' ' + textValue[1];
  56115. }
  56116. else if (value[1] === dataBound[1]) {
  56117. return edgeSymbols[1] + ' ' + textValue[0];
  56118. }
  56119. else {
  56120. return textValue[0] + ' - ' + textValue[1];
  56121. }
  56122. }
  56123. else { // Format single value (includes category case).
  56124. return textValue;
  56125. }
  56126. function toFixed(val) {
  56127. return val === dataBound[0]
  56128. ? 'min'
  56129. : val === dataBound[1]
  56130. ? 'max'
  56131. : (+val).toFixed(Math.min(precision, 20));
  56132. }
  56133. },
  56134. /**
  56135. * @protected
  56136. */
  56137. resetExtent: function () {
  56138. var thisOption = this.option;
  56139. // Can not calculate data extent by data here.
  56140. // Because series and data may be modified in processing stage.
  56141. // So we do not support the feature "auto min/max".
  56142. var extent = asc$3([thisOption.min, thisOption.max]);
  56143. this._dataExtent = extent;
  56144. },
  56145. /**
  56146. * @public
  56147. * @param {module:echarts/data/List} list
  56148. * @return {string} Concrete dimention. If return null/undefined,
  56149. * no dimension used.
  56150. */
  56151. getDataDimension: function (list) {
  56152. var optDim = this.option.dimension;
  56153. return optDim != null
  56154. ? optDim : list.dimensions.length - 1;
  56155. },
  56156. /**
  56157. * @public
  56158. * @override
  56159. */
  56160. getExtent: function () {
  56161. return this._dataExtent.slice();
  56162. },
  56163. /**
  56164. * @protected
  56165. */
  56166. completeVisualOption: function () {
  56167. var thisOption = this.option;
  56168. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  56169. var target = thisOption.target || (thisOption.target = {});
  56170. var controller = thisOption.controller || (thisOption.controller = {});
  56171. merge(target, base); // Do not override
  56172. merge(controller, base); // Do not override
  56173. var isCategory = this.isCategory();
  56174. completeSingle.call(this, target);
  56175. completeSingle.call(this, controller);
  56176. completeInactive.call(this, target, 'inRange', 'outOfRange');
  56177. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  56178. completeController.call(this, controller);
  56179. function completeSingle(base) {
  56180. // Compatible with ec2 dataRange.color.
  56181. // The mapping order of dataRange.color is: [high value, ..., low value]
  56182. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  56183. // Notice: ec2 has no inverse.
  56184. if (isArray$3(thisOption.color)
  56185. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  56186. // So adding color only when no inRange defined.
  56187. && !base.inRange
  56188. ) {
  56189. base.inRange = {color: thisOption.color.slice().reverse()};
  56190. }
  56191. // Compatible with previous logic, always give a defautl color, otherwise
  56192. // simple config with no inRange and outOfRange will not work.
  56193. // Originally we use visualMap.color as the default color, but setOption at
  56194. // the second time the default color will be erased. So we change to use
  56195. // constant DEFAULT_COLOR.
  56196. // If user do not want the defualt color, set inRange: {color: null}.
  56197. base.inRange = base.inRange || {color: DEFAULT_COLOR};
  56198. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  56199. each$28(this.stateList, function (state) {
  56200. var visualType = base[state];
  56201. if (isString(visualType)) {
  56202. var defa = visualDefault.get(visualType, 'active', isCategory);
  56203. if (defa) {
  56204. base[state] = {};
  56205. base[state][visualType] = defa;
  56206. }
  56207. else {
  56208. // Mark as not specified.
  56209. delete base[state];
  56210. }
  56211. }
  56212. }, this);
  56213. }
  56214. function completeInactive(base, stateExist, stateAbsent) {
  56215. var optExist = base[stateExist];
  56216. var optAbsent = base[stateAbsent];
  56217. if (optExist && !optAbsent) {
  56218. optAbsent = base[stateAbsent] = {};
  56219. each$28(optExist, function (visualData, visualType) {
  56220. if (!VisualMapping.isValidType(visualType)) {
  56221. return;
  56222. }
  56223. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  56224. if (defa != null) {
  56225. optAbsent[visualType] = defa;
  56226. // Compatibable with ec2:
  56227. // Only inactive color to rgba(0,0,0,0) can not
  56228. // make label transparent, so use opacity also.
  56229. if (visualType === 'color'
  56230. && !optAbsent.hasOwnProperty('opacity')
  56231. && !optAbsent.hasOwnProperty('colorAlpha')
  56232. ) {
  56233. optAbsent.opacity = [0, 0];
  56234. }
  56235. }
  56236. });
  56237. }
  56238. }
  56239. function completeController(controller) {
  56240. var symbolExists = (controller.inRange || {}).symbol
  56241. || (controller.outOfRange || {}).symbol;
  56242. var symbolSizeExists = (controller.inRange || {}).symbolSize
  56243. || (controller.outOfRange || {}).symbolSize;
  56244. var inactiveColor = this.get('inactiveColor');
  56245. each$28(this.stateList, function (state) {
  56246. var itemSize = this.itemSize;
  56247. var visuals = controller[state];
  56248. // Set inactive color for controller if no other color
  56249. // attr (like colorAlpha) specified.
  56250. if (!visuals) {
  56251. visuals = controller[state] = {
  56252. color: isCategory ? inactiveColor : [inactiveColor]
  56253. };
  56254. }
  56255. // Consistent symbol and symbolSize if not specified.
  56256. if (visuals.symbol == null) {
  56257. visuals.symbol = symbolExists
  56258. && clone(symbolExists)
  56259. || (isCategory ? 'roundRect' : ['roundRect']);
  56260. }
  56261. if (visuals.symbolSize == null) {
  56262. visuals.symbolSize = symbolSizeExists
  56263. && clone(symbolSizeExists)
  56264. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  56265. }
  56266. // Filter square and none.
  56267. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  56268. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  56269. });
  56270. // Normalize symbolSize
  56271. var symbolSize = visuals.symbolSize;
  56272. if (symbolSize != null) {
  56273. var max = -Infinity;
  56274. // symbolSize can be object when categories defined.
  56275. eachVisual(symbolSize, function (value) {
  56276. value > max && (max = value);
  56277. });
  56278. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  56279. return linearMap$3(value, [0, max], [0, itemSize[0]], true);
  56280. });
  56281. }
  56282. }, this);
  56283. }
  56284. },
  56285. /**
  56286. * @protected
  56287. */
  56288. resetItemSize: function () {
  56289. this.itemSize = [
  56290. parseFloat(this.get('itemWidth')),
  56291. parseFloat(this.get('itemHeight'))
  56292. ];
  56293. },
  56294. /**
  56295. * @public
  56296. */
  56297. isCategory: function () {
  56298. return !!this.option.categories;
  56299. },
  56300. /**
  56301. * @public
  56302. * @abstract
  56303. */
  56304. setSelected: noop$2,
  56305. /**
  56306. * @public
  56307. * @abstract
  56308. * @param {*|module:echarts/data/List} valueOrData
  56309. * @param {number} dataIndex
  56310. * @return {string} state See this.stateList
  56311. */
  56312. getValueState: noop$2,
  56313. /**
  56314. * FIXME
  56315. * Do not publish to thirt-part-dev temporarily
  56316. * util the interface is stable. (Should it return
  56317. * a function but not visual meta?)
  56318. *
  56319. * @pubilc
  56320. * @abstract
  56321. * @param {Function} getColorVisual
  56322. * params: value, valueState
  56323. * return: color
  56324. * @return {Object} visualMeta
  56325. * should includes {stops, outerColors}
  56326. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  56327. */
  56328. getVisualMeta: noop$2
  56329. });
  56330. // Constant
  56331. var DEFAULT_BAR_BOUND = [20, 140];
  56332. var ContinuousModel = VisualMapModel.extend({
  56333. type: 'visualMap.continuous',
  56334. /**
  56335. * @protected
  56336. */
  56337. defaultOption: {
  56338. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  56339. calculable: false, // This prop effect default component type determine,
  56340. // See echarts/component/visualMap/typeDefaulter.
  56341. range: null, // selected range. In default case `range` is [min, max]
  56342. // and can auto change along with modification of min max,
  56343. // util use specifid a range.
  56344. realtime: true, // Whether realtime update.
  56345. itemHeight: null, // The length of the range control edge.
  56346. itemWidth: null, // The length of the other side.
  56347. hoverLink: true, // Enable hover highlight.
  56348. hoverLinkDataSize: null,// The size of hovered data.
  56349. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  56350. // If not specified, follow the value of `realtime`.
  56351. },
  56352. /**
  56353. * @override
  56354. */
  56355. optionUpdated: function (newOption, isInit) {
  56356. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  56357. this.resetExtent();
  56358. this.resetVisual(function (mappingOption) {
  56359. mappingOption.mappingMethod = 'linear';
  56360. mappingOption.dataExtent = this.getExtent();
  56361. });
  56362. this._resetRange();
  56363. },
  56364. /**
  56365. * @protected
  56366. * @override
  56367. */
  56368. resetItemSize: function () {
  56369. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  56370. var itemSize = this.itemSize;
  56371. this._orient === 'horizontal' && itemSize.reverse();
  56372. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  56373. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  56374. },
  56375. /**
  56376. * @private
  56377. */
  56378. _resetRange: function () {
  56379. var dataExtent = this.getExtent();
  56380. var range = this.option.range;
  56381. if (!range || range.auto) {
  56382. // `range` should always be array (so we dont use other
  56383. // value like 'auto') for user-friend. (consider getOption).
  56384. dataExtent.auto = 1;
  56385. this.option.range = dataExtent;
  56386. }
  56387. else if (isArray(range)) {
  56388. if (range[0] > range[1]) {
  56389. range.reverse();
  56390. }
  56391. range[0] = Math.max(range[0], dataExtent[0]);
  56392. range[1] = Math.min(range[1], dataExtent[1]);
  56393. }
  56394. },
  56395. /**
  56396. * @protected
  56397. * @override
  56398. */
  56399. completeVisualOption: function () {
  56400. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  56401. each$1(this.stateList, function (state) {
  56402. var symbolSize = this.option.controller[state].symbolSize;
  56403. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  56404. symbolSize[0] = 0; // For good looking.
  56405. }
  56406. }, this);
  56407. },
  56408. /**
  56409. * @override
  56410. */
  56411. setSelected: function (selected) {
  56412. this.option.range = selected.slice();
  56413. this._resetRange();
  56414. },
  56415. /**
  56416. * @public
  56417. */
  56418. getSelected: function () {
  56419. var dataExtent = this.getExtent();
  56420. var dataInterval = asc(
  56421. (this.get('range') || []).slice()
  56422. );
  56423. // Clamp
  56424. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  56425. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  56426. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  56427. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  56428. return dataInterval;
  56429. },
  56430. /**
  56431. * @override
  56432. */
  56433. getValueState: function (value) {
  56434. var range = this.option.range;
  56435. var dataExtent = this.getExtent();
  56436. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  56437. // range[1] is processed likewise.
  56438. return (
  56439. (range[0] <= dataExtent[0] || range[0] <= value)
  56440. && (range[1] >= dataExtent[1] || value <= range[1])
  56441. ) ? 'inRange' : 'outOfRange';
  56442. },
  56443. /**
  56444. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  56445. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  56446. */
  56447. findTargetDataIndices: function (range) {
  56448. var result = [];
  56449. this.eachTargetSeries(function (seriesModel) {
  56450. var dataIndices = [];
  56451. var data = seriesModel.getData();
  56452. data.each(this.getDataDimension(data), function (value, dataIndex) {
  56453. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  56454. }, true, this);
  56455. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  56456. }, this);
  56457. return result;
  56458. },
  56459. /**
  56460. * @implement
  56461. */
  56462. getVisualMeta: function (getColorVisual) {
  56463. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  56464. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  56465. var stops = [];
  56466. function setStop(value, valueState) {
  56467. stops.push({
  56468. value: value,
  56469. color: getColorVisual(value, valueState)
  56470. });
  56471. }
  56472. // Format to: outOfRange -- inRange -- outOfRange.
  56473. var iIdx = 0;
  56474. var oIdx = 0;
  56475. var iLen = iVals.length;
  56476. var oLen = oVals.length;
  56477. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  56478. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  56479. if (oVals[oIdx] < iVals[iIdx]) {
  56480. setStop(oVals[oIdx], 'outOfRange');
  56481. }
  56482. }
  56483. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  56484. // If range is full, value beyond min, max will be clamped.
  56485. // make a singularity
  56486. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  56487. setStop(iVals[iIdx], 'inRange');
  56488. }
  56489. for (var first = 1; oIdx < oLen; oIdx++) {
  56490. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  56491. // make a singularity
  56492. if (first) {
  56493. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  56494. first = 0;
  56495. }
  56496. setStop(oVals[oIdx], 'outOfRange');
  56497. }
  56498. }
  56499. var stopsLen = stops.length;
  56500. return {
  56501. stops: stops,
  56502. outerColors: [
  56503. stopsLen ? stops[0].color : 'transparent',
  56504. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  56505. ]
  56506. };
  56507. }
  56508. });
  56509. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  56510. if (dataExtent[0] === dataExtent[1]) {
  56511. return dataExtent.slice();
  56512. }
  56513. // When using colorHue mapping, it is not linear color any more.
  56514. // Moreover, canvas gradient seems not to be accurate linear.
  56515. // FIXME
  56516. // Should be arbitrary value 100? or based on pixel size?
  56517. var count = 200;
  56518. var step = (dataExtent[1] - dataExtent[0]) / count;
  56519. var value = dataExtent[0];
  56520. var stopValues = [];
  56521. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  56522. stopValues.push(value);
  56523. value += step;
  56524. }
  56525. stopValues.push(dataExtent[1]);
  56526. return stopValues;
  56527. }
  56528. var VisualMapView = extendComponentView({
  56529. type: 'visualMap',
  56530. /**
  56531. * @readOnly
  56532. * @type {Object}
  56533. */
  56534. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  56535. init: function (ecModel, api) {
  56536. /**
  56537. * @readOnly
  56538. * @type {module:echarts/model/Global}
  56539. */
  56540. this.ecModel = ecModel;
  56541. /**
  56542. * @readOnly
  56543. * @type {module:echarts/ExtensionAPI}
  56544. */
  56545. this.api = api;
  56546. /**
  56547. * @readOnly
  56548. * @type {module:echarts/component/visualMap/visualMapModel}
  56549. */
  56550. this.visualMapModel;
  56551. },
  56552. /**
  56553. * @protected
  56554. */
  56555. render: function (visualMapModel, ecModel, api, payload) {
  56556. this.visualMapModel = visualMapModel;
  56557. if (visualMapModel.get('show') === false) {
  56558. this.group.removeAll();
  56559. return;
  56560. }
  56561. this.doRender.apply(this, arguments);
  56562. },
  56563. /**
  56564. * @protected
  56565. */
  56566. renderBackground: function (group) {
  56567. var visualMapModel = this.visualMapModel;
  56568. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  56569. var rect = group.getBoundingRect();
  56570. group.add(new Rect({
  56571. z2: -1, // Lay background rect on the lowest layer.
  56572. silent: true,
  56573. shape: {
  56574. x: rect.x - padding[3],
  56575. y: rect.y - padding[0],
  56576. width: rect.width + padding[3] + padding[1],
  56577. height: rect.height + padding[0] + padding[2]
  56578. },
  56579. style: {
  56580. fill: visualMapModel.get('backgroundColor'),
  56581. stroke: visualMapModel.get('borderColor'),
  56582. lineWidth: visualMapModel.get('borderWidth')
  56583. }
  56584. }));
  56585. },
  56586. /**
  56587. * @protected
  56588. * @param {number} targetValue can be Infinity or -Infinity
  56589. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  56590. * @param {Object} [opts]
  56591. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  56592. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  56593. * @return {*} Visual value.
  56594. */
  56595. getControllerVisual: function (targetValue, visualCluster, opts) {
  56596. opts = opts || {};
  56597. var forceState = opts.forceState;
  56598. var visualMapModel = this.visualMapModel;
  56599. var visualObj = {};
  56600. // Default values.
  56601. if (visualCluster === 'symbol') {
  56602. visualObj.symbol = visualMapModel.get('itemSymbol');
  56603. }
  56604. if (visualCluster === 'color') {
  56605. var defaultColor = visualMapModel.get('contentColor');
  56606. visualObj.color = defaultColor;
  56607. }
  56608. function getter(key) {
  56609. return visualObj[key];
  56610. }
  56611. function setter(key, value) {
  56612. visualObj[key] = value;
  56613. }
  56614. var mappings = visualMapModel.controllerVisuals[
  56615. forceState || visualMapModel.getValueState(targetValue)
  56616. ];
  56617. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  56618. each$1(visualTypes, function (type) {
  56619. var visualMapping = mappings[type];
  56620. if (opts.convertOpacityToAlpha && type === 'opacity') {
  56621. type = 'colorAlpha';
  56622. visualMapping = mappings.__alphaForOpacity;
  56623. }
  56624. if (VisualMapping.dependsOn(type, visualCluster)) {
  56625. visualMapping && visualMapping.applyVisual(
  56626. targetValue, getter, setter
  56627. );
  56628. }
  56629. });
  56630. return visualObj[visualCluster];
  56631. },
  56632. /**
  56633. * @protected
  56634. */
  56635. positionGroup: function (group) {
  56636. var model = this.visualMapModel;
  56637. var api = this.api;
  56638. positionElement(
  56639. group,
  56640. model.getBoxLayoutParams(),
  56641. {width: api.getWidth(), height: api.getHeight()}
  56642. );
  56643. },
  56644. /**
  56645. * @protected
  56646. * @abstract
  56647. */
  56648. doRender: noop
  56649. });
  56650. /**
  56651. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  56652. * @param {module:echarts/ExtensionAPI} api
  56653. * @param {Array.<number>} itemSize always [short, long]
  56654. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  56655. */
  56656. function getItemAlign(visualMapModel, api, itemSize) {
  56657. var modelOption = visualMapModel.option;
  56658. var itemAlign = modelOption.align;
  56659. if (itemAlign != null && itemAlign !== 'auto') {
  56660. return itemAlign;
  56661. }
  56662. // Auto decision align.
  56663. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  56664. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  56665. var paramsSet = [
  56666. ['left', 'right', 'width'],
  56667. ['top', 'bottom', 'height']
  56668. ];
  56669. var reals = paramsSet[realIndex];
  56670. var fakeValue = [0, null, 10];
  56671. var layoutInput = {};
  56672. for (var i = 0; i < 3; i++) {
  56673. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  56674. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  56675. }
  56676. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  56677. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  56678. return reals[
  56679. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  56680. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  56681. ];
  56682. }
  56683. /**
  56684. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  56685. * dataIndexInside means filtered index.
  56686. */
  56687. function convertDataIndex(batch) {
  56688. each$1(batch || [], function (batchItem) {
  56689. if (batch.dataIndex != null) {
  56690. batch.dataIndexInside = batch.dataIndex;
  56691. batch.dataIndex = null;
  56692. }
  56693. });
  56694. return batch;
  56695. }
  56696. var linearMap$4 = linearMap;
  56697. var each$29 = each$1;
  56698. var mathMin$7 = Math.min;
  56699. var mathMax$7 = Math.max;
  56700. // Arbitrary value
  56701. var HOVER_LINK_SIZE = 12;
  56702. var HOVER_LINK_OUT = 6;
  56703. // Notice:
  56704. // Any "interval" should be by the order of [low, high].
  56705. // "handle0" (handleIndex === 0) maps to
  56706. // low data value: this._dataInterval[0] and has low coord.
  56707. // "handle1" (handleIndex === 1) maps to
  56708. // high data value: this._dataInterval[1] and has high coord.
  56709. // The logic of transform is implemented in this._createBarGroup.
  56710. var ContinuousView = VisualMapView.extend({
  56711. type: 'visualMap.continuous',
  56712. /**
  56713. * @override
  56714. */
  56715. init: function () {
  56716. ContinuousView.superApply(this, 'init', arguments);
  56717. /**
  56718. * @private
  56719. */
  56720. this._shapes = {};
  56721. /**
  56722. * @private
  56723. */
  56724. this._dataInterval = [];
  56725. /**
  56726. * @private
  56727. */
  56728. this._handleEnds = [];
  56729. /**
  56730. * @private
  56731. */
  56732. this._orient;
  56733. /**
  56734. * @private
  56735. */
  56736. this._useHandle;
  56737. /**
  56738. * @private
  56739. */
  56740. this._hoverLinkDataIndices = [];
  56741. /**
  56742. * @private
  56743. */
  56744. this._dragging;
  56745. /**
  56746. * @private
  56747. */
  56748. this._hovering;
  56749. },
  56750. /**
  56751. * @protected
  56752. * @override
  56753. */
  56754. doRender: function (visualMapModel, ecModel, api, payload) {
  56755. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  56756. this._buildView();
  56757. }
  56758. },
  56759. /**
  56760. * @private
  56761. */
  56762. _buildView: function () {
  56763. this.group.removeAll();
  56764. var visualMapModel = this.visualMapModel;
  56765. var thisGroup = this.group;
  56766. this._orient = visualMapModel.get('orient');
  56767. this._useHandle = visualMapModel.get('calculable');
  56768. this._resetInterval();
  56769. this._renderBar(thisGroup);
  56770. var dataRangeText = visualMapModel.get('text');
  56771. this._renderEndsText(thisGroup, dataRangeText, 0);
  56772. this._renderEndsText(thisGroup, dataRangeText, 1);
  56773. // Do this for background size calculation.
  56774. this._updateView(true);
  56775. // After updating view, inner shapes is built completely,
  56776. // and then background can be rendered.
  56777. this.renderBackground(thisGroup);
  56778. // Real update view
  56779. this._updateView();
  56780. this._enableHoverLinkToSeries();
  56781. this._enableHoverLinkFromSeries();
  56782. this.positionGroup(thisGroup);
  56783. },
  56784. /**
  56785. * @private
  56786. */
  56787. _renderEndsText: function (group, dataRangeText, endsIndex) {
  56788. if (!dataRangeText) {
  56789. return;
  56790. }
  56791. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  56792. var text = dataRangeText[1 - endsIndex];
  56793. text = text != null ? text + '' : '';
  56794. var visualMapModel = this.visualMapModel;
  56795. var textGap = visualMapModel.get('textGap');
  56796. var itemSize = visualMapModel.itemSize;
  56797. var barGroup = this._shapes.barGroup;
  56798. var position = this._applyTransform(
  56799. [
  56800. itemSize[0] / 2,
  56801. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  56802. ],
  56803. barGroup
  56804. );
  56805. var align = this._applyTransform(
  56806. endsIndex === 0 ? 'bottom' : 'top',
  56807. barGroup
  56808. );
  56809. var orient = this._orient;
  56810. var textStyleModel = this.visualMapModel.textStyleModel;
  56811. this.group.add(new Text({
  56812. style: {
  56813. x: position[0],
  56814. y: position[1],
  56815. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  56816. textAlign: orient === 'horizontal' ? align : 'center',
  56817. text: text,
  56818. textFont: textStyleModel.getFont(),
  56819. textFill: textStyleModel.getTextColor()
  56820. }
  56821. }));
  56822. },
  56823. /**
  56824. * @private
  56825. */
  56826. _renderBar: function (targetGroup) {
  56827. var visualMapModel = this.visualMapModel;
  56828. var shapes = this._shapes;
  56829. var itemSize = visualMapModel.itemSize;
  56830. var orient = this._orient;
  56831. var useHandle = this._useHandle;
  56832. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  56833. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  56834. // Bar
  56835. barGroup.add(shapes.outOfRange = createPolygon());
  56836. barGroup.add(shapes.inRange = createPolygon(
  56837. null,
  56838. useHandle ? getCursor$1(this._orient) : null,
  56839. bind(this._dragHandle, this, 'all', false),
  56840. bind(this._dragHandle, this, 'all', true)
  56841. ));
  56842. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  56843. var textSize = mathMax$7(textRect.width, textRect.height);
  56844. // Handle
  56845. if (useHandle) {
  56846. shapes.handleThumbs = [];
  56847. shapes.handleLabels = [];
  56848. shapes.handleLabelPoints = [];
  56849. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  56850. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  56851. }
  56852. this._createIndicator(barGroup, itemSize, textSize, orient);
  56853. targetGroup.add(barGroup);
  56854. },
  56855. /**
  56856. * @private
  56857. */
  56858. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  56859. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  56860. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  56861. var handleThumb = createPolygon(
  56862. createHandlePoints(handleIndex, textSize),
  56863. getCursor$1(this._orient),
  56864. onDrift,
  56865. onDragEnd
  56866. );
  56867. handleThumb.position[0] = itemSize[0];
  56868. barGroup.add(handleThumb);
  56869. // Text is always horizontal layout but should not be effected by
  56870. // transform (orient/inverse). So label is built separately but not
  56871. // use zrender/graphic/helper/RectText, and is located based on view
  56872. // group (according to handleLabelPoint) but not barGroup.
  56873. var textStyleModel = this.visualMapModel.textStyleModel;
  56874. var handleLabel = new Text({
  56875. draggable: true,
  56876. drift: onDrift,
  56877. onmousemove: function (e) {
  56878. // Fot mobile devicem, prevent screen slider on the button.
  56879. stop(e.event);
  56880. },
  56881. ondragend: onDragEnd,
  56882. style: {
  56883. x: 0, y: 0, text: '',
  56884. textFont: textStyleModel.getFont(),
  56885. textFill: textStyleModel.getTextColor()
  56886. }
  56887. });
  56888. this.group.add(handleLabel);
  56889. var handleLabelPoint = [
  56890. orient === 'horizontal'
  56891. ? textSize / 2
  56892. : textSize * 1.5,
  56893. orient === 'horizontal'
  56894. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  56895. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  56896. ];
  56897. var shapes = this._shapes;
  56898. shapes.handleThumbs[handleIndex] = handleThumb;
  56899. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  56900. shapes.handleLabels[handleIndex] = handleLabel;
  56901. },
  56902. /**
  56903. * @private
  56904. */
  56905. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  56906. var indicator = createPolygon([[0, 0]], 'move');
  56907. indicator.position[0] = itemSize[0];
  56908. indicator.attr({invisible: true, silent: true});
  56909. barGroup.add(indicator);
  56910. var textStyleModel = this.visualMapModel.textStyleModel;
  56911. var indicatorLabel = new Text({
  56912. silent: true,
  56913. invisible: true,
  56914. style: {
  56915. x: 0, y: 0, text: '',
  56916. textFont: textStyleModel.getFont(),
  56917. textFill: textStyleModel.getTextColor()
  56918. }
  56919. });
  56920. this.group.add(indicatorLabel);
  56921. var indicatorLabelPoint = [
  56922. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  56923. 0
  56924. ];
  56925. var shapes = this._shapes;
  56926. shapes.indicator = indicator;
  56927. shapes.indicatorLabel = indicatorLabel;
  56928. shapes.indicatorLabelPoint = indicatorLabelPoint;
  56929. },
  56930. /**
  56931. * @private
  56932. */
  56933. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  56934. if (!this._useHandle) {
  56935. return;
  56936. }
  56937. this._dragging = !isEnd;
  56938. if (!isEnd) {
  56939. // Transform dx, dy to bar coordination.
  56940. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  56941. this._updateInterval(handleIndex, vertex[1]);
  56942. // Considering realtime, update view should be executed
  56943. // before dispatch action.
  56944. this._updateView();
  56945. }
  56946. // dragEnd do not dispatch action when realtime.
  56947. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  56948. this.api.dispatchAction({
  56949. type: 'selectDataRange',
  56950. from: this.uid,
  56951. visualMapId: this.visualMapModel.id,
  56952. selected: this._dataInterval.slice()
  56953. });
  56954. }
  56955. if (isEnd) {
  56956. !this._hovering && this._clearHoverLinkToSeries();
  56957. }
  56958. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  56959. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  56960. }
  56961. },
  56962. /**
  56963. * @private
  56964. */
  56965. _resetInterval: function () {
  56966. var visualMapModel = this.visualMapModel;
  56967. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  56968. var dataExtent = visualMapModel.getExtent();
  56969. var sizeExtent = [0, visualMapModel.itemSize[1]];
  56970. this._handleEnds = [
  56971. linearMap$4(dataInterval[0], dataExtent, sizeExtent, true),
  56972. linearMap$4(dataInterval[1], dataExtent, sizeExtent, true)
  56973. ];
  56974. },
  56975. /**
  56976. * @private
  56977. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  56978. * @param {number} dx
  56979. * @param {number} dy
  56980. */
  56981. _updateInterval: function (handleIndex, delta) {
  56982. delta = delta || 0;
  56983. var visualMapModel = this.visualMapModel;
  56984. var handleEnds = this._handleEnds;
  56985. var sizeExtent = [0, visualMapModel.itemSize[1]];
  56986. sliderMove(
  56987. delta,
  56988. handleEnds,
  56989. sizeExtent,
  56990. handleIndex,
  56991. // cross is forbiden
  56992. 0
  56993. );
  56994. var dataExtent = visualMapModel.getExtent();
  56995. // Update data interval.
  56996. this._dataInterval = [
  56997. linearMap$4(handleEnds[0], sizeExtent, dataExtent, true),
  56998. linearMap$4(handleEnds[1], sizeExtent, dataExtent, true)
  56999. ];
  57000. },
  57001. /**
  57002. * @private
  57003. */
  57004. _updateView: function (forSketch) {
  57005. var visualMapModel = this.visualMapModel;
  57006. var dataExtent = visualMapModel.getExtent();
  57007. var shapes = this._shapes;
  57008. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  57009. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  57010. var visualInRange = this._createBarVisual(
  57011. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  57012. );
  57013. var visualOutOfRange = this._createBarVisual(
  57014. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  57015. );
  57016. shapes.inRange
  57017. .setStyle({
  57018. fill: visualInRange.barColor,
  57019. opacity: visualInRange.opacity
  57020. })
  57021. .setShape('points', visualInRange.barPoints);
  57022. shapes.outOfRange
  57023. .setStyle({
  57024. fill: visualOutOfRange.barColor,
  57025. opacity: visualOutOfRange.opacity
  57026. })
  57027. .setShape('points', visualOutOfRange.barPoints);
  57028. this._updateHandle(inRangeHandleEnds, visualInRange);
  57029. },
  57030. /**
  57031. * @private
  57032. */
  57033. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  57034. var opts = {
  57035. forceState: forceState,
  57036. convertOpacityToAlpha: true
  57037. };
  57038. var colorStops = this._makeColorGradient(dataInterval, opts);
  57039. var symbolSizes = [
  57040. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  57041. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  57042. ];
  57043. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  57044. return {
  57045. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  57046. barPoints: barPoints,
  57047. handlesColor: [
  57048. colorStops[0].color,
  57049. colorStops[colorStops.length - 1].color
  57050. ]
  57051. };
  57052. },
  57053. /**
  57054. * @private
  57055. */
  57056. _makeColorGradient: function (dataInterval, opts) {
  57057. // Considering colorHue, which is not linear, so we have to sample
  57058. // to calculate gradient color stops, but not only caculate head
  57059. // and tail.
  57060. var sampleNumber = 100; // Arbitrary value.
  57061. var colorStops = [];
  57062. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  57063. colorStops.push({
  57064. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  57065. offset: 0
  57066. });
  57067. for (var i = 1; i < sampleNumber; i++) {
  57068. var currValue = dataInterval[0] + step * i;
  57069. if (currValue > dataInterval[1]) {
  57070. break;
  57071. }
  57072. colorStops.push({
  57073. color: this.getControllerVisual(currValue, 'color', opts),
  57074. offset: i / sampleNumber
  57075. });
  57076. }
  57077. colorStops.push({
  57078. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  57079. offset: 1
  57080. });
  57081. return colorStops;
  57082. },
  57083. /**
  57084. * @private
  57085. */
  57086. _createBarPoints: function (handleEnds, symbolSizes) {
  57087. var itemSize = this.visualMapModel.itemSize;
  57088. return [
  57089. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  57090. [itemSize[0], handleEnds[0]],
  57091. [itemSize[0], handleEnds[1]],
  57092. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  57093. ];
  57094. },
  57095. /**
  57096. * @private
  57097. */
  57098. _createBarGroup: function (itemAlign) {
  57099. var orient = this._orient;
  57100. var inverse = this.visualMapModel.get('inverse');
  57101. return new Group(
  57102. (orient === 'horizontal' && !inverse)
  57103. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  57104. : (orient === 'horizontal' && inverse)
  57105. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  57106. : (orient === 'vertical' && !inverse)
  57107. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  57108. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  57109. );
  57110. },
  57111. /**
  57112. * @private
  57113. */
  57114. _updateHandle: function (handleEnds, visualInRange) {
  57115. if (!this._useHandle) {
  57116. return;
  57117. }
  57118. var shapes = this._shapes;
  57119. var visualMapModel = this.visualMapModel;
  57120. var handleThumbs = shapes.handleThumbs;
  57121. var handleLabels = shapes.handleLabels;
  57122. each$29([0, 1], function (handleIndex) {
  57123. var handleThumb = handleThumbs[handleIndex];
  57124. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  57125. handleThumb.position[1] = handleEnds[handleIndex];
  57126. // Update handle label position.
  57127. var textPoint = applyTransform$1(
  57128. shapes.handleLabelPoints[handleIndex],
  57129. getTransform(handleThumb, this.group)
  57130. );
  57131. handleLabels[handleIndex].setStyle({
  57132. x: textPoint[0],
  57133. y: textPoint[1],
  57134. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  57135. textVerticalAlign: 'middle',
  57136. textAlign: this._applyTransform(
  57137. this._orient === 'horizontal'
  57138. ? (handleIndex === 0 ? 'bottom' : 'top')
  57139. : 'left',
  57140. shapes.barGroup
  57141. )
  57142. });
  57143. }, this);
  57144. },
  57145. /**
  57146. * @private
  57147. * @param {number} cursorValue
  57148. * @param {number} textValue
  57149. * @param {string} [rangeSymbol]
  57150. * @param {number} [halfHoverLinkSize]
  57151. */
  57152. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  57153. var visualMapModel = this.visualMapModel;
  57154. var dataExtent = visualMapModel.getExtent();
  57155. var itemSize = visualMapModel.itemSize;
  57156. var sizeExtent = [0, itemSize[1]];
  57157. var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true);
  57158. var shapes = this._shapes;
  57159. var indicator = shapes.indicator;
  57160. if (!indicator) {
  57161. return;
  57162. }
  57163. indicator.position[1] = pos;
  57164. indicator.attr('invisible', false);
  57165. indicator.setShape('points', createIndicatorPoints(
  57166. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  57167. ));
  57168. var opts = {convertOpacityToAlpha: true};
  57169. var color = this.getControllerVisual(cursorValue, 'color', opts);
  57170. indicator.setStyle('fill', color);
  57171. // Update handle label position.
  57172. var textPoint = applyTransform$1(
  57173. shapes.indicatorLabelPoint,
  57174. getTransform(indicator, this.group)
  57175. );
  57176. var indicatorLabel = shapes.indicatorLabel;
  57177. indicatorLabel.attr('invisible', false);
  57178. var align = this._applyTransform('left', shapes.barGroup);
  57179. var orient = this._orient;
  57180. indicatorLabel.setStyle({
  57181. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  57182. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  57183. textAlign: orient === 'horizontal' ? 'center' : align,
  57184. x: textPoint[0],
  57185. y: textPoint[1]
  57186. });
  57187. },
  57188. /**
  57189. * @private
  57190. */
  57191. _enableHoverLinkToSeries: function () {
  57192. var self = this;
  57193. this._shapes.barGroup
  57194. .on('mousemove', function (e) {
  57195. self._hovering = true;
  57196. if (!self._dragging) {
  57197. var itemSize = self.visualMapModel.itemSize;
  57198. var pos = self._applyTransform(
  57199. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  57200. );
  57201. // For hover link show when hover handle, which might be
  57202. // below or upper than sizeExtent.
  57203. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  57204. self._doHoverLinkToSeries(
  57205. pos[1],
  57206. 0 <= pos[0] && pos[0] <= itemSize[0]
  57207. );
  57208. }
  57209. })
  57210. .on('mouseout', function () {
  57211. // When mouse is out of handle, hoverLink still need
  57212. // to be displayed when realtime is set as false.
  57213. self._hovering = false;
  57214. !self._dragging && self._clearHoverLinkToSeries();
  57215. });
  57216. },
  57217. /**
  57218. * @private
  57219. */
  57220. _enableHoverLinkFromSeries: function () {
  57221. var zr = this.api.getZr();
  57222. if (this.visualMapModel.option.hoverLink) {
  57223. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  57224. zr.on('mouseout', this._hideIndicator, this);
  57225. }
  57226. else {
  57227. this._clearHoverLinkFromSeries();
  57228. }
  57229. },
  57230. /**
  57231. * @private
  57232. */
  57233. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  57234. var visualMapModel = this.visualMapModel;
  57235. var itemSize = visualMapModel.itemSize;
  57236. if (!visualMapModel.option.hoverLink) {
  57237. return;
  57238. }
  57239. var sizeExtent = [0, itemSize[1]];
  57240. var dataExtent = visualMapModel.getExtent();
  57241. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  57242. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  57243. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  57244. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  57245. var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true);
  57246. var valueRange = [
  57247. linearMap$4(hoverRange[0], sizeExtent, dataExtent, true),
  57248. linearMap$4(hoverRange[1], sizeExtent, dataExtent, true)
  57249. ];
  57250. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  57251. // where china and india has very large population.
  57252. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  57253. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  57254. // Do not show indicator when mouse is over handle,
  57255. // otherwise labels overlap, especially when dragging.
  57256. if (hoverOnBar) {
  57257. if (valueRange[0] === -Infinity) {
  57258. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  57259. }
  57260. else if (valueRange[1] === Infinity) {
  57261. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  57262. }
  57263. else {
  57264. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  57265. }
  57266. }
  57267. // When realtime is set as false, handles, which are in barGroup,
  57268. // also trigger hoverLink, which help user to realize where they
  57269. // focus on when dragging. (see test/heatmap-large.html)
  57270. // When realtime is set as true, highlight will not show when hover
  57271. // handle, because the label on handle, which displays a exact value
  57272. // but not range, might mislead users.
  57273. var oldBatch = this._hoverLinkDataIndices;
  57274. var newBatch = [];
  57275. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  57276. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  57277. }
  57278. var resultBatches = compressBatches(oldBatch, newBatch);
  57279. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  57280. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  57281. },
  57282. /**
  57283. * @private
  57284. */
  57285. _hoverLinkFromSeriesMouseOver: function (e) {
  57286. var el = e.target;
  57287. var visualMapModel = this.visualMapModel;
  57288. if (!el || el.dataIndex == null) {
  57289. return;
  57290. }
  57291. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  57292. if (!visualMapModel.isTargetSeries(dataModel)) {
  57293. return;
  57294. }
  57295. var data = dataModel.getData(el.dataType);
  57296. var dim = data.getDimension(visualMapModel.getDataDimension(data));
  57297. var value = data.get(dim, el.dataIndex, true);
  57298. if (!isNaN(value)) {
  57299. this._showIndicator(value, value);
  57300. }
  57301. },
  57302. /**
  57303. * @private
  57304. */
  57305. _hideIndicator: function () {
  57306. var shapes = this._shapes;
  57307. shapes.indicator && shapes.indicator.attr('invisible', true);
  57308. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  57309. },
  57310. /**
  57311. * @private
  57312. */
  57313. _clearHoverLinkToSeries: function () {
  57314. this._hideIndicator();
  57315. var indices = this._hoverLinkDataIndices;
  57316. this._dispatchHighDown('downplay', convertDataIndex(indices));
  57317. indices.length = 0;
  57318. },
  57319. /**
  57320. * @private
  57321. */
  57322. _clearHoverLinkFromSeries: function () {
  57323. this._hideIndicator();
  57324. var zr = this.api.getZr();
  57325. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  57326. zr.off('mouseout', this._hideIndicator);
  57327. },
  57328. /**
  57329. * @private
  57330. */
  57331. _applyTransform: function (vertex, element, inverse, global) {
  57332. var transform = getTransform(element, global ? null : this.group);
  57333. return graphic[
  57334. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  57335. ](vertex, transform, inverse);
  57336. },
  57337. /**
  57338. * @private
  57339. */
  57340. _dispatchHighDown: function (type, batch) {
  57341. batch && batch.length && this.api.dispatchAction({
  57342. type: type,
  57343. batch: batch
  57344. });
  57345. },
  57346. /**
  57347. * @override
  57348. */
  57349. dispose: function () {
  57350. this._clearHoverLinkFromSeries();
  57351. this._clearHoverLinkToSeries();
  57352. },
  57353. /**
  57354. * @override
  57355. */
  57356. remove: function () {
  57357. this._clearHoverLinkFromSeries();
  57358. this._clearHoverLinkToSeries();
  57359. }
  57360. });
  57361. function createPolygon(points, cursor, onDrift, onDragEnd) {
  57362. return new Polygon({
  57363. shape: {points: points},
  57364. draggable: !!onDrift,
  57365. cursor: cursor,
  57366. drift: onDrift,
  57367. onmousemove: function (e) {
  57368. // Fot mobile devicem, prevent screen slider on the button.
  57369. stop(e.event);
  57370. },
  57371. ondragend: onDragEnd
  57372. });
  57373. }
  57374. function createHandlePoints(handleIndex, textSize) {
  57375. return handleIndex === 0
  57376. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  57377. : [[0, 0], [textSize, 0], [textSize, textSize]];
  57378. }
  57379. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  57380. return isRange
  57381. ? [ // indicate range
  57382. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  57383. [HOVER_LINK_OUT, 0],
  57384. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  57385. ]
  57386. : [ // indicate single value
  57387. [0, 0], [5, -5], [5, 5]
  57388. ];
  57389. }
  57390. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  57391. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  57392. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  57393. if (hoverLinkDataSize) {
  57394. halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  57395. }
  57396. return halfHoverLinkSize;
  57397. }
  57398. function useHoverLinkOnHandle(visualMapModel) {
  57399. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  57400. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  57401. }
  57402. function getCursor$1(orient) {
  57403. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  57404. }
  57405. var actionInfo$2 = {
  57406. type: 'selectDataRange',
  57407. event: 'dataRangeSelected',
  57408. // FIXME use updateView appears wrong
  57409. update: 'update'
  57410. };
  57411. registerAction(actionInfo$2, function (payload, ecModel) {
  57412. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  57413. model.setSelected(payload.selected);
  57414. });
  57415. });
  57416. /**
  57417. * DataZoom component entry
  57418. */
  57419. registerPreprocessor(preprocessor$2);
  57420. var PiecewiseModel = VisualMapModel.extend({
  57421. type: 'visualMap.piecewise',
  57422. /**
  57423. * Order Rule:
  57424. *
  57425. * option.categories / option.pieces / option.text / option.selected:
  57426. * If !option.inverse,
  57427. * Order when vertical: ['top', ..., 'bottom'].
  57428. * Order when horizontal: ['left', ..., 'right'].
  57429. * If option.inverse, the meaning of
  57430. * the order should be reversed.
  57431. *
  57432. * this._pieceList:
  57433. * The order is always [low, ..., high].
  57434. *
  57435. * Mapping from location to low-high:
  57436. * If !option.inverse
  57437. * When vertical, top is high.
  57438. * When horizontal, right is high.
  57439. * If option.inverse, reverse.
  57440. */
  57441. /**
  57442. * @protected
  57443. */
  57444. defaultOption: {
  57445. selected: null, // Object. If not specified, means selected.
  57446. // When pieces and splitNumber: {'0': true, '5': true}
  57447. // When categories: {'cate1': false, 'cate3': true}
  57448. // When selected === false, means all unselected.
  57449. minOpen: false, // Whether include values that smaller than `min`.
  57450. maxOpen: false, // Whether include values that bigger than `max`.
  57451. align: 'auto', // 'auto', 'left', 'right'
  57452. itemWidth: 20, // When put the controller vertically, it is the length of
  57453. // horizontal side of each item. Otherwise, vertical side.
  57454. itemHeight: 14, // When put the controller vertically, it is the length of
  57455. // vertical side of each item. Otherwise, horizontal side.
  57456. itemSymbol: 'roundRect',
  57457. pieceList: null, // Each item is Object, with some of those attrs:
  57458. // {min, max, lt, gt, lte, gte, value,
  57459. // color, colorSaturation, colorAlpha, opacity,
  57460. // symbol, symbolSize}, which customize the range or visual
  57461. // coding of the certain piece. Besides, see "Order Rule".
  57462. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  57463. // Attr min/max are ignored when categories set. See "Order Rule"
  57464. splitNumber: 5, // If set to 5, auto split five pieces equally.
  57465. // If set to 0 and component type not set, component type will be
  57466. // determined as "continuous". (It is less reasonable but for ec2
  57467. // compatibility, see echarts/component/visualMap/typeDefaulter)
  57468. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  57469. itemGap: 10, // The gap between two items, in px.
  57470. hoverLink: true, // Enable hover highlight.
  57471. showLabel: null // By default, when text is used, label will hide (the logic
  57472. // is remained for compatibility reason)
  57473. },
  57474. /**
  57475. * @override
  57476. */
  57477. optionUpdated: function (newOption, isInit) {
  57478. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  57479. /**
  57480. * The order is always [low, ..., high].
  57481. * [{text: string, interval: Array.<number>}, ...]
  57482. * @private
  57483. * @type {Array.<Object>}
  57484. */
  57485. this._pieceList = [];
  57486. this.resetExtent();
  57487. /**
  57488. * 'pieces', 'categories', 'splitNumber'
  57489. * @type {string}
  57490. */
  57491. var mode = this._mode = this._determineMode();
  57492. resetMethods[this._mode].call(this);
  57493. this._resetSelected(newOption, isInit);
  57494. var categories = this.option.categories;
  57495. this.resetVisual(function (mappingOption, state) {
  57496. if (mode === 'categories') {
  57497. mappingOption.mappingMethod = 'category';
  57498. mappingOption.categories = clone(categories);
  57499. }
  57500. else {
  57501. mappingOption.dataExtent = this.getExtent();
  57502. mappingOption.mappingMethod = 'piecewise';
  57503. mappingOption.pieceList = map(this._pieceList, function (piece) {
  57504. var piece = clone(piece);
  57505. if (state !== 'inRange') {
  57506. // FIXME
  57507. // outOfRange do not support special visual in pieces.
  57508. piece.visual = null;
  57509. }
  57510. return piece;
  57511. });
  57512. }
  57513. });
  57514. },
  57515. /**
  57516. * @protected
  57517. * @override
  57518. */
  57519. completeVisualOption: function () {
  57520. // Consider this case:
  57521. // visualMap: {
  57522. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  57523. // }
  57524. // where no inRange/outOfRange set but only pieces. So we should make
  57525. // default inRange/outOfRange for this case, otherwise visuals that only
  57526. // appear in `pieces` will not be taken into account in visual encoding.
  57527. var option = this.option;
  57528. var visualTypesInPieces = {};
  57529. var visualTypes = VisualMapping.listVisualTypes();
  57530. var isCategory = this.isCategory();
  57531. each$1(option.pieces, function (piece) {
  57532. each$1(visualTypes, function (visualType) {
  57533. if (piece.hasOwnProperty(visualType)) {
  57534. visualTypesInPieces[visualType] = 1;
  57535. }
  57536. });
  57537. });
  57538. each$1(visualTypesInPieces, function (v, visualType) {
  57539. var exists = 0;
  57540. each$1(this.stateList, function (state) {
  57541. exists |= has(option, state, visualType)
  57542. || has(option.target, state, visualType);
  57543. }, this);
  57544. !exists && each$1(this.stateList, function (state) {
  57545. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  57546. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  57547. );
  57548. });
  57549. }, this);
  57550. function has(obj, state, visualType) {
  57551. return obj && obj[state] && (
  57552. isObject(obj[state])
  57553. ? obj[state].hasOwnProperty(visualType)
  57554. : obj[state] === visualType // e.g., inRange: 'symbol'
  57555. );
  57556. }
  57557. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  57558. },
  57559. _resetSelected: function (newOption, isInit) {
  57560. var thisOption = this.option;
  57561. var pieceList = this._pieceList;
  57562. // Selected do not merge but all override.
  57563. var selected = (isInit ? thisOption : newOption).selected || {};
  57564. thisOption.selected = selected;
  57565. // Consider 'not specified' means true.
  57566. each$1(pieceList, function (piece, index) {
  57567. var key = this.getSelectedMapKey(piece);
  57568. if (!selected.hasOwnProperty(key)) {
  57569. selected[key] = true;
  57570. }
  57571. }, this);
  57572. if (thisOption.selectedMode === 'single') {
  57573. // Ensure there is only one selected.
  57574. var hasSel = false;
  57575. each$1(pieceList, function (piece, index) {
  57576. var key = this.getSelectedMapKey(piece);
  57577. if (selected[key]) {
  57578. hasSel
  57579. ? (selected[key] = false)
  57580. : (hasSel = true);
  57581. }
  57582. }, this);
  57583. }
  57584. // thisOption.selectedMode === 'multiple', default: all selected.
  57585. },
  57586. /**
  57587. * @public
  57588. */
  57589. getSelectedMapKey: function (piece) {
  57590. return this._mode === 'categories'
  57591. ? piece.value + '' : piece.index + '';
  57592. },
  57593. /**
  57594. * @public
  57595. */
  57596. getPieceList: function () {
  57597. return this._pieceList;
  57598. },
  57599. /**
  57600. * @private
  57601. * @return {string}
  57602. */
  57603. _determineMode: function () {
  57604. var option = this.option;
  57605. return option.pieces && option.pieces.length > 0
  57606. ? 'pieces'
  57607. : this.option.categories
  57608. ? 'categories'
  57609. : 'splitNumber';
  57610. },
  57611. /**
  57612. * @public
  57613. * @override
  57614. */
  57615. setSelected: function (selected) {
  57616. this.option.selected = clone(selected);
  57617. },
  57618. /**
  57619. * @public
  57620. * @override
  57621. */
  57622. getValueState: function (value) {
  57623. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  57624. return index != null
  57625. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  57626. ? 'inRange' : 'outOfRange'
  57627. )
  57628. : 'outOfRange';
  57629. },
  57630. /**
  57631. * @public
  57632. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  57633. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  57634. */
  57635. findTargetDataIndices: function (pieceIndex) {
  57636. var result = [];
  57637. this.eachTargetSeries(function (seriesModel) {
  57638. var dataIndices = [];
  57639. var data = seriesModel.getData();
  57640. data.each(this.getDataDimension(data), function (value, dataIndex) {
  57641. // Should always base on model pieceList, because it is order sensitive.
  57642. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  57643. pIdx === pieceIndex && dataIndices.push(dataIndex);
  57644. }, true, this);
  57645. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  57646. }, this);
  57647. return result;
  57648. },
  57649. /**
  57650. * @private
  57651. * @param {Object} piece piece.value or piece.interval is required.
  57652. * @return {number} Can be Infinity or -Infinity
  57653. */
  57654. getRepresentValue: function (piece) {
  57655. var representValue;
  57656. if (this.isCategory()) {
  57657. representValue = piece.value;
  57658. }
  57659. else {
  57660. if (piece.value != null) {
  57661. representValue = piece.value;
  57662. }
  57663. else {
  57664. var pieceInterval = piece.interval || [];
  57665. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  57666. ? 0
  57667. : (pieceInterval[0] + pieceInterval[1]) / 2;
  57668. }
  57669. }
  57670. return representValue;
  57671. },
  57672. getVisualMeta: function (getColorVisual) {
  57673. // Do not support category. (category axis is ordinal, numerical)
  57674. if (this.isCategory()) {
  57675. return;
  57676. }
  57677. var stops = [];
  57678. var outerColors = [];
  57679. var visualMapModel = this;
  57680. function setStop(interval, valueState) {
  57681. var representValue = visualMapModel.getRepresentValue({interval: interval});
  57682. if (!valueState) {
  57683. valueState = visualMapModel.getValueState(representValue);
  57684. }
  57685. var color = getColorVisual(representValue, valueState);
  57686. if (interval[0] === -Infinity) {
  57687. outerColors[0] = color;
  57688. }
  57689. else if (interval[1] === Infinity) {
  57690. outerColors[1] = color;
  57691. }
  57692. else {
  57693. stops.push(
  57694. {value: interval[0], color: color},
  57695. {value: interval[1], color: color}
  57696. );
  57697. }
  57698. }
  57699. // Suplement
  57700. var pieceList = this._pieceList.slice();
  57701. if (!pieceList.length) {
  57702. pieceList.push({interval: [-Infinity, Infinity]});
  57703. }
  57704. else {
  57705. var edge = pieceList[0].interval[0];
  57706. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  57707. edge = pieceList[pieceList.length - 1].interval[1];
  57708. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  57709. }
  57710. var curr = -Infinity;
  57711. each$1(pieceList, function (piece) {
  57712. var interval = piece.interval;
  57713. if (interval) {
  57714. // Fulfill gap.
  57715. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  57716. setStop(interval.slice());
  57717. curr = interval[1];
  57718. }
  57719. }, this);
  57720. return {stops: stops, outerColors: outerColors};
  57721. }
  57722. });
  57723. /**
  57724. * Key is this._mode
  57725. * @type {Object}
  57726. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  57727. */
  57728. var resetMethods = {
  57729. splitNumber: function () {
  57730. var thisOption = this.option;
  57731. var pieceList = this._pieceList;
  57732. var precision = Math.min(thisOption.precision, 20);
  57733. var dataExtent = this.getExtent();
  57734. var splitNumber = thisOption.splitNumber;
  57735. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  57736. thisOption.splitNumber = splitNumber;
  57737. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  57738. // Precision auto-adaption
  57739. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  57740. precision++;
  57741. }
  57742. thisOption.precision = precision;
  57743. splitStep = +splitStep.toFixed(precision);
  57744. var index = 0;
  57745. if (thisOption.minOpen) {
  57746. pieceList.push({
  57747. index: index++,
  57748. interval: [-Infinity, dataExtent[0]],
  57749. close: [0, 0]
  57750. });
  57751. }
  57752. for (
  57753. var curr = dataExtent[0], len = index + splitNumber;
  57754. index < len;
  57755. curr += splitStep
  57756. ) {
  57757. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  57758. pieceList.push({
  57759. index: index++,
  57760. interval: [curr, max],
  57761. close: [1, 1]
  57762. });
  57763. }
  57764. if (thisOption.maxOpen) {
  57765. pieceList.push({
  57766. index: index++,
  57767. interval: [dataExtent[1], Infinity],
  57768. close: [0, 0]
  57769. });
  57770. }
  57771. reformIntervals(pieceList);
  57772. each$1(pieceList, function (piece) {
  57773. piece.text = this.formatValueText(piece.interval);
  57774. }, this);
  57775. },
  57776. categories: function () {
  57777. var thisOption = this.option;
  57778. each$1(thisOption.categories, function (cate) {
  57779. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  57780. // 是否改一致。
  57781. this._pieceList.push({
  57782. text: this.formatValueText(cate, true),
  57783. value: cate
  57784. });
  57785. }, this);
  57786. // See "Order Rule".
  57787. normalizeReverse(thisOption, this._pieceList);
  57788. },
  57789. pieces: function () {
  57790. var thisOption = this.option;
  57791. var pieceList = this._pieceList;
  57792. each$1(thisOption.pieces, function (pieceListItem, index) {
  57793. if (!isObject(pieceListItem)) {
  57794. pieceListItem = {value: pieceListItem};
  57795. }
  57796. var item = {text: '', index: index};
  57797. if (pieceListItem.label != null) {
  57798. item.text = pieceListItem.label;
  57799. }
  57800. if (pieceListItem.hasOwnProperty('value')) {
  57801. var value = item.value = pieceListItem.value;
  57802. item.interval = [value, value];
  57803. item.close = [1, 1];
  57804. }
  57805. else {
  57806. // `min` `max` is legacy option.
  57807. // `lt` `gt` `lte` `gte` is recommanded.
  57808. var interval = item.interval = [];
  57809. var close = item.close = [0, 0];
  57810. var closeList = [1, 0, 1];
  57811. var infinityList = [-Infinity, Infinity];
  57812. var useMinMax = [];
  57813. for (var lg = 0; lg < 2; lg++) {
  57814. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  57815. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  57816. interval[lg] = pieceListItem[names[i]];
  57817. close[lg] = closeList[i];
  57818. useMinMax[lg] = i === 2;
  57819. }
  57820. interval[lg] == null && (interval[lg] = infinityList[lg]);
  57821. }
  57822. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  57823. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  57824. if (__DEV__) {
  57825. if (interval[0] > interval[1]) {
  57826. console.warn(
  57827. 'Piece ' + index + 'is illegal: ' + interval
  57828. + ' lower bound should not greater then uppper bound.'
  57829. );
  57830. }
  57831. }
  57832. if (interval[0] === interval[1] && close[0] && close[1]) {
  57833. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  57834. // we use value to lift the priority when min === max
  57835. item.value = interval[0];
  57836. }
  57837. }
  57838. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  57839. pieceList.push(item);
  57840. }, this);
  57841. // See "Order Rule".
  57842. normalizeReverse(thisOption, pieceList);
  57843. // Only pieces
  57844. reformIntervals(pieceList);
  57845. each$1(pieceList, function (piece) {
  57846. var close = piece.close;
  57847. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  57848. piece.text = piece.text || this.formatValueText(
  57849. piece.value != null ? piece.value : piece.interval,
  57850. false,
  57851. edgeSymbols
  57852. );
  57853. }, this);
  57854. }
  57855. };
  57856. function normalizeReverse(thisOption, pieceList) {
  57857. var inverse = thisOption.inverse;
  57858. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  57859. pieceList.reverse();
  57860. }
  57861. }
  57862. var PiecewiseVisualMapView = VisualMapView.extend({
  57863. type: 'visualMap.piecewise',
  57864. /**
  57865. * @protected
  57866. * @override
  57867. */
  57868. doRender: function () {
  57869. var thisGroup = this.group;
  57870. thisGroup.removeAll();
  57871. var visualMapModel = this.visualMapModel;
  57872. var textGap = visualMapModel.get('textGap');
  57873. var textStyleModel = visualMapModel.textStyleModel;
  57874. var textFont = textStyleModel.getFont();
  57875. var textFill = textStyleModel.getTextColor();
  57876. var itemAlign = this._getItemAlign();
  57877. var itemSize = visualMapModel.itemSize;
  57878. var viewData = this._getViewData();
  57879. var endsText = viewData.endsText;
  57880. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  57881. endsText && this._renderEndsText(
  57882. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  57883. );
  57884. each$1(viewData.viewPieceList, renderItem, this);
  57885. endsText && this._renderEndsText(
  57886. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  57887. );
  57888. box(
  57889. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  57890. );
  57891. this.renderBackground(thisGroup);
  57892. this.positionGroup(thisGroup);
  57893. function renderItem(item) {
  57894. var piece = item.piece;
  57895. var itemGroup = new Group();
  57896. itemGroup.onclick = bind(this._onItemClick, this, piece);
  57897. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  57898. var representValue = visualMapModel.getRepresentValue(piece);
  57899. this._createItemSymbol(
  57900. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  57901. );
  57902. if (showLabel) {
  57903. var visualState = this.visualMapModel.getValueState(representValue);
  57904. itemGroup.add(new Text({
  57905. style: {
  57906. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  57907. y: itemSize[1] / 2,
  57908. text: piece.text,
  57909. textVerticalAlign: 'middle',
  57910. textAlign: itemAlign,
  57911. textFont: textFont,
  57912. textFill: textFill,
  57913. opacity: visualState === 'outOfRange' ? 0.5 : 1
  57914. }
  57915. }));
  57916. }
  57917. thisGroup.add(itemGroup);
  57918. }
  57919. },
  57920. /**
  57921. * @private
  57922. */
  57923. _enableHoverLink: function (itemGroup, pieceIndex) {
  57924. itemGroup
  57925. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  57926. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  57927. function onHoverLink(method) {
  57928. var visualMapModel = this.visualMapModel;
  57929. visualMapModel.option.hoverLink && this.api.dispatchAction({
  57930. type: method,
  57931. batch: convertDataIndex(
  57932. visualMapModel.findTargetDataIndices(pieceIndex)
  57933. )
  57934. });
  57935. }
  57936. },
  57937. /**
  57938. * @private
  57939. */
  57940. _getItemAlign: function () {
  57941. var visualMapModel = this.visualMapModel;
  57942. var modelOption = visualMapModel.option;
  57943. if (modelOption.orient === 'vertical') {
  57944. return getItemAlign(
  57945. visualMapModel, this.api, visualMapModel.itemSize
  57946. );
  57947. }
  57948. else { // horizontal, most case left unless specifying right.
  57949. var align = modelOption.align;
  57950. if (!align || align === 'auto') {
  57951. align = 'left';
  57952. }
  57953. return align;
  57954. }
  57955. },
  57956. /**
  57957. * @private
  57958. */
  57959. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  57960. if (!text) {
  57961. return;
  57962. }
  57963. var itemGroup = new Group();
  57964. var textStyleModel = this.visualMapModel.textStyleModel;
  57965. itemGroup.add(new Text({
  57966. style: {
  57967. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  57968. y: itemSize[1] / 2,
  57969. textVerticalAlign: 'middle',
  57970. textAlign: showLabel ? itemAlign : 'center',
  57971. text: text,
  57972. textFont: textStyleModel.getFont(),
  57973. textFill: textStyleModel.getTextColor()
  57974. }
  57975. }));
  57976. group.add(itemGroup);
  57977. },
  57978. /**
  57979. * @private
  57980. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  57981. */
  57982. _getViewData: function () {
  57983. var visualMapModel = this.visualMapModel;
  57984. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  57985. return {piece: piece, indexInModelPieceList: index};
  57986. });
  57987. var endsText = visualMapModel.get('text');
  57988. // Consider orient and inverse.
  57989. var orient = visualMapModel.get('orient');
  57990. var inverse = visualMapModel.get('inverse');
  57991. // Order of model pieceList is always [low, ..., high]
  57992. if (orient === 'horizontal' ? inverse : !inverse) {
  57993. viewPieceList.reverse();
  57994. }
  57995. // Origin order of endsText is [high, low]
  57996. else if (endsText) {
  57997. endsText = endsText.slice().reverse();
  57998. }
  57999. return {viewPieceList: viewPieceList, endsText: endsText};
  58000. },
  58001. /**
  58002. * @private
  58003. */
  58004. _createItemSymbol: function (group, representValue, shapeParam) {
  58005. group.add(createSymbol(
  58006. this.getControllerVisual(representValue, 'symbol'),
  58007. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  58008. this.getControllerVisual(representValue, 'color')
  58009. ));
  58010. },
  58011. /**
  58012. * @private
  58013. */
  58014. _onItemClick: function (piece) {
  58015. var visualMapModel = this.visualMapModel;
  58016. var option = visualMapModel.option;
  58017. var selected = clone(option.selected);
  58018. var newKey = visualMapModel.getSelectedMapKey(piece);
  58019. if (option.selectedMode === 'single') {
  58020. selected[newKey] = true;
  58021. each$1(selected, function (o, key) {
  58022. selected[key] = key === newKey;
  58023. });
  58024. }
  58025. else {
  58026. selected[newKey] = !selected[newKey];
  58027. }
  58028. this.api.dispatchAction({
  58029. type: 'selectDataRange',
  58030. from: this.uid,
  58031. visualMapId: this.visualMapModel.id,
  58032. selected: selected
  58033. });
  58034. }
  58035. });
  58036. /**
  58037. * DataZoom component entry
  58038. */
  58039. registerPreprocessor(preprocessor$2);
  58040. /**
  58041. * visualMap component entry
  58042. */
  58043. var addCommas$1 = addCommas;
  58044. var encodeHTML$1 = encodeHTML;
  58045. function fillLabel(opt) {
  58046. defaultEmphasis(opt.label, ['show']);
  58047. }
  58048. var MarkerModel = extendComponentModel({
  58049. type: 'marker',
  58050. dependencies: ['series', 'grid', 'polar', 'geo'],
  58051. /**
  58052. * @overrite
  58053. */
  58054. init: function (option, parentModel, ecModel, extraOpt) {
  58055. if (__DEV__) {
  58056. if (this.type === 'marker') {
  58057. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  58058. }
  58059. }
  58060. this.mergeDefaultAndTheme(option, ecModel);
  58061. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  58062. },
  58063. /**
  58064. * @return {boolean}
  58065. */
  58066. isAnimationEnabled: function () {
  58067. if (env$1.node) {
  58068. return false;
  58069. }
  58070. var hostSeries = this.__hostSeries;
  58071. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  58072. },
  58073. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  58074. var MarkerModel = this.constructor;
  58075. var modelPropName = this.mainType + 'Model';
  58076. if (!createdBySelf) {
  58077. ecModel.eachSeries(function (seriesModel) {
  58078. var markerOpt = seriesModel.get(this.mainType);
  58079. var markerModel = seriesModel[modelPropName];
  58080. if (!markerOpt || !markerOpt.data) {
  58081. seriesModel[modelPropName] = null;
  58082. return;
  58083. }
  58084. if (!markerModel) {
  58085. if (isInit) {
  58086. // Default label emphasis `position` and `show`
  58087. fillLabel(markerOpt);
  58088. }
  58089. each$1(markerOpt.data, function (item) {
  58090. // FIXME Overwrite fillLabel method ?
  58091. if (item instanceof Array) {
  58092. fillLabel(item[0]);
  58093. fillLabel(item[1]);
  58094. }
  58095. else {
  58096. fillLabel(item);
  58097. }
  58098. });
  58099. markerModel = new MarkerModel(
  58100. markerOpt, this, ecModel
  58101. );
  58102. extend(markerModel, {
  58103. mainType: this.mainType,
  58104. // Use the same series index and name
  58105. seriesIndex: seriesModel.seriesIndex,
  58106. name: seriesModel.name,
  58107. createdBySelf: true
  58108. });
  58109. markerModel.__hostSeries = seriesModel;
  58110. }
  58111. else {
  58112. markerModel.mergeOption(markerOpt, ecModel, true);
  58113. }
  58114. seriesModel[modelPropName] = markerModel;
  58115. }, this);
  58116. }
  58117. },
  58118. formatTooltip: function (dataIndex) {
  58119. var data = this.getData();
  58120. var value = this.getRawValue(dataIndex);
  58121. var formattedValue = isArray(value)
  58122. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  58123. var name = data.getName(dataIndex);
  58124. var html = encodeHTML$1(this.name);
  58125. if (value != null || name) {
  58126. html += '<br />';
  58127. }
  58128. if (name) {
  58129. html += encodeHTML$1(name);
  58130. if (value != null) {
  58131. html += ' : ';
  58132. }
  58133. }
  58134. if (value != null) {
  58135. html += encodeHTML$1(formattedValue);
  58136. }
  58137. return html;
  58138. },
  58139. getData: function () {
  58140. return this._data;
  58141. },
  58142. setData: function (data) {
  58143. this._data = data;
  58144. }
  58145. });
  58146. mixin(MarkerModel, dataFormatMixin);
  58147. MarkerModel.extend({
  58148. type: 'markPoint',
  58149. defaultOption: {
  58150. zlevel: 0,
  58151. z: 5,
  58152. symbol: 'pin',
  58153. symbolSize: 50,
  58154. //symbolRotate: 0,
  58155. //symbolOffset: [0, 0]
  58156. tooltip: {
  58157. trigger: 'item'
  58158. },
  58159. label: {
  58160. normal: {
  58161. show: true,
  58162. position: 'inside'
  58163. },
  58164. emphasis: {
  58165. show: true
  58166. }
  58167. },
  58168. itemStyle: {
  58169. normal: {
  58170. borderWidth: 2
  58171. }
  58172. }
  58173. }
  58174. });
  58175. var indexOf$3 = indexOf;
  58176. function hasXOrY(item) {
  58177. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  58178. }
  58179. function hasXAndY(item) {
  58180. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  58181. }
  58182. function getPrecision$1(data, valueAxisDim, dataIndex) {
  58183. var precision = -1;
  58184. do {
  58185. precision = Math.max(
  58186. getPrecision(data.get(
  58187. valueAxisDim, dataIndex
  58188. )),
  58189. precision
  58190. );
  58191. data = data.stackedOn;
  58192. } while (data);
  58193. return precision;
  58194. }
  58195. function markerTypeCalculatorWithExtent(
  58196. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  58197. ) {
  58198. var coordArr = [];
  58199. var value = numCalculate(data, targetDataDim, mlType);
  58200. var dataIndex = data.indicesOfNearest(targetDataDim, value, true)[0];
  58201. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex, true);
  58202. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex, true);
  58203. var precision = getPrecision$1(data, targetDataDim, dataIndex);
  58204. precision = Math.min(precision, 20);
  58205. if (precision >= 0) {
  58206. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  58207. }
  58208. return coordArr;
  58209. }
  58210. var curry$7 = curry;
  58211. // TODO Specified percent
  58212. var markerTypeCalculator = {
  58213. /**
  58214. * @method
  58215. * @param {module:echarts/data/List} data
  58216. * @param {string} baseAxisDim
  58217. * @param {string} valueAxisDim
  58218. */
  58219. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  58220. /**
  58221. * @method
  58222. * @param {module:echarts/data/List} data
  58223. * @param {string} baseAxisDim
  58224. * @param {string} valueAxisDim
  58225. */
  58226. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  58227. /**
  58228. * @method
  58229. * @param {module:echarts/data/List} data
  58230. * @param {string} baseAxisDim
  58231. * @param {string} valueAxisDim
  58232. */
  58233. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  58234. };
  58235. /**
  58236. * Transform markPoint data item to format used in List by do the following
  58237. * 1. Calculate statistic like `max`, `min`, `average`
  58238. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  58239. * @param {module:echarts/model/Series} seriesModel
  58240. * @param {module:echarts/coord/*} [coordSys]
  58241. * @param {Object} item
  58242. * @return {Object}
  58243. */
  58244. function dataTransform(seriesModel, item) {
  58245. var data = seriesModel.getData();
  58246. var coordSys = seriesModel.coordinateSystem;
  58247. // 1. If not specify the position with pixel directly
  58248. // 2. If `coord` is not a data array. Which uses `xAxis`,
  58249. // `yAxis` to specify the coord on each dimension
  58250. // parseFloat first because item.x and item.y can be percent string like '20%'
  58251. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  58252. var dims = coordSys.dimensions;
  58253. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  58254. // Clone the option
  58255. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  58256. item = clone(item);
  58257. if (item.type
  58258. && markerTypeCalculator[item.type]
  58259. && axisInfo.baseAxis && axisInfo.valueAxis
  58260. ) {
  58261. var otherCoordIndex = indexOf$3(dims, axisInfo.baseAxis.dim);
  58262. var targetCoordIndex = indexOf$3(dims, axisInfo.valueAxis.dim);
  58263. item.coord = markerTypeCalculator[item.type](
  58264. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  58265. otherCoordIndex, targetCoordIndex
  58266. );
  58267. // Force to use the value of calculated value.
  58268. item.value = item.coord[targetCoordIndex];
  58269. }
  58270. else {
  58271. // FIXME Only has one of xAxis and yAxis.
  58272. var coord = [
  58273. item.xAxis != null ? item.xAxis : item.radiusAxis,
  58274. item.yAxis != null ? item.yAxis : item.angleAxis
  58275. ];
  58276. // Each coord support max, min, average
  58277. for (var i = 0; i < 2; i++) {
  58278. if (markerTypeCalculator[coord[i]]) {
  58279. var dataDim = seriesModel.coordDimToDataDim(dims[i])[0];
  58280. coord[i] = numCalculate(data, dataDim, coord[i]);
  58281. }
  58282. }
  58283. item.coord = coord;
  58284. }
  58285. }
  58286. return item;
  58287. }
  58288. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  58289. var ret = {};
  58290. if (item.valueIndex != null || item.valueDim != null) {
  58291. ret.valueDataDim = item.valueIndex != null
  58292. ? data.getDimension(item.valueIndex) : item.valueDim;
  58293. ret.valueAxis = coordSys.getAxis(seriesModel.dataDimToCoordDim(ret.valueDataDim));
  58294. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  58295. ret.baseDataDim = seriesModel.coordDimToDataDim(ret.baseAxis.dim)[0];
  58296. }
  58297. else {
  58298. ret.baseAxis = seriesModel.getBaseAxis();
  58299. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  58300. ret.baseDataDim = seriesModel.coordDimToDataDim(ret.baseAxis.dim)[0];
  58301. ret.valueDataDim = seriesModel.coordDimToDataDim(ret.valueAxis.dim)[0];
  58302. }
  58303. return ret;
  58304. }
  58305. /**
  58306. * Filter data which is out of coordinateSystem range
  58307. * [dataFilter description]
  58308. * @param {module:echarts/coord/*} [coordSys]
  58309. * @param {Object} item
  58310. * @return {boolean}
  58311. */
  58312. function dataFilter$1(coordSys, item) {
  58313. // Alwalys return true if there is no coordSys
  58314. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  58315. ? coordSys.containData(item.coord) : true;
  58316. }
  58317. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  58318. // x, y, radius, angle
  58319. if (dimIndex < 2) {
  58320. return item.coord && item.coord[dimIndex];
  58321. }
  58322. return item.value;
  58323. }
  58324. function numCalculate(data, valueDataDim, type) {
  58325. if (type === 'average') {
  58326. var sum = 0;
  58327. var count = 0;
  58328. data.each(valueDataDim, function (val, idx) {
  58329. if (!isNaN(val)) {
  58330. sum += val;
  58331. count++;
  58332. }
  58333. }, true);
  58334. return sum / count;
  58335. }
  58336. else {
  58337. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  58338. }
  58339. }
  58340. var MarkerView = extendComponentView({
  58341. type: 'marker',
  58342. init: function () {
  58343. /**
  58344. * Markline grouped by series
  58345. * @private
  58346. * @type {module:zrender/core/util.HashMap}
  58347. */
  58348. this.markerGroupMap = createHashMap();
  58349. },
  58350. render: function (markerModel, ecModel, api) {
  58351. var markerGroupMap = this.markerGroupMap;
  58352. markerGroupMap.each(function (item) {
  58353. item.__keep = false;
  58354. });
  58355. var markerModelKey = this.type + 'Model';
  58356. ecModel.eachSeries(function (seriesModel) {
  58357. var markerModel = seriesModel[markerModelKey];
  58358. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  58359. }, this);
  58360. markerGroupMap.each(function (item) {
  58361. !item.__keep && this.group.remove(item.group);
  58362. }, this);
  58363. },
  58364. renderSeries: function () {}
  58365. });
  58366. function updateMarkerLayout(mpData, seriesModel, api) {
  58367. var coordSys = seriesModel.coordinateSystem;
  58368. mpData.each(function (idx) {
  58369. var itemModel = mpData.getItemModel(idx);
  58370. var point;
  58371. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  58372. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  58373. if (!isNaN(xPx) && !isNaN(yPx)) {
  58374. point = [xPx, yPx];
  58375. }
  58376. // Chart like bar may have there own marker positioning logic
  58377. else if (seriesModel.getMarkerPosition) {
  58378. // Use the getMarkerPoisition
  58379. point = seriesModel.getMarkerPosition(
  58380. mpData.getValues(mpData.dimensions, idx)
  58381. );
  58382. }
  58383. else if (coordSys) {
  58384. var x = mpData.get(coordSys.dimensions[0], idx);
  58385. var y = mpData.get(coordSys.dimensions[1], idx);
  58386. point = coordSys.dataToPoint([x, y]);
  58387. }
  58388. // Use x, y if has any
  58389. if (!isNaN(xPx)) {
  58390. point[0] = xPx;
  58391. }
  58392. if (!isNaN(yPx)) {
  58393. point[1] = yPx;
  58394. }
  58395. mpData.setItemLayout(idx, point);
  58396. });
  58397. }
  58398. MarkerView.extend({
  58399. type: 'markPoint',
  58400. updateLayout: function (markPointModel, ecModel, api) {
  58401. ecModel.eachSeries(function (seriesModel) {
  58402. var mpModel = seriesModel.markPointModel;
  58403. if (mpModel) {
  58404. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  58405. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  58406. }
  58407. }, this);
  58408. },
  58409. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  58410. var coordSys = seriesModel.coordinateSystem;
  58411. var seriesId = seriesModel.id;
  58412. var seriesData = seriesModel.getData();
  58413. var symbolDrawMap = this.markerGroupMap;
  58414. var symbolDraw = symbolDrawMap.get(seriesId)
  58415. || symbolDrawMap.set(seriesId, new SymbolDraw());
  58416. var mpData = createList$1(coordSys, seriesModel, mpModel);
  58417. // FIXME
  58418. mpModel.setData(mpData);
  58419. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  58420. mpData.each(function (idx) {
  58421. var itemModel = mpData.getItemModel(idx);
  58422. var symbolSize = itemModel.getShallow('symbolSize');
  58423. if (typeof symbolSize === 'function') {
  58424. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  58425. symbolSize = symbolSize(
  58426. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  58427. );
  58428. }
  58429. mpData.setItemVisual(idx, {
  58430. symbolSize: symbolSize,
  58431. color: itemModel.get('itemStyle.normal.color')
  58432. || seriesData.getVisual('color'),
  58433. symbol: itemModel.getShallow('symbol')
  58434. });
  58435. });
  58436. // TODO Text are wrong
  58437. symbolDraw.updateData(mpData);
  58438. this.group.add(symbolDraw.group);
  58439. // Set host model for tooltip
  58440. // FIXME
  58441. mpData.eachItemGraphicEl(function (el) {
  58442. el.traverse(function (child) {
  58443. child.dataModel = mpModel;
  58444. });
  58445. });
  58446. symbolDraw.__keep = true;
  58447. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  58448. }
  58449. });
  58450. /**
  58451. * @inner
  58452. * @param {module:echarts/coord/*} [coordSys]
  58453. * @param {module:echarts/model/Series} seriesModel
  58454. * @param {module:echarts/model/Model} mpModel
  58455. */
  58456. function createList$1(coordSys, seriesModel, mpModel) {
  58457. var coordDimsInfos;
  58458. if (coordSys) {
  58459. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  58460. var info = seriesModel.getData().getDimensionInfo(
  58461. seriesModel.coordDimToDataDim(coordDim)[0]
  58462. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  58463. info.name = coordDim;
  58464. return info;
  58465. });
  58466. }
  58467. else {
  58468. coordDimsInfos =[{
  58469. name: 'value',
  58470. type: 'float'
  58471. }];
  58472. }
  58473. var mpData = new List(coordDimsInfos, mpModel);
  58474. var dataOpt = map(mpModel.get('data'), curry(
  58475. dataTransform, seriesModel
  58476. ));
  58477. if (coordSys) {
  58478. dataOpt = filter(
  58479. dataOpt, curry(dataFilter$1, coordSys)
  58480. );
  58481. }
  58482. mpData.initData(dataOpt, null,
  58483. coordSys ? dimValueGetter : function (item) {
  58484. return item.value;
  58485. }
  58486. );
  58487. return mpData;
  58488. }
  58489. // HINT Markpoint can't be used too much
  58490. registerPreprocessor(function (opt) {
  58491. // Make sure markPoint component is enabled
  58492. opt.markPoint = opt.markPoint || {};
  58493. });
  58494. MarkerModel.extend({
  58495. type: 'markLine',
  58496. defaultOption: {
  58497. zlevel: 0,
  58498. z: 5,
  58499. symbol: ['circle', 'arrow'],
  58500. symbolSize: [8, 16],
  58501. //symbolRotate: 0,
  58502. precision: 2,
  58503. tooltip: {
  58504. trigger: 'item'
  58505. },
  58506. label: {
  58507. normal: {
  58508. show: true,
  58509. position: 'end'
  58510. },
  58511. emphasis: {
  58512. show: true
  58513. }
  58514. },
  58515. lineStyle: {
  58516. normal: {
  58517. type: 'dashed'
  58518. },
  58519. emphasis: {
  58520. width: 3
  58521. }
  58522. },
  58523. animationEasing: 'linear'
  58524. }
  58525. });
  58526. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  58527. var data = seriesModel.getData();
  58528. // Special type markLine like 'min', 'max', 'average'
  58529. var mlType = item.type;
  58530. if (!isArray(item)
  58531. && (
  58532. mlType === 'min' || mlType === 'max' || mlType === 'average'
  58533. // In case
  58534. // data: [{
  58535. // yAxis: 10
  58536. // }]
  58537. || (item.xAxis != null || item.yAxis != null)
  58538. )
  58539. ) {
  58540. var valueAxis;
  58541. var valueDataDim;
  58542. var value;
  58543. if (item.yAxis != null || item.xAxis != null) {
  58544. valueDataDim = item.yAxis != null ? 'y' : 'x';
  58545. valueAxis = coordSys.getAxis(valueDataDim);
  58546. value = retrieve(item.yAxis, item.xAxis);
  58547. }
  58548. else {
  58549. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  58550. valueDataDim = axisInfo.valueDataDim;
  58551. valueAxis = axisInfo.valueAxis;
  58552. value = numCalculate(data, valueDataDim, mlType);
  58553. }
  58554. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  58555. var baseIndex = 1 - valueIndex;
  58556. var mlFrom = clone(item);
  58557. var mlTo = {};
  58558. mlFrom.type = null;
  58559. mlFrom.coord = [];
  58560. mlTo.coord = [];
  58561. mlFrom.coord[baseIndex] = -Infinity;
  58562. mlTo.coord[baseIndex] = Infinity;
  58563. var precision = mlModel.get('precision');
  58564. if (precision >= 0 && typeof value === 'number') {
  58565. value = +value.toFixed(Math.min(precision, 20));
  58566. }
  58567. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  58568. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  58569. type: mlType,
  58570. valueIndex: item.valueIndex,
  58571. // Force to use the value of calculated value.
  58572. value: value
  58573. }];
  58574. }
  58575. item = [
  58576. dataTransform(seriesModel, item[0]),
  58577. dataTransform(seriesModel, item[1]),
  58578. extend({}, item[2])
  58579. ];
  58580. // Avoid line data type is extended by from(to) data type
  58581. item[2].type = item[2].type || '';
  58582. // Merge from option and to option into line option
  58583. merge(item[2], item[0]);
  58584. merge(item[2], item[1]);
  58585. return item;
  58586. };
  58587. function isInifinity(val) {
  58588. return !isNaN(val) && !isFinite(val);
  58589. }
  58590. // If a markLine has one dim
  58591. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  58592. var otherDimIndex = 1 - dimIndex;
  58593. var dimName = coordSys.dimensions[dimIndex];
  58594. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  58595. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  58596. }
  58597. function markLineFilter(coordSys, item) {
  58598. if (coordSys.type === 'cartesian2d') {
  58599. var fromCoord = item[0].coord;
  58600. var toCoord = item[1].coord;
  58601. // In case
  58602. // {
  58603. // markLine: {
  58604. // data: [{ yAxis: 2 }]
  58605. // }
  58606. // }
  58607. if (
  58608. fromCoord && toCoord &&
  58609. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  58610. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  58611. ) {
  58612. return true;
  58613. }
  58614. }
  58615. return dataFilter$1(coordSys, item[0])
  58616. && dataFilter$1(coordSys, item[1]);
  58617. }
  58618. function updateSingleMarkerEndLayout(
  58619. data, idx, isFrom, seriesModel, api
  58620. ) {
  58621. var coordSys = seriesModel.coordinateSystem;
  58622. var itemModel = data.getItemModel(idx);
  58623. var point;
  58624. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  58625. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  58626. if (!isNaN(xPx) && !isNaN(yPx)) {
  58627. point = [xPx, yPx];
  58628. }
  58629. else {
  58630. // Chart like bar may have there own marker positioning logic
  58631. if (seriesModel.getMarkerPosition) {
  58632. // Use the getMarkerPoisition
  58633. point = seriesModel.getMarkerPosition(
  58634. data.getValues(data.dimensions, idx)
  58635. );
  58636. }
  58637. else {
  58638. var dims = coordSys.dimensions;
  58639. var x = data.get(dims[0], idx);
  58640. var y = data.get(dims[1], idx);
  58641. point = coordSys.dataToPoint([x, y]);
  58642. }
  58643. // Expand line to the edge of grid if value on one axis is Inifnity
  58644. // In case
  58645. // markLine: {
  58646. // data: [{
  58647. // yAxis: 2
  58648. // // or
  58649. // type: 'average'
  58650. // }]
  58651. // }
  58652. if (coordSys.type === 'cartesian2d') {
  58653. var xAxis = coordSys.getAxis('x');
  58654. var yAxis = coordSys.getAxis('y');
  58655. var dims = coordSys.dimensions;
  58656. if (isInifinity(data.get(dims[0], idx))) {
  58657. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  58658. }
  58659. else if (isInifinity(data.get(dims[1], idx))) {
  58660. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  58661. }
  58662. }
  58663. // Use x, y if has any
  58664. if (!isNaN(xPx)) {
  58665. point[0] = xPx;
  58666. }
  58667. if (!isNaN(yPx)) {
  58668. point[1] = yPx;
  58669. }
  58670. }
  58671. data.setItemLayout(idx, point);
  58672. }
  58673. MarkerView.extend({
  58674. type: 'markLine',
  58675. updateLayout: function (markLineModel, ecModel, api) {
  58676. ecModel.eachSeries(function (seriesModel) {
  58677. var mlModel = seriesModel.markLineModel;
  58678. if (mlModel) {
  58679. var mlData = mlModel.getData();
  58680. var fromData = mlModel.__from;
  58681. var toData = mlModel.__to;
  58682. // Update visual and layout of from symbol and to symbol
  58683. fromData.each(function (idx) {
  58684. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  58685. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  58686. });
  58687. // Update layout of line
  58688. mlData.each(function (idx) {
  58689. mlData.setItemLayout(idx, [
  58690. fromData.getItemLayout(idx),
  58691. toData.getItemLayout(idx)
  58692. ]);
  58693. });
  58694. this.markerGroupMap.get(seriesModel.id).updateLayout();
  58695. }
  58696. }, this);
  58697. },
  58698. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  58699. var coordSys = seriesModel.coordinateSystem;
  58700. var seriesId = seriesModel.id;
  58701. var seriesData = seriesModel.getData();
  58702. var lineDrawMap = this.markerGroupMap;
  58703. var lineDraw = lineDrawMap.get(seriesId)
  58704. || lineDrawMap.set(seriesId, new LineDraw());
  58705. this.group.add(lineDraw.group);
  58706. var mlData = createList$2(coordSys, seriesModel, mlModel);
  58707. var fromData = mlData.from;
  58708. var toData = mlData.to;
  58709. var lineData = mlData.line;
  58710. mlModel.__from = fromData;
  58711. mlModel.__to = toData;
  58712. // Line data for tooltip and formatter
  58713. mlModel.setData(lineData);
  58714. var symbolType = mlModel.get('symbol');
  58715. var symbolSize = mlModel.get('symbolSize');
  58716. if (!isArray(symbolType)) {
  58717. symbolType = [symbolType, symbolType];
  58718. }
  58719. if (typeof symbolSize === 'number') {
  58720. symbolSize = [symbolSize, symbolSize];
  58721. }
  58722. // Update visual and layout of from symbol and to symbol
  58723. mlData.from.each(function (idx) {
  58724. updateDataVisualAndLayout(fromData, idx, true);
  58725. updateDataVisualAndLayout(toData, idx, false);
  58726. });
  58727. // Update visual and layout of line
  58728. lineData.each(function (idx) {
  58729. var lineColor = lineData.getItemModel(idx).get('lineStyle.normal.color');
  58730. lineData.setItemVisual(idx, {
  58731. color: lineColor || fromData.getItemVisual(idx, 'color')
  58732. });
  58733. lineData.setItemLayout(idx, [
  58734. fromData.getItemLayout(idx),
  58735. toData.getItemLayout(idx)
  58736. ]);
  58737. lineData.setItemVisual(idx, {
  58738. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  58739. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  58740. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  58741. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  58742. });
  58743. });
  58744. lineDraw.updateData(lineData);
  58745. // Set host model for tooltip
  58746. // FIXME
  58747. mlData.line.eachItemGraphicEl(function (el, idx) {
  58748. el.traverse(function (child) {
  58749. child.dataModel = mlModel;
  58750. });
  58751. });
  58752. function updateDataVisualAndLayout(data, idx, isFrom) {
  58753. var itemModel = data.getItemModel(idx);
  58754. updateSingleMarkerEndLayout(
  58755. data, idx, isFrom, seriesModel, api
  58756. );
  58757. data.setItemVisual(idx, {
  58758. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  58759. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  58760. color: itemModel.get('itemStyle.normal.color') || seriesData.getVisual('color')
  58761. });
  58762. }
  58763. lineDraw.__keep = true;
  58764. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  58765. }
  58766. });
  58767. /**
  58768. * @inner
  58769. * @param {module:echarts/coord/*} coordSys
  58770. * @param {module:echarts/model/Series} seriesModel
  58771. * @param {module:echarts/model/Model} mpModel
  58772. */
  58773. function createList$2(coordSys, seriesModel, mlModel) {
  58774. var coordDimsInfos;
  58775. if (coordSys) {
  58776. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  58777. var info = seriesModel.getData().getDimensionInfo(
  58778. seriesModel.coordDimToDataDim(coordDim)[0]
  58779. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  58780. info.name = coordDim;
  58781. return info;
  58782. });
  58783. }
  58784. else {
  58785. coordDimsInfos =[{
  58786. name: 'value',
  58787. type: 'float'
  58788. }];
  58789. }
  58790. var fromData = new List(coordDimsInfos, mlModel);
  58791. var toData = new List(coordDimsInfos, mlModel);
  58792. // No dimensions
  58793. var lineData = new List([], mlModel);
  58794. var optData = map(mlModel.get('data'), curry(
  58795. markLineTransform, seriesModel, coordSys, mlModel
  58796. ));
  58797. if (coordSys) {
  58798. optData = filter(
  58799. optData, curry(markLineFilter, coordSys)
  58800. );
  58801. }
  58802. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  58803. return item.value;
  58804. };
  58805. fromData.initData(
  58806. map(optData, function (item) { return item[0]; }),
  58807. null, dimValueGetter$$1
  58808. );
  58809. toData.initData(
  58810. map(optData, function (item) { return item[1]; }),
  58811. null, dimValueGetter$$1
  58812. );
  58813. lineData.initData(
  58814. map(optData, function (item) { return item[2]; })
  58815. );
  58816. lineData.hasItemOption = true;
  58817. return {
  58818. from: fromData,
  58819. to: toData,
  58820. line: lineData
  58821. };
  58822. }
  58823. registerPreprocessor(function (opt) {
  58824. // Make sure markLine component is enabled
  58825. opt.markLine = opt.markLine || {};
  58826. });
  58827. MarkerModel.extend({
  58828. type: 'markArea',
  58829. defaultOption: {
  58830. zlevel: 0,
  58831. // PENDING
  58832. z: 1,
  58833. tooltip: {
  58834. trigger: 'item'
  58835. },
  58836. // markArea should fixed on the coordinate system
  58837. animation: false,
  58838. label: {
  58839. normal: {
  58840. show: true,
  58841. position: 'top'
  58842. },
  58843. emphasis: {
  58844. show: true,
  58845. position: 'top'
  58846. }
  58847. },
  58848. itemStyle: {
  58849. normal: {
  58850. // color and borderColor default to use color from series
  58851. // color: 'auto'
  58852. // borderColor: 'auto'
  58853. borderWidth: 0
  58854. }
  58855. }
  58856. }
  58857. });
  58858. // TODO Better on polar
  58859. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  58860. var lt = dataTransform(seriesModel, item[0]);
  58861. var rb = dataTransform(seriesModel, item[1]);
  58862. var retrieve$$1 = retrieve;
  58863. // FIXME make sure lt is less than rb
  58864. var ltCoord = lt.coord;
  58865. var rbCoord = rb.coord;
  58866. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  58867. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  58868. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  58869. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  58870. // Merge option into one
  58871. var result = mergeAll([{}, lt, rb]);
  58872. result.coord = [
  58873. lt.coord, rb.coord
  58874. ];
  58875. result.x0 = lt.x;
  58876. result.y0 = lt.y;
  58877. result.x1 = rb.x;
  58878. result.y1 = rb.y;
  58879. return result;
  58880. };
  58881. function isInifinity$1(val) {
  58882. return !isNaN(val) && !isFinite(val);
  58883. }
  58884. // If a markArea has one dim
  58885. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  58886. var otherDimIndex = 1 - dimIndex;
  58887. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  58888. }
  58889. function markAreaFilter(coordSys, item) {
  58890. var fromCoord = item.coord[0];
  58891. var toCoord = item.coord[1];
  58892. if (coordSys.type === 'cartesian2d') {
  58893. // In case
  58894. // {
  58895. // markArea: {
  58896. // data: [{ yAxis: 2 }]
  58897. // }
  58898. // }
  58899. if (
  58900. fromCoord && toCoord &&
  58901. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  58902. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  58903. ) {
  58904. return true;
  58905. }
  58906. }
  58907. return dataFilter$1(coordSys, {
  58908. coord: fromCoord,
  58909. x: item.x0,
  58910. y: item.y0
  58911. })
  58912. || dataFilter$1(coordSys, {
  58913. coord: toCoord,
  58914. x: item.x1,
  58915. y: item.y1
  58916. });
  58917. }
  58918. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  58919. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  58920. var coordSys = seriesModel.coordinateSystem;
  58921. var itemModel = data.getItemModel(idx);
  58922. var point;
  58923. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  58924. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  58925. if (!isNaN(xPx) && !isNaN(yPx)) {
  58926. point = [xPx, yPx];
  58927. }
  58928. else {
  58929. // Chart like bar may have there own marker positioning logic
  58930. if (seriesModel.getMarkerPosition) {
  58931. // Use the getMarkerPoisition
  58932. point = seriesModel.getMarkerPosition(
  58933. data.getValues(dims, idx)
  58934. );
  58935. }
  58936. else {
  58937. var x = data.get(dims[0], idx);
  58938. var y = data.get(dims[1], idx);
  58939. point = coordSys.dataToPoint([x, y], true);
  58940. }
  58941. if (coordSys.type === 'cartesian2d') {
  58942. var xAxis = coordSys.getAxis('x');
  58943. var yAxis = coordSys.getAxis('y');
  58944. var x = data.get(dims[0], idx);
  58945. var y = data.get(dims[1], idx);
  58946. if (isInifinity$1(x)) {
  58947. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  58948. }
  58949. else if (isInifinity$1(y)) {
  58950. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  58951. }
  58952. }
  58953. // Use x, y if has any
  58954. if (!isNaN(xPx)) {
  58955. point[0] = xPx;
  58956. }
  58957. if (!isNaN(yPx)) {
  58958. point[1] = yPx;
  58959. }
  58960. }
  58961. return point;
  58962. }
  58963. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  58964. MarkerView.extend({
  58965. type: 'markArea',
  58966. updateLayout: function (markAreaModel, ecModel, api) {
  58967. ecModel.eachSeries(function (seriesModel) {
  58968. var maModel = seriesModel.markAreaModel;
  58969. if (maModel) {
  58970. var areaData = maModel.getData();
  58971. areaData.each(function (idx) {
  58972. var points = map(dimPermutations, function (dim) {
  58973. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  58974. });
  58975. // Layout
  58976. areaData.setItemLayout(idx, points);
  58977. var el = areaData.getItemGraphicEl(idx);
  58978. el.setShape('points', points);
  58979. });
  58980. }
  58981. }, this);
  58982. },
  58983. renderSeries: function (seriesModel, maModel, ecModel, api) {
  58984. var coordSys = seriesModel.coordinateSystem;
  58985. var seriesName = seriesModel.name;
  58986. var seriesData = seriesModel.getData();
  58987. var areaGroupMap = this.markerGroupMap;
  58988. var polygonGroup = areaGroupMap.get(seriesName)
  58989. || areaGroupMap.set(seriesName, {group: new Group()});
  58990. this.group.add(polygonGroup.group);
  58991. polygonGroup.__keep = true;
  58992. var areaData = createList$3(coordSys, seriesModel, maModel);
  58993. // Line data for tooltip and formatter
  58994. maModel.setData(areaData);
  58995. // Update visual and layout of line
  58996. areaData.each(function (idx) {
  58997. // Layout
  58998. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  58999. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  59000. }));
  59001. // Visual
  59002. areaData.setItemVisual(idx, {
  59003. color: seriesData.getVisual('color')
  59004. });
  59005. });
  59006. areaData.diff(polygonGroup.__data)
  59007. .add(function (idx) {
  59008. var polygon = new Polygon({
  59009. shape: {
  59010. points: areaData.getItemLayout(idx)
  59011. }
  59012. });
  59013. areaData.setItemGraphicEl(idx, polygon);
  59014. polygonGroup.group.add(polygon);
  59015. })
  59016. .update(function (newIdx, oldIdx) {
  59017. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  59018. updateProps(polygon, {
  59019. shape: {
  59020. points: areaData.getItemLayout(newIdx)
  59021. }
  59022. }, maModel, newIdx);
  59023. polygonGroup.group.add(polygon);
  59024. areaData.setItemGraphicEl(newIdx, polygon);
  59025. })
  59026. .remove(function (idx) {
  59027. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  59028. polygonGroup.group.remove(polygon);
  59029. })
  59030. .execute();
  59031. areaData.eachItemGraphicEl(function (polygon, idx) {
  59032. var itemModel = areaData.getItemModel(idx);
  59033. var labelModel = itemModel.getModel('label.normal');
  59034. var labelHoverModel = itemModel.getModel('label.emphasis');
  59035. var color = areaData.getItemVisual(idx, 'color');
  59036. polygon.useStyle(
  59037. defaults(
  59038. itemModel.getModel('itemStyle.normal').getItemStyle(),
  59039. {
  59040. fill: modifyAlpha(color, 0.4),
  59041. stroke: color
  59042. }
  59043. )
  59044. );
  59045. polygon.hoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  59046. setLabelStyle(
  59047. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  59048. {
  59049. labelFetcher: maModel,
  59050. labelDataIndex: idx,
  59051. defaultText: areaData.getName(idx) || '',
  59052. isRectText: true,
  59053. autoColor: color
  59054. }
  59055. );
  59056. setHoverStyle(polygon, {});
  59057. polygon.dataModel = maModel;
  59058. });
  59059. polygonGroup.__data = areaData;
  59060. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  59061. }
  59062. });
  59063. /**
  59064. * @inner
  59065. * @param {module:echarts/coord/*} coordSys
  59066. * @param {module:echarts/model/Series} seriesModel
  59067. * @param {module:echarts/model/Model} mpModel
  59068. */
  59069. function createList$3(coordSys, seriesModel, maModel) {
  59070. var coordDimsInfos;
  59071. var areaData;
  59072. var dims = ['x0', 'y0', 'x1', 'y1'];
  59073. if (coordSys) {
  59074. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  59075. var info = seriesModel.getData().getDimensionInfo(
  59076. seriesModel.coordDimToDataDim(coordDim)[0]
  59077. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  59078. info.name = coordDim;
  59079. return info;
  59080. });
  59081. areaData = new List(map(dims, function (dim, idx) {
  59082. return {
  59083. name: dim,
  59084. type: coordDimsInfos[idx % 2].type
  59085. };
  59086. }), maModel);
  59087. }
  59088. else {
  59089. coordDimsInfos =[{
  59090. name: 'value',
  59091. type: 'float'
  59092. }];
  59093. areaData = new List(coordDimsInfos, maModel);
  59094. }
  59095. var optData = map(maModel.get('data'), curry(
  59096. markAreaTransform, seriesModel, coordSys, maModel
  59097. ));
  59098. if (coordSys) {
  59099. optData = filter(
  59100. optData, curry(markAreaFilter, coordSys)
  59101. );
  59102. }
  59103. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  59104. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  59105. } : function (item) {
  59106. return item.value;
  59107. };
  59108. areaData.initData(optData, null, dimValueGetter$$1);
  59109. areaData.hasItemOption = true;
  59110. return areaData;
  59111. }
  59112. registerPreprocessor(function (opt) {
  59113. // Make sure markArea component is enabled
  59114. opt.markArea = opt.markArea || {};
  59115. });
  59116. var preprocessor$3 = function (option) {
  59117. var timelineOpt = option && option.timeline;
  59118. if (!isArray(timelineOpt)) {
  59119. timelineOpt = timelineOpt ? [timelineOpt] : [];
  59120. }
  59121. each$1(timelineOpt, function (opt) {
  59122. if (!opt) {
  59123. return;
  59124. }
  59125. compatibleEC2(opt);
  59126. });
  59127. };
  59128. function compatibleEC2(opt) {
  59129. var type = opt.type;
  59130. var ec2Types = {'number': 'value', 'time': 'time'};
  59131. // Compatible with ec2
  59132. if (ec2Types[type]) {
  59133. opt.axisType = ec2Types[type];
  59134. delete opt.type;
  59135. }
  59136. transferItem(opt);
  59137. if (has$2(opt, 'controlPosition')) {
  59138. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  59139. if (!has$2(controlStyle, 'position')) {
  59140. controlStyle.position = opt.controlPosition;
  59141. }
  59142. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  59143. controlStyle.show = false;
  59144. delete controlStyle.position;
  59145. }
  59146. delete opt.controlPosition;
  59147. }
  59148. each$1(opt.data || [], function (dataItem) {
  59149. if (isObject(dataItem) && !isArray(dataItem)) {
  59150. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  59151. // In ec2, using name as value.
  59152. dataItem.value = dataItem.name;
  59153. }
  59154. transferItem(dataItem);
  59155. }
  59156. });
  59157. }
  59158. function transferItem(opt) {
  59159. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  59160. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  59161. // Transfer label out
  59162. var label = opt.label || (opt.label || {});
  59163. var labelNormal = label.normal || (label.normal = {});
  59164. var excludeLabelAttr = {normal: 1, emphasis: 1};
  59165. each$1(label, function (value, name) {
  59166. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  59167. labelNormal[name] = value;
  59168. }
  59169. });
  59170. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  59171. label.emphasis = itemStyleEmphasis.label;
  59172. delete itemStyleEmphasis.label;
  59173. }
  59174. }
  59175. function has$2(obj, attr) {
  59176. return obj.hasOwnProperty(attr);
  59177. }
  59178. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  59179. // Only slider now.
  59180. return 'slider';
  59181. });
  59182. registerAction(
  59183. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  59184. function (payload, ecModel) {
  59185. var timelineModel = ecModel.getComponent('timeline');
  59186. if (timelineModel && payload.currentIndex != null) {
  59187. timelineModel.setCurrentIndex(payload.currentIndex);
  59188. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  59189. timelineModel.setPlayState(false);
  59190. }
  59191. }
  59192. // Set normalized currentIndex to payload.
  59193. ecModel.resetOption('timeline');
  59194. return defaults({
  59195. currentIndex: timelineModel.option.currentIndex
  59196. }, payload);
  59197. }
  59198. );
  59199. registerAction(
  59200. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  59201. function (payload, ecModel) {
  59202. var timelineModel = ecModel.getComponent('timeline');
  59203. if (timelineModel && payload.playState != null) {
  59204. timelineModel.setPlayState(payload.playState);
  59205. }
  59206. }
  59207. );
  59208. var TimelineModel = ComponentModel.extend({
  59209. type: 'timeline',
  59210. layoutMode: 'box',
  59211. /**
  59212. * @protected
  59213. */
  59214. defaultOption: {
  59215. zlevel: 0, // 一级层叠
  59216. z: 4, // 二级层叠
  59217. show: true,
  59218. axisType: 'time', // 模式是时间类型,支持 value, category
  59219. realtime: true,
  59220. left: '20%',
  59221. top: null,
  59222. right: '20%',
  59223. bottom: 0,
  59224. width: null,
  59225. height: 40,
  59226. padding: 5,
  59227. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  59228. autoPlay: false,
  59229. rewind: false, // 反向播放
  59230. loop: true,
  59231. playInterval: 2000, // 播放时间间隔,单位ms
  59232. currentIndex: 0,
  59233. itemStyle: {
  59234. normal: {},
  59235. emphasis: {}
  59236. },
  59237. label: {
  59238. normal: {
  59239. color: '#000'
  59240. },
  59241. emphasis: {}
  59242. },
  59243. data: []
  59244. },
  59245. /**
  59246. * @override
  59247. */
  59248. init: function (option, parentModel, ecModel) {
  59249. /**
  59250. * @private
  59251. * @type {module:echarts/data/List}
  59252. */
  59253. this._data;
  59254. /**
  59255. * @private
  59256. * @type {Array.<string>}
  59257. */
  59258. this._names;
  59259. this.mergeDefaultAndTheme(option, ecModel);
  59260. this._initData();
  59261. },
  59262. /**
  59263. * @override
  59264. */
  59265. mergeOption: function (option) {
  59266. TimelineModel.superApply(this, 'mergeOption', arguments);
  59267. this._initData();
  59268. },
  59269. /**
  59270. * @param {number} [currentIndex]
  59271. */
  59272. setCurrentIndex: function (currentIndex) {
  59273. if (currentIndex == null) {
  59274. currentIndex = this.option.currentIndex;
  59275. }
  59276. var count = this._data.count();
  59277. if (this.option.loop) {
  59278. currentIndex = (currentIndex % count + count) % count;
  59279. }
  59280. else {
  59281. currentIndex >= count && (currentIndex = count - 1);
  59282. currentIndex < 0 && (currentIndex = 0);
  59283. }
  59284. this.option.currentIndex = currentIndex;
  59285. },
  59286. /**
  59287. * @return {number} currentIndex
  59288. */
  59289. getCurrentIndex: function () {
  59290. return this.option.currentIndex;
  59291. },
  59292. /**
  59293. * @return {boolean}
  59294. */
  59295. isIndexMax: function () {
  59296. return this.getCurrentIndex() >= this._data.count() - 1;
  59297. },
  59298. /**
  59299. * @param {boolean} state true: play, false: stop
  59300. */
  59301. setPlayState: function (state) {
  59302. this.option.autoPlay = !!state;
  59303. },
  59304. /**
  59305. * @return {boolean} true: play, false: stop
  59306. */
  59307. getPlayState: function () {
  59308. return !!this.option.autoPlay;
  59309. },
  59310. /**
  59311. * @private
  59312. */
  59313. _initData: function () {
  59314. var thisOption = this.option;
  59315. var dataArr = thisOption.data || [];
  59316. var axisType = thisOption.axisType;
  59317. var names = this._names = [];
  59318. if (axisType === 'category') {
  59319. var idxArr = [];
  59320. each$1(dataArr, function (item, index) {
  59321. var value = getDataItemValue(item);
  59322. var newItem;
  59323. if (isObject(item)) {
  59324. newItem = clone(item);
  59325. newItem.value = index;
  59326. }
  59327. else {
  59328. newItem = index;
  59329. }
  59330. idxArr.push(newItem);
  59331. if (!isString(value) && (value == null || isNaN(value))) {
  59332. value = '';
  59333. }
  59334. names.push(value + '');
  59335. });
  59336. dataArr = idxArr;
  59337. }
  59338. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  59339. var data = this._data = new List([{name: 'value', type: dimType}], this);
  59340. data.initData(dataArr, names);
  59341. },
  59342. getData: function () {
  59343. return this._data;
  59344. },
  59345. /**
  59346. * @public
  59347. * @return {Array.<string>} categoreis
  59348. */
  59349. getCategories: function () {
  59350. if (this.get('axisType') === 'category') {
  59351. return this._names.slice();
  59352. }
  59353. }
  59354. });
  59355. var SliderTimelineModel = TimelineModel.extend({
  59356. type: 'timeline.slider',
  59357. /**
  59358. * @protected
  59359. */
  59360. defaultOption: {
  59361. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  59362. borderColor: '#ccc', // 时间轴边框颜色
  59363. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  59364. orient: 'horizontal', // 'vertical'
  59365. inverse: false,
  59366. tooltip: { // boolean or Object
  59367. trigger: 'item' // data item may also have tootip attr.
  59368. },
  59369. symbol: 'emptyCircle',
  59370. symbolSize: 10,
  59371. lineStyle: {
  59372. show: true,
  59373. width: 2,
  59374. color: '#304654'
  59375. },
  59376. label: { // 文本标签
  59377. position: 'auto', // auto left right top bottom
  59378. // When using number, label position is not
  59379. // restricted by viewRect.
  59380. // positive: right/bottom, negative: left/top
  59381. normal: {
  59382. show: true,
  59383. interval: 'auto',
  59384. rotate: 0,
  59385. // formatter: null,
  59386. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  59387. color: '#304654'
  59388. },
  59389. emphasis: {
  59390. show: true,
  59391. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  59392. color: '#c23531'
  59393. }
  59394. },
  59395. itemStyle: {
  59396. normal: {
  59397. color: '#304654',
  59398. borderWidth: 1
  59399. },
  59400. emphasis: {
  59401. color: '#c23531'
  59402. }
  59403. },
  59404. checkpointStyle: {
  59405. symbol: 'circle',
  59406. symbolSize: 13,
  59407. color: '#c23531',
  59408. borderWidth: 5,
  59409. borderColor: 'rgba(194,53,49, 0.5)',
  59410. animation: true,
  59411. animationDuration: 300,
  59412. animationEasing: 'quinticInOut'
  59413. },
  59414. controlStyle: {
  59415. show: true,
  59416. showPlayBtn: true,
  59417. showPrevBtn: true,
  59418. showNextBtn: true,
  59419. itemSize: 22,
  59420. itemGap: 12,
  59421. position: 'left', // 'left' 'right' 'top' 'bottom'
  59422. 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
  59423. 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
  59424. 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
  59425. 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
  59426. normal: {
  59427. color: '#304654',
  59428. borderColor: '#304654',
  59429. borderWidth: 1
  59430. },
  59431. emphasis: {
  59432. color: '#c23531',
  59433. borderColor: '#c23531',
  59434. borderWidth: 2
  59435. }
  59436. },
  59437. data: []
  59438. }
  59439. });
  59440. mixin(SliderTimelineModel, dataFormatMixin);
  59441. var TimelineView = Component.extend({
  59442. type: 'timeline'
  59443. });
  59444. /**
  59445. * Extend axis 2d
  59446. * @constructor module:echarts/coord/cartesian/Axis2D
  59447. * @extends {module:echarts/coord/cartesian/Axis}
  59448. * @param {string} dim
  59449. * @param {*} scale
  59450. * @param {Array.<number>} coordExtent
  59451. * @param {string} axisType
  59452. * @param {string} position
  59453. */
  59454. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  59455. Axis.call(this, dim, scale, coordExtent);
  59456. /**
  59457. * Axis type
  59458. * - 'category'
  59459. * - 'value'
  59460. * - 'time'
  59461. * - 'log'
  59462. * @type {string}
  59463. */
  59464. this.type = axisType || 'value';
  59465. /**
  59466. * @private
  59467. * @type {number}
  59468. */
  59469. this._autoLabelInterval;
  59470. /**
  59471. * Axis model
  59472. * @param {module:echarts/component/TimelineModel}
  59473. */
  59474. this.model = null;
  59475. };
  59476. TimelineAxis.prototype = {
  59477. constructor: TimelineAxis,
  59478. /**
  59479. * @public
  59480. * @return {number}
  59481. */
  59482. getLabelInterval: function () {
  59483. var timelineModel = this.model;
  59484. var labelModel = timelineModel.getModel('label.normal');
  59485. var labelInterval = labelModel.get('interval');
  59486. if (labelInterval != null && labelInterval != 'auto') {
  59487. return labelInterval;
  59488. }
  59489. var labelInterval = this._autoLabelInterval;
  59490. if (!labelInterval) {
  59491. labelInterval = this._autoLabelInterval = getAxisLabelInterval(
  59492. map(this.scale.getTicks(), this.dataToCoord, this),
  59493. getFormattedLabels(this, labelModel.get('formatter')),
  59494. labelModel.getFont(),
  59495. timelineModel.get('orient') === 'horizontal' ? 0 : 90,
  59496. labelModel.get('rotate')
  59497. );
  59498. }
  59499. return labelInterval;
  59500. },
  59501. /**
  59502. * If label is ignored.
  59503. * Automatically used when axis is category and label can not be all shown
  59504. * @public
  59505. * @param {number} idx
  59506. * @return {boolean}
  59507. */
  59508. isLabelIgnored: function (idx) {
  59509. if (this.type === 'category') {
  59510. var labelInterval = this.getLabelInterval();
  59511. return ((typeof labelInterval === 'function')
  59512. && !labelInterval(idx, this.scale.getLabel(idx)))
  59513. || idx % (labelInterval + 1);
  59514. }
  59515. }
  59516. };
  59517. inherits(TimelineAxis, Axis);
  59518. var bind$6 = bind;
  59519. var each$30 = each$1;
  59520. var PI$4 = Math.PI;
  59521. TimelineView.extend({
  59522. type: 'timeline.slider',
  59523. init: function (ecModel, api) {
  59524. this.api = api;
  59525. /**
  59526. * @private
  59527. * @type {module:echarts/component/timeline/TimelineAxis}
  59528. */
  59529. this._axis;
  59530. /**
  59531. * @private
  59532. * @type {module:zrender/core/BoundingRect}
  59533. */
  59534. this._viewRect;
  59535. /**
  59536. * @type {number}
  59537. */
  59538. this._timer;
  59539. /**
  59540. * @type {module:zrender/Element}
  59541. */
  59542. this._currentPointer;
  59543. /**
  59544. * @type {module:zrender/container/Group}
  59545. */
  59546. this._mainGroup;
  59547. /**
  59548. * @type {module:zrender/container/Group}
  59549. */
  59550. this._labelGroup;
  59551. },
  59552. /**
  59553. * @override
  59554. */
  59555. render: function (timelineModel, ecModel, api, payload) {
  59556. this.model = timelineModel;
  59557. this.api = api;
  59558. this.ecModel = ecModel;
  59559. this.group.removeAll();
  59560. if (timelineModel.get('show', true)) {
  59561. var layoutInfo = this._layout(timelineModel, api);
  59562. var mainGroup = this._createGroup('mainGroup');
  59563. var labelGroup = this._createGroup('labelGroup');
  59564. /**
  59565. * @private
  59566. * @type {module:echarts/component/timeline/TimelineAxis}
  59567. */
  59568. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  59569. timelineModel.formatTooltip = function (dataIndex) {
  59570. return encodeHTML(axis.scale.getLabel(dataIndex));
  59571. };
  59572. each$30(
  59573. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  59574. function (name) {
  59575. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  59576. },
  59577. this
  59578. );
  59579. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  59580. this._position(layoutInfo, timelineModel);
  59581. }
  59582. this._doPlayStop();
  59583. },
  59584. /**
  59585. * @override
  59586. */
  59587. remove: function () {
  59588. this._clearTimer();
  59589. this.group.removeAll();
  59590. },
  59591. /**
  59592. * @override
  59593. */
  59594. dispose: function () {
  59595. this._clearTimer();
  59596. },
  59597. _layout: function (timelineModel, api) {
  59598. var labelPosOpt = timelineModel.get('label.normal.position');
  59599. var orient = timelineModel.get('orient');
  59600. var viewRect = getViewRect$4(timelineModel, api);
  59601. // Auto label offset.
  59602. if (labelPosOpt == null || labelPosOpt === 'auto') {
  59603. labelPosOpt = orient === 'horizontal'
  59604. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  59605. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  59606. }
  59607. else if (isNaN(labelPosOpt)) {
  59608. labelPosOpt = ({
  59609. horizontal: {top: '-', bottom: '+'},
  59610. vertical: {left: '-', right: '+'}
  59611. })[orient][labelPosOpt];
  59612. }
  59613. var labelAlignMap = {
  59614. horizontal: 'center',
  59615. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  59616. };
  59617. var labelBaselineMap = {
  59618. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  59619. vertical: 'middle'
  59620. };
  59621. var rotationMap = {
  59622. horizontal: 0,
  59623. vertical: PI$4 / 2
  59624. };
  59625. // Position
  59626. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  59627. var controlModel = timelineModel.getModel('controlStyle');
  59628. var showControl = controlModel.get('show');
  59629. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  59630. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  59631. var sizePlusGap = controlSize + controlGap;
  59632. // Special label rotate.
  59633. var labelRotation = timelineModel.get('label.normal.rotate') || 0;
  59634. labelRotation = labelRotation * PI$4 / 180; // To radian.
  59635. var playPosition;
  59636. var prevBtnPosition;
  59637. var nextBtnPosition;
  59638. var axisExtent;
  59639. var controlPosition = controlModel.get('position', true);
  59640. var showControl = controlModel.get('show', true);
  59641. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  59642. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  59643. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  59644. var xLeft = 0;
  59645. var xRight = mainLength;
  59646. // position[0] means left, position[1] means middle.
  59647. if (controlPosition === 'left' || controlPosition === 'bottom') {
  59648. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  59649. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  59650. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59651. }
  59652. else { // 'top' 'right'
  59653. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59654. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  59655. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59656. }
  59657. axisExtent = [xLeft, xRight];
  59658. if (timelineModel.get('inverse')) {
  59659. axisExtent.reverse();
  59660. }
  59661. return {
  59662. viewRect: viewRect,
  59663. mainLength: mainLength,
  59664. orient: orient,
  59665. rotation: rotationMap[orient],
  59666. labelRotation: labelRotation,
  59667. labelPosOpt: labelPosOpt,
  59668. labelAlign: timelineModel.get('label.normal.align') || labelAlignMap[orient],
  59669. labelBaseline: timelineModel.get('label.normal.verticalAlign')
  59670. || timelineModel.get('label.normal.baseline')
  59671. || labelBaselineMap[orient],
  59672. // Based on mainGroup.
  59673. playPosition: playPosition,
  59674. prevBtnPosition: prevBtnPosition,
  59675. nextBtnPosition: nextBtnPosition,
  59676. axisExtent: axisExtent,
  59677. controlSize: controlSize,
  59678. controlGap: controlGap
  59679. };
  59680. },
  59681. _position: function (layoutInfo, timelineModel) {
  59682. // Position is be called finally, because bounding rect is needed for
  59683. // adapt content to fill viewRect (auto adapt offset).
  59684. // Timeline may be not all in the viewRect when 'offset' is specified
  59685. // as a number, because it is more appropriate that label aligns at
  59686. // 'offset' but not the other edge defined by viewRect.
  59687. var mainGroup = this._mainGroup;
  59688. var labelGroup = this._labelGroup;
  59689. var viewRect = layoutInfo.viewRect;
  59690. if (layoutInfo.orient === 'vertical') {
  59691. // transfrom to horizontal, inverse rotate by left-top point.
  59692. var m = create$1();
  59693. var rotateOriginX = viewRect.x;
  59694. var rotateOriginY = viewRect.y + viewRect.height;
  59695. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  59696. rotate(m, m, -PI$4 / 2);
  59697. translate(m, m, [rotateOriginX, rotateOriginY]);
  59698. viewRect = viewRect.clone();
  59699. viewRect.applyTransform(m);
  59700. }
  59701. var viewBound = getBound(viewRect);
  59702. var mainBound = getBound(mainGroup.getBoundingRect());
  59703. var labelBound = getBound(labelGroup.getBoundingRect());
  59704. var mainPosition = mainGroup.position;
  59705. var labelsPosition = labelGroup.position;
  59706. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  59707. var labelPosOpt = layoutInfo.labelPosOpt;
  59708. if (isNaN(labelPosOpt)) { // '+' or '-'
  59709. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  59710. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  59711. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  59712. }
  59713. else {
  59714. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  59715. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  59716. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  59717. }
  59718. mainGroup.attr('position', mainPosition);
  59719. labelGroup.attr('position', labelsPosition);
  59720. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  59721. setOrigin(mainGroup);
  59722. setOrigin(labelGroup);
  59723. function setOrigin(targetGroup) {
  59724. var pos = targetGroup.position;
  59725. targetGroup.origin = [
  59726. viewBound[0][0] - pos[0],
  59727. viewBound[1][0] - pos[1]
  59728. ];
  59729. }
  59730. function getBound(rect) {
  59731. // [[xmin, xmax], [ymin, ymax]]
  59732. return [
  59733. [rect.x, rect.x + rect.width],
  59734. [rect.y, rect.y + rect.height]
  59735. ];
  59736. }
  59737. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  59738. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  59739. }
  59740. },
  59741. _createAxis: function (layoutInfo, timelineModel) {
  59742. var data = timelineModel.getData();
  59743. var axisType = timelineModel.get('axisType');
  59744. var scale = createScaleByModel(timelineModel, axisType);
  59745. var dataExtent = data.getDataExtent('value');
  59746. scale.setExtent(dataExtent[0], dataExtent[1]);
  59747. this._customizeScale(scale, data);
  59748. scale.niceTicks();
  59749. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  59750. axis.model = timelineModel;
  59751. return axis;
  59752. },
  59753. _customizeScale: function (scale, data) {
  59754. scale.getTicks = function () {
  59755. return data.mapArray(['value'], function (value) {
  59756. return value;
  59757. });
  59758. };
  59759. scale.getTicksLabels = function () {
  59760. return map(this.getTicks(), scale.getLabel, scale);
  59761. };
  59762. },
  59763. _createGroup: function (name) {
  59764. var newGroup = this['_' + name] = new Group();
  59765. this.group.add(newGroup);
  59766. return newGroup;
  59767. },
  59768. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  59769. var axisExtent = axis.getExtent();
  59770. if (!timelineModel.get('lineStyle.show')) {
  59771. return;
  59772. }
  59773. group.add(new Line({
  59774. shape: {
  59775. x1: axisExtent[0], y1: 0,
  59776. x2: axisExtent[1], y2: 0
  59777. },
  59778. style: extend(
  59779. {lineCap: 'round'},
  59780. timelineModel.getModel('lineStyle').getLineStyle()
  59781. ),
  59782. silent: true,
  59783. z2: 1
  59784. }));
  59785. },
  59786. /**
  59787. * @private
  59788. */
  59789. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  59790. var data = timelineModel.getData();
  59791. var ticks = axis.scale.getTicks();
  59792. each$30(ticks, function (value, dataIndex) {
  59793. var tickCoord = axis.dataToCoord(value);
  59794. var itemModel = data.getItemModel(dataIndex);
  59795. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  59796. var hoverStyleModel = itemModel.getModel('itemStyle.emphasis');
  59797. var symbolOpt = {
  59798. position: [tickCoord, 0],
  59799. onclick: bind$6(this._changeTimeline, this, dataIndex)
  59800. };
  59801. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  59802. setHoverStyle(el, hoverStyleModel.getItemStyle());
  59803. if (itemModel.get('tooltip')) {
  59804. el.dataIndex = dataIndex;
  59805. el.dataModel = timelineModel;
  59806. }
  59807. else {
  59808. el.dataIndex = el.dataModel = null;
  59809. }
  59810. }, this);
  59811. },
  59812. /**
  59813. * @private
  59814. */
  59815. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  59816. var labelModel = timelineModel.getModel('label.normal');
  59817. if (!labelModel.get('show')) {
  59818. return;
  59819. }
  59820. var data = timelineModel.getData();
  59821. var ticks = axis.scale.getTicks();
  59822. var labels = getFormattedLabels(
  59823. axis, labelModel.get('formatter')
  59824. );
  59825. var labelInterval = axis.getLabelInterval();
  59826. each$30(ticks, function (tick, dataIndex) {
  59827. if (axis.isLabelIgnored(dataIndex, labelInterval)) {
  59828. return;
  59829. }
  59830. var itemModel = data.getItemModel(dataIndex);
  59831. var normalLabelModel = itemModel.getModel('label.normal');
  59832. var hoverLabelModel = itemModel.getModel('label.emphasis');
  59833. var tickCoord = axis.dataToCoord(tick);
  59834. var textEl = new Text({
  59835. position: [tickCoord, 0],
  59836. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  59837. onclick: bind$6(this._changeTimeline, this, dataIndex),
  59838. silent: false
  59839. });
  59840. setTextStyle(textEl.style, normalLabelModel, {
  59841. text: labels[dataIndex],
  59842. textAlign: layoutInfo.labelAlign,
  59843. textVerticalAlign: layoutInfo.labelBaseline
  59844. });
  59845. group.add(textEl);
  59846. setHoverStyle(
  59847. textEl, setTextStyle({}, hoverLabelModel)
  59848. );
  59849. }, this);
  59850. },
  59851. /**
  59852. * @private
  59853. */
  59854. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  59855. var controlSize = layoutInfo.controlSize;
  59856. var rotation = layoutInfo.rotation;
  59857. var itemStyle = timelineModel.getModel('controlStyle.normal').getItemStyle();
  59858. var hoverStyle = timelineModel.getModel('controlStyle.emphasis').getItemStyle();
  59859. var rect = [0, -controlSize / 2, controlSize, controlSize];
  59860. var playState = timelineModel.getPlayState();
  59861. var inverse = timelineModel.get('inverse', true);
  59862. makeBtn(
  59863. layoutInfo.nextBtnPosition,
  59864. 'controlStyle.nextIcon',
  59865. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  59866. );
  59867. makeBtn(
  59868. layoutInfo.prevBtnPosition,
  59869. 'controlStyle.prevIcon',
  59870. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  59871. );
  59872. makeBtn(
  59873. layoutInfo.playPosition,
  59874. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  59875. bind$6(this._handlePlayClick, this, !playState),
  59876. true
  59877. );
  59878. function makeBtn(position, iconPath, onclick, willRotate) {
  59879. if (!position) {
  59880. return;
  59881. }
  59882. var opt = {
  59883. position: position,
  59884. origin: [controlSize / 2, 0],
  59885. rotation: willRotate ? -rotation : 0,
  59886. rectHover: true,
  59887. style: itemStyle,
  59888. onclick: onclick
  59889. };
  59890. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  59891. group.add(btn);
  59892. setHoverStyle(btn, hoverStyle);
  59893. }
  59894. },
  59895. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  59896. var data = timelineModel.getData();
  59897. var currentIndex = timelineModel.getCurrentIndex();
  59898. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  59899. var me = this;
  59900. var callback = {
  59901. onCreate: function (pointer) {
  59902. pointer.draggable = true;
  59903. pointer.drift = bind$6(me._handlePointerDrag, me);
  59904. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  59905. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  59906. },
  59907. onUpdate: function (pointer) {
  59908. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  59909. }
  59910. };
  59911. // Reuse when exists, for animation and drag.
  59912. this._currentPointer = giveSymbol(
  59913. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  59914. );
  59915. },
  59916. _handlePlayClick: function (nextState) {
  59917. this._clearTimer();
  59918. this.api.dispatchAction({
  59919. type: 'timelinePlayChange',
  59920. playState: nextState,
  59921. from: this.uid
  59922. });
  59923. },
  59924. _handlePointerDrag: function (dx, dy, e) {
  59925. this._clearTimer();
  59926. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  59927. },
  59928. _handlePointerDragend: function (e) {
  59929. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  59930. },
  59931. _pointerChangeTimeline: function (mousePos, trigger) {
  59932. var toCoord = this._toAxisCoord(mousePos)[0];
  59933. var axis = this._axis;
  59934. var axisExtent = asc(axis.getExtent().slice());
  59935. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  59936. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  59937. this._currentPointer.position[0] = toCoord;
  59938. this._currentPointer.dirty();
  59939. var targetDataIndex = this._findNearestTick(toCoord);
  59940. var timelineModel = this.model;
  59941. if (trigger || (
  59942. targetDataIndex !== timelineModel.getCurrentIndex()
  59943. && timelineModel.get('realtime')
  59944. )) {
  59945. this._changeTimeline(targetDataIndex);
  59946. }
  59947. },
  59948. _doPlayStop: function () {
  59949. this._clearTimer();
  59950. if (this.model.getPlayState()) {
  59951. this._timer = setTimeout(
  59952. bind$6(handleFrame, this),
  59953. this.model.get('playInterval')
  59954. );
  59955. }
  59956. function handleFrame() {
  59957. // Do not cache
  59958. var timelineModel = this.model;
  59959. this._changeTimeline(
  59960. timelineModel.getCurrentIndex()
  59961. + (timelineModel.get('rewind', true) ? -1 : 1)
  59962. );
  59963. }
  59964. },
  59965. _toAxisCoord: function (vertex) {
  59966. var trans = this._mainGroup.getLocalTransform();
  59967. return applyTransform$1(vertex, trans, true);
  59968. },
  59969. _findNearestTick: function (axisCoord) {
  59970. var data = this.model.getData();
  59971. var dist = Infinity;
  59972. var targetDataIndex;
  59973. var axis = this._axis;
  59974. data.each(['value'], function (value, dataIndex) {
  59975. var coord = axis.dataToCoord(value);
  59976. var d = Math.abs(coord - axisCoord);
  59977. if (d < dist) {
  59978. dist = d;
  59979. targetDataIndex = dataIndex;
  59980. }
  59981. });
  59982. return targetDataIndex;
  59983. },
  59984. _clearTimer: function () {
  59985. if (this._timer) {
  59986. clearTimeout(this._timer);
  59987. this._timer = null;
  59988. }
  59989. },
  59990. _changeTimeline: function (nextIndex) {
  59991. var currentIndex = this.model.getCurrentIndex();
  59992. if (nextIndex === '+') {
  59993. nextIndex = currentIndex + 1;
  59994. }
  59995. else if (nextIndex === '-') {
  59996. nextIndex = currentIndex - 1;
  59997. }
  59998. this.api.dispatchAction({
  59999. type: 'timelineChange',
  60000. currentIndex: nextIndex,
  60001. from: this.uid
  60002. });
  60003. }
  60004. });
  60005. function getViewRect$4(model, api) {
  60006. return getLayoutRect(
  60007. model.getBoxLayoutParams(),
  60008. {
  60009. width: api.getWidth(),
  60010. height: api.getHeight()
  60011. },
  60012. model.get('padding')
  60013. );
  60014. }
  60015. function makeIcon(timelineModel, objPath, rect, opts) {
  60016. var icon = makePath(
  60017. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  60018. clone(opts || {}),
  60019. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  60020. 'center'
  60021. );
  60022. return icon;
  60023. }
  60024. /**
  60025. * Create symbol or update symbol
  60026. * opt: basic position and event handlers
  60027. */
  60028. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  60029. var color = itemStyleModel.get('color');
  60030. if (!symbol) {
  60031. var symbolType = hostModel.get('symbol');
  60032. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  60033. symbol.setStyle('strokeNoScale', true);
  60034. group.add(symbol);
  60035. callback && callback.onCreate(symbol);
  60036. }
  60037. else {
  60038. symbol.setColor(color);
  60039. group.add(symbol); // Group may be new, also need to add.
  60040. callback && callback.onUpdate(symbol);
  60041. }
  60042. // Style
  60043. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  60044. symbol.setStyle(itemStyle);
  60045. // Transform and events.
  60046. opt = merge({
  60047. rectHover: true,
  60048. z2: 100
  60049. }, opt, true);
  60050. var symbolSize = hostModel.get('symbolSize');
  60051. symbolSize = symbolSize instanceof Array
  60052. ? symbolSize.slice()
  60053. : [+symbolSize, +symbolSize];
  60054. symbolSize[0] /= 2;
  60055. symbolSize[1] /= 2;
  60056. opt.scale = symbolSize;
  60057. var symbolOffset = hostModel.get('symbolOffset');
  60058. if (symbolOffset) {
  60059. var pos = opt.position = opt.position || [0, 0];
  60060. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  60061. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  60062. }
  60063. var symbolRotate = hostModel.get('symbolRotate');
  60064. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  60065. symbol.attr(opt);
  60066. // FIXME
  60067. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  60068. // getBoundingRect will return wrong result.
  60069. // (This is supposed to be resolved in zrender, but it is a little difficult to
  60070. // leverage performance and auto updateTransform)
  60071. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  60072. symbol.updateTransform();
  60073. return symbol;
  60074. }
  60075. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  60076. if (pointer.dragging) {
  60077. return;
  60078. }
  60079. var pointerModel = timelineModel.getModel('checkpointStyle');
  60080. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  60081. if (noAnimation || !pointerModel.get('animation', true)) {
  60082. pointer.attr({position: [toCoord, 0]});
  60083. }
  60084. else {
  60085. pointer.stopAnimation(true);
  60086. pointer.animateTo(
  60087. {position: [toCoord, 0]},
  60088. pointerModel.get('animationDuration', true),
  60089. pointerModel.get('animationEasing', true)
  60090. );
  60091. }
  60092. }
  60093. /**
  60094. * DataZoom component entry
  60095. */
  60096. registerPreprocessor(preprocessor$3);
  60097. var ToolboxModel = extendComponentModel({
  60098. type: 'toolbox',
  60099. layoutMode: {
  60100. type: 'box',
  60101. ignoreSize: true
  60102. },
  60103. mergeDefaultAndTheme: function (option) {
  60104. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  60105. each$1(this.option.feature, function (featureOpt, featureName) {
  60106. var Feature = get$5(featureName);
  60107. Feature && merge(featureOpt, Feature.defaultOption);
  60108. });
  60109. },
  60110. defaultOption: {
  60111. show: true,
  60112. z: 6,
  60113. zlevel: 0,
  60114. orient: 'horizontal',
  60115. left: 'right',
  60116. top: 'top',
  60117. // right
  60118. // bottom
  60119. backgroundColor: 'transparent',
  60120. borderColor: '#ccc',
  60121. borderRadius: 0,
  60122. borderWidth: 0,
  60123. padding: 5,
  60124. itemSize: 15,
  60125. itemGap: 8,
  60126. showTitle: true,
  60127. iconStyle: {
  60128. normal: {
  60129. borderColor: '#666',
  60130. color: 'none'
  60131. },
  60132. emphasis: {
  60133. borderColor: '#3E98C5'
  60134. }
  60135. }
  60136. // textStyle: {},
  60137. // feature
  60138. }
  60139. });
  60140. extendComponentView({
  60141. type: 'toolbox',
  60142. render: function (toolboxModel, ecModel, api, payload) {
  60143. var group = this.group;
  60144. group.removeAll();
  60145. if (!toolboxModel.get('show')) {
  60146. return;
  60147. }
  60148. var itemSize = +toolboxModel.get('itemSize');
  60149. var featureOpts = toolboxModel.get('feature') || {};
  60150. var features = this._features || (this._features = {});
  60151. var featureNames = [];
  60152. each$1(featureOpts, function (opt, name) {
  60153. featureNames.push(name);
  60154. });
  60155. (new DataDiffer(this._featureNames || [], featureNames))
  60156. .add(processFeature)
  60157. .update(processFeature)
  60158. .remove(curry(processFeature, null))
  60159. .execute();
  60160. // Keep for diff.
  60161. this._featureNames = featureNames;
  60162. function processFeature(newIndex, oldIndex) {
  60163. var featureName = featureNames[newIndex];
  60164. var oldName = featureNames[oldIndex];
  60165. var featureOpt = featureOpts[featureName];
  60166. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  60167. var feature;
  60168. if (featureName && !oldName) { // Create
  60169. if (isUserFeatureName(featureName)) {
  60170. feature = {
  60171. model: featureModel,
  60172. onclick: featureModel.option.onclick,
  60173. featureName: featureName
  60174. };
  60175. }
  60176. else {
  60177. var Feature = get$5(featureName);
  60178. if (!Feature) {
  60179. return;
  60180. }
  60181. feature = new Feature(featureModel, ecModel, api);
  60182. }
  60183. features[featureName] = feature;
  60184. }
  60185. else {
  60186. feature = features[oldName];
  60187. // If feature does not exsit.
  60188. if (!feature) {
  60189. return;
  60190. }
  60191. feature.model = featureModel;
  60192. feature.ecModel = ecModel;
  60193. feature.api = api;
  60194. }
  60195. if (!featureName && oldName) {
  60196. feature.dispose && feature.dispose(ecModel, api);
  60197. return;
  60198. }
  60199. if (!featureModel.get('show') || feature.unusable) {
  60200. feature.remove && feature.remove(ecModel, api);
  60201. return;
  60202. }
  60203. createIconPaths(featureModel, feature, featureName);
  60204. featureModel.setIconStatus = function (iconName, status) {
  60205. var option = this.option;
  60206. var iconPaths = this.iconPaths;
  60207. option.iconStatus = option.iconStatus || {};
  60208. option.iconStatus[iconName] = status;
  60209. // FIXME
  60210. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  60211. };
  60212. if (feature.render) {
  60213. feature.render(featureModel, ecModel, api, payload);
  60214. }
  60215. }
  60216. function createIconPaths(featureModel, feature, featureName) {
  60217. var iconStyleModel = featureModel.getModel('iconStyle');
  60218. // If one feature has mutiple icon. they are orginaized as
  60219. // {
  60220. // icon: {
  60221. // foo: '',
  60222. // bar: ''
  60223. // },
  60224. // title: {
  60225. // foo: '',
  60226. // bar: ''
  60227. // }
  60228. // }
  60229. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  60230. var titles = featureModel.get('title') || {};
  60231. if (typeof icons === 'string') {
  60232. var icon = icons;
  60233. var title = titles;
  60234. icons = {};
  60235. titles = {};
  60236. icons[featureName] = icon;
  60237. titles[featureName] = title;
  60238. }
  60239. var iconPaths = featureModel.iconPaths = {};
  60240. each$1(icons, function (iconStr, iconName) {
  60241. var path = createIcon(
  60242. iconStr,
  60243. {},
  60244. {
  60245. x: -itemSize / 2,
  60246. y: -itemSize / 2,
  60247. width: itemSize,
  60248. height: itemSize
  60249. }
  60250. );
  60251. path.setStyle(iconStyleModel.getModel('normal').getItemStyle());
  60252. path.hoverStyle = iconStyleModel.getModel('emphasis').getItemStyle();
  60253. setHoverStyle(path);
  60254. if (toolboxModel.get('showTitle')) {
  60255. path.__title = titles[iconName];
  60256. path.on('mouseover', function () {
  60257. // Should not reuse above hoverStyle, which might be modified.
  60258. var hoverStyle = iconStyleModel.getModel('emphasis').getItemStyle();
  60259. path.setStyle({
  60260. text: titles[iconName],
  60261. textPosition: hoverStyle.textPosition || 'bottom',
  60262. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  60263. textAlign: hoverStyle.textAlign || 'center'
  60264. });
  60265. })
  60266. .on('mouseout', function () {
  60267. path.setStyle({
  60268. textFill: null
  60269. });
  60270. });
  60271. }
  60272. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  60273. group.add(path);
  60274. path.on('click', bind(
  60275. feature.onclick, feature, ecModel, api, iconName
  60276. ));
  60277. iconPaths[iconName] = path;
  60278. });
  60279. }
  60280. layout$2(group, toolboxModel, api);
  60281. // Render background after group is layout
  60282. // FIXME
  60283. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  60284. // Adjust icon title positions to avoid them out of screen
  60285. group.eachChild(function (icon) {
  60286. var titleText = icon.__title;
  60287. var hoverStyle = icon.hoverStyle;
  60288. // May be background element
  60289. if (hoverStyle && titleText) {
  60290. var rect = getBoundingRect(
  60291. titleText, makeFont(hoverStyle)
  60292. );
  60293. var offsetX = icon.position[0] + group.position[0];
  60294. var offsetY = icon.position[1] + group.position[1] + itemSize;
  60295. var needPutOnTop = false;
  60296. if (offsetY + rect.height > api.getHeight()) {
  60297. hoverStyle.textPosition = 'top';
  60298. needPutOnTop = true;
  60299. }
  60300. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  60301. if (offsetX + rect.width / 2 > api.getWidth()) {
  60302. hoverStyle.textPosition = ['100%', topOffset];
  60303. hoverStyle.textAlign = 'right';
  60304. }
  60305. else if (offsetX - rect.width / 2 < 0) {
  60306. hoverStyle.textPosition = [0, topOffset];
  60307. hoverStyle.textAlign = 'left';
  60308. }
  60309. }
  60310. });
  60311. },
  60312. updateView: function (toolboxModel, ecModel, api, payload) {
  60313. each$1(this._features, function (feature) {
  60314. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  60315. });
  60316. },
  60317. updateLayout: function (toolboxModel, ecModel, api, payload) {
  60318. each$1(this._features, function (feature) {
  60319. feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  60320. });
  60321. },
  60322. remove: function (ecModel, api) {
  60323. each$1(this._features, function (feature) {
  60324. feature.remove && feature.remove(ecModel, api);
  60325. });
  60326. this.group.removeAll();
  60327. },
  60328. dispose: function (ecModel, api) {
  60329. each$1(this._features, function (feature) {
  60330. feature.dispose && feature.dispose(ecModel, api);
  60331. });
  60332. }
  60333. });
  60334. function isUserFeatureName(featureName) {
  60335. return featureName.indexOf('my') === 0;
  60336. }
  60337. var saveAsImageLang = lang.toolbox.saveAsImage;
  60338. function SaveAsImage(model) {
  60339. this.model = model;
  60340. }
  60341. SaveAsImage.defaultOption = {
  60342. show: true,
  60343. 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',
  60344. title: saveAsImageLang.title,
  60345. type: 'png',
  60346. // Default use option.backgroundColor
  60347. // backgroundColor: '#fff',
  60348. name: '',
  60349. excludeComponents: ['toolbox'],
  60350. pixelRatio: 1,
  60351. lang: saveAsImageLang.lang.slice()
  60352. };
  60353. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  60354. var proto$2 = SaveAsImage.prototype;
  60355. proto$2.onclick = function (ecModel, api) {
  60356. var model = this.model;
  60357. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  60358. var $a = document.createElement('a');
  60359. var type = model.get('type', true) || 'png';
  60360. $a.download = title + '.' + type;
  60361. $a.target = '_blank';
  60362. var url = api.getConnectedDataURL({
  60363. type: type,
  60364. backgroundColor: model.get('backgroundColor', true)
  60365. || ecModel.get('backgroundColor') || '#fff',
  60366. excludeComponents: model.get('excludeComponents'),
  60367. pixelRatio: model.get('pixelRatio')
  60368. });
  60369. $a.href = url;
  60370. // Chrome and Firefox
  60371. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  60372. var evt = new MouseEvent('click', {
  60373. view: window,
  60374. bubbles: true,
  60375. cancelable: false
  60376. });
  60377. $a.dispatchEvent(evt);
  60378. }
  60379. // IE
  60380. else {
  60381. if (window.navigator.msSaveOrOpenBlob) {
  60382. var bstr = atob(url.split(',')[1]);
  60383. var n = bstr.length;
  60384. var u8arr = new Uint8Array(n);
  60385. while(n--) {
  60386. u8arr[n] = bstr.charCodeAt(n);
  60387. }
  60388. var blob = new Blob([u8arr]);
  60389. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  60390. }
  60391. else {
  60392. var lang$$1 = model.get('lang');
  60393. var html = '' +
  60394. '<body style="margin:0;">' +
  60395. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  60396. '</body>';
  60397. var tab = window.open();
  60398. tab.document.write(html);
  60399. }
  60400. }
  60401. };
  60402. register$1(
  60403. 'saveAsImage', SaveAsImage
  60404. );
  60405. var magicTypeLang = lang.toolbox.magicType;
  60406. function MagicType(model) {
  60407. this.model = model;
  60408. }
  60409. MagicType.defaultOption = {
  60410. show: true,
  60411. type: [],
  60412. // Icon group
  60413. icon: {
  60414. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  60415. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  60416. 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
  60417. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  60418. },
  60419. // `line`, `bar`, `stack`, `tiled`
  60420. title: clone(magicTypeLang.title),
  60421. option: {},
  60422. seriesIndex: {}
  60423. };
  60424. var proto$3 = MagicType.prototype;
  60425. proto$3.getIcons = function () {
  60426. var model = this.model;
  60427. var availableIcons = model.get('icon');
  60428. var icons = {};
  60429. each$1(model.get('type'), function (type) {
  60430. if (availableIcons[type]) {
  60431. icons[type] = availableIcons[type];
  60432. }
  60433. });
  60434. return icons;
  60435. };
  60436. var seriesOptGenreator = {
  60437. 'line': function (seriesType, seriesId, seriesModel, model) {
  60438. if (seriesType === 'bar') {
  60439. return merge({
  60440. id: seriesId,
  60441. type: 'line',
  60442. // Preserve data related option
  60443. data: seriesModel.get('data'),
  60444. stack: seriesModel.get('stack'),
  60445. markPoint: seriesModel.get('markPoint'),
  60446. markLine: seriesModel.get('markLine')
  60447. }, model.get('option.line') || {}, true);
  60448. }
  60449. },
  60450. 'bar': function (seriesType, seriesId, seriesModel, model) {
  60451. if (seriesType === 'line') {
  60452. return merge({
  60453. id: seriesId,
  60454. type: 'bar',
  60455. // Preserve data related option
  60456. data: seriesModel.get('data'),
  60457. stack: seriesModel.get('stack'),
  60458. markPoint: seriesModel.get('markPoint'),
  60459. markLine: seriesModel.get('markLine')
  60460. }, model.get('option.bar') || {}, true);
  60461. }
  60462. },
  60463. 'stack': function (seriesType, seriesId, seriesModel, model) {
  60464. if (seriesType === 'line' || seriesType === 'bar') {
  60465. return merge({
  60466. id: seriesId,
  60467. stack: '__ec_magicType_stack__'
  60468. }, model.get('option.stack') || {}, true);
  60469. }
  60470. },
  60471. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  60472. if (seriesType === 'line' || seriesType === 'bar') {
  60473. return merge({
  60474. id: seriesId,
  60475. stack: ''
  60476. }, model.get('option.tiled') || {}, true);
  60477. }
  60478. }
  60479. };
  60480. var radioTypes = [
  60481. ['line', 'bar'],
  60482. ['stack', 'tiled']
  60483. ];
  60484. proto$3.onclick = function (ecModel, api, type) {
  60485. var model = this.model;
  60486. var seriesIndex = model.get('seriesIndex.' + type);
  60487. // Not supported magicType
  60488. if (!seriesOptGenreator[type]) {
  60489. return;
  60490. }
  60491. var newOption = {
  60492. series: []
  60493. };
  60494. var generateNewSeriesTypes = function (seriesModel) {
  60495. var seriesType = seriesModel.subType;
  60496. var seriesId = seriesModel.id;
  60497. var newSeriesOpt = seriesOptGenreator[type](
  60498. seriesType, seriesId, seriesModel, model
  60499. );
  60500. if (newSeriesOpt) {
  60501. // PENDING If merge original option?
  60502. defaults(newSeriesOpt, seriesModel.option);
  60503. newOption.series.push(newSeriesOpt);
  60504. }
  60505. // Modify boundaryGap
  60506. var coordSys = seriesModel.coordinateSystem;
  60507. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  60508. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  60509. if (categoryAxis) {
  60510. var axisDim = categoryAxis.dim;
  60511. var axisType = axisDim + 'Axis';
  60512. var axisModel = ecModel.queryComponents({
  60513. mainType: axisType,
  60514. index: seriesModel.get(name + 'Index'),
  60515. id: seriesModel.get(name + 'Id')
  60516. })[0];
  60517. var axisIndex = axisModel.componentIndex;
  60518. newOption[axisType] = newOption[axisType] || [];
  60519. for (var i = 0; i <= axisIndex; i++) {
  60520. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  60521. }
  60522. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  60523. }
  60524. }
  60525. };
  60526. each$1(radioTypes, function (radio) {
  60527. if (indexOf(radio, type) >= 0) {
  60528. each$1(radio, function (item) {
  60529. model.setIconStatus(item, 'normal');
  60530. });
  60531. }
  60532. });
  60533. model.setIconStatus(type, 'emphasis');
  60534. ecModel.eachComponent(
  60535. {
  60536. mainType: 'series',
  60537. query: seriesIndex == null ? null : {
  60538. seriesIndex: seriesIndex
  60539. }
  60540. }, generateNewSeriesTypes
  60541. );
  60542. api.dispatchAction({
  60543. type: 'changeMagicType',
  60544. currentType: type,
  60545. newOption: newOption
  60546. });
  60547. };
  60548. registerAction({
  60549. type: 'changeMagicType',
  60550. event: 'magicTypeChanged',
  60551. update: 'prepareAndUpdate'
  60552. }, function (payload, ecModel) {
  60553. ecModel.mergeOption(payload.newOption);
  60554. });
  60555. register$1('magicType', MagicType);
  60556. var dataViewLang = lang.toolbox.dataView;
  60557. var BLOCK_SPLITER = new Array(60).join('-');
  60558. var ITEM_SPLITER = '\t';
  60559. /**
  60560. * Group series into two types
  60561. * 1. on category axis, like line, bar
  60562. * 2. others, like scatter, pie
  60563. * @param {module:echarts/model/Global} ecModel
  60564. * @return {Object}
  60565. * @inner
  60566. */
  60567. function groupSeries(ecModel) {
  60568. var seriesGroupByCategoryAxis = {};
  60569. var otherSeries = [];
  60570. var meta = [];
  60571. ecModel.eachRawSeries(function (seriesModel) {
  60572. var coordSys = seriesModel.coordinateSystem;
  60573. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  60574. var baseAxis = coordSys.getBaseAxis();
  60575. if (baseAxis.type === 'category') {
  60576. var key = baseAxis.dim + '_' + baseAxis.index;
  60577. if (!seriesGroupByCategoryAxis[key]) {
  60578. seriesGroupByCategoryAxis[key] = {
  60579. categoryAxis: baseAxis,
  60580. valueAxis: coordSys.getOtherAxis(baseAxis),
  60581. series: []
  60582. };
  60583. meta.push({
  60584. axisDim: baseAxis.dim,
  60585. axisIndex: baseAxis.index
  60586. });
  60587. }
  60588. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  60589. }
  60590. else {
  60591. otherSeries.push(seriesModel);
  60592. }
  60593. }
  60594. else {
  60595. otherSeries.push(seriesModel);
  60596. }
  60597. });
  60598. return {
  60599. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  60600. other: otherSeries,
  60601. meta: meta
  60602. };
  60603. }
  60604. /**
  60605. * Assemble content of series on cateogory axis
  60606. * @param {Array.<module:echarts/model/Series>} series
  60607. * @return {string}
  60608. * @inner
  60609. */
  60610. function assembleSeriesWithCategoryAxis(series) {
  60611. var tables = [];
  60612. each$1(series, function (group, key) {
  60613. var categoryAxis = group.categoryAxis;
  60614. var valueAxis = group.valueAxis;
  60615. var valueAxisDim = valueAxis.dim;
  60616. var headers = [' '].concat(map(group.series, function (series) {
  60617. return series.name;
  60618. }));
  60619. var columns = [categoryAxis.model.getCategories()];
  60620. each$1(group.series, function (series) {
  60621. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  60622. return val;
  60623. }));
  60624. });
  60625. // Assemble table content
  60626. var lines = [headers.join(ITEM_SPLITER)];
  60627. for (var i = 0; i < columns[0].length; i++) {
  60628. var items = [];
  60629. for (var j = 0; j < columns.length; j++) {
  60630. items.push(columns[j][i]);
  60631. }
  60632. lines.push(items.join(ITEM_SPLITER));
  60633. }
  60634. tables.push(lines.join('\n'));
  60635. });
  60636. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  60637. }
  60638. /**
  60639. * Assemble content of other series
  60640. * @param {Array.<module:echarts/model/Series>} series
  60641. * @return {string}
  60642. * @inner
  60643. */
  60644. function assembleOtherSeries(series) {
  60645. return map(series, function (series) {
  60646. var data = series.getRawData();
  60647. var lines = [series.name];
  60648. var vals = [];
  60649. data.each(data.dimensions, function () {
  60650. var argLen = arguments.length;
  60651. var dataIndex = arguments[argLen - 1];
  60652. var name = data.getName(dataIndex);
  60653. for (var i = 0; i < argLen - 1; i++) {
  60654. vals[i] = arguments[i];
  60655. }
  60656. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  60657. });
  60658. return lines.join('\n');
  60659. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  60660. }
  60661. /**
  60662. * @param {module:echarts/model/Global}
  60663. * @return {Object}
  60664. * @inner
  60665. */
  60666. function getContentFromModel(ecModel) {
  60667. var result = groupSeries(ecModel);
  60668. return {
  60669. value: filter([
  60670. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  60671. assembleOtherSeries(result.other)
  60672. ], function (str) {
  60673. return str.replace(/[\n\t\s]/g, '');
  60674. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  60675. meta: result.meta
  60676. };
  60677. }
  60678. function trim(str) {
  60679. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  60680. }
  60681. /**
  60682. * If a block is tsv format
  60683. */
  60684. function isTSVFormat(block) {
  60685. // Simple method to find out if a block is tsv format
  60686. var firstLine = block.slice(0, block.indexOf('\n'));
  60687. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  60688. return true;
  60689. }
  60690. }
  60691. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  60692. /**
  60693. * @param {string} tsv
  60694. * @return {Object}
  60695. */
  60696. function parseTSVContents(tsv) {
  60697. var tsvLines = tsv.split(/\n+/g);
  60698. var headers = trim(tsvLines.shift()).split(itemSplitRegex);
  60699. var categories = [];
  60700. var series = map(headers, function (header) {
  60701. return {
  60702. name: header,
  60703. data: []
  60704. };
  60705. });
  60706. for (var i = 0; i < tsvLines.length; i++) {
  60707. var items = trim(tsvLines[i]).split(itemSplitRegex);
  60708. categories.push(items.shift());
  60709. for (var j = 0; j < items.length; j++) {
  60710. series[j] && (series[j].data[i] = items[j]);
  60711. }
  60712. }
  60713. return {
  60714. series: series,
  60715. categories: categories
  60716. };
  60717. }
  60718. /**
  60719. * @param {string} str
  60720. * @return {Array.<Object>}
  60721. * @inner
  60722. */
  60723. function parseListContents(str) {
  60724. var lines = str.split(/\n+/g);
  60725. var seriesName = trim(lines.shift());
  60726. var data = [];
  60727. for (var i = 0; i < lines.length; i++) {
  60728. var items = trim(lines[i]).split(itemSplitRegex);
  60729. var name = '';
  60730. var value;
  60731. var hasName = false;
  60732. if (isNaN(items[0])) { // First item is name
  60733. hasName = true;
  60734. name = items[0];
  60735. items = items.slice(1);
  60736. data[i] = {
  60737. name: name,
  60738. value: []
  60739. };
  60740. value = data[i].value;
  60741. }
  60742. else {
  60743. value = data[i] = [];
  60744. }
  60745. for (var j = 0; j < items.length; j++) {
  60746. value.push(+items[j]);
  60747. }
  60748. if (value.length === 1) {
  60749. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  60750. }
  60751. }
  60752. return {
  60753. name: seriesName,
  60754. data: data
  60755. };
  60756. }
  60757. /**
  60758. * @param {string} str
  60759. * @param {Array.<Object>} blockMetaList
  60760. * @return {Object}
  60761. * @inner
  60762. */
  60763. function parseContents(str, blockMetaList) {
  60764. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  60765. var newOption = {
  60766. series: []
  60767. };
  60768. each$1(blocks, function (block, idx) {
  60769. if (isTSVFormat(block)) {
  60770. var result = parseTSVContents(block);
  60771. var blockMeta = blockMetaList[idx];
  60772. var axisKey = blockMeta.axisDim + 'Axis';
  60773. if (blockMeta) {
  60774. newOption[axisKey] = newOption[axisKey] || [];
  60775. newOption[axisKey][blockMeta.axisIndex] = {
  60776. data: result.categories
  60777. };
  60778. newOption.series = newOption.series.concat(result.series);
  60779. }
  60780. }
  60781. else {
  60782. var result = parseListContents(block);
  60783. newOption.series.push(result);
  60784. }
  60785. });
  60786. return newOption;
  60787. }
  60788. /**
  60789. * @alias {module:echarts/component/toolbox/feature/DataView}
  60790. * @constructor
  60791. * @param {module:echarts/model/Model} model
  60792. */
  60793. function DataView(model) {
  60794. this._dom = null;
  60795. this.model = model;
  60796. }
  60797. DataView.defaultOption = {
  60798. show: true,
  60799. readOnly: false,
  60800. optionToContent: null,
  60801. contentToOption: null,
  60802. 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',
  60803. title: clone(dataViewLang.title),
  60804. lang: clone(dataViewLang.lang),
  60805. backgroundColor: '#fff',
  60806. textColor: '#000',
  60807. textareaColor: '#fff',
  60808. textareaBorderColor: '#333',
  60809. buttonColor: '#c23531',
  60810. buttonTextColor: '#fff'
  60811. };
  60812. DataView.prototype.onclick = function (ecModel, api) {
  60813. var container = api.getDom();
  60814. var model = this.model;
  60815. if (this._dom) {
  60816. container.removeChild(this._dom);
  60817. }
  60818. var root = document.createElement('div');
  60819. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  60820. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  60821. // Create elements
  60822. var header = document.createElement('h4');
  60823. var lang$$1 = model.get('lang') || [];
  60824. header.innerHTML = lang$$1[0] || model.get('title');
  60825. header.style.cssText = 'margin: 10px 20px;';
  60826. header.style.color = model.get('textColor');
  60827. var viewMain = document.createElement('div');
  60828. var textarea = document.createElement('textarea');
  60829. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  60830. var optionToContent = model.get('optionToContent');
  60831. var contentToOption = model.get('contentToOption');
  60832. var result = getContentFromModel(ecModel);
  60833. if (typeof optionToContent === 'function') {
  60834. var htmlOrDom = optionToContent(api.getOption());
  60835. if (typeof htmlOrDom === 'string') {
  60836. viewMain.innerHTML = htmlOrDom;
  60837. }
  60838. else if (isDom(htmlOrDom)) {
  60839. viewMain.appendChild(htmlOrDom);
  60840. }
  60841. }
  60842. else {
  60843. // Use default textarea
  60844. viewMain.appendChild(textarea);
  60845. textarea.readOnly = model.get('readOnly');
  60846. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  60847. textarea.style.color = model.get('textColor');
  60848. textarea.style.borderColor = model.get('textareaBorderColor');
  60849. textarea.style.backgroundColor = model.get('textareaColor');
  60850. textarea.value = result.value;
  60851. }
  60852. var blockMetaList = result.meta;
  60853. var buttonContainer = document.createElement('div');
  60854. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  60855. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  60856. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  60857. var closeButton = document.createElement('div');
  60858. var refreshButton = document.createElement('div');
  60859. buttonStyle += ';background-color:' + model.get('buttonColor');
  60860. buttonStyle += ';color:' + model.get('buttonTextColor');
  60861. var self = this;
  60862. function close() {
  60863. container.removeChild(root);
  60864. self._dom = null;
  60865. }
  60866. addEventListener(closeButton, 'click', close);
  60867. addEventListener(refreshButton, 'click', function () {
  60868. var newOption;
  60869. try {
  60870. if (typeof contentToOption === 'function') {
  60871. newOption = contentToOption(viewMain, api.getOption());
  60872. }
  60873. else {
  60874. newOption = parseContents(textarea.value, blockMetaList);
  60875. }
  60876. }
  60877. catch (e) {
  60878. close();
  60879. throw new Error('Data view format error ' + e);
  60880. }
  60881. if (newOption) {
  60882. api.dispatchAction({
  60883. type: 'changeDataView',
  60884. newOption: newOption
  60885. });
  60886. }
  60887. close();
  60888. });
  60889. closeButton.innerHTML = lang$$1[1];
  60890. refreshButton.innerHTML = lang$$1[2];
  60891. refreshButton.style.cssText = buttonStyle;
  60892. closeButton.style.cssText = buttonStyle;
  60893. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  60894. buttonContainer.appendChild(closeButton);
  60895. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  60896. addEventListener(textarea, 'keydown', function (e) {
  60897. if ((e.keyCode || e.which) === 9) {
  60898. // get caret position/selection
  60899. var val = this.value;
  60900. var start = this.selectionStart;
  60901. var end = this.selectionEnd;
  60902. // set textarea value to: text before caret + tab + text after caret
  60903. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  60904. // put caret at right position again
  60905. this.selectionStart = this.selectionEnd = start + 1;
  60906. // prevent the focus lose
  60907. stop(e);
  60908. }
  60909. });
  60910. root.appendChild(header);
  60911. root.appendChild(viewMain);
  60912. root.appendChild(buttonContainer);
  60913. viewMain.style.height = (container.clientHeight - 80) + 'px';
  60914. container.appendChild(root);
  60915. this._dom = root;
  60916. };
  60917. DataView.prototype.remove = function (ecModel, api) {
  60918. this._dom && api.getDom().removeChild(this._dom);
  60919. };
  60920. DataView.prototype.dispose = function (ecModel, api) {
  60921. this.remove(ecModel, api);
  60922. };
  60923. /**
  60924. * @inner
  60925. */
  60926. function tryMergeDataOption(newData, originalData) {
  60927. return map(newData, function (newVal, idx) {
  60928. var original = originalData && originalData[idx];
  60929. if (isObject(original) && !isArray(original)) {
  60930. if (isObject(newVal) && !isArray(newVal)) {
  60931. newVal = newVal.value;
  60932. }
  60933. // Original data has option
  60934. return defaults({
  60935. value: newVal
  60936. }, original);
  60937. }
  60938. else {
  60939. return newVal;
  60940. }
  60941. });
  60942. }
  60943. register$1('dataView', DataView);
  60944. registerAction({
  60945. type: 'changeDataView',
  60946. event: 'dataViewChanged',
  60947. update: 'prepareAndUpdate'
  60948. }, function (payload, ecModel) {
  60949. var newSeriesOptList = [];
  60950. each$1(payload.newOption.series, function (seriesOpt) {
  60951. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  60952. if (!seriesModel) {
  60953. // New created series
  60954. // Geuss the series type
  60955. newSeriesOptList.push(extend({
  60956. // Default is scatter
  60957. type: 'scatter'
  60958. }, seriesOpt));
  60959. }
  60960. else {
  60961. var originalData = seriesModel.get('data');
  60962. newSeriesOptList.push({
  60963. name: seriesOpt.name,
  60964. data: tryMergeDataOption(seriesOpt.data, originalData)
  60965. });
  60966. }
  60967. });
  60968. ecModel.mergeOption(defaults({
  60969. series: newSeriesOptList
  60970. }, payload.newOption));
  60971. });
  60972. var each$32 = each$1;
  60973. var ATTR$2 = '\0_ec_hist_store';
  60974. /**
  60975. * @param {module:echarts/model/Global} ecModel
  60976. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  60977. */
  60978. function push(ecModel, newSnapshot) {
  60979. var store = giveStore$1(ecModel);
  60980. // If previous dataZoom can not be found,
  60981. // complete an range with current range.
  60982. each$32(newSnapshot, function (batchItem, dataZoomId) {
  60983. var i = store.length - 1;
  60984. for (; i >= 0; i--) {
  60985. var snapshot = store[i];
  60986. if (snapshot[dataZoomId]) {
  60987. break;
  60988. }
  60989. }
  60990. if (i < 0) {
  60991. // No origin range set, create one by current range.
  60992. var dataZoomModel = ecModel.queryComponents(
  60993. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  60994. )[0];
  60995. if (dataZoomModel) {
  60996. var percentRange = dataZoomModel.getPercentRange();
  60997. store[0][dataZoomId] = {
  60998. dataZoomId: dataZoomId,
  60999. start: percentRange[0],
  61000. end: percentRange[1]
  61001. };
  61002. }
  61003. }
  61004. });
  61005. store.push(newSnapshot);
  61006. }
  61007. /**
  61008. * @param {module:echarts/model/Global} ecModel
  61009. * @return {Object} snapshot
  61010. */
  61011. function pop(ecModel) {
  61012. var store = giveStore$1(ecModel);
  61013. var head = store[store.length - 1];
  61014. store.length > 1 && store.pop();
  61015. // Find top for all dataZoom.
  61016. var snapshot = {};
  61017. each$32(head, function (batchItem, dataZoomId) {
  61018. for (var i = store.length - 1; i >= 0; i--) {
  61019. var batchItem = store[i][dataZoomId];
  61020. if (batchItem) {
  61021. snapshot[dataZoomId] = batchItem;
  61022. break;
  61023. }
  61024. }
  61025. });
  61026. return snapshot;
  61027. }
  61028. /**
  61029. * @param {module:echarts/model/Global} ecModel
  61030. */
  61031. function clear$1(ecModel) {
  61032. ecModel[ATTR$2] = null;
  61033. }
  61034. /**
  61035. * @param {module:echarts/model/Global} ecModel
  61036. * @return {number} records. always >= 1.
  61037. */
  61038. function count(ecModel) {
  61039. return giveStore$1(ecModel).length;
  61040. }
  61041. /**
  61042. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  61043. * History length of each dataZoom may be different.
  61044. * this._history[0] is used to store origin range.
  61045. * @type {Array.<Object>}
  61046. */
  61047. function giveStore$1(ecModel) {
  61048. var store = ecModel[ATTR$2];
  61049. if (!store) {
  61050. store = ecModel[ATTR$2] = [{}];
  61051. }
  61052. return store;
  61053. }
  61054. DataZoomModel.extend({
  61055. type: 'dataZoom.select'
  61056. });
  61057. DataZoomView.extend({
  61058. type: 'dataZoom.select'
  61059. });
  61060. /**
  61061. * DataZoom component entry
  61062. */
  61063. // Use dataZoomSelect
  61064. var dataZoomLang = lang.toolbox.dataZoom;
  61065. var each$31 = each$1;
  61066. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  61067. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  61068. function DataZoom(model, ecModel, api) {
  61069. /**
  61070. * @private
  61071. * @type {module:echarts/component/helper/BrushController}
  61072. */
  61073. (this._brushController = new BrushController(api.getZr()))
  61074. .on('brush', bind(this._onBrush, this))
  61075. .mount();
  61076. /**
  61077. * @private
  61078. * @type {boolean}
  61079. */
  61080. this._isZoomActive;
  61081. }
  61082. DataZoom.defaultOption = {
  61083. show: true,
  61084. // Icon group
  61085. icon: {
  61086. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  61087. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  61088. },
  61089. // `zoom`, `back`
  61090. title: clone(dataZoomLang.title)
  61091. };
  61092. var proto$4 = DataZoom.prototype;
  61093. proto$4.render = function (featureModel, ecModel, api, payload) {
  61094. this.model = featureModel;
  61095. this.ecModel = ecModel;
  61096. this.api = api;
  61097. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  61098. updateBackBtnStatus(featureModel, ecModel);
  61099. };
  61100. proto$4.onclick = function (ecModel, api, type) {
  61101. handlers$1[type].call(this);
  61102. };
  61103. proto$4.remove = function (ecModel, api) {
  61104. this._brushController.unmount();
  61105. };
  61106. proto$4.dispose = function (ecModel, api) {
  61107. this._brushController.dispose();
  61108. };
  61109. /**
  61110. * @private
  61111. */
  61112. var handlers$1 = {
  61113. zoom: function () {
  61114. var nextActive = !this._isZoomActive;
  61115. this.api.dispatchAction({
  61116. type: 'takeGlobalCursor',
  61117. key: 'dataZoomSelect',
  61118. dataZoomSelectActive: nextActive
  61119. });
  61120. },
  61121. back: function () {
  61122. this._dispatchZoomAction(pop(this.ecModel));
  61123. }
  61124. };
  61125. /**
  61126. * @private
  61127. */
  61128. proto$4._onBrush = function (areas, opt) {
  61129. if (!opt.isEnd || !areas.length) {
  61130. return;
  61131. }
  61132. var snapshot = {};
  61133. var ecModel = this.ecModel;
  61134. this._brushController.updateCovers([]); // remove cover
  61135. var brushTargetManager = new BrushTargetManager(
  61136. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  61137. );
  61138. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  61139. if (coordSys.type !== 'cartesian2d') {
  61140. return;
  61141. }
  61142. var brushType = area.brushType;
  61143. if (brushType === 'rect') {
  61144. setBatch('x', coordSys, coordRange[0]);
  61145. setBatch('y', coordSys, coordRange[1]);
  61146. }
  61147. else {
  61148. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  61149. }
  61150. });
  61151. push(ecModel, snapshot);
  61152. this._dispatchZoomAction(snapshot);
  61153. function setBatch(dimName, coordSys, minMax) {
  61154. var axis = coordSys.getAxis(dimName);
  61155. var axisModel = axis.model;
  61156. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  61157. // Restrict range.
  61158. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  61159. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  61160. minMax = sliderMove(
  61161. 0, minMax.slice(), axis.scale.getExtent(), 0,
  61162. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  61163. );
  61164. }
  61165. dataZoomModel && (snapshot[dataZoomModel.id] = {
  61166. dataZoomId: dataZoomModel.id,
  61167. startValue: minMax[0],
  61168. endValue: minMax[1]
  61169. });
  61170. }
  61171. function findDataZoom(dimName, axisModel, ecModel) {
  61172. var found;
  61173. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  61174. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  61175. has && (found = dzModel);
  61176. });
  61177. return found;
  61178. }
  61179. };
  61180. /**
  61181. * @private
  61182. */
  61183. proto$4._dispatchZoomAction = function (snapshot) {
  61184. var batch = [];
  61185. // Convert from hash map to array.
  61186. each$31(snapshot, function (batchItem, dataZoomId) {
  61187. batch.push(clone(batchItem));
  61188. });
  61189. batch.length && this.api.dispatchAction({
  61190. type: 'dataZoom',
  61191. from: this.uid,
  61192. batch: batch
  61193. });
  61194. };
  61195. function retrieveAxisSetting(option) {
  61196. var setting = {};
  61197. // Compatible with previous setting: null => all axis, false => no axis.
  61198. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  61199. setting[name] = option[name];
  61200. setting[name] == null && (setting[name] = 'all');
  61201. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  61202. });
  61203. return setting;
  61204. }
  61205. function updateBackBtnStatus(featureModel, ecModel) {
  61206. featureModel.setIconStatus(
  61207. 'back',
  61208. count(ecModel) > 1 ? 'emphasis' : 'normal'
  61209. );
  61210. }
  61211. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  61212. var zoomActive = view._isZoomActive;
  61213. if (payload && payload.type === 'takeGlobalCursor') {
  61214. zoomActive = payload.key === 'dataZoomSelect'
  61215. ? payload.dataZoomSelectActive : false;
  61216. }
  61217. view._isZoomActive = zoomActive;
  61218. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  61219. var brushTargetManager = new BrushTargetManager(
  61220. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  61221. );
  61222. view._brushController
  61223. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  61224. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  61225. ? 'lineX'
  61226. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  61227. ? 'lineY'
  61228. : 'rect';
  61229. }))
  61230. .enableBrush(
  61231. zoomActive
  61232. ? {
  61233. brushType: 'auto',
  61234. brushStyle: {
  61235. // FIXME user customized?
  61236. lineWidth: 0,
  61237. fill: 'rgba(0,0,0,0.2)'
  61238. }
  61239. }
  61240. : false
  61241. );
  61242. }
  61243. register$1('dataZoom', DataZoom);
  61244. // Create special dataZoom option for select
  61245. registerPreprocessor(function (option) {
  61246. if (!option) {
  61247. return;
  61248. }
  61249. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  61250. if (!isArray(dataZoomOpts)) {
  61251. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  61252. }
  61253. var toolboxOpt = option.toolbox;
  61254. if (toolboxOpt) {
  61255. // Assume there is only one toolbox
  61256. if (isArray(toolboxOpt)) {
  61257. toolboxOpt = toolboxOpt[0];
  61258. }
  61259. if (toolboxOpt && toolboxOpt.feature) {
  61260. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  61261. addForAxis('xAxis', dataZoomOpt);
  61262. addForAxis('yAxis', dataZoomOpt);
  61263. }
  61264. }
  61265. function addForAxis(axisName, dataZoomOpt) {
  61266. if (!dataZoomOpt) {
  61267. return;
  61268. }
  61269. // Try not to modify model, because it is not merged yet.
  61270. var axisIndicesName = axisName + 'Index';
  61271. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  61272. if (givenAxisIndices != null
  61273. && givenAxisIndices != 'all'
  61274. && !isArray(givenAxisIndices)
  61275. ) {
  61276. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  61277. }
  61278. forEachComponent(axisName, function (axisOpt, axisIndex) {
  61279. if (givenAxisIndices != null
  61280. && givenAxisIndices != 'all'
  61281. && indexOf(givenAxisIndices, axisIndex) === -1
  61282. ) {
  61283. return;
  61284. }
  61285. var newOpt = {
  61286. type: 'select',
  61287. $fromToolbox: true,
  61288. // Id for merge mapping.
  61289. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  61290. };
  61291. // FIXME
  61292. // Only support one axis now.
  61293. newOpt[axisIndicesName] = axisIndex;
  61294. dataZoomOpts.push(newOpt);
  61295. });
  61296. }
  61297. function forEachComponent(mainType, cb) {
  61298. var opts = option[mainType];
  61299. if (!isArray(opts)) {
  61300. opts = opts ? [opts] : [];
  61301. }
  61302. each$31(opts, cb);
  61303. }
  61304. });
  61305. var restoreLang = lang.toolbox.restore;
  61306. function Restore(model) {
  61307. this.model = model;
  61308. }
  61309. Restore.defaultOption = {
  61310. show: true,
  61311. 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',
  61312. title: restoreLang.title
  61313. };
  61314. var proto$5 = Restore.prototype;
  61315. proto$5.onclick = function (ecModel, api, type) {
  61316. clear$1(ecModel);
  61317. api.dispatchAction({
  61318. type: 'restore',
  61319. from: this.uid
  61320. });
  61321. };
  61322. register$1('restore', Restore);
  61323. registerAction(
  61324. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  61325. function (payload, ecModel) {
  61326. ecModel.resetOption('recreate');
  61327. }
  61328. );
  61329. var urn = 'urn:schemas-microsoft-com:vml';
  61330. var win = typeof window === 'undefined' ? null : window;
  61331. var vmlInited = false;
  61332. var doc = win && win.document;
  61333. function createNode(tagName) {
  61334. return doCreateNode(tagName);
  61335. }
  61336. // Avoid assign to an exported variable, for transforming to cjs.
  61337. var doCreateNode;
  61338. if (doc && !env$1.canvasSupported) {
  61339. try {
  61340. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  61341. doCreateNode = function (tagName) {
  61342. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  61343. };
  61344. }
  61345. catch (e) {
  61346. doCreateNode = function (tagName) {
  61347. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  61348. };
  61349. }
  61350. }
  61351. // From raphael
  61352. function initVML() {
  61353. if (vmlInited || !doc) {
  61354. return;
  61355. }
  61356. vmlInited = true;
  61357. var styleSheets = doc.styleSheets;
  61358. if (styleSheets.length < 31) {
  61359. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  61360. }
  61361. else {
  61362. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  61363. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  61364. }
  61365. }
  61366. // http://www.w3.org/TR/NOTE-VML
  61367. // TODO Use proxy like svg instead of overwrite brush methods
  61368. var CMD$3 = PathProxy.CMD;
  61369. var round$3 = Math.round;
  61370. var sqrt = Math.sqrt;
  61371. var abs$1 = Math.abs;
  61372. var cos = Math.cos;
  61373. var sin = Math.sin;
  61374. var mathMax$8 = Math.max;
  61375. if (!env$1.canvasSupported) {
  61376. var comma = ',';
  61377. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  61378. var Z = 21600;
  61379. var Z2 = Z / 2;
  61380. var ZLEVEL_BASE = 100000;
  61381. var Z_BASE$1 = 1000;
  61382. var initRootElStyle = function (el) {
  61383. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  61384. el.coordsize = Z + ',' + Z;
  61385. el.coordorigin = '0,0';
  61386. };
  61387. var encodeHtmlAttribute = function (s) {
  61388. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  61389. };
  61390. var rgb2Str = function (r, g, b) {
  61391. return 'rgb(' + [r, g, b].join(',') + ')';
  61392. };
  61393. var append = function (parent, child) {
  61394. if (child && parent && child.parentNode !== parent) {
  61395. parent.appendChild(child);
  61396. }
  61397. };
  61398. var remove = function (parent, child) {
  61399. if (child && parent && child.parentNode === parent) {
  61400. parent.removeChild(child);
  61401. }
  61402. };
  61403. var getZIndex = function (zlevel, z, z2) {
  61404. // z 的取值范围为 [0, 1000]
  61405. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  61406. };
  61407. var parsePercent$3 = function (value, maxValue) {
  61408. if (typeof value === 'string') {
  61409. if (value.lastIndexOf('%') >= 0) {
  61410. return parseFloat(value) / 100 * maxValue;
  61411. }
  61412. return parseFloat(value);
  61413. }
  61414. return value;
  61415. };
  61416. /***************************************************
  61417. * PATH
  61418. **************************************************/
  61419. var setColorAndOpacity = function (el, color, opacity) {
  61420. var colorArr = parse(color);
  61421. opacity = +opacity;
  61422. if (isNaN(opacity)) {
  61423. opacity = 1;
  61424. }
  61425. if (colorArr) {
  61426. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  61427. el.opacity = opacity * colorArr[3];
  61428. }
  61429. };
  61430. var getColorAndAlpha = function (color) {
  61431. var colorArr = parse(color);
  61432. return [
  61433. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  61434. colorArr[3]
  61435. ];
  61436. };
  61437. var updateFillNode = function (el, style, zrEl) {
  61438. // TODO pattern
  61439. var fill = style.fill;
  61440. if (fill != null) {
  61441. // Modified from excanvas
  61442. if (fill instanceof Gradient) {
  61443. var gradientType;
  61444. var angle = 0;
  61445. var focus = [0, 0];
  61446. // additional offset
  61447. var shift = 0;
  61448. // scale factor for offset
  61449. var expansion = 1;
  61450. var rect = zrEl.getBoundingRect();
  61451. var rectWidth = rect.width;
  61452. var rectHeight = rect.height;
  61453. if (fill.type === 'linear') {
  61454. gradientType = 'gradient';
  61455. var transform = zrEl.transform;
  61456. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  61457. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  61458. if (transform) {
  61459. applyTransform(p0, p0, transform);
  61460. applyTransform(p1, p1, transform);
  61461. }
  61462. var dx = p1[0] - p0[0];
  61463. var dy = p1[1] - p0[1];
  61464. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  61465. // The angle should be a non-negative number.
  61466. if (angle < 0) {
  61467. angle += 360;
  61468. }
  61469. // Very small angles produce an unexpected result because they are
  61470. // converted to a scientific notation string.
  61471. if (angle < 1e-6) {
  61472. angle = 0;
  61473. }
  61474. }
  61475. else {
  61476. gradientType = 'gradientradial';
  61477. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  61478. var transform = zrEl.transform;
  61479. var scale$$1 = zrEl.scale;
  61480. var width = rectWidth;
  61481. var height = rectHeight;
  61482. focus = [
  61483. // Percent in bounding rect
  61484. (p0[0] - rect.x) / width,
  61485. (p0[1] - rect.y) / height
  61486. ];
  61487. if (transform) {
  61488. applyTransform(p0, p0, transform);
  61489. }
  61490. width /= scale$$1[0] * Z;
  61491. height /= scale$$1[1] * Z;
  61492. var dimension = mathMax$8(width, height);
  61493. shift = 2 * 0 / dimension;
  61494. expansion = 2 * fill.r / dimension - shift;
  61495. }
  61496. // We need to sort the color stops in ascending order by offset,
  61497. // otherwise IE won't interpret it correctly.
  61498. var stops = fill.colorStops.slice();
  61499. stops.sort(function(cs1, cs2) {
  61500. return cs1.offset - cs2.offset;
  61501. });
  61502. var length$$1 = stops.length;
  61503. // Color and alpha list of first and last stop
  61504. var colorAndAlphaList = [];
  61505. var colors = [];
  61506. for (var i = 0; i < length$$1; i++) {
  61507. var stop = stops[i];
  61508. var colorAndAlpha = getColorAndAlpha(stop.color);
  61509. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  61510. if (i === 0 || i === length$$1 - 1) {
  61511. colorAndAlphaList.push(colorAndAlpha);
  61512. }
  61513. }
  61514. if (length$$1 >= 2) {
  61515. var color1 = colorAndAlphaList[0][0];
  61516. var color2 = colorAndAlphaList[1][0];
  61517. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  61518. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  61519. el.type = gradientType;
  61520. el.method = 'none';
  61521. el.focus = '100%';
  61522. el.angle = angle;
  61523. el.color = color1;
  61524. el.color2 = color2;
  61525. el.colors = colors.join(',');
  61526. // When colors attribute is used, the meanings of opacity and o:opacity2
  61527. // are reversed.
  61528. el.opacity = opacity2;
  61529. // FIXME g_o_:opacity ?
  61530. el.opacity2 = opacity1;
  61531. }
  61532. if (gradientType === 'radial') {
  61533. el.focusposition = focus.join(',');
  61534. }
  61535. }
  61536. else {
  61537. // FIXME Change from Gradient fill to color fill
  61538. setColorAndOpacity(el, fill, style.opacity);
  61539. }
  61540. }
  61541. };
  61542. var updateStrokeNode = function (el, style) {
  61543. // if (style.lineJoin != null) {
  61544. // el.joinstyle = style.lineJoin;
  61545. // }
  61546. // if (style.miterLimit != null) {
  61547. // el.miterlimit = style.miterLimit * Z;
  61548. // }
  61549. // if (style.lineCap != null) {
  61550. // el.endcap = style.lineCap;
  61551. // }
  61552. if (style.lineDash != null) {
  61553. el.dashstyle = style.lineDash.join(' ');
  61554. }
  61555. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  61556. setColorAndOpacity(el, style.stroke, style.opacity);
  61557. }
  61558. };
  61559. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  61560. var isFill = type == 'fill';
  61561. var el = vmlEl.getElementsByTagName(type)[0];
  61562. // Stroke must have lineWidth
  61563. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  61564. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  61565. // FIXME Remove before updating, or set `colors` will throw error
  61566. if (style[type] instanceof Gradient) {
  61567. remove(vmlEl, el);
  61568. }
  61569. if (!el) {
  61570. el = createNode(type);
  61571. }
  61572. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  61573. append(vmlEl, el);
  61574. }
  61575. else {
  61576. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  61577. remove(vmlEl, el);
  61578. }
  61579. };
  61580. var points$3 = [[], [], []];
  61581. var pathDataToString = function (path, m) {
  61582. var M = CMD$3.M;
  61583. var C = CMD$3.C;
  61584. var L = CMD$3.L;
  61585. var A = CMD$3.A;
  61586. var Q = CMD$3.Q;
  61587. var str = [];
  61588. var nPoint;
  61589. var cmdStr;
  61590. var cmd;
  61591. var i;
  61592. var xi;
  61593. var yi;
  61594. var data = path.data;
  61595. var dataLength = path.len();
  61596. for (i = 0; i < dataLength;) {
  61597. cmd = data[i++];
  61598. cmdStr = '';
  61599. nPoint = 0;
  61600. switch (cmd) {
  61601. case M:
  61602. cmdStr = ' m ';
  61603. nPoint = 1;
  61604. xi = data[i++];
  61605. yi = data[i++];
  61606. points$3[0][0] = xi;
  61607. points$3[0][1] = yi;
  61608. break;
  61609. case L:
  61610. cmdStr = ' l ';
  61611. nPoint = 1;
  61612. xi = data[i++];
  61613. yi = data[i++];
  61614. points$3[0][0] = xi;
  61615. points$3[0][1] = yi;
  61616. break;
  61617. case Q:
  61618. case C:
  61619. cmdStr = ' c ';
  61620. nPoint = 3;
  61621. var x1 = data[i++];
  61622. var y1 = data[i++];
  61623. var x2 = data[i++];
  61624. var y2 = data[i++];
  61625. var x3;
  61626. var y3;
  61627. if (cmd === Q) {
  61628. // Convert quadratic to cubic using degree elevation
  61629. x3 = x2;
  61630. y3 = y2;
  61631. x2 = (x2 + 2 * x1) / 3;
  61632. y2 = (y2 + 2 * y1) / 3;
  61633. x1 = (xi + 2 * x1) / 3;
  61634. y1 = (yi + 2 * y1) / 3;
  61635. }
  61636. else {
  61637. x3 = data[i++];
  61638. y3 = data[i++];
  61639. }
  61640. points$3[0][0] = x1;
  61641. points$3[0][1] = y1;
  61642. points$3[1][0] = x2;
  61643. points$3[1][1] = y2;
  61644. points$3[2][0] = x3;
  61645. points$3[2][1] = y3;
  61646. xi = x3;
  61647. yi = y3;
  61648. break;
  61649. case A:
  61650. var x = 0;
  61651. var y = 0;
  61652. var sx = 1;
  61653. var sy = 1;
  61654. var angle = 0;
  61655. if (m) {
  61656. // Extract SRT from matrix
  61657. x = m[4];
  61658. y = m[5];
  61659. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  61660. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  61661. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  61662. }
  61663. var cx = data[i++];
  61664. var cy = data[i++];
  61665. var rx = data[i++];
  61666. var ry = data[i++];
  61667. var startAngle = data[i++] + angle;
  61668. var endAngle = data[i++] + startAngle + angle;
  61669. // FIXME
  61670. // var psi = data[i++];
  61671. i++;
  61672. var clockwise = data[i++];
  61673. var x0 = cx + cos(startAngle) * rx;
  61674. var y0 = cy + sin(startAngle) * ry;
  61675. var x1 = cx + cos(endAngle) * rx;
  61676. var y1 = cy + sin(endAngle) * ry;
  61677. var type = clockwise ? ' wa ' : ' at ';
  61678. if (Math.abs(x0 - x1) < 1e-4) {
  61679. // IE won't render arches drawn counter clockwise if x0 == x1.
  61680. if (Math.abs(endAngle - startAngle) > 1e-2) {
  61681. // Offset x0 by 1/80 of a pixel. Use something
  61682. // that can be represented in binary
  61683. if (clockwise) {
  61684. x0 += 270 / Z;
  61685. }
  61686. }
  61687. else {
  61688. // Avoid case draw full circle
  61689. if (Math.abs(y0 - cy) < 1e-4) {
  61690. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  61691. y1 -= 270 / Z;
  61692. }
  61693. else {
  61694. y1 += 270 / Z;
  61695. }
  61696. }
  61697. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  61698. x1 += 270 / Z;
  61699. }
  61700. else {
  61701. x1 -= 270 / Z;
  61702. }
  61703. }
  61704. }
  61705. str.push(
  61706. type,
  61707. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  61708. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  61709. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  61710. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  61711. round$3((x0 * sx + x) * Z - Z2), comma,
  61712. round$3((y0 * sy + y) * Z - Z2), comma,
  61713. round$3((x1 * sx + x) * Z - Z2), comma,
  61714. round$3((y1 * sy + y) * Z - Z2)
  61715. );
  61716. xi = x1;
  61717. yi = y1;
  61718. break;
  61719. case CMD$3.R:
  61720. var p0 = points$3[0];
  61721. var p1 = points$3[1];
  61722. // x0, y0
  61723. p0[0] = data[i++];
  61724. p0[1] = data[i++];
  61725. // x1, y1
  61726. p1[0] = p0[0] + data[i++];
  61727. p1[1] = p0[1] + data[i++];
  61728. if (m) {
  61729. applyTransform(p0, p0, m);
  61730. applyTransform(p1, p1, m);
  61731. }
  61732. p0[0] = round$3(p0[0] * Z - Z2);
  61733. p1[0] = round$3(p1[0] * Z - Z2);
  61734. p0[1] = round$3(p0[1] * Z - Z2);
  61735. p1[1] = round$3(p1[1] * Z - Z2);
  61736. str.push(
  61737. // x0, y0
  61738. ' m ', p0[0], comma, p0[1],
  61739. // x1, y0
  61740. ' l ', p1[0], comma, p0[1],
  61741. // x1, y1
  61742. ' l ', p1[0], comma, p1[1],
  61743. // x0, y1
  61744. ' l ', p0[0], comma, p1[1]
  61745. );
  61746. break;
  61747. case CMD$3.Z:
  61748. // FIXME Update xi, yi
  61749. str.push(' x ');
  61750. }
  61751. if (nPoint > 0) {
  61752. str.push(cmdStr);
  61753. for (var k = 0; k < nPoint; k++) {
  61754. var p = points$3[k];
  61755. m && applyTransform(p, p, m);
  61756. // 不 round 会非常慢
  61757. str.push(
  61758. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  61759. k < nPoint - 1 ? comma : ''
  61760. );
  61761. }
  61762. }
  61763. }
  61764. return str.join('');
  61765. };
  61766. // Rewrite the original path method
  61767. Path.prototype.brushVML = function (vmlRoot) {
  61768. var style = this.style;
  61769. var vmlEl = this._vmlEl;
  61770. if (!vmlEl) {
  61771. vmlEl = createNode('shape');
  61772. initRootElStyle(vmlEl);
  61773. this._vmlEl = vmlEl;
  61774. }
  61775. updateFillAndStroke(vmlEl, 'fill', style, this);
  61776. updateFillAndStroke(vmlEl, 'stroke', style, this);
  61777. var m = this.transform;
  61778. var needTransform = m != null;
  61779. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  61780. if (strokeEl) {
  61781. var lineWidth = style.lineWidth;
  61782. // Get the line scale.
  61783. // Determinant of this.m_ means how much the area is enlarged by the
  61784. // transformation. So its square root can be used as a scale factor
  61785. // for width.
  61786. if (needTransform && !style.strokeNoScale) {
  61787. var det = m[0] * m[3] - m[1] * m[2];
  61788. lineWidth *= sqrt(abs$1(det));
  61789. }
  61790. strokeEl.weight = lineWidth + 'px';
  61791. }
  61792. var path = this.path || (this.path = new PathProxy());
  61793. if (this.__dirtyPath) {
  61794. path.beginPath();
  61795. this.buildPath(path, this.shape);
  61796. path.toStatic();
  61797. this.__dirtyPath = false;
  61798. }
  61799. vmlEl.path = pathDataToString(path, this.transform);
  61800. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  61801. // Append to root
  61802. append(vmlRoot, vmlEl);
  61803. // Text
  61804. if (style.text != null) {
  61805. this.drawRectText(vmlRoot, this.getBoundingRect());
  61806. }
  61807. else {
  61808. this.removeRectText(vmlRoot);
  61809. }
  61810. };
  61811. Path.prototype.onRemove = function (vmlRoot) {
  61812. remove(vmlRoot, this._vmlEl);
  61813. this.removeRectText(vmlRoot);
  61814. };
  61815. Path.prototype.onAdd = function (vmlRoot) {
  61816. append(vmlRoot, this._vmlEl);
  61817. this.appendRectText(vmlRoot);
  61818. };
  61819. /***************************************************
  61820. * IMAGE
  61821. **************************************************/
  61822. var isImage = function (img) {
  61823. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  61824. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  61825. // return img instanceof Image;
  61826. };
  61827. // Rewrite the original path method
  61828. ZImage.prototype.brushVML = function (vmlRoot) {
  61829. var style = this.style;
  61830. var image = style.image;
  61831. // Image original width, height
  61832. var ow;
  61833. var oh;
  61834. if (isImage(image)) {
  61835. var src = image.src;
  61836. if (src === this._imageSrc) {
  61837. ow = this._imageWidth;
  61838. oh = this._imageHeight;
  61839. }
  61840. else {
  61841. var imageRuntimeStyle = image.runtimeStyle;
  61842. var oldRuntimeWidth = imageRuntimeStyle.width;
  61843. var oldRuntimeHeight = imageRuntimeStyle.height;
  61844. imageRuntimeStyle.width = 'auto';
  61845. imageRuntimeStyle.height = 'auto';
  61846. // get the original size
  61847. ow = image.width;
  61848. oh = image.height;
  61849. // and remove overides
  61850. imageRuntimeStyle.width = oldRuntimeWidth;
  61851. imageRuntimeStyle.height = oldRuntimeHeight;
  61852. // Caching image original width, height and src
  61853. this._imageSrc = src;
  61854. this._imageWidth = ow;
  61855. this._imageHeight = oh;
  61856. }
  61857. image = src;
  61858. }
  61859. else {
  61860. if (image === this._imageSrc) {
  61861. ow = this._imageWidth;
  61862. oh = this._imageHeight;
  61863. }
  61864. }
  61865. if (!image) {
  61866. return;
  61867. }
  61868. var x = style.x || 0;
  61869. var y = style.y || 0;
  61870. var dw = style.width;
  61871. var dh = style.height;
  61872. var sw = style.sWidth;
  61873. var sh = style.sHeight;
  61874. var sx = style.sx || 0;
  61875. var sy = style.sy || 0;
  61876. var hasCrop = sw && sh;
  61877. var vmlEl = this._vmlEl;
  61878. if (!vmlEl) {
  61879. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  61880. // vmlEl = vmlCore.createNode('group');
  61881. vmlEl = doc.createElement('div');
  61882. initRootElStyle(vmlEl);
  61883. this._vmlEl = vmlEl;
  61884. }
  61885. var vmlElStyle = vmlEl.style;
  61886. var hasRotation = false;
  61887. var m;
  61888. var scaleX = 1;
  61889. var scaleY = 1;
  61890. if (this.transform) {
  61891. m = this.transform;
  61892. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  61893. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  61894. hasRotation = m[1] || m[2];
  61895. }
  61896. if (hasRotation) {
  61897. // If filters are necessary (rotation exists), create them
  61898. // filters are bog-slow, so only create them if abbsolutely necessary
  61899. // The following check doesn't account for skews (which don't exist
  61900. // in the canvas spec (yet) anyway.
  61901. // From excanvas
  61902. var p0 = [x, y];
  61903. var p1 = [x + dw, y];
  61904. var p2 = [x, y + dh];
  61905. var p3 = [x + dw, y + dh];
  61906. applyTransform(p0, p0, m);
  61907. applyTransform(p1, p1, m);
  61908. applyTransform(p2, p2, m);
  61909. applyTransform(p3, p3, m);
  61910. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  61911. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  61912. var transformFilter = [];
  61913. transformFilter.push('M11=', m[0] / scaleX, comma,
  61914. 'M12=', m[2] / scaleY, comma,
  61915. 'M21=', m[1] / scaleX, comma,
  61916. 'M22=', m[3] / scaleY, comma,
  61917. 'Dx=', round$3(x * scaleX + m[4]), comma,
  61918. 'Dy=', round$3(y * scaleY + m[5]));
  61919. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  61920. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  61921. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  61922. + transformFilter.join('') + ', SizingMethod=clip)';
  61923. }
  61924. else {
  61925. if (m) {
  61926. x = x * scaleX + m[4];
  61927. y = y * scaleY + m[5];
  61928. }
  61929. vmlElStyle.filter = '';
  61930. vmlElStyle.left = round$3(x) + 'px';
  61931. vmlElStyle.top = round$3(y) + 'px';
  61932. }
  61933. var imageEl = this._imageEl;
  61934. var cropEl = this._cropEl;
  61935. if (!imageEl) {
  61936. imageEl = doc.createElement('div');
  61937. this._imageEl = imageEl;
  61938. }
  61939. var imageELStyle = imageEl.style;
  61940. if (hasCrop) {
  61941. // Needs know image original width and height
  61942. if (! (ow && oh)) {
  61943. var tmpImage = new Image();
  61944. var self = this;
  61945. tmpImage.onload = function () {
  61946. tmpImage.onload = null;
  61947. ow = tmpImage.width;
  61948. oh = tmpImage.height;
  61949. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  61950. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  61951. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  61952. // Caching image original width, height and src
  61953. self._imageWidth = ow;
  61954. self._imageHeight = oh;
  61955. self._imageSrc = image;
  61956. };
  61957. tmpImage.src = image;
  61958. }
  61959. else {
  61960. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  61961. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  61962. }
  61963. if (! cropEl) {
  61964. cropEl = doc.createElement('div');
  61965. cropEl.style.overflow = 'hidden';
  61966. this._cropEl = cropEl;
  61967. }
  61968. var cropElStyle = cropEl.style;
  61969. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  61970. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  61971. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  61972. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  61973. if (! cropEl.parentNode) {
  61974. vmlEl.appendChild(cropEl);
  61975. }
  61976. if (imageEl.parentNode != cropEl) {
  61977. cropEl.appendChild(imageEl);
  61978. }
  61979. }
  61980. else {
  61981. imageELStyle.width = round$3(scaleX * dw) + 'px';
  61982. imageELStyle.height = round$3(scaleY * dh) + 'px';
  61983. vmlEl.appendChild(imageEl);
  61984. if (cropEl && cropEl.parentNode) {
  61985. vmlEl.removeChild(cropEl);
  61986. this._cropEl = null;
  61987. }
  61988. }
  61989. var filterStr = '';
  61990. var alpha = style.opacity;
  61991. if (alpha < 1) {
  61992. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  61993. }
  61994. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  61995. imageELStyle.filter = filterStr;
  61996. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  61997. // Append to root
  61998. append(vmlRoot, vmlEl);
  61999. // Text
  62000. if (style.text != null) {
  62001. this.drawRectText(vmlRoot, this.getBoundingRect());
  62002. }
  62003. };
  62004. ZImage.prototype.onRemove = function (vmlRoot) {
  62005. remove(vmlRoot, this._vmlEl);
  62006. this._vmlEl = null;
  62007. this._cropEl = null;
  62008. this._imageEl = null;
  62009. this.removeRectText(vmlRoot);
  62010. };
  62011. ZImage.prototype.onAdd = function (vmlRoot) {
  62012. append(vmlRoot, this._vmlEl);
  62013. this.appendRectText(vmlRoot);
  62014. };
  62015. /***************************************************
  62016. * TEXT
  62017. **************************************************/
  62018. var DEFAULT_STYLE_NORMAL = 'normal';
  62019. var fontStyleCache = {};
  62020. var fontStyleCacheCount = 0;
  62021. var MAX_FONT_CACHE_SIZE = 100;
  62022. var fontEl = document.createElement('div');
  62023. var getFontStyle = function (fontString) {
  62024. var fontStyle = fontStyleCache[fontString];
  62025. if (!fontStyle) {
  62026. // Clear cache
  62027. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  62028. fontStyleCacheCount = 0;
  62029. fontStyleCache = {};
  62030. }
  62031. var style = fontEl.style;
  62032. var fontFamily;
  62033. try {
  62034. style.font = fontString;
  62035. fontFamily = style.fontFamily.split(',')[0];
  62036. }
  62037. catch (e) {
  62038. }
  62039. fontStyle = {
  62040. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  62041. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  62042. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  62043. size: parseFloat(style.fontSize || 12) | 0,
  62044. family: fontFamily || 'Microsoft YaHei'
  62045. };
  62046. fontStyleCache[fontString] = fontStyle;
  62047. fontStyleCacheCount++;
  62048. }
  62049. return fontStyle;
  62050. };
  62051. var textMeasureEl;
  62052. // Overwrite measure text method
  62053. $override$1('measureText', function (text, textFont) {
  62054. var doc$$1 = doc;
  62055. if (!textMeasureEl) {
  62056. textMeasureEl = doc$$1.createElement('div');
  62057. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  62058. + 'padding:0;margin:0;border:none;white-space:pre;';
  62059. doc.body.appendChild(textMeasureEl);
  62060. }
  62061. try {
  62062. textMeasureEl.style.font = textFont;
  62063. } catch (ex) {
  62064. // Ignore failures to set to invalid font.
  62065. }
  62066. textMeasureEl.innerHTML = '';
  62067. // Don't use innerHTML or innerText because they allow markup/whitespace.
  62068. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  62069. return {
  62070. width: textMeasureEl.offsetWidth
  62071. };
  62072. });
  62073. var tmpRect$2 = new BoundingRect();
  62074. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  62075. var style = this.style;
  62076. // Optimize, avoid normalize every time.
  62077. this.__dirty && normalizeTextStyle(style, true);
  62078. var text = style.text;
  62079. // Convert to string
  62080. text != null && (text += '');
  62081. if (!text) {
  62082. return;
  62083. }
  62084. // Convert rich text to plain text. Rich text is not supported in
  62085. // IE8-, but tags in rich text template will be removed.
  62086. if (style.rich) {
  62087. var contentBlock = parseRichText(text, style);
  62088. text = [];
  62089. for (var i = 0; i < contentBlock.lines.length; i++) {
  62090. var tokens = contentBlock.lines[i].tokens;
  62091. var textLine = [];
  62092. for (var j = 0; j < tokens.length; j++) {
  62093. textLine.push(tokens[j].text);
  62094. }
  62095. text.push(textLine.join(''));
  62096. }
  62097. text = text.join('\n');
  62098. }
  62099. var x;
  62100. var y;
  62101. var align = style.textAlign;
  62102. var verticalAlign = style.textVerticalAlign;
  62103. var fontStyle = getFontStyle(style.font);
  62104. // FIXME encodeHtmlAttribute ?
  62105. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  62106. + fontStyle.size + 'px "' + fontStyle.family + '"';
  62107. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  62108. // Transform rect to view space
  62109. var m = this.transform;
  62110. // Ignore transform for text in other element
  62111. if (m && !fromTextEl) {
  62112. tmpRect$2.copy(rect);
  62113. tmpRect$2.applyTransform(m);
  62114. rect = tmpRect$2;
  62115. }
  62116. if (!fromTextEl) {
  62117. var textPosition = style.textPosition;
  62118. var distance$$1 = style.textDistance;
  62119. // Text position represented by coord
  62120. if (textPosition instanceof Array) {
  62121. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  62122. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  62123. align = align || 'left';
  62124. }
  62125. else {
  62126. var res = adjustTextPositionOnRect(
  62127. textPosition, rect, distance$$1
  62128. );
  62129. x = res.x;
  62130. y = res.y;
  62131. // Default align and baseline when has textPosition
  62132. align = align || res.textAlign;
  62133. verticalAlign = verticalAlign || res.textVerticalAlign;
  62134. }
  62135. }
  62136. else {
  62137. x = rect.x;
  62138. y = rect.y;
  62139. }
  62140. x = adjustTextX(x, textRect.width, align);
  62141. y = adjustTextY(y, textRect.height, verticalAlign);
  62142. // Force baseline 'middle'
  62143. y += textRect.height / 2;
  62144. // var fontSize = fontStyle.size;
  62145. // 1.75 is an arbitrary number, as there is no info about the text baseline
  62146. // switch (baseline) {
  62147. // case 'hanging':
  62148. // case 'top':
  62149. // y += fontSize / 1.75;
  62150. // break;
  62151. // case 'middle':
  62152. // break;
  62153. // default:
  62154. // // case null:
  62155. // // case 'alphabetic':
  62156. // // case 'ideographic':
  62157. // // case 'bottom':
  62158. // y -= fontSize / 2.25;
  62159. // break;
  62160. // }
  62161. // switch (align) {
  62162. // case 'left':
  62163. // break;
  62164. // case 'center':
  62165. // x -= textRect.width / 2;
  62166. // break;
  62167. // case 'right':
  62168. // x -= textRect.width;
  62169. // break;
  62170. // case 'end':
  62171. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  62172. // break;
  62173. // case 'start':
  62174. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  62175. // break;
  62176. // default:
  62177. // align = 'left';
  62178. // }
  62179. var createNode$$1 = createNode;
  62180. var textVmlEl = this._textVmlEl;
  62181. var pathEl;
  62182. var textPathEl;
  62183. var skewEl;
  62184. if (!textVmlEl) {
  62185. textVmlEl = createNode$$1('line');
  62186. pathEl = createNode$$1('path');
  62187. textPathEl = createNode$$1('textpath');
  62188. skewEl = createNode$$1('skew');
  62189. // FIXME Why here is not cammel case
  62190. // Align 'center' seems wrong
  62191. textPathEl.style['v-text-align'] = 'left';
  62192. initRootElStyle(textVmlEl);
  62193. pathEl.textpathok = true;
  62194. textPathEl.on = true;
  62195. textVmlEl.from = '0 0';
  62196. textVmlEl.to = '1000 0.05';
  62197. append(textVmlEl, skewEl);
  62198. append(textVmlEl, pathEl);
  62199. append(textVmlEl, textPathEl);
  62200. this._textVmlEl = textVmlEl;
  62201. }
  62202. else {
  62203. // 这里是在前面 appendChild 保证顺序的前提下
  62204. skewEl = textVmlEl.firstChild;
  62205. pathEl = skewEl.nextSibling;
  62206. textPathEl = pathEl.nextSibling;
  62207. }
  62208. var coords = [x, y];
  62209. var textVmlElStyle = textVmlEl.style;
  62210. // Ignore transform for text in other element
  62211. if (m && fromTextEl) {
  62212. applyTransform(coords, coords, m);
  62213. skewEl.on = true;
  62214. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  62215. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  62216. // Text position
  62217. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  62218. // Left top point as origin
  62219. skewEl.origin = '0 0';
  62220. textVmlElStyle.left = '0px';
  62221. textVmlElStyle.top = '0px';
  62222. }
  62223. else {
  62224. skewEl.on = false;
  62225. textVmlElStyle.left = round$3(x) + 'px';
  62226. textVmlElStyle.top = round$3(y) + 'px';
  62227. }
  62228. textPathEl.string = encodeHtmlAttribute(text);
  62229. // TODO
  62230. try {
  62231. textPathEl.style.font = font;
  62232. }
  62233. // Error font format
  62234. catch (e) {}
  62235. updateFillAndStroke(textVmlEl, 'fill', {
  62236. fill: style.textFill,
  62237. opacity: style.opacity
  62238. }, this);
  62239. updateFillAndStroke(textVmlEl, 'stroke', {
  62240. stroke: style.textStroke,
  62241. opacity: style.opacity,
  62242. lineDash: style.lineDash
  62243. }, this);
  62244. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  62245. // Attached to root
  62246. append(vmlRoot, textVmlEl);
  62247. };
  62248. var removeRectText = function (vmlRoot) {
  62249. remove(vmlRoot, this._textVmlEl);
  62250. this._textVmlEl = null;
  62251. };
  62252. var appendRectText = function (vmlRoot) {
  62253. append(vmlRoot, this._textVmlEl);
  62254. };
  62255. var list = [RectText, Displayable, ZImage, Path, Text];
  62256. // In case Displayable has been mixed in RectText
  62257. for (var i$3 = 0; i$3 < list.length; i$3++) {
  62258. var proto$6 = list[i$3].prototype;
  62259. proto$6.drawRectText = drawRectText;
  62260. proto$6.removeRectText = removeRectText;
  62261. proto$6.appendRectText = appendRectText;
  62262. }
  62263. Text.prototype.brushVML = function (vmlRoot) {
  62264. var style = this.style;
  62265. if (style.text != null) {
  62266. this.drawRectText(vmlRoot, {
  62267. x: style.x || 0, y: style.y || 0,
  62268. width: 0, height: 0
  62269. }, this.getBoundingRect(), true);
  62270. }
  62271. else {
  62272. this.removeRectText(vmlRoot);
  62273. }
  62274. };
  62275. Text.prototype.onRemove = function (vmlRoot) {
  62276. this.removeRectText(vmlRoot);
  62277. };
  62278. Text.prototype.onAdd = function (vmlRoot) {
  62279. this.appendRectText(vmlRoot);
  62280. };
  62281. }
  62282. /**
  62283. * VML Painter.
  62284. *
  62285. * @module zrender/vml/Painter
  62286. */
  62287. function parseInt10$1(val) {
  62288. return parseInt(val, 10);
  62289. }
  62290. /**
  62291. * @alias module:zrender/vml/Painter
  62292. */
  62293. function VMLPainter(root, storage) {
  62294. initVML();
  62295. this.root = root;
  62296. this.storage = storage;
  62297. var vmlViewport = document.createElement('div');
  62298. var vmlRoot = document.createElement('div');
  62299. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  62300. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  62301. root.appendChild(vmlViewport);
  62302. this._vmlRoot = vmlRoot;
  62303. this._vmlViewport = vmlViewport;
  62304. this.resize();
  62305. // Modify storage
  62306. var oldDelFromStorage = storage.delFromStorage;
  62307. var oldAddToStorage = storage.addToStorage;
  62308. storage.delFromStorage = function (el) {
  62309. oldDelFromStorage.call(storage, el);
  62310. if (el) {
  62311. el.onRemove && el.onRemove(vmlRoot);
  62312. }
  62313. };
  62314. storage.addToStorage = function (el) {
  62315. // Displayable already has a vml node
  62316. el.onAdd && el.onAdd(vmlRoot);
  62317. oldAddToStorage.call(storage, el);
  62318. };
  62319. this._firstPaint = true;
  62320. }
  62321. VMLPainter.prototype = {
  62322. constructor: VMLPainter,
  62323. getType: function () {
  62324. return 'vml';
  62325. },
  62326. /**
  62327. * @return {HTMLDivElement}
  62328. */
  62329. getViewportRoot: function () {
  62330. return this._vmlViewport;
  62331. },
  62332. getViewportRootOffset: function () {
  62333. var viewportRoot = this.getViewportRoot();
  62334. if (viewportRoot) {
  62335. return {
  62336. offsetLeft: viewportRoot.offsetLeft || 0,
  62337. offsetTop: viewportRoot.offsetTop || 0
  62338. };
  62339. }
  62340. },
  62341. /**
  62342. * 刷新
  62343. */
  62344. refresh: function () {
  62345. var list = this.storage.getDisplayList(true, true);
  62346. this._paintList(list);
  62347. },
  62348. _paintList: function (list) {
  62349. var vmlRoot = this._vmlRoot;
  62350. for (var i = 0; i < list.length; i++) {
  62351. var el = list[i];
  62352. if (el.invisible || el.ignore) {
  62353. if (!el.__alreadyNotVisible) {
  62354. el.onRemove(vmlRoot);
  62355. }
  62356. // Set as already invisible
  62357. el.__alreadyNotVisible = true;
  62358. }
  62359. else {
  62360. if (el.__alreadyNotVisible) {
  62361. el.onAdd(vmlRoot);
  62362. }
  62363. el.__alreadyNotVisible = false;
  62364. if (el.__dirty) {
  62365. el.beforeBrush && el.beforeBrush();
  62366. (el.brushVML || el.brush).call(el, vmlRoot);
  62367. el.afterBrush && el.afterBrush();
  62368. }
  62369. }
  62370. el.__dirty = false;
  62371. }
  62372. if (this._firstPaint) {
  62373. // Detached from document at first time
  62374. // to avoid page refreshing too many times
  62375. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  62376. this._vmlViewport.appendChild(vmlRoot);
  62377. this._firstPaint = false;
  62378. }
  62379. },
  62380. resize: function (width, height) {
  62381. var width = width == null ? this._getWidth() : width;
  62382. var height = height == null ? this._getHeight() : height;
  62383. if (this._width != width || this._height != height) {
  62384. this._width = width;
  62385. this._height = height;
  62386. var vmlViewportStyle = this._vmlViewport.style;
  62387. vmlViewportStyle.width = width + 'px';
  62388. vmlViewportStyle.height = height + 'px';
  62389. }
  62390. },
  62391. dispose: function () {
  62392. this.root.innerHTML = '';
  62393. this._vmlRoot =
  62394. this._vmlViewport =
  62395. this.storage = null;
  62396. },
  62397. getWidth: function () {
  62398. return this._width;
  62399. },
  62400. getHeight: function () {
  62401. return this._height;
  62402. },
  62403. clear: function () {
  62404. if (this._vmlViewport) {
  62405. this.root.removeChild(this._vmlViewport);
  62406. }
  62407. },
  62408. _getWidth: function () {
  62409. var root = this.root;
  62410. var stl = root.currentStyle;
  62411. return ((root.clientWidth || parseInt10$1(stl.width))
  62412. - parseInt10$1(stl.paddingLeft)
  62413. - parseInt10$1(stl.paddingRight)) | 0;
  62414. },
  62415. _getHeight: function () {
  62416. var root = this.root;
  62417. var stl = root.currentStyle;
  62418. return ((root.clientHeight || parseInt10$1(stl.height))
  62419. - parseInt10$1(stl.paddingTop)
  62420. - parseInt10$1(stl.paddingBottom)) | 0;
  62421. }
  62422. };
  62423. // Not supported methods
  62424. function createMethodNotSupport(method) {
  62425. return function () {
  62426. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  62427. };
  62428. }
  62429. // Unsupported methods
  62430. each$1([
  62431. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  62432. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  62433. ], function (name) {
  62434. VMLPainter.prototype[name] = createMethodNotSupport(name);
  62435. });
  62436. registerPainter('vml', VMLPainter);
  62437. var svgURI = 'http://www.w3.org/2000/svg';
  62438. function createElement(name) {
  62439. return document.createElementNS(svgURI, name);
  62440. }
  62441. // TODO
  62442. // 1. shadow
  62443. // 2. Image: sx, sy, sw, sh
  62444. var CMD$4 = PathProxy.CMD;
  62445. var arrayJoin = Array.prototype.join;
  62446. var NONE = 'none';
  62447. var mathRound = Math.round;
  62448. var mathSin$3 = Math.sin;
  62449. var mathCos$3 = Math.cos;
  62450. var PI$5 = Math.PI;
  62451. var PI2$6 = Math.PI * 2;
  62452. var degree = 180 / PI$5;
  62453. var EPSILON$4 = 1e-4;
  62454. function round4(val) {
  62455. return mathRound(val * 1e4) / 1e4;
  62456. }
  62457. function isAroundZero$1(val) {
  62458. return val < EPSILON$4 && val > -EPSILON$4;
  62459. }
  62460. function pathHasFill(style, isText) {
  62461. var fill = isText ? style.textFill : style.fill;
  62462. return fill != null && fill !== NONE;
  62463. }
  62464. function pathHasStroke(style, isText) {
  62465. var stroke = isText ? style.textStroke : style.stroke;
  62466. return stroke != null && stroke !== NONE;
  62467. }
  62468. function setTransform(svgEl, m) {
  62469. if (m) {
  62470. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  62471. }
  62472. }
  62473. function attr(el, key, val) {
  62474. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  62475. // Don't set attribute for gradient, since it need new dom nodes
  62476. el.setAttribute(key, val);
  62477. }
  62478. }
  62479. function attrXLink(el, key, val) {
  62480. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  62481. }
  62482. function bindStyle(svgEl, style, isText) {
  62483. if (pathHasFill(style, isText)) {
  62484. var fill = isText ? style.textFill : style.fill;
  62485. fill = fill === 'transparent' ? NONE : fill;
  62486. /**
  62487. * FIXME:
  62488. * This is a temporary fix for Chrome's clipping bug
  62489. * that happens when a clip-path is referring another one.
  62490. * This fix should be used before Chrome's bug is fixed.
  62491. * For an element that has clip-path, and fill is none,
  62492. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  62493. * Otherwise, it will show black fill color.
  62494. * 0.002 is used because this won't work for alpha values smaller
  62495. * than 0.002.
  62496. *
  62497. * See
  62498. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  62499. * for more information.
  62500. */
  62501. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  62502. fill = 'rgba(0, 0, 0, 0.002)';
  62503. }
  62504. attr(svgEl, 'fill', fill);
  62505. attr(svgEl, 'fill-opacity', style.opacity);
  62506. }
  62507. else {
  62508. attr(svgEl, 'fill', NONE);
  62509. }
  62510. if (pathHasStroke(style, isText)) {
  62511. var stroke = isText ? style.textStroke : style.stroke;
  62512. stroke = stroke === 'transparent' ? NONE : stroke;
  62513. attr(svgEl, 'stroke', stroke);
  62514. var strokeWidth = isText
  62515. ? style.textStrokeWidth
  62516. : style.lineWidth;
  62517. var strokeScale = style.strokeNoScale
  62518. ? style.host.getLineScale()
  62519. : 1;
  62520. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  62521. attr(svgEl, 'paint-order', 'stroke');
  62522. attr(svgEl, 'stroke-opacity', style.opacity);
  62523. var lineDash = style.lineDash;
  62524. if (lineDash) {
  62525. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  62526. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  62527. }
  62528. else {
  62529. attr(svgEl, 'stroke-dasharray', '');
  62530. }
  62531. // PENDING
  62532. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  62533. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  62534. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  62535. }
  62536. else {
  62537. attr(svgEl, 'stroke', NONE);
  62538. }
  62539. }
  62540. /***************************************************
  62541. * PATH
  62542. **************************************************/
  62543. function pathDataToString$1(path) {
  62544. var str = [];
  62545. var data = path.data;
  62546. var dataLength = path.len();
  62547. for (var i = 0; i < dataLength;) {
  62548. var cmd = data[i++];
  62549. var cmdStr = '';
  62550. var nData = 0;
  62551. switch (cmd) {
  62552. case CMD$4.M:
  62553. cmdStr = 'M';
  62554. nData = 2;
  62555. break;
  62556. case CMD$4.L:
  62557. cmdStr = 'L';
  62558. nData = 2;
  62559. break;
  62560. case CMD$4.Q:
  62561. cmdStr = 'Q';
  62562. nData = 4;
  62563. break;
  62564. case CMD$4.C:
  62565. cmdStr = 'C';
  62566. nData = 6;
  62567. break;
  62568. case CMD$4.A:
  62569. var cx = data[i++];
  62570. var cy = data[i++];
  62571. var rx = data[i++];
  62572. var ry = data[i++];
  62573. var theta = data[i++];
  62574. var dTheta = data[i++];
  62575. var psi = data[i++];
  62576. var clockwise = data[i++];
  62577. var dThetaPositive = Math.abs(dTheta);
  62578. var isCircle = isAroundZero$1(dThetaPositive % PI2$6)
  62579. && !isAroundZero$1(dThetaPositive);
  62580. var large = false;
  62581. if (dThetaPositive >= PI2$6) {
  62582. large = true;
  62583. }
  62584. else if (isAroundZero$1(dThetaPositive)) {
  62585. large = false;
  62586. }
  62587. else {
  62588. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  62589. === !!clockwise;
  62590. }
  62591. var x0 = round4(cx + rx * mathCos$3(theta));
  62592. var y0 = round4(cy + ry * mathSin$3(theta));
  62593. // It will not draw if start point and end point are exactly the same
  62594. // We need to shift the end point with a small value
  62595. // FIXME A better way to draw circle ?
  62596. if (isCircle) {
  62597. if (clockwise) {
  62598. dTheta = PI2$6 - 1e-4;
  62599. }
  62600. else {
  62601. dTheta = -PI2$6 + 1e-4;
  62602. }
  62603. large = true;
  62604. if (i === 9) {
  62605. // Move to (x0, y0) only when CMD.A comes at the
  62606. // first position of a shape.
  62607. // For instance, when drawing a ring, CMD.A comes
  62608. // after CMD.M, so it's unnecessary to move to
  62609. // (x0, y0).
  62610. str.push('M', x0, y0);
  62611. }
  62612. }
  62613. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  62614. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  62615. // FIXME Ellipse
  62616. str.push('A', round4(rx), round4(ry),
  62617. mathRound(psi * degree), +large, +clockwise, x, y);
  62618. break;
  62619. case CMD$4.Z:
  62620. cmdStr = 'Z';
  62621. break;
  62622. case CMD$4.R:
  62623. var x = round4(data[i++]);
  62624. var y = round4(data[i++]);
  62625. var w = round4(data[i++]);
  62626. var h = round4(data[i++]);
  62627. str.push(
  62628. 'M', x, y,
  62629. 'L', x + w, y,
  62630. 'L', x + w, y + h,
  62631. 'L', x, y + h,
  62632. 'L', x, y
  62633. );
  62634. break;
  62635. }
  62636. cmdStr && str.push(cmdStr);
  62637. for (var j = 0; j < nData; j++) {
  62638. // PENDING With scale
  62639. str.push(round4(data[i++]));
  62640. }
  62641. }
  62642. return str.join(' ');
  62643. }
  62644. var svgPath = {};
  62645. svgPath.brush = function (el) {
  62646. var style = el.style;
  62647. var svgEl = el.__svgEl;
  62648. if (!svgEl) {
  62649. svgEl = createElement('path');
  62650. el.__svgEl = svgEl;
  62651. }
  62652. if (!el.path) {
  62653. el.createPathProxy();
  62654. }
  62655. var path = el.path;
  62656. if (el.__dirtyPath) {
  62657. path.beginPath();
  62658. el.buildPath(path, el.shape);
  62659. el.__dirtyPath = false;
  62660. var pathStr = pathDataToString$1(path);
  62661. if (pathStr.indexOf('NaN') < 0) {
  62662. // Ignore illegal path, which may happen such in out-of-range
  62663. // data in Calendar series.
  62664. attr(svgEl, 'd', pathStr);
  62665. }
  62666. }
  62667. bindStyle(svgEl, style);
  62668. setTransform(svgEl, el.transform);
  62669. if (style.text != null) {
  62670. svgTextDrawRectText(el, el.getBoundingRect());
  62671. }
  62672. };
  62673. /***************************************************
  62674. * IMAGE
  62675. **************************************************/
  62676. var svgImage = {};
  62677. svgImage.brush = function (el) {
  62678. var style = el.style;
  62679. var image = style.image;
  62680. if (image instanceof HTMLImageElement) {
  62681. var src = image.src;
  62682. image = src;
  62683. }
  62684. if (! image) {
  62685. return;
  62686. }
  62687. var x = style.x || 0;
  62688. var y = style.y || 0;
  62689. var dw = style.width;
  62690. var dh = style.height;
  62691. var svgEl = el.__svgEl;
  62692. if (! svgEl) {
  62693. svgEl = createElement('image');
  62694. el.__svgEl = svgEl;
  62695. }
  62696. if (image !== el.__imageSrc) {
  62697. attrXLink(svgEl, 'href', image);
  62698. // Caching image src
  62699. el.__imageSrc = image;
  62700. }
  62701. attr(svgEl, 'width', dw);
  62702. attr(svgEl, 'height', dh);
  62703. attr(svgEl, 'x', x);
  62704. attr(svgEl, 'y', y);
  62705. setTransform(svgEl, el.transform);
  62706. if (style.text != null) {
  62707. svgTextDrawRectText(el, el.getBoundingRect());
  62708. }
  62709. };
  62710. /***************************************************
  62711. * TEXT
  62712. **************************************************/
  62713. var svgText = {};
  62714. var tmpRect$3 = new BoundingRect();
  62715. var svgTextDrawRectText = function (el, rect, textRect) {
  62716. var style = el.style;
  62717. el.__dirty && normalizeTextStyle(style, true);
  62718. var text = style.text;
  62719. // Convert to string
  62720. if (text == null) {
  62721. // Draw no text only when text is set to null, but not ''
  62722. return;
  62723. }
  62724. else {
  62725. text += '';
  62726. }
  62727. var textSvgEl = el.__textSvgEl;
  62728. if (! textSvgEl) {
  62729. textSvgEl = createElement('text');
  62730. el.__textSvgEl = textSvgEl;
  62731. }
  62732. bindStyle(textSvgEl, style, true);
  62733. if (el instanceof Text || el.style.transformText) {
  62734. // Transform text with element
  62735. setTransform(textSvgEl, el.transform);
  62736. }
  62737. else {
  62738. if (el.transform) {
  62739. tmpRect$3.copy(rect);
  62740. tmpRect$3.applyTransform(el.transform);
  62741. rect = tmpRect$3;
  62742. }
  62743. else {
  62744. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  62745. rect.x = pos[0];
  62746. rect.y = pos[1];
  62747. }
  62748. }
  62749. var x;
  62750. var y;
  62751. var textPosition = style.textPosition;
  62752. var distance = style.textDistance;
  62753. var align = style.textAlign || 'left';
  62754. if (typeof style.fontSize === 'number') {
  62755. style.fontSize += 'px';
  62756. }
  62757. var font = style.font
  62758. || [
  62759. style.fontStyle || '',
  62760. style.fontWeight || '',
  62761. style.fontSize || '',
  62762. style.fontFamily || ''
  62763. ].join(' ')
  62764. || DEFAULT_FONT;
  62765. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  62766. textRect = getBoundingRect(text, font, align,
  62767. verticalAlign);
  62768. var lineHeight = textRect.lineHeight;
  62769. // Text position represented by coord
  62770. if (textPosition instanceof Array) {
  62771. x = rect.x + textPosition[0];
  62772. y = rect.y + textPosition[1];
  62773. }
  62774. else {
  62775. var newPos = adjustTextPositionOnRect(
  62776. textPosition, rect, distance
  62777. );
  62778. x = newPos.x;
  62779. y = newPos.y;
  62780. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  62781. align = newPos.textAlign;
  62782. }
  62783. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  62784. if (font) {
  62785. textSvgEl.style.font = font;
  62786. }
  62787. var textPadding = style.textPadding;
  62788. // Make baseline top
  62789. attr(textSvgEl, 'x', x);
  62790. attr(textSvgEl, 'y', y);
  62791. var textLines = text.split('\n');
  62792. var nTextLines = textLines.length;
  62793. var textAnchor = align;
  62794. // PENDING
  62795. if (textAnchor === 'left') {
  62796. textAnchor = 'start';
  62797. textPadding && (x += textPadding[3]);
  62798. }
  62799. else if (textAnchor === 'right') {
  62800. textAnchor = 'end';
  62801. textPadding && (x -= textPadding[1]);
  62802. }
  62803. else if (textAnchor === 'center') {
  62804. textAnchor = 'middle';
  62805. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  62806. }
  62807. var dy = 0;
  62808. if (verticalAlign === 'baseline') {
  62809. dy = -textRect.height + lineHeight;
  62810. textPadding && (dy -= textPadding[2]);
  62811. }
  62812. else if (verticalAlign === 'middle') {
  62813. dy = (-textRect.height + lineHeight) / 2;
  62814. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  62815. }
  62816. else {
  62817. textPadding && (dy += textPadding[0]);
  62818. }
  62819. // Font may affect position of each tspan elements
  62820. if (el.__text !== text || el.__textFont !== font) {
  62821. var tspanList = el.__tspanList || [];
  62822. el.__tspanList = tspanList;
  62823. for (var i = 0; i < nTextLines; i++) {
  62824. // Using cached tspan elements
  62825. var tspan = tspanList[i];
  62826. if (! tspan) {
  62827. tspan = tspanList[i] = createElement('tspan');
  62828. textSvgEl.appendChild(tspan);
  62829. attr(tspan, 'alignment-baseline', verticalAlign);
  62830. attr(tspan, 'text-anchor', textAnchor);
  62831. }
  62832. else {
  62833. tspan.innerHTML = '';
  62834. }
  62835. attr(tspan, 'x', x);
  62836. attr(tspan, 'y', y + i * lineHeight + dy);
  62837. tspan.appendChild(document.createTextNode(textLines[i]));
  62838. }
  62839. // Remove unsed tspan elements
  62840. for (; i < tspanList.length; i++) {
  62841. textSvgEl.removeChild(tspanList[i]);
  62842. }
  62843. tspanList.length = nTextLines;
  62844. el.__text = text;
  62845. el.__textFont = font;
  62846. }
  62847. else if (el.__tspanList.length) {
  62848. // Update span x and y
  62849. var len = el.__tspanList.length;
  62850. for (var i = 0; i < len; ++i) {
  62851. var tspan = el.__tspanList[i];
  62852. if (tspan) {
  62853. attr(tspan, 'x', x);
  62854. attr(tspan, 'y', y + i * lineHeight + dy);
  62855. }
  62856. }
  62857. }
  62858. };
  62859. function getVerticalAlignForSvg(verticalAlign) {
  62860. if (verticalAlign === 'middle') {
  62861. return 'middle';
  62862. }
  62863. else if (verticalAlign === 'bottom') {
  62864. return 'baseline';
  62865. }
  62866. else {
  62867. return 'hanging';
  62868. }
  62869. }
  62870. svgText.drawRectText = svgTextDrawRectText;
  62871. svgText.brush = function (el) {
  62872. var style = el.style;
  62873. if (style.text != null) {
  62874. // 强制设置 textPosition
  62875. style.textPosition = [0, 0];
  62876. svgTextDrawRectText(el, {
  62877. x: style.x || 0, y: style.y || 0,
  62878. width: 0, height: 0
  62879. }, el.getBoundingRect());
  62880. }
  62881. };
  62882. // Myers' Diff Algorithm
  62883. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  62884. function Diff() {}
  62885. Diff.prototype = {
  62886. diff: function (oldArr, newArr, equals) {
  62887. if (!equals) {
  62888. equals = function (a, b) {
  62889. return a === b;
  62890. };
  62891. }
  62892. this.equals = equals;
  62893. var self = this;
  62894. oldArr = oldArr.slice();
  62895. newArr = newArr.slice();
  62896. // Allow subclasses to massage the input prior to running
  62897. var newLen = newArr.length;
  62898. var oldLen = oldArr.length;
  62899. var editLength = 1;
  62900. var maxEditLength = newLen + oldLen;
  62901. var bestPath = [{ newPos: -1, components: [] }];
  62902. // Seed editLength = 0, i.e. the content starts with the same values
  62903. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  62904. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  62905. var indices = [];
  62906. for (var i = 0; i < newArr.length; i++) {
  62907. indices.push(i);
  62908. }
  62909. // Identity per the equality and tokenizer
  62910. return [{
  62911. indices: indices, count: newArr.length
  62912. }];
  62913. }
  62914. // Main worker method. checks all permutations of a given edit length for acceptance.
  62915. function execEditLength() {
  62916. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  62917. var basePath;
  62918. var addPath = bestPath[diagonalPath - 1];
  62919. var removePath = bestPath[diagonalPath + 1];
  62920. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  62921. if (addPath) {
  62922. // No one else is going to attempt to use this value, clear it
  62923. bestPath[diagonalPath - 1] = undefined;
  62924. }
  62925. var canAdd = addPath && addPath.newPos + 1 < newLen;
  62926. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  62927. if (!canAdd && !canRemove) {
  62928. // If this path is a terminal then prune
  62929. bestPath[diagonalPath] = undefined;
  62930. continue;
  62931. }
  62932. // Select the diagonal that we want to branch from. We select the prior
  62933. // path whose position in the new string is the farthest from the origin
  62934. // and does not pass the bounds of the diff graph
  62935. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  62936. basePath = clonePath(removePath);
  62937. self.pushComponent(basePath.components, undefined, true);
  62938. }
  62939. else {
  62940. basePath = addPath; // No need to clone, we've pulled it from the list
  62941. basePath.newPos++;
  62942. self.pushComponent(basePath.components, true, undefined);
  62943. }
  62944. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  62945. // If we have hit the end of both strings, then we are done
  62946. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  62947. return buildValues(self, basePath.components, newArr, oldArr);
  62948. }
  62949. else {
  62950. // Otherwise track this path as a potential candidate and continue.
  62951. bestPath[diagonalPath] = basePath;
  62952. }
  62953. }
  62954. editLength++;
  62955. }
  62956. while (editLength <= maxEditLength) {
  62957. var ret = execEditLength();
  62958. if (ret) {
  62959. return ret;
  62960. }
  62961. }
  62962. },
  62963. pushComponent: function (components, added, removed) {
  62964. var last = components[components.length - 1];
  62965. if (last && last.added === added && last.removed === removed) {
  62966. // We need to clone here as the component clone operation is just
  62967. // as shallow array clone
  62968. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  62969. }
  62970. else {
  62971. components.push({count: 1, added: added, removed: removed });
  62972. }
  62973. },
  62974. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  62975. var newLen = newArr.length;
  62976. var oldLen = oldArr.length;
  62977. var newPos = basePath.newPos;
  62978. var oldPos = newPos - diagonalPath;
  62979. var commonCount = 0;
  62980. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  62981. newPos++;
  62982. oldPos++;
  62983. commonCount++;
  62984. }
  62985. if (commonCount) {
  62986. basePath.components.push({count: commonCount});
  62987. }
  62988. basePath.newPos = newPos;
  62989. return oldPos;
  62990. },
  62991. tokenize: function (value) {
  62992. return value.slice();
  62993. },
  62994. join: function (value) {
  62995. return value.slice();
  62996. }
  62997. };
  62998. function buildValues(diff, components, newArr, oldArr) {
  62999. var componentPos = 0;
  63000. var componentLen = components.length;
  63001. var newPos = 0;
  63002. var oldPos = 0;
  63003. for (; componentPos < componentLen; componentPos++) {
  63004. var component = components[componentPos];
  63005. if (!component.removed) {
  63006. var indices = [];
  63007. for (var i = newPos; i < newPos + component.count; i++) {
  63008. indices.push(i);
  63009. }
  63010. component.indices = indices;
  63011. newPos += component.count;
  63012. // Common case
  63013. if (!component.added) {
  63014. oldPos += component.count;
  63015. }
  63016. }
  63017. else {
  63018. var indices = [];
  63019. for (var i = oldPos; i < oldPos + component.count; i++) {
  63020. indices.push(i);
  63021. }
  63022. component.indices = indices;
  63023. oldPos += component.count;
  63024. }
  63025. }
  63026. return components;
  63027. }
  63028. function clonePath(path) {
  63029. return { newPos: path.newPos, components: path.components.slice(0) };
  63030. }
  63031. var arrayDiff = new Diff();
  63032. var arrayDiff$1 = function (oldArr, newArr, callback) {
  63033. return arrayDiff.diff(oldArr, newArr, callback);
  63034. };
  63035. /**
  63036. * @file Manages elements that can be defined in <defs> in SVG,
  63037. * e.g., gradients, clip path, etc.
  63038. * @author Zhang Wenli
  63039. */
  63040. var MARK_UNUSED = '0';
  63041. var MARK_USED = '1';
  63042. /**
  63043. * Manages elements that can be defined in <defs> in SVG,
  63044. * e.g., gradients, clip path, etc.
  63045. *
  63046. * @class
  63047. * @param {SVGElement} svgRoot root of SVG document
  63048. * @param {string|string[]} tagNames possible tag names
  63049. * @param {string} markLabel label name to make if the element
  63050. * is used
  63051. */
  63052. function Definable(
  63053. svgRoot,
  63054. tagNames,
  63055. markLabel
  63056. ) {
  63057. this._svgRoot = svgRoot;
  63058. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  63059. this._markLabel = markLabel;
  63060. this.nextId = 0;
  63061. }
  63062. Definable.prototype.createElement = createElement;
  63063. /**
  63064. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  63065. *
  63066. * @param {boolean} isForceCreating if need to create when not exists
  63067. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  63068. * exist and isForceCreating is false
  63069. */
  63070. Definable.prototype.getDefs = function (isForceCreating) {
  63071. var svgRoot = this._svgRoot;
  63072. var defs = this._svgRoot.getElementsByTagName('defs');
  63073. if (defs.length === 0) {
  63074. // Not exist
  63075. if (isForceCreating) {
  63076. defs = svgRoot.insertBefore(
  63077. this.createElement('defs'), // Create new tag
  63078. svgRoot.firstChild // Insert in the front of svg
  63079. );
  63080. if (!defs.contains) {
  63081. // IE doesn't support contains method
  63082. defs.contains = function (el) {
  63083. var children = defs.children;
  63084. if (!children) {
  63085. return false;
  63086. }
  63087. for (var i = children.length - 1; i >= 0; --i) {
  63088. if (children[i] === el) {
  63089. return true;
  63090. }
  63091. }
  63092. return false;
  63093. };
  63094. }
  63095. return defs;
  63096. }
  63097. else {
  63098. return null;
  63099. }
  63100. }
  63101. else {
  63102. return defs[0];
  63103. }
  63104. };
  63105. /**
  63106. * Update DOM element if necessary.
  63107. *
  63108. * @param {Object|string} element style element. e.g., for gradient,
  63109. * it may be '#ccc' or {type: 'linear', ...}
  63110. * @param {Function|undefined} onUpdate update callback
  63111. */
  63112. Definable.prototype.update = function (element, onUpdate) {
  63113. if (!element) {
  63114. return;
  63115. }
  63116. var defs = this.getDefs(false);
  63117. if (element._dom && defs.contains(element._dom)) {
  63118. // Update DOM
  63119. if (typeof onUpdate === 'function') {
  63120. onUpdate();
  63121. }
  63122. }
  63123. else {
  63124. // No previous dom, create new
  63125. var dom = this.add(element);
  63126. if (dom) {
  63127. element._dom = dom;
  63128. }
  63129. }
  63130. };
  63131. /**
  63132. * Add gradient dom to defs
  63133. *
  63134. * @param {SVGElement} dom DOM to be added to <defs>
  63135. */
  63136. Definable.prototype.addDom = function (dom) {
  63137. var defs = this.getDefs(true);
  63138. defs.appendChild(dom);
  63139. };
  63140. /**
  63141. * Remove DOM of a given element.
  63142. *
  63143. * @param {SVGElement} element element to remove dom
  63144. */
  63145. Definable.prototype.removeDom = function (element) {
  63146. var defs = this.getDefs(false);
  63147. defs.removeChild(element._dom);
  63148. };
  63149. /**
  63150. * Get DOMs of this element.
  63151. *
  63152. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  63153. */
  63154. Definable.prototype.getDoms = function () {
  63155. var defs = this.getDefs(false);
  63156. if (!defs) {
  63157. // No dom when defs is not defined
  63158. return [];
  63159. }
  63160. var doms = [];
  63161. each$1(this._tagNames, function (tagName) {
  63162. var tags = defs.getElementsByTagName(tagName);
  63163. // Note that tags is HTMLCollection, which is array-like
  63164. // rather than real array.
  63165. // So `doms.concat(tags)` add tags as one object.
  63166. doms = doms.concat([].slice.call(tags));
  63167. });
  63168. return doms;
  63169. };
  63170. /**
  63171. * Mark DOMs to be unused before painting, and clear unused ones at the end
  63172. * of the painting.
  63173. */
  63174. Definable.prototype.markAllUnused = function () {
  63175. var doms = this.getDoms();
  63176. var that = this;
  63177. each$1(doms, function (dom) {
  63178. dom[that._markLabel] = MARK_UNUSED;
  63179. });
  63180. };
  63181. /**
  63182. * Mark a single DOM to be used.
  63183. *
  63184. * @param {SVGElement} dom DOM to mark
  63185. */
  63186. Definable.prototype.markUsed = function (dom) {
  63187. if (dom) {
  63188. dom[this._markLabel] = MARK_USED;
  63189. }
  63190. };
  63191. /**
  63192. * Remove unused DOMs defined in <defs>
  63193. */
  63194. Definable.prototype.removeUnused = function () {
  63195. var defs = this.getDefs(false);
  63196. if (!defs) {
  63197. // Nothing to remove
  63198. return;
  63199. }
  63200. var doms = this.getDoms();
  63201. var that = this;
  63202. each$1(doms, function (dom) {
  63203. if (dom[that._markLabel] !== MARK_USED) {
  63204. // Remove gradient
  63205. defs.removeChild(dom);
  63206. }
  63207. });
  63208. };
  63209. /**
  63210. * Get SVG proxy.
  63211. *
  63212. * @param {Displayable} displayable displayable element
  63213. * @return {Path|Image|Text} svg proxy of given element
  63214. */
  63215. Definable.prototype.getSvgProxy = function (displayable) {
  63216. if (displayable instanceof Path) {
  63217. return svgPath;
  63218. }
  63219. else if (displayable instanceof ZImage) {
  63220. return svgImage;
  63221. }
  63222. else if (displayable instanceof Text) {
  63223. return svgText;
  63224. }
  63225. else {
  63226. return svgPath;
  63227. }
  63228. };
  63229. /**
  63230. * Get text SVG element.
  63231. *
  63232. * @param {Displayable} displayable displayable element
  63233. * @return {SVGElement} SVG element of text
  63234. */
  63235. Definable.prototype.getTextSvgElement = function (displayable) {
  63236. return displayable.__textSvgEl;
  63237. };
  63238. /**
  63239. * Get SVG element.
  63240. *
  63241. * @param {Displayable} displayable displayable element
  63242. * @return {SVGElement} SVG element
  63243. */
  63244. Definable.prototype.getSvgElement = function (displayable) {
  63245. return displayable.__svgEl;
  63246. };
  63247. /**
  63248. * @file Manages SVG gradient elements.
  63249. * @author Zhang Wenli
  63250. */
  63251. /**
  63252. * Manages SVG gradient elements.
  63253. *
  63254. * @class
  63255. * @extends Definable
  63256. * @param {SVGElement} svgRoot root of SVG document
  63257. */
  63258. function GradientManager(svgRoot) {
  63259. Definable.call(
  63260. this,
  63261. svgRoot,
  63262. ['linearGradient', 'radialGradient'],
  63263. '__gradient_in_use__'
  63264. );
  63265. }
  63266. inherits(GradientManager, Definable);
  63267. /**
  63268. * Create new gradient DOM for fill or stroke if not exist,
  63269. * but will not update gradient if exists.
  63270. *
  63271. * @param {SvgElement} svgElement SVG element to paint
  63272. * @param {Displayable} displayable zrender displayable element
  63273. */
  63274. GradientManager.prototype.addWithoutUpdate = function (
  63275. svgElement,
  63276. displayable
  63277. ) {
  63278. if (displayable && displayable.style) {
  63279. var that = this;
  63280. each$1(['fill', 'stroke'], function (fillOrStroke) {
  63281. if (displayable.style[fillOrStroke]
  63282. && (displayable.style[fillOrStroke].type === 'linear'
  63283. || displayable.style[fillOrStroke].type === 'radial')
  63284. ) {
  63285. var gradient = displayable.style[fillOrStroke];
  63286. var defs = that.getDefs(true);
  63287. // Create dom in <defs> if not exists
  63288. var dom;
  63289. if (gradient._dom) {
  63290. // Gradient exists
  63291. dom = gradient._dom;
  63292. if (!defs.contains(gradient._dom)) {
  63293. // _dom is no longer in defs, recreate
  63294. that.addDom(dom);
  63295. }
  63296. }
  63297. else {
  63298. // New dom
  63299. dom = that.add(gradient);
  63300. }
  63301. that.markUsed(displayable);
  63302. var id = dom.getAttribute('id');
  63303. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  63304. }
  63305. });
  63306. }
  63307. };
  63308. /**
  63309. * Add a new gradient tag in <defs>
  63310. *
  63311. * @param {Gradient} gradient zr gradient instance
  63312. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  63313. * created DOM
  63314. */
  63315. GradientManager.prototype.add = function (gradient) {
  63316. var dom;
  63317. if (gradient.type === 'linear') {
  63318. dom = this.createElement('linearGradient');
  63319. }
  63320. else if (gradient.type === 'radial') {
  63321. dom = this.createElement('radialGradient');
  63322. }
  63323. else {
  63324. zrLog('Illegal gradient type.');
  63325. return null;
  63326. }
  63327. // Set dom id with gradient id, since each gradient instance
  63328. // will have no more than one dom element.
  63329. // id may exists before for those dirty elements, in which case
  63330. // id should remain the same, and other attributes should be
  63331. // updated.
  63332. gradient.id = gradient.id || this.nextId++;
  63333. dom.setAttribute('id', 'zr-gradient-' + gradient.id);
  63334. this.updateDom(gradient, dom);
  63335. this.addDom(dom);
  63336. return dom;
  63337. };
  63338. /**
  63339. * Update gradient.
  63340. *
  63341. * @param {Gradient} gradient zr gradient instance
  63342. */
  63343. GradientManager.prototype.update = function (gradient) {
  63344. var that = this;
  63345. Definable.prototype.update.call(this, gradient, function () {
  63346. var type = gradient.type;
  63347. var tagName = gradient._dom.tagName;
  63348. if (type === 'linear' && tagName === 'linearGradient'
  63349. || type === 'radial' && tagName === 'radialGradient'
  63350. ) {
  63351. // Gradient type is not changed, update gradient
  63352. that.updateDom(gradient, gradient._dom);
  63353. }
  63354. else {
  63355. // Remove and re-create if type is changed
  63356. that.removeDom(gradient);
  63357. that.add(gradient);
  63358. }
  63359. });
  63360. };
  63361. /**
  63362. * Update gradient dom
  63363. *
  63364. * @param {Gradient} gradient zr gradient instance
  63365. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  63366. * DOM to update
  63367. */
  63368. GradientManager.prototype.updateDom = function (gradient, dom) {
  63369. if (gradient.type === 'linear') {
  63370. dom.setAttribute('x1', gradient.x);
  63371. dom.setAttribute('y1', gradient.y);
  63372. dom.setAttribute('x2', gradient.x2);
  63373. dom.setAttribute('y2', gradient.y2);
  63374. }
  63375. else if (gradient.type === 'radial') {
  63376. dom.setAttribute('cx', gradient.x);
  63377. dom.setAttribute('cy', gradient.y);
  63378. dom.setAttribute('r', gradient.r);
  63379. }
  63380. else {
  63381. zrLog('Illegal gradient type.');
  63382. return;
  63383. }
  63384. if (gradient.global) {
  63385. // x1, x2, y1, y2 in range of 0 to canvas width or height
  63386. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  63387. }
  63388. else {
  63389. // x1, x2, y1, y2 in range of 0 to 1
  63390. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  63391. }
  63392. // Remove color stops if exists
  63393. dom.innerHTML = '';
  63394. // Add color stops
  63395. var colors = gradient.colorStops;
  63396. for (var i = 0, len = colors.length; i < len; ++i) {
  63397. var stop = this.createElement('stop');
  63398. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  63399. stop.setAttribute('stop-color', colors[i].color);
  63400. dom.appendChild(stop);
  63401. }
  63402. // Store dom element in gradient, to avoid creating multiple
  63403. // dom instances for the same gradient element
  63404. gradient._dom = dom;
  63405. };
  63406. /**
  63407. * Mark a single gradient to be used
  63408. *
  63409. * @param {Displayable} displayable displayable element
  63410. */
  63411. GradientManager.prototype.markUsed = function (displayable) {
  63412. if (displayable.style) {
  63413. var gradient = displayable.style.fill;
  63414. if (gradient && gradient._dom) {
  63415. Definable.prototype.markUsed.call(this, gradient._dom);
  63416. }
  63417. gradient = displayable.style.stroke;
  63418. if (gradient && gradient._dom) {
  63419. Definable.prototype.markUsed.call(this, gradient._dom);
  63420. }
  63421. }
  63422. };
  63423. /**
  63424. * @file Manages SVG clipPath elements.
  63425. * @author Zhang Wenli
  63426. */
  63427. /**
  63428. * Manages SVG clipPath elements.
  63429. *
  63430. * @class
  63431. * @extends Definable
  63432. * @param {SVGElement} svgRoot root of SVG document
  63433. */
  63434. function ClippathManager(svgRoot) {
  63435. Definable.call(this, svgRoot, 'clipPath', '__clippath_in_use__');
  63436. }
  63437. inherits(ClippathManager, Definable);
  63438. /**
  63439. * Update clipPath.
  63440. *
  63441. * @param {Displayable} displayable displayable element
  63442. */
  63443. ClippathManager.prototype.update = function (displayable) {
  63444. var svgEl = this.getSvgElement(displayable);
  63445. if (svgEl) {
  63446. this.updateDom(svgEl, displayable.__clipPaths, false);
  63447. }
  63448. var textEl = this.getTextSvgElement(displayable);
  63449. if (textEl) {
  63450. // Make another clipPath for text, since it's transform
  63451. // matrix is not the same with svgElement
  63452. this.updateDom(textEl, displayable.__clipPaths, true);
  63453. }
  63454. this.markUsed(displayable);
  63455. };
  63456. /**
  63457. * Create an SVGElement of displayable and create a <clipPath> of its
  63458. * clipPath
  63459. *
  63460. * @param {Displayable} parentEl parent element
  63461. * @param {ClipPath[]} clipPaths clipPaths of parent element
  63462. * @param {boolean} isText if parent element is Text
  63463. */
  63464. ClippathManager.prototype.updateDom = function (
  63465. parentEl,
  63466. clipPaths,
  63467. isText
  63468. ) {
  63469. if (clipPaths && clipPaths.length > 0) {
  63470. // Has clipPath, create <clipPath> with the first clipPath
  63471. var defs = this.getDefs(true);
  63472. var clipPath = clipPaths[0];
  63473. var clipPathEl;
  63474. var id;
  63475. var dom = isText ? '_textDom' : '_dom';
  63476. if (clipPath[dom]) {
  63477. // Use a dom that is already in <defs>
  63478. id = clipPath[dom].getAttribute('id');
  63479. clipPathEl = clipPath[dom];
  63480. // Use a dom that is already in <defs>
  63481. if (!defs.contains(clipPathEl)) {
  63482. // This happens when set old clipPath that has
  63483. // been previously removed
  63484. defs.appendChild(clipPathEl);
  63485. }
  63486. }
  63487. else {
  63488. // New <clipPath>
  63489. id = 'zr-clip-' + this.nextId;
  63490. ++this.nextId;
  63491. clipPathEl = this.createElement('clipPath');
  63492. clipPathEl.setAttribute('id', id);
  63493. defs.appendChild(clipPathEl);
  63494. clipPath[dom] = clipPathEl;
  63495. }
  63496. // Build path and add to <clipPath>
  63497. var svgProxy = this.getSvgProxy(clipPath);
  63498. if (clipPath.transform
  63499. && clipPath.parent.invTransform
  63500. && !isText
  63501. ) {
  63502. /**
  63503. * If a clipPath has a parent with transform, the transform
  63504. * of parent should not be considered when setting transform
  63505. * of clipPath. So we need to transform back from parent's
  63506. * transform, which is done by multiplying parent's inverse
  63507. * transform.
  63508. */
  63509. // Store old transform
  63510. var transform = Array.prototype.slice.call(
  63511. clipPath.transform
  63512. );
  63513. // Transform back from parent, and brush path
  63514. mul$1(
  63515. clipPath.transform,
  63516. clipPath.parent.invTransform,
  63517. clipPath.transform
  63518. );
  63519. svgProxy.brush(clipPath);
  63520. // Set back transform of clipPath
  63521. clipPath.transform = transform;
  63522. }
  63523. else {
  63524. svgProxy.brush(clipPath);
  63525. }
  63526. var pathEl = this.getSvgElement(clipPath);
  63527. /**
  63528. * Use `cloneNode()` here to appendChild to multiple parents,
  63529. * which may happend when Text and other shapes are using the same
  63530. * clipPath. Since Text will create an extra clipPath DOM due to
  63531. * different transform rules.
  63532. */
  63533. clipPathEl.appendChild(pathEl.cloneNode());
  63534. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  63535. if (clipPaths.length > 1) {
  63536. // Make the other clipPaths recursively
  63537. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  63538. }
  63539. }
  63540. else {
  63541. // No clipPath
  63542. if (parentEl) {
  63543. parentEl.setAttribute('clip-path', 'none');
  63544. }
  63545. }
  63546. };
  63547. /**
  63548. * Mark a single clipPath to be used
  63549. *
  63550. * @param {Displayable} displayable displayable element
  63551. */
  63552. ClippathManager.prototype.markUsed = function (displayable) {
  63553. var that = this;
  63554. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  63555. each$1(displayable.__clipPaths, function (clipPath) {
  63556. if (clipPath._dom) {
  63557. Definable.prototype.markUsed.call(that, clipPath._dom);
  63558. }
  63559. if (clipPath._textDom) {
  63560. Definable.prototype.markUsed.call(that, clipPath._textDom);
  63561. }
  63562. });
  63563. }
  63564. };
  63565. /**
  63566. * SVG Painter
  63567. * @module zrender/svg/Painter
  63568. */
  63569. function parseInt10$2(val) {
  63570. return parseInt(val, 10);
  63571. }
  63572. function getSvgProxy(el) {
  63573. if (el instanceof Path) {
  63574. return svgPath;
  63575. }
  63576. else if (el instanceof ZImage) {
  63577. return svgImage;
  63578. }
  63579. else if (el instanceof Text) {
  63580. return svgText;
  63581. }
  63582. else {
  63583. return svgPath;
  63584. }
  63585. }
  63586. function checkParentAvailable(parent, child) {
  63587. return child && parent && child.parentNode !== parent;
  63588. }
  63589. function insertAfter(parent, child, prevSibling) {
  63590. if (checkParentAvailable(parent, child) && prevSibling) {
  63591. var nextSibling = prevSibling.nextSibling;
  63592. nextSibling ? parent.insertBefore(child, nextSibling)
  63593. : parent.appendChild(child);
  63594. }
  63595. }
  63596. function prepend(parent, child) {
  63597. if (checkParentAvailable(parent, child)) {
  63598. var firstChild = parent.firstChild;
  63599. firstChild ? parent.insertBefore(child, firstChild)
  63600. : parent.appendChild(child);
  63601. }
  63602. }
  63603. function remove$1(parent, child) {
  63604. if (child && parent && child.parentNode === parent) {
  63605. parent.removeChild(child);
  63606. }
  63607. }
  63608. function getTextSvgElement(displayable) {
  63609. return displayable.__textSvgEl;
  63610. }
  63611. function getSvgElement(displayable) {
  63612. return displayable.__svgEl;
  63613. }
  63614. /**
  63615. * @alias module:zrender/svg/Painter
  63616. */
  63617. var SVGPainter = function (root, storage) {
  63618. this.root = root;
  63619. this.storage = storage;
  63620. var svgRoot = createElement('svg');
  63621. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  63622. svgRoot.setAttribute('version', '1.1');
  63623. svgRoot.setAttribute('baseProfile', 'full');
  63624. svgRoot.style['user-select'] = 'none';
  63625. this.gradientManager = new GradientManager(svgRoot);
  63626. this.clipPathManager = new ClippathManager(svgRoot);
  63627. var viewport = document.createElement('div');
  63628. viewport.style.cssText = 'overflow: hidden;';
  63629. this._svgRoot = svgRoot;
  63630. this._viewport = viewport;
  63631. root.appendChild(viewport);
  63632. viewport.appendChild(svgRoot);
  63633. this.resize();
  63634. this._visibleList = [];
  63635. };
  63636. SVGPainter.prototype = {
  63637. constructor: SVGPainter,
  63638. getType: function () {
  63639. return 'svg';
  63640. },
  63641. getViewportRoot: function () {
  63642. return this._viewport;
  63643. },
  63644. getViewportRootOffset: function () {
  63645. var viewportRoot = this.getViewportRoot();
  63646. if (viewportRoot) {
  63647. return {
  63648. offsetLeft: viewportRoot.offsetLeft || 0,
  63649. offsetTop: viewportRoot.offsetTop || 0
  63650. };
  63651. }
  63652. },
  63653. refresh: function () {
  63654. var list = this.storage.getDisplayList(true);
  63655. this._paintList(list);
  63656. },
  63657. _paintList: function (list) {
  63658. this.gradientManager.markAllUnused();
  63659. this.clipPathManager.markAllUnused();
  63660. var svgRoot = this._svgRoot;
  63661. var visibleList = this._visibleList;
  63662. var listLen = list.length;
  63663. var newVisibleList = [];
  63664. var i;
  63665. for (i = 0; i < listLen; i++) {
  63666. var displayable = list[i];
  63667. var svgProxy = getSvgProxy(displayable);
  63668. if (!displayable.invisible) {
  63669. if (displayable.__dirty) {
  63670. svgProxy && svgProxy.brush(displayable);
  63671. // Update clipPath
  63672. this.clipPathManager.update(displayable);
  63673. // Update gradient
  63674. if (displayable.style) {
  63675. this.gradientManager
  63676. .update(displayable.style.fill);
  63677. this.gradientManager
  63678. .update(displayable.style.stroke);
  63679. }
  63680. displayable.__dirty = false;
  63681. }
  63682. newVisibleList.push(displayable);
  63683. }
  63684. }
  63685. var diff = arrayDiff$1(visibleList, newVisibleList);
  63686. var prevSvgElement;
  63687. // First do remove, in case element moved to the head and do remove
  63688. // after add
  63689. for (i = 0; i < diff.length; i++) {
  63690. var item = diff[i];
  63691. if (item.removed) {
  63692. for (var k = 0; k < item.count; k++) {
  63693. var displayable = visibleList[item.indices[k]];
  63694. var svgElement = getSvgElement(displayable);
  63695. var textSvgElement = getTextSvgElement(displayable);
  63696. remove$1(svgRoot, svgElement);
  63697. remove$1(svgRoot, textSvgElement);
  63698. }
  63699. }
  63700. }
  63701. for (i = 0; i < diff.length; i++) {
  63702. var item = diff[i];
  63703. if (item.added) {
  63704. for (var k = 0; k < item.count; k++) {
  63705. var displayable = newVisibleList[item.indices[k]];
  63706. var svgElement = getSvgElement(displayable);
  63707. var textSvgElement = getTextSvgElement(displayable);
  63708. prevSvgElement
  63709. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  63710. : prepend(svgRoot, svgElement);
  63711. if (svgElement) {
  63712. insertAfter(svgRoot, textSvgElement, svgElement);
  63713. }
  63714. else if (prevSvgElement) {
  63715. insertAfter(
  63716. svgRoot, textSvgElement, prevSvgElement
  63717. );
  63718. }
  63719. else {
  63720. prepend(svgRoot, textSvgElement);
  63721. }
  63722. // Insert text
  63723. insertAfter(svgRoot, textSvgElement, svgElement);
  63724. prevSvgElement = textSvgElement || svgElement
  63725. || prevSvgElement;
  63726. this.gradientManager
  63727. .addWithoutUpdate(svgElement, displayable);
  63728. this.clipPathManager.markUsed(displayable);
  63729. }
  63730. }
  63731. else if (!item.removed) {
  63732. for (var k = 0; k < item.count; k++) {
  63733. var displayable = newVisibleList[item.indices[k]];
  63734. prevSvgElement
  63735. = svgElement
  63736. = getTextSvgElement(displayable)
  63737. || getSvgElement(displayable)
  63738. || prevSvgElement;
  63739. this.gradientManager.markUsed(displayable);
  63740. this.gradientManager
  63741. .addWithoutUpdate(svgElement, displayable);
  63742. this.clipPathManager.markUsed(displayable);
  63743. }
  63744. }
  63745. }
  63746. this.gradientManager.removeUnused();
  63747. this.clipPathManager.removeUnused();
  63748. this._visibleList = newVisibleList;
  63749. },
  63750. _getDefs: function (isForceCreating) {
  63751. var svgRoot = this._svgRoot;
  63752. var defs = this._svgRoot.getElementsByTagName('defs');
  63753. if (defs.length === 0) {
  63754. // Not exist
  63755. if (isForceCreating) {
  63756. var defs = svgRoot.insertBefore(
  63757. createElement('defs'), // Create new tag
  63758. svgRoot.firstChild // Insert in the front of svg
  63759. );
  63760. if (!defs.contains) {
  63761. // IE doesn't support contains method
  63762. defs.contains = function (el) {
  63763. var children = defs.children;
  63764. if (!children) {
  63765. return false;
  63766. }
  63767. for (var i = children.length - 1; i >= 0; --i) {
  63768. if (children[i] === el) {
  63769. return true;
  63770. }
  63771. }
  63772. return false;
  63773. };
  63774. }
  63775. return defs;
  63776. }
  63777. else {
  63778. return null;
  63779. }
  63780. }
  63781. else {
  63782. return defs[0];
  63783. }
  63784. },
  63785. resize: function () {
  63786. var width = this._getWidth();
  63787. var height = this._getHeight();
  63788. if (this._width !== width && this._height !== height) {
  63789. this._width = width;
  63790. this._height = height;
  63791. var viewportStyle = this._viewport.style;
  63792. viewportStyle.width = width + 'px';
  63793. viewportStyle.height = height + 'px';
  63794. var svgRoot = this._svgRoot;
  63795. // Set width by 'svgRoot.width = width' is invalid
  63796. svgRoot.setAttribute('width', width);
  63797. svgRoot.setAttribute('height', height);
  63798. }
  63799. },
  63800. getWidth: function () {
  63801. return this._getWidth();
  63802. },
  63803. getHeight: function () {
  63804. return this._getHeight();
  63805. },
  63806. _getWidth: function () {
  63807. var root = this.root;
  63808. var stl = document.defaultView.getComputedStyle(root);
  63809. return ((root.clientWidth || parseInt10$2(stl.width))
  63810. - parseInt10$2(stl.paddingLeft)
  63811. - parseInt10$2(stl.paddingRight)) | 0;
  63812. },
  63813. _getHeight: function () {
  63814. var root = this.root;
  63815. var stl = document.defaultView.getComputedStyle(root);
  63816. return ((root.clientHeight || parseInt10$2(stl.height))
  63817. - parseInt10$2(stl.paddingTop)
  63818. - parseInt10$2(stl.paddingBottom)) | 0;
  63819. },
  63820. dispose: function () {
  63821. this.root.innerHTML = '';
  63822. this._svgRoot
  63823. = this._viewport
  63824. = this.storage
  63825. = null;
  63826. },
  63827. clear: function () {
  63828. if (this._viewport) {
  63829. this.root.removeChild(this._viewport);
  63830. }
  63831. },
  63832. pathToSvg: function () {
  63833. this.refresh();
  63834. var html = this._svgRoot.outerHTML;
  63835. return 'data:img/svg+xml;utf-8,' + unescape(html);
  63836. }
  63837. };
  63838. // Not supported methods
  63839. function createMethodNotSupport$1(method) {
  63840. return function () {
  63841. zrLog('In SVG mode painter not support method "' + method + '"');
  63842. };
  63843. }
  63844. // Unsuppoted methods
  63845. each$1([
  63846. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  63847. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  63848. 'toDataURL', 'pathToImage'
  63849. ], function (name) {
  63850. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  63851. });
  63852. registerPainter('svg', SVGPainter);
  63853. // Import all charts and components
  63854. exports.version = version;
  63855. exports.dependencies = dependencies;
  63856. exports.PRIORITY = PRIORITY;
  63857. exports.init = init;
  63858. exports.connect = connect;
  63859. exports.disConnect = disConnect;
  63860. exports.disconnect = disconnect;
  63861. exports.dispose = dispose;
  63862. exports.getInstanceByDom = getInstanceByDom;
  63863. exports.getInstanceById = getInstanceById;
  63864. exports.registerTheme = registerTheme;
  63865. exports.registerPreprocessor = registerPreprocessor;
  63866. exports.registerProcessor = registerProcessor;
  63867. exports.registerPostUpdate = registerPostUpdate;
  63868. exports.registerAction = registerAction;
  63869. exports.registerCoordinateSystem = registerCoordinateSystem;
  63870. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  63871. exports.registerLayout = registerLayout;
  63872. exports.registerVisual = registerVisual;
  63873. exports.registerLoading = registerLoading;
  63874. exports.extendComponentModel = extendComponentModel;
  63875. exports.extendComponentView = extendComponentView;
  63876. exports.extendSeriesModel = extendSeriesModel;
  63877. exports.extendChartView = extendChartView;
  63878. exports.setCanvasCreator = setCanvasCreator;
  63879. exports.registerMap = registerMap;
  63880. exports.getMap = getMap;
  63881. exports.dataTool = dataTool;
  63882. exports.zrender = zrender;
  63883. exports.graphic = graphic;
  63884. exports.number = number;
  63885. exports.format = format;
  63886. exports.throttle = throttle;
  63887. exports.helper = helper;
  63888. exports.matrix = matrix;
  63889. exports.vector = vector;
  63890. exports.color = color;
  63891. exports.util = ecUtil;
  63892. exports.List = List;
  63893. exports.Model = Model;
  63894. exports.Axis = Axis;
  63895. exports.env = env$1;
  63896. exports.parseGeoJson = parseGeoJson;
  63897. })));
  63898. //# sourceMappingURL=echarts.js.map