echarts.js 2.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803
  1. /*!
  2. * Copyright (c) 2017 Sumit Kumar
  3. * echarts(https://github.com/apache/incubator-echarts)
  4. * license: Apache2.0
  5. * version: v3.8.5
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  9. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  10. (factory((global.echarts = {})));
  11. }(this, (function (exports) { 'use strict';
  12. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  13. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  14. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  15. // declaration is behind of the using position (for example in `Model.extent`,
  16. // And tools like rollup can not analysis the dependency if not import).
  17. var dev;
  18. // In browser
  19. if (typeof window !== 'undefined') {
  20. dev = window.__DEV__;
  21. }
  22. // In node
  23. else if (typeof global !== 'undefined') {
  24. dev = global.__DEV__;
  25. }
  26. if (typeof dev === 'undefined') {
  27. dev = true;
  28. }
  29. var __DEV__ = dev;
  30. /**
  31. * zrender: 生成唯一id
  32. *
  33. * @author errorrik (errorrik@gmail.com)
  34. */
  35. var idStart = 0x0907;
  36. var guid = function () {
  37. return idStart++;
  38. };
  39. /**
  40. * echarts设备环境识别
  41. *
  42. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  43. * @author firede[firede@firede.us]
  44. * @desc thanks zepto.
  45. */
  46. var env = {};
  47. if (typeof navigator === 'undefined') {
  48. // In node
  49. env = {
  50. browser: {},
  51. os: {},
  52. node: true,
  53. // Assume canvas is supported
  54. canvasSupported: true,
  55. svgSupported: true
  56. };
  57. }
  58. else {
  59. env = detect(navigator.userAgent);
  60. }
  61. var env$1 = env;
  62. // Zepto.js
  63. // (c) 2010-2013 Thomas Fuchs
  64. // Zepto.js may be freely distributed under the MIT license.
  65. function detect(ua) {
  66. var os = {};
  67. var browser = {};
  68. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  69. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  70. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  71. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  72. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  73. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  74. // var touchpad = webos && ua.match(/TouchPad/);
  75. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  76. // var silk = ua.match(/Silk\/([\d._]+)/);
  77. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  78. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  79. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  80. // var playbook = ua.match(/PlayBook/);
  81. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  82. var firefox = ua.match(/Firefox\/([\d.]+)/);
  83. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  84. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  85. var ie = ua.match(/MSIE\s([\d.]+)/)
  86. // IE 11 Trident/7.0; rv:11.0
  87. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  88. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  89. var weChat = (/micromessenger/i).test(ua);
  90. // Todo: clean this up with a better OS/browser seperation:
  91. // - discern (more) between multiple browsers on android
  92. // - decide if kindle fire in silk mode is android or not
  93. // - Firefox on Android doesn't specify the Android version
  94. // - possibly devide in os, device and browser hashes
  95. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  96. // if (android) os.android = true, os.version = android[2];
  97. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  98. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  99. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  100. // if (webos) os.webos = true, os.version = webos[2];
  101. // if (touchpad) os.touchpad = true;
  102. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  103. // if (bb10) os.bb10 = true, os.version = bb10[2];
  104. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  105. // if (playbook) browser.playbook = true;
  106. // if (kindle) os.kindle = true, os.version = kindle[1];
  107. // if (silk) browser.silk = true, browser.version = silk[1];
  108. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  109. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  110. if (firefox) {
  111. browser.firefox = true;
  112. browser.version = firefox[1];
  113. }
  114. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  115. // if (webview) browser.webview = true;
  116. if (ie) {
  117. browser.ie = true;
  118. browser.version = ie[1];
  119. }
  120. if (edge) {
  121. browser.edge = true;
  122. browser.version = edge[1];
  123. }
  124. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  125. // not be set on win phone. So we do not consider Win Phone.
  126. if (weChat) {
  127. browser.weChat = true;
  128. }
  129. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  130. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  131. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  132. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  133. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  134. return {
  135. browser: browser,
  136. os: os,
  137. node: false,
  138. // 原生canvas支持,改极端点了
  139. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  140. canvasSupported: !!document.createElement('canvas').getContext,
  141. svgSupported: typeof SVGRect !== 'undefined',
  142. // @see <http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript>
  143. // works on most browsers
  144. // IE10/11 does not support touch event, and MS Edge supports them but not by
  145. // default, so we dont check navigator.maxTouchPoints for them here.
  146. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  147. // <http://caniuse.com/#search=pointer%20event>.
  148. pointerEventsSupported: 'onpointerdown' in window
  149. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  150. // events currently. So we dont use that on other browsers unless tested sufficiently.
  151. // Although IE 10 supports pointer event, it use old style and is different from the
  152. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  153. && (browser.edge || (browser.ie && browser.version >= 11))
  154. };
  155. }
  156. /**
  157. * @module zrender/core/util
  158. */
  159. // 用于处理merge时无法遍历Date等对象的问题
  160. var BUILTIN_OBJECT = {
  161. '[object Function]': 1,
  162. '[object RegExp]': 1,
  163. '[object Date]': 1,
  164. '[object Error]': 1,
  165. '[object CanvasGradient]': 1,
  166. '[object CanvasPattern]': 1,
  167. // For node-canvas
  168. '[object Image]': 1,
  169. '[object Canvas]': 1
  170. };
  171. var TYPED_ARRAY = {
  172. '[object Int8Array]': 1,
  173. '[object Uint8Array]': 1,
  174. '[object Uint8ClampedArray]': 1,
  175. '[object Int16Array]': 1,
  176. '[object Uint16Array]': 1,
  177. '[object Int32Array]': 1,
  178. '[object Uint32Array]': 1,
  179. '[object Float32Array]': 1,
  180. '[object Float64Array]': 1
  181. };
  182. var objToString = Object.prototype.toString;
  183. var arrayProto = Array.prototype;
  184. var nativeForEach = arrayProto.forEach;
  185. var nativeFilter = arrayProto.filter;
  186. var nativeSlice = arrayProto.slice;
  187. var nativeMap = arrayProto.map;
  188. var nativeReduce = arrayProto.reduce;
  189. // Avoid assign to an exported variable, for transforming to cjs.
  190. var methods = {};
  191. function $override(name, fn) {
  192. methods[name] = fn;
  193. }
  194. /**
  195. * Those data types can be cloned:
  196. * Plain object, Array, TypedArray, number, string, null, undefined.
  197. * Those data types will be assgined using the orginal data:
  198. * BUILTIN_OBJECT
  199. * Instance of user defined class will be cloned to a plain object, without
  200. * properties in prototype.
  201. * Other data types is not supported (not sure what will happen).
  202. *
  203. * Caution: do not support clone Date, for performance consideration.
  204. * (There might be a large number of date in `series.data`).
  205. * So date should not be modified in and out of echarts.
  206. *
  207. * @param {*} source
  208. * @return {*} new
  209. */
  210. function clone(source) {
  211. if (source == null || typeof source != 'object') {
  212. return source;
  213. }
  214. var result = source;
  215. var typeStr = objToString.call(source);
  216. if (typeStr === '[object Array]') {
  217. result = [];
  218. for (var i = 0, len = source.length; i < len; i++) {
  219. result[i] = clone(source[i]);
  220. }
  221. }
  222. else if (TYPED_ARRAY[typeStr]) {
  223. var Ctor = source.constructor;
  224. if (source.constructor.from) {
  225. result = Ctor.from(source);
  226. }
  227. else {
  228. result = new Ctor(source.length);
  229. for (var i = 0, len = source.length; i < len; i++) {
  230. result[i] = clone(source[i]);
  231. }
  232. }
  233. }
  234. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  235. result = {};
  236. for (var key in source) {
  237. if (source.hasOwnProperty(key)) {
  238. result[key] = clone(source[key]);
  239. }
  240. }
  241. }
  242. return result;
  243. }
  244. /**
  245. * @memberOf module:zrender/core/util
  246. * @param {*} target
  247. * @param {*} source
  248. * @param {boolean} [overwrite=false]
  249. */
  250. function merge(target, source, overwrite) {
  251. // We should escapse that source is string
  252. // and enter for ... in ...
  253. if (!isObject(source) || !isObject(target)) {
  254. return overwrite ? clone(source) : target;
  255. }
  256. for (var key in source) {
  257. if (source.hasOwnProperty(key)) {
  258. var targetProp = target[key];
  259. var sourceProp = source[key];
  260. if (isObject(sourceProp)
  261. && isObject(targetProp)
  262. && !isArray(sourceProp)
  263. && !isArray(targetProp)
  264. && !isDom(sourceProp)
  265. && !isDom(targetProp)
  266. && !isBuiltInObject(sourceProp)
  267. && !isBuiltInObject(targetProp)
  268. && !isPrimitive(sourceProp)
  269. && !isPrimitive(targetProp)
  270. ) {
  271. // 如果需要递归覆盖,就递归调用merge
  272. merge(targetProp, sourceProp, overwrite);
  273. }
  274. else if (overwrite || !(key in target)) {
  275. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  276. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  277. target[key] = clone(source[key], true);
  278. }
  279. }
  280. }
  281. return target;
  282. }
  283. /**
  284. * @param {Array} targetAndSources The first item is target, and the rests are source.
  285. * @param {boolean} [overwrite=false]
  286. * @return {*} target
  287. */
  288. function mergeAll(targetAndSources, overwrite) {
  289. var result = targetAndSources[0];
  290. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  291. result = merge(result, targetAndSources[i], overwrite);
  292. }
  293. return result;
  294. }
  295. /**
  296. * @param {*} target
  297. * @param {*} source
  298. * @memberOf module:zrender/core/util
  299. */
  300. function extend(target, source) {
  301. for (var key in source) {
  302. if (source.hasOwnProperty(key)) {
  303. target[key] = source[key];
  304. }
  305. }
  306. return target;
  307. }
  308. /**
  309. * @param {*} target
  310. * @param {*} source
  311. * @param {boolean} [overlay=false]
  312. * @memberOf module:zrender/core/util
  313. */
  314. function defaults(target, source, overlay) {
  315. for (var key in source) {
  316. if (source.hasOwnProperty(key)
  317. && (overlay ? source[key] != null : target[key] == null)
  318. ) {
  319. target[key] = source[key];
  320. }
  321. }
  322. return target;
  323. }
  324. var createCanvas = function () {
  325. return methods.createCanvas();
  326. };
  327. methods.createCanvas = function () {
  328. return document.createElement('canvas');
  329. };
  330. // FIXME
  331. var _ctx;
  332. function getContext() {
  333. if (!_ctx) {
  334. // Use util.createCanvas instead of createCanvas
  335. // because createCanvas may be overwritten in different environment
  336. _ctx = createCanvas().getContext('2d');
  337. }
  338. return _ctx;
  339. }
  340. /**
  341. * 查询数组中元素的index
  342. * @memberOf module:zrender/core/util
  343. */
  344. function indexOf(array, value) {
  345. if (array) {
  346. if (array.indexOf) {
  347. return array.indexOf(value);
  348. }
  349. for (var i = 0, len = array.length; i < len; i++) {
  350. if (array[i] === value) {
  351. return i;
  352. }
  353. }
  354. }
  355. return -1;
  356. }
  357. /**
  358. * 构造类继承关系
  359. *
  360. * @memberOf module:zrender/core/util
  361. * @param {Function} clazz 源类
  362. * @param {Function} baseClazz 基类
  363. */
  364. function inherits(clazz, baseClazz) {
  365. var clazzPrototype = clazz.prototype;
  366. function F() {}
  367. F.prototype = baseClazz.prototype;
  368. clazz.prototype = new F();
  369. for (var prop in clazzPrototype) {
  370. clazz.prototype[prop] = clazzPrototype[prop];
  371. }
  372. clazz.prototype.constructor = clazz;
  373. clazz.superClass = baseClazz;
  374. }
  375. /**
  376. * @memberOf module:zrender/core/util
  377. * @param {Object|Function} target
  378. * @param {Object|Function} sorce
  379. * @param {boolean} overlay
  380. */
  381. function mixin(target, source, overlay) {
  382. target = 'prototype' in target ? target.prototype : target;
  383. source = 'prototype' in source ? source.prototype : source;
  384. defaults(target, source, overlay);
  385. }
  386. /**
  387. * Consider typed array.
  388. * @param {Array|TypedArray} data
  389. */
  390. function isArrayLike(data) {
  391. if (! data) {
  392. return;
  393. }
  394. if (typeof data == 'string') {
  395. return false;
  396. }
  397. return typeof data.length == 'number';
  398. }
  399. /**
  400. * 数组或对象遍历
  401. * @memberOf module:zrender/core/util
  402. * @param {Object|Array} obj
  403. * @param {Function} cb
  404. * @param {*} [context]
  405. */
  406. function each$1(obj, cb, context) {
  407. if (!(obj && cb)) {
  408. return;
  409. }
  410. if (obj.forEach && obj.forEach === nativeForEach) {
  411. obj.forEach(cb, context);
  412. }
  413. else if (obj.length === +obj.length) {
  414. for (var i = 0, len = obj.length; i < len; i++) {
  415. cb.call(context, obj[i], i, obj);
  416. }
  417. }
  418. else {
  419. for (var key in obj) {
  420. if (obj.hasOwnProperty(key)) {
  421. cb.call(context, obj[key], key, obj);
  422. }
  423. }
  424. }
  425. }
  426. /**
  427. * 数组映射
  428. * @memberOf module:zrender/core/util
  429. * @param {Array} obj
  430. * @param {Function} cb
  431. * @param {*} [context]
  432. * @return {Array}
  433. */
  434. function map(obj, cb, context) {
  435. if (!(obj && cb)) {
  436. return;
  437. }
  438. if (obj.map && obj.map === nativeMap) {
  439. return obj.map(cb, context);
  440. }
  441. else {
  442. var result = [];
  443. for (var i = 0, len = obj.length; i < len; i++) {
  444. result.push(cb.call(context, obj[i], i, obj));
  445. }
  446. return result;
  447. }
  448. }
  449. /**
  450. * @memberOf module:zrender/core/util
  451. * @param {Array} obj
  452. * @param {Function} cb
  453. * @param {Object} [memo]
  454. * @param {*} [context]
  455. * @return {Array}
  456. */
  457. function reduce(obj, cb, memo, context) {
  458. if (!(obj && cb)) {
  459. return;
  460. }
  461. if (obj.reduce && obj.reduce === nativeReduce) {
  462. return obj.reduce(cb, memo, context);
  463. }
  464. else {
  465. for (var i = 0, len = obj.length; i < len; i++) {
  466. memo = cb.call(context, memo, obj[i], i, obj);
  467. }
  468. return memo;
  469. }
  470. }
  471. /**
  472. * 数组过滤
  473. * @memberOf module:zrender/core/util
  474. * @param {Array} obj
  475. * @param {Function} cb
  476. * @param {*} [context]
  477. * @return {Array}
  478. */
  479. function filter(obj, cb, context) {
  480. if (!(obj && cb)) {
  481. return;
  482. }
  483. if (obj.filter && obj.filter === nativeFilter) {
  484. return obj.filter(cb, context);
  485. }
  486. else {
  487. var result = [];
  488. for (var i = 0, len = obj.length; i < len; i++) {
  489. if (cb.call(context, obj[i], i, obj)) {
  490. result.push(obj[i]);
  491. }
  492. }
  493. return result;
  494. }
  495. }
  496. /**
  497. * 数组项查找
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {*}
  503. */
  504. function find(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. for (var i = 0, len = obj.length; i < len; i++) {
  509. if (cb.call(context, obj[i], i, obj)) {
  510. return obj[i];
  511. }
  512. }
  513. }
  514. /**
  515. * @memberOf module:zrender/core/util
  516. * @param {Function} func
  517. * @param {*} context
  518. * @return {Function}
  519. */
  520. function bind(func, context) {
  521. var args = nativeSlice.call(arguments, 2);
  522. return function () {
  523. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  524. };
  525. }
  526. /**
  527. * @memberOf module:zrender/core/util
  528. * @param {Function} func
  529. * @return {Function}
  530. */
  531. function curry(func) {
  532. var args = nativeSlice.call(arguments, 1);
  533. return function () {
  534. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  535. };
  536. }
  537. /**
  538. * @memberOf module:zrender/core/util
  539. * @param {*} value
  540. * @return {boolean}
  541. */
  542. function isArray(value) {
  543. return objToString.call(value) === '[object Array]';
  544. }
  545. /**
  546. * @memberOf module:zrender/core/util
  547. * @param {*} value
  548. * @return {boolean}
  549. */
  550. function isFunction(value) {
  551. return typeof value === 'function';
  552. }
  553. /**
  554. * @memberOf module:zrender/core/util
  555. * @param {*} value
  556. * @return {boolean}
  557. */
  558. function isString(value) {
  559. return objToString.call(value) === '[object String]';
  560. }
  561. /**
  562. * @memberOf module:zrender/core/util
  563. * @param {*} value
  564. * @return {boolean}
  565. */
  566. function isObject(value) {
  567. // Avoid a V8 JIT bug in Chrome 19-20.
  568. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  569. var type = typeof value;
  570. return type === 'function' || (!!value && type == 'object');
  571. }
  572. /**
  573. * @memberOf module:zrender/core/util
  574. * @param {*} value
  575. * @return {boolean}
  576. */
  577. function isBuiltInObject(value) {
  578. return !!BUILTIN_OBJECT[objToString.call(value)];
  579. }
  580. /**
  581. * @memberOf module:zrender/core/util
  582. * @param {*} value
  583. * @return {boolean}
  584. */
  585. function isDom(value) {
  586. return typeof value === 'object'
  587. && typeof value.nodeType === 'number'
  588. && typeof value.ownerDocument === 'object';
  589. }
  590. /**
  591. * Whether is exactly NaN. Notice isNaN('a') returns true.
  592. * @param {*} value
  593. * @return {boolean}
  594. */
  595. function eqNaN(value) {
  596. return value !== value;
  597. }
  598. /**
  599. * If value1 is not null, then return value1, otherwise judget rest of values.
  600. * Low performance.
  601. * @memberOf module:zrender/core/util
  602. * @return {*} Final value
  603. */
  604. function retrieve(values) {
  605. for (var i = 0, len = arguments.length; i < len; i++) {
  606. if (arguments[i] != null) {
  607. return arguments[i];
  608. }
  609. }
  610. }
  611. function retrieve2(value0, value1) {
  612. return value0 != null
  613. ? value0
  614. : value1;
  615. }
  616. function retrieve3(value0, value1, value2) {
  617. return value0 != null
  618. ? value0
  619. : value1 != null
  620. ? value1
  621. : value2;
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {Array} arr
  626. * @param {number} startIndex
  627. * @param {number} endIndex
  628. * @return {Array}
  629. */
  630. function slice() {
  631. return Function.call.apply(nativeSlice, arguments);
  632. }
  633. /**
  634. * Normalize css liked array configuration
  635. * e.g.
  636. * 3 => [3, 3, 3, 3]
  637. * [4, 2] => [4, 2, 4, 2]
  638. * [4, 3, 2] => [4, 3, 2, 3]
  639. * @param {number|Array.<number>} val
  640. * @return {Array.<number>}
  641. */
  642. function normalizeCssArray(val) {
  643. if (typeof (val) === 'number') {
  644. return [val, val, val, val];
  645. }
  646. var len = val.length;
  647. if (len === 2) {
  648. // vertical | horizontal
  649. return [val[0], val[1], val[0], val[1]];
  650. }
  651. else if (len === 3) {
  652. // top | horizontal | bottom
  653. return [val[0], val[1], val[2], val[1]];
  654. }
  655. return val;
  656. }
  657. /**
  658. * @memberOf module:zrender/core/util
  659. * @param {boolean} condition
  660. * @param {string} message
  661. */
  662. function assert(condition, message) {
  663. if (!condition) {
  664. throw new Error(message);
  665. }
  666. }
  667. var primitiveKey = '__ec_primitive__';
  668. /**
  669. * Set an object as primitive to be ignored traversing children in clone or merge
  670. */
  671. function setAsPrimitive(obj) {
  672. obj[primitiveKey] = true;
  673. }
  674. function isPrimitive(obj) {
  675. return obj[primitiveKey];
  676. }
  677. /**
  678. * @constructor
  679. * @param {Object} obj Only apply `ownProperty`.
  680. */
  681. function HashMap(obj) {
  682. obj && each$1(obj, function (value, key) {
  683. this.set(key, value);
  684. }, this);
  685. }
  686. // Add prefix to avoid conflict with Object.prototype.
  687. var HASH_MAP_PREFIX = '_ec_';
  688. var HASH_MAP_PREFIX_LENGTH = 4;
  689. HashMap.prototype = {
  690. constructor: HashMap,
  691. // Do not provide `has` method to avoid defining what is `has`.
  692. // (We usually treat `null` and `undefined` as the same, different
  693. // from ES6 Map).
  694. get: function (key) {
  695. return this[HASH_MAP_PREFIX + key];
  696. },
  697. set: function (key, value) {
  698. this[HASH_MAP_PREFIX + key] = value;
  699. // Comparing with invocation chaining, `return value` is more commonly
  700. // used in this case: `var someVal = map.set('a', genVal());`
  701. return value;
  702. },
  703. // Although util.each can be performed on this hashMap directly, user
  704. // should not use the exposed keys, who are prefixed.
  705. each: function (cb, context) {
  706. context !== void 0 && (cb = bind(cb, context));
  707. for (var prefixedKey in this) {
  708. this.hasOwnProperty(prefixedKey)
  709. && cb(this[prefixedKey], prefixedKey.slice(HASH_MAP_PREFIX_LENGTH));
  710. }
  711. },
  712. // Do not use this method if performance sensitive.
  713. removeKey: function (key) {
  714. delete this[HASH_MAP_PREFIX + key];
  715. }
  716. };
  717. function createHashMap(obj) {
  718. return new HashMap(obj);
  719. }
  720. function noop() {}
  721. var zrUtil = (Object.freeze || Object)({
  722. $override: $override,
  723. clone: clone,
  724. merge: merge,
  725. mergeAll: mergeAll,
  726. extend: extend,
  727. defaults: defaults,
  728. createCanvas: createCanvas,
  729. getContext: getContext,
  730. indexOf: indexOf,
  731. inherits: inherits,
  732. mixin: mixin,
  733. isArrayLike: isArrayLike,
  734. each: each$1,
  735. map: map,
  736. reduce: reduce,
  737. filter: filter,
  738. find: find,
  739. bind: bind,
  740. curry: curry,
  741. isArray: isArray,
  742. isFunction: isFunction,
  743. isString: isString,
  744. isObject: isObject,
  745. isBuiltInObject: isBuiltInObject,
  746. isDom: isDom,
  747. eqNaN: eqNaN,
  748. retrieve: retrieve,
  749. retrieve2: retrieve2,
  750. retrieve3: retrieve3,
  751. slice: slice,
  752. normalizeCssArray: normalizeCssArray,
  753. assert: assert,
  754. setAsPrimitive: setAsPrimitive,
  755. isPrimitive: isPrimitive,
  756. createHashMap: createHashMap,
  757. noop: noop
  758. });
  759. var ArrayCtor = typeof Float32Array === 'undefined'
  760. ? Array
  761. : Float32Array;
  762. /**
  763. * 创建一个向量
  764. * @param {number} [x=0]
  765. * @param {number} [y=0]
  766. * @return {Vector2}
  767. */
  768. function create(x, y) {
  769. var out = new ArrayCtor(2);
  770. if (x == null) {
  771. x = 0;
  772. }
  773. if (y == null) {
  774. y = 0;
  775. }
  776. out[0] = x;
  777. out[1] = y;
  778. return out;
  779. }
  780. /**
  781. * 复制向量数据
  782. * @param {Vector2} out
  783. * @param {Vector2} v
  784. * @return {Vector2}
  785. */
  786. function copy(out, v) {
  787. out[0] = v[0];
  788. out[1] = v[1];
  789. return out;
  790. }
  791. /**
  792. * 克隆一个向量
  793. * @param {Vector2} v
  794. * @return {Vector2}
  795. */
  796. function clone$1(v) {
  797. var out = new ArrayCtor(2);
  798. out[0] = v[0];
  799. out[1] = v[1];
  800. return out;
  801. }
  802. /**
  803. * 设置向量的两个项
  804. * @param {Vector2} out
  805. * @param {number} a
  806. * @param {number} b
  807. * @return {Vector2} 结果
  808. */
  809. function set(out, a, b) {
  810. out[0] = a;
  811. out[1] = b;
  812. return out;
  813. }
  814. /**
  815. * 向量相加
  816. * @param {Vector2} out
  817. * @param {Vector2} v1
  818. * @param {Vector2} v2
  819. */
  820. function add(out, v1, v2) {
  821. out[0] = v1[0] + v2[0];
  822. out[1] = v1[1] + v2[1];
  823. return out;
  824. }
  825. /**
  826. * 向量缩放后相加
  827. * @param {Vector2} out
  828. * @param {Vector2} v1
  829. * @param {Vector2} v2
  830. * @param {number} a
  831. */
  832. function scaleAndAdd(out, v1, v2, a) {
  833. out[0] = v1[0] + v2[0] * a;
  834. out[1] = v1[1] + v2[1] * a;
  835. return out;
  836. }
  837. /**
  838. * 向量相减
  839. * @param {Vector2} out
  840. * @param {Vector2} v1
  841. * @param {Vector2} v2
  842. */
  843. function sub(out, v1, v2) {
  844. out[0] = v1[0] - v2[0];
  845. out[1] = v1[1] - v2[1];
  846. return out;
  847. }
  848. /**
  849. * 向量长度
  850. * @param {Vector2} v
  851. * @return {number}
  852. */
  853. function len(v) {
  854. return Math.sqrt(lenSquare(v));
  855. }
  856. var length = len; // jshint ignore:line
  857. /**
  858. * 向量长度平方
  859. * @param {Vector2} v
  860. * @return {number}
  861. */
  862. function lenSquare(v) {
  863. return v[0] * v[0] + v[1] * v[1];
  864. }
  865. var lengthSquare = lenSquare;
  866. /**
  867. * 向量乘法
  868. * @param {Vector2} out
  869. * @param {Vector2} v1
  870. * @param {Vector2} v2
  871. */
  872. function mul(out, v1, v2) {
  873. out[0] = v1[0] * v2[0];
  874. out[1] = v1[1] * v2[1];
  875. return out;
  876. }
  877. /**
  878. * 向量除法
  879. * @param {Vector2} out
  880. * @param {Vector2} v1
  881. * @param {Vector2} v2
  882. */
  883. function div(out, v1, v2) {
  884. out[0] = v1[0] / v2[0];
  885. out[1] = v1[1] / v2[1];
  886. return out;
  887. }
  888. /**
  889. * 向量点乘
  890. * @param {Vector2} v1
  891. * @param {Vector2} v2
  892. * @return {number}
  893. */
  894. function dot(v1, v2) {
  895. return v1[0] * v2[0] + v1[1] * v2[1];
  896. }
  897. /**
  898. * 向量缩放
  899. * @param {Vector2} out
  900. * @param {Vector2} v
  901. * @param {number} s
  902. */
  903. function scale(out, v, s) {
  904. out[0] = v[0] * s;
  905. out[1] = v[1] * s;
  906. return out;
  907. }
  908. /**
  909. * 向量归一化
  910. * @param {Vector2} out
  911. * @param {Vector2} v
  912. */
  913. function normalize(out, v) {
  914. var d = len(v);
  915. if (d === 0) {
  916. out[0] = 0;
  917. out[1] = 0;
  918. }
  919. else {
  920. out[0] = v[0] / d;
  921. out[1] = v[1] / d;
  922. }
  923. return out;
  924. }
  925. /**
  926. * 计算向量间距离
  927. * @param {Vector2} v1
  928. * @param {Vector2} v2
  929. * @return {number}
  930. */
  931. function distance(v1, v2) {
  932. return Math.sqrt(
  933. (v1[0] - v2[0]) * (v1[0] - v2[0])
  934. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  935. );
  936. }
  937. var dist = distance;
  938. /**
  939. * 向量距离平方
  940. * @param {Vector2} v1
  941. * @param {Vector2} v2
  942. * @return {number}
  943. */
  944. function distanceSquare(v1, v2) {
  945. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  946. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  947. }
  948. var distSquare = distanceSquare;
  949. /**
  950. * 求负向量
  951. * @param {Vector2} out
  952. * @param {Vector2} v
  953. */
  954. function negate(out, v) {
  955. out[0] = -v[0];
  956. out[1] = -v[1];
  957. return out;
  958. }
  959. /**
  960. * 插值两个点
  961. * @param {Vector2} out
  962. * @param {Vector2} v1
  963. * @param {Vector2} v2
  964. * @param {number} t
  965. */
  966. function lerp(out, v1, v2, t) {
  967. out[0] = v1[0] + t * (v2[0] - v1[0]);
  968. out[1] = v1[1] + t * (v2[1] - v1[1]);
  969. return out;
  970. }
  971. /**
  972. * 矩阵左乘向量
  973. * @param {Vector2} out
  974. * @param {Vector2} v
  975. * @param {Vector2} m
  976. */
  977. function applyTransform(out, v, m) {
  978. var x = v[0];
  979. var y = v[1];
  980. out[0] = m[0] * x + m[2] * y + m[4];
  981. out[1] = m[1] * x + m[3] * y + m[5];
  982. return out;
  983. }
  984. /**
  985. * 求两个向量最小值
  986. * @param {Vector2} out
  987. * @param {Vector2} v1
  988. * @param {Vector2} v2
  989. */
  990. function min(out, v1, v2) {
  991. out[0] = Math.min(v1[0], v2[0]);
  992. out[1] = Math.min(v1[1], v2[1]);
  993. return out;
  994. }
  995. /**
  996. * 求两个向量最大值
  997. * @param {Vector2} out
  998. * @param {Vector2} v1
  999. * @param {Vector2} v2
  1000. */
  1001. function max(out, v1, v2) {
  1002. out[0] = Math.max(v1[0], v2[0]);
  1003. out[1] = Math.max(v1[1], v2[1]);
  1004. return out;
  1005. }
  1006. var vector = (Object.freeze || Object)({
  1007. create: create,
  1008. copy: copy,
  1009. clone: clone$1,
  1010. set: set,
  1011. add: add,
  1012. scaleAndAdd: scaleAndAdd,
  1013. sub: sub,
  1014. len: len,
  1015. length: length,
  1016. lenSquare: lenSquare,
  1017. lengthSquare: lengthSquare,
  1018. mul: mul,
  1019. div: div,
  1020. dot: dot,
  1021. scale: scale,
  1022. normalize: normalize,
  1023. distance: distance,
  1024. dist: dist,
  1025. distanceSquare: distanceSquare,
  1026. distSquare: distSquare,
  1027. negate: negate,
  1028. lerp: lerp,
  1029. applyTransform: applyTransform,
  1030. min: min,
  1031. max: max
  1032. });
  1033. // TODO Draggable for group
  1034. // FIXME Draggable on element which has parent rotation or scale
  1035. function Draggable() {
  1036. this.on('mousedown', this._dragStart, this);
  1037. this.on('mousemove', this._drag, this);
  1038. this.on('mouseup', this._dragEnd, this);
  1039. this.on('globalout', this._dragEnd, this);
  1040. // this._dropTarget = null;
  1041. // this._draggingTarget = null;
  1042. // this._x = 0;
  1043. // this._y = 0;
  1044. }
  1045. Draggable.prototype = {
  1046. constructor: Draggable,
  1047. _dragStart: function (e) {
  1048. var draggingTarget = e.target;
  1049. if (draggingTarget && draggingTarget.draggable) {
  1050. this._draggingTarget = draggingTarget;
  1051. draggingTarget.dragging = true;
  1052. this._x = e.offsetX;
  1053. this._y = e.offsetY;
  1054. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1055. }
  1056. },
  1057. _drag: function (e) {
  1058. var draggingTarget = this._draggingTarget;
  1059. if (draggingTarget) {
  1060. var x = e.offsetX;
  1061. var y = e.offsetY;
  1062. var dx = x - this._x;
  1063. var dy = y - this._y;
  1064. this._x = x;
  1065. this._y = y;
  1066. draggingTarget.drift(dx, dy, e);
  1067. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1068. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1069. var lastDropTarget = this._dropTarget;
  1070. this._dropTarget = dropTarget;
  1071. if (draggingTarget !== dropTarget) {
  1072. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1073. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1074. }
  1075. if (dropTarget && dropTarget !== lastDropTarget) {
  1076. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1077. }
  1078. }
  1079. }
  1080. },
  1081. _dragEnd: function (e) {
  1082. var draggingTarget = this._draggingTarget;
  1083. if (draggingTarget) {
  1084. draggingTarget.dragging = false;
  1085. }
  1086. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1087. if (this._dropTarget) {
  1088. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1089. }
  1090. this._draggingTarget = null;
  1091. this._dropTarget = null;
  1092. }
  1093. };
  1094. function param(target, e) {
  1095. return {target: target, topTarget: e && e.topTarget};
  1096. }
  1097. /**
  1098. * 事件扩展
  1099. * @module zrender/mixin/Eventful
  1100. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1101. * pissang (https://www.github.com/pissang)
  1102. */
  1103. var arrySlice = Array.prototype.slice;
  1104. /**
  1105. * 事件分发器
  1106. * @alias module:zrender/mixin/Eventful
  1107. * @constructor
  1108. */
  1109. var Eventful = function () {
  1110. this._$handlers = {};
  1111. };
  1112. Eventful.prototype = {
  1113. constructor: Eventful,
  1114. /**
  1115. * 单次触发绑定,trigger后销毁
  1116. *
  1117. * @param {string} event 事件名
  1118. * @param {Function} handler 响应函数
  1119. * @param {Object} context
  1120. */
  1121. one: function (event, handler, context) {
  1122. var _h = this._$handlers;
  1123. if (!handler || !event) {
  1124. return this;
  1125. }
  1126. if (!_h[event]) {
  1127. _h[event] = [];
  1128. }
  1129. for (var i = 0; i < _h[event].length; i++) {
  1130. if (_h[event][i].h === handler) {
  1131. return this;
  1132. }
  1133. }
  1134. _h[event].push({
  1135. h: handler,
  1136. one: true,
  1137. ctx: context || this
  1138. });
  1139. return this;
  1140. },
  1141. /**
  1142. * 绑定事件
  1143. * @param {string} event 事件名
  1144. * @param {Function} handler 事件处理函数
  1145. * @param {Object} [context]
  1146. */
  1147. on: function (event, handler, context) {
  1148. var _h = this._$handlers;
  1149. if (!handler || !event) {
  1150. return this;
  1151. }
  1152. if (!_h[event]) {
  1153. _h[event] = [];
  1154. }
  1155. for (var i = 0; i < _h[event].length; i++) {
  1156. if (_h[event][i].h === handler) {
  1157. return this;
  1158. }
  1159. }
  1160. _h[event].push({
  1161. h: handler,
  1162. one: false,
  1163. ctx: context || this
  1164. });
  1165. return this;
  1166. },
  1167. /**
  1168. * 是否绑定了事件
  1169. * @param {string} event
  1170. * @return {boolean}
  1171. */
  1172. isSilent: function (event) {
  1173. var _h = this._$handlers;
  1174. return _h[event] && _h[event].length;
  1175. },
  1176. /**
  1177. * 解绑事件
  1178. * @param {string} event 事件名
  1179. * @param {Function} [handler] 事件处理函数
  1180. */
  1181. off: function (event, handler) {
  1182. var _h = this._$handlers;
  1183. if (!event) {
  1184. this._$handlers = {};
  1185. return this;
  1186. }
  1187. if (handler) {
  1188. if (_h[event]) {
  1189. var newList = [];
  1190. for (var i = 0, l = _h[event].length; i < l; i++) {
  1191. if (_h[event][i]['h'] != handler) {
  1192. newList.push(_h[event][i]);
  1193. }
  1194. }
  1195. _h[event] = newList;
  1196. }
  1197. if (_h[event] && _h[event].length === 0) {
  1198. delete _h[event];
  1199. }
  1200. }
  1201. else {
  1202. delete _h[event];
  1203. }
  1204. return this;
  1205. },
  1206. /**
  1207. * 事件分发
  1208. *
  1209. * @param {string} type 事件类型
  1210. */
  1211. trigger: function (type) {
  1212. if (this._$handlers[type]) {
  1213. var args = arguments;
  1214. var argLen = args.length;
  1215. if (argLen > 3) {
  1216. args = arrySlice.call(args, 1);
  1217. }
  1218. var _h = this._$handlers[type];
  1219. var len = _h.length;
  1220. for (var i = 0; i < len;) {
  1221. // Optimize advise from backbone
  1222. switch (argLen) {
  1223. case 1:
  1224. _h[i]['h'].call(_h[i]['ctx']);
  1225. break;
  1226. case 2:
  1227. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1228. break;
  1229. case 3:
  1230. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1231. break;
  1232. default:
  1233. // have more than 2 given arguments
  1234. _h[i]['h'].apply(_h[i]['ctx'], args);
  1235. break;
  1236. }
  1237. if (_h[i]['one']) {
  1238. _h.splice(i, 1);
  1239. len--;
  1240. }
  1241. else {
  1242. i++;
  1243. }
  1244. }
  1245. }
  1246. return this;
  1247. },
  1248. /**
  1249. * 带有context的事件分发, 最后一个参数是事件回调的context
  1250. * @param {string} type 事件类型
  1251. */
  1252. triggerWithContext: function (type) {
  1253. if (this._$handlers[type]) {
  1254. var args = arguments;
  1255. var argLen = args.length;
  1256. if (argLen > 4) {
  1257. args = arrySlice.call(args, 1, args.length - 1);
  1258. }
  1259. var ctx = args[args.length - 1];
  1260. var _h = this._$handlers[type];
  1261. var len = _h.length;
  1262. for (var i = 0; i < len;) {
  1263. // Optimize advise from backbone
  1264. switch (argLen) {
  1265. case 1:
  1266. _h[i]['h'].call(ctx);
  1267. break;
  1268. case 2:
  1269. _h[i]['h'].call(ctx, args[1]);
  1270. break;
  1271. case 3:
  1272. _h[i]['h'].call(ctx, args[1], args[2]);
  1273. break;
  1274. default:
  1275. // have more than 2 given arguments
  1276. _h[i]['h'].apply(ctx, args);
  1277. break;
  1278. }
  1279. if (_h[i]['one']) {
  1280. _h.splice(i, 1);
  1281. len--;
  1282. }
  1283. else {
  1284. i++;
  1285. }
  1286. }
  1287. }
  1288. return this;
  1289. }
  1290. };
  1291. /**
  1292. * Handler
  1293. * @module zrender/Handler
  1294. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1295. * errorrik (errorrik@gmail.com)
  1296. * pissang (shenyi.914@gmail.com)
  1297. */
  1298. var SILENT = 'silent';
  1299. function makeEventPacket(eveType, targetInfo, event) {
  1300. return {
  1301. type: eveType,
  1302. event: event,
  1303. // target can only be an element that is not silent.
  1304. target: targetInfo.target,
  1305. // topTarget can be a silent element.
  1306. topTarget: targetInfo.topTarget,
  1307. cancelBubble: false,
  1308. offsetX: event.zrX,
  1309. offsetY: event.zrY,
  1310. gestureEvent: event.gestureEvent,
  1311. pinchX: event.pinchX,
  1312. pinchY: event.pinchY,
  1313. pinchScale: event.pinchScale,
  1314. wheelDelta: event.zrDelta,
  1315. zrByTouch: event.zrByTouch,
  1316. which: event.which
  1317. };
  1318. }
  1319. function EmptyProxy () {}
  1320. EmptyProxy.prototype.dispose = function () {};
  1321. var handlerNames = [
  1322. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1323. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1324. ];
  1325. /**
  1326. * @alias module:zrender/Handler
  1327. * @constructor
  1328. * @extends module:zrender/mixin/Eventful
  1329. * @param {module:zrender/Storage} storage Storage instance.
  1330. * @param {module:zrender/Painter} painter Painter instance.
  1331. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1332. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1333. */
  1334. var Handler = function(storage, painter, proxy, painterRoot) {
  1335. Eventful.call(this);
  1336. this.storage = storage;
  1337. this.painter = painter;
  1338. this.painterRoot = painterRoot;
  1339. proxy = proxy || new EmptyProxy();
  1340. /**
  1341. * Proxy of event. can be Dom, WebGLSurface, etc.
  1342. */
  1343. this.proxy = proxy;
  1344. // Attach handler
  1345. proxy.handler = this;
  1346. /**
  1347. * {target, topTarget, x, y}
  1348. * @private
  1349. * @type {Object}
  1350. */
  1351. this._hovered = {};
  1352. /**
  1353. * @private
  1354. * @type {Date}
  1355. */
  1356. this._lastTouchMoment;
  1357. /**
  1358. * @private
  1359. * @type {number}
  1360. */
  1361. this._lastX;
  1362. /**
  1363. * @private
  1364. * @type {number}
  1365. */
  1366. this._lastY;
  1367. Draggable.call(this);
  1368. each$1(handlerNames, function (name) {
  1369. proxy.on && proxy.on(name, this[name], this);
  1370. }, this);
  1371. };
  1372. Handler.prototype = {
  1373. constructor: Handler,
  1374. mousemove: function (event) {
  1375. var x = event.zrX;
  1376. var y = event.zrY;
  1377. var lastHovered = this._hovered;
  1378. var lastHoveredTarget = lastHovered.target;
  1379. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1380. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1381. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1382. // See #6198.
  1383. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1384. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1385. lastHoveredTarget = lastHovered.target;
  1386. }
  1387. var hovered = this._hovered = this.findHover(x, y);
  1388. var hoveredTarget = hovered.target;
  1389. var proxy = this.proxy;
  1390. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1391. // Mouse out on previous hovered element
  1392. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1393. this.dispatchToElement(lastHovered, 'mouseout', event);
  1394. }
  1395. // Mouse moving on one element
  1396. this.dispatchToElement(hovered, 'mousemove', event);
  1397. // Mouse over on a new element
  1398. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1399. this.dispatchToElement(hovered, 'mouseover', event);
  1400. }
  1401. },
  1402. mouseout: function (event) {
  1403. this.dispatchToElement(this._hovered, 'mouseout', event);
  1404. // There might be some doms created by upper layer application
  1405. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1406. // dom created by echarts), where 'globalout' event should not
  1407. // be triggered when mouse enters these doms. (But 'mouseout'
  1408. // should be triggered at the original hovered element as usual).
  1409. var element = event.toElement || event.relatedTarget;
  1410. var innerDom;
  1411. do {
  1412. element = element && element.parentNode;
  1413. }
  1414. while (element && element.nodeType != 9 && !(
  1415. innerDom = element === this.painterRoot
  1416. ));
  1417. !innerDom && this.trigger('globalout', {event: event});
  1418. },
  1419. /**
  1420. * Resize
  1421. */
  1422. resize: function (event) {
  1423. this._hovered = {};
  1424. },
  1425. /**
  1426. * Dispatch event
  1427. * @param {string} eventName
  1428. * @param {event=} eventArgs
  1429. */
  1430. dispatch: function (eventName, eventArgs) {
  1431. var handler = this[eventName];
  1432. handler && handler.call(this, eventArgs);
  1433. },
  1434. /**
  1435. * Dispose
  1436. */
  1437. dispose: function () {
  1438. this.proxy.dispose();
  1439. this.storage =
  1440. this.proxy =
  1441. this.painter = null;
  1442. },
  1443. /**
  1444. * 设置默认的cursor style
  1445. * @param {string} [cursorStyle='default'] 例如 crosshair
  1446. */
  1447. setCursorStyle: function (cursorStyle) {
  1448. var proxy = this.proxy;
  1449. proxy.setCursor && proxy.setCursor(cursorStyle);
  1450. },
  1451. /**
  1452. * 事件分发代理
  1453. *
  1454. * @private
  1455. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1456. * @param {string} eventName 事件名称
  1457. * @param {Object} event 事件对象
  1458. */
  1459. dispatchToElement: function (targetInfo, eventName, event) {
  1460. targetInfo = targetInfo || {};
  1461. var el = targetInfo.target;
  1462. if (el && el.silent) {
  1463. return;
  1464. }
  1465. var eventHandler = 'on' + eventName;
  1466. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1467. while (el) {
  1468. el[eventHandler]
  1469. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1470. el.trigger(eventName, eventPacket);
  1471. el = el.parent;
  1472. if (eventPacket.cancelBubble) {
  1473. break;
  1474. }
  1475. }
  1476. if (!eventPacket.cancelBubble) {
  1477. // 冒泡到顶级 zrender 对象
  1478. this.trigger(eventName, eventPacket);
  1479. // 分发事件到用户自定义层
  1480. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1481. this.painter && this.painter.eachOtherLayer(function (layer) {
  1482. if (typeof(layer[eventHandler]) == 'function') {
  1483. layer[eventHandler].call(layer, eventPacket);
  1484. }
  1485. if (layer.trigger) {
  1486. layer.trigger(eventName, eventPacket);
  1487. }
  1488. });
  1489. }
  1490. },
  1491. /**
  1492. * @private
  1493. * @param {number} x
  1494. * @param {number} y
  1495. * @param {module:zrender/graphic/Displayable} exclude
  1496. * @return {model:zrender/Element}
  1497. * @method
  1498. */
  1499. findHover: function(x, y, exclude) {
  1500. var list = this.storage.getDisplayList();
  1501. var out = {x: x, y: y};
  1502. for (var i = list.length - 1; i >= 0 ; i--) {
  1503. var hoverCheckResult;
  1504. if (list[i] !== exclude
  1505. // getDisplayList may include ignored item in VML mode
  1506. && !list[i].ignore
  1507. && (hoverCheckResult = isHover(list[i], x, y))
  1508. ) {
  1509. !out.topTarget && (out.topTarget = list[i]);
  1510. if (hoverCheckResult !== SILENT) {
  1511. out.target = list[i];
  1512. break;
  1513. }
  1514. }
  1515. }
  1516. return out;
  1517. }
  1518. };
  1519. // Common handlers
  1520. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1521. Handler.prototype[name] = function (event) {
  1522. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1523. var hovered = this.findHover(event.zrX, event.zrY);
  1524. var hoveredTarget = hovered.target;
  1525. if (name === 'mousedown') {
  1526. this._downEl = hoveredTarget;
  1527. this._downPoint = [event.zrX, event.zrY];
  1528. // In case click triggered before mouseup
  1529. this._upEl = hoveredTarget;
  1530. }
  1531. else if (name === 'mosueup') {
  1532. this._upEl = hoveredTarget;
  1533. }
  1534. else if (name === 'click') {
  1535. if (this._downEl !== this._upEl
  1536. // Original click event is triggered on the whole canvas element,
  1537. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1538. // which should be filtered, otherwise it will bring trouble to
  1539. // pan and zoom.
  1540. || !this._downPoint
  1541. // Arbitrary value
  1542. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1543. ) {
  1544. return;
  1545. }
  1546. this._downPoint = null;
  1547. }
  1548. this.dispatchToElement(hovered, name, event);
  1549. };
  1550. });
  1551. function isHover(displayable, x, y) {
  1552. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1553. var el = displayable;
  1554. var isSilent;
  1555. while (el) {
  1556. // If clipped by ancestor.
  1557. // FIXME: If clipPath has neither stroke nor fill,
  1558. // el.clipPath.contain(x, y) will always return false.
  1559. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1560. return false;
  1561. }
  1562. if (el.silent) {
  1563. isSilent = true;
  1564. }
  1565. el = el.parent;
  1566. }
  1567. return isSilent ? SILENT : true;
  1568. }
  1569. return false;
  1570. }
  1571. mixin(Handler, Eventful);
  1572. mixin(Handler, Draggable);
  1573. /**
  1574. * 3x2矩阵操作类
  1575. * @exports zrender/tool/matrix
  1576. */
  1577. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1578. ? Array
  1579. : Float32Array;
  1580. /**
  1581. * 创建一个单位矩阵
  1582. * @return {Float32Array|Array.<number>}
  1583. */
  1584. function create$1() {
  1585. var out = new ArrayCtor$1(6);
  1586. identity(out);
  1587. return out;
  1588. }
  1589. /**
  1590. * 设置矩阵为单位矩阵
  1591. * @param {Float32Array|Array.<number>} out
  1592. */
  1593. function identity(out) {
  1594. out[0] = 1;
  1595. out[1] = 0;
  1596. out[2] = 0;
  1597. out[3] = 1;
  1598. out[4] = 0;
  1599. out[5] = 0;
  1600. return out;
  1601. }
  1602. /**
  1603. * 复制矩阵
  1604. * @param {Float32Array|Array.<number>} out
  1605. * @param {Float32Array|Array.<number>} m
  1606. */
  1607. function copy$1(out, m) {
  1608. out[0] = m[0];
  1609. out[1] = m[1];
  1610. out[2] = m[2];
  1611. out[3] = m[3];
  1612. out[4] = m[4];
  1613. out[5] = m[5];
  1614. return out;
  1615. }
  1616. /**
  1617. * 矩阵相乘
  1618. * @param {Float32Array|Array.<number>} out
  1619. * @param {Float32Array|Array.<number>} m1
  1620. * @param {Float32Array|Array.<number>} m2
  1621. */
  1622. function mul$1(out, m1, m2) {
  1623. // Consider matrix.mul(m, m2, m);
  1624. // where out is the same as m2.
  1625. // So use temp variable to escape error.
  1626. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1627. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1628. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1629. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1630. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1631. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1632. out[0] = out0;
  1633. out[1] = out1;
  1634. out[2] = out2;
  1635. out[3] = out3;
  1636. out[4] = out4;
  1637. out[5] = out5;
  1638. return out;
  1639. }
  1640. /**
  1641. * 平移变换
  1642. * @param {Float32Array|Array.<number>} out
  1643. * @param {Float32Array|Array.<number>} a
  1644. * @param {Float32Array|Array.<number>} v
  1645. */
  1646. function translate(out, a, v) {
  1647. out[0] = a[0];
  1648. out[1] = a[1];
  1649. out[2] = a[2];
  1650. out[3] = a[3];
  1651. out[4] = a[4] + v[0];
  1652. out[5] = a[5] + v[1];
  1653. return out;
  1654. }
  1655. /**
  1656. * 旋转变换
  1657. * @param {Float32Array|Array.<number>} out
  1658. * @param {Float32Array|Array.<number>} a
  1659. * @param {number} rad
  1660. */
  1661. function rotate(out, a, rad) {
  1662. var aa = a[0];
  1663. var ac = a[2];
  1664. var atx = a[4];
  1665. var ab = a[1];
  1666. var ad = a[3];
  1667. var aty = a[5];
  1668. var st = Math.sin(rad);
  1669. var ct = Math.cos(rad);
  1670. out[0] = aa * ct + ab * st;
  1671. out[1] = -aa * st + ab * ct;
  1672. out[2] = ac * ct + ad * st;
  1673. out[3] = -ac * st + ct * ad;
  1674. out[4] = ct * atx + st * aty;
  1675. out[5] = ct * aty - st * atx;
  1676. return out;
  1677. }
  1678. /**
  1679. * 缩放变换
  1680. * @param {Float32Array|Array.<number>} out
  1681. * @param {Float32Array|Array.<number>} a
  1682. * @param {Float32Array|Array.<number>} v
  1683. */
  1684. function scale$1(out, a, v) {
  1685. var vx = v[0];
  1686. var vy = v[1];
  1687. out[0] = a[0] * vx;
  1688. out[1] = a[1] * vy;
  1689. out[2] = a[2] * vx;
  1690. out[3] = a[3] * vy;
  1691. out[4] = a[4] * vx;
  1692. out[5] = a[5] * vy;
  1693. return out;
  1694. }
  1695. /**
  1696. * 求逆矩阵
  1697. * @param {Float32Array|Array.<number>} out
  1698. * @param {Float32Array|Array.<number>} a
  1699. */
  1700. function invert(out, a) {
  1701. var aa = a[0];
  1702. var ac = a[2];
  1703. var atx = a[4];
  1704. var ab = a[1];
  1705. var ad = a[3];
  1706. var aty = a[5];
  1707. var det = aa * ad - ab * ac;
  1708. if (!det) {
  1709. return null;
  1710. }
  1711. det = 1.0 / det;
  1712. out[0] = ad * det;
  1713. out[1] = -ab * det;
  1714. out[2] = -ac * det;
  1715. out[3] = aa * det;
  1716. out[4] = (ac * aty - ad * atx) * det;
  1717. out[5] = (ab * atx - aa * aty) * det;
  1718. return out;
  1719. }
  1720. var matrix = (Object.freeze || Object)({
  1721. create: create$1,
  1722. identity: identity,
  1723. copy: copy$1,
  1724. mul: mul$1,
  1725. translate: translate,
  1726. rotate: rotate,
  1727. scale: scale$1,
  1728. invert: invert
  1729. });
  1730. /**
  1731. * 提供变换扩展
  1732. * @module zrender/mixin/Transformable
  1733. * @author pissang (https://www.github.com/pissang)
  1734. */
  1735. var mIdentity = identity;
  1736. var EPSILON = 5e-5;
  1737. function isNotAroundZero(val) {
  1738. return val > EPSILON || val < -EPSILON;
  1739. }
  1740. /**
  1741. * @alias module:zrender/mixin/Transformable
  1742. * @constructor
  1743. */
  1744. var Transformable = function (opts) {
  1745. opts = opts || {};
  1746. // If there are no given position, rotation, scale
  1747. if (!opts.position) {
  1748. /**
  1749. * 平移
  1750. * @type {Array.<number>}
  1751. * @default [0, 0]
  1752. */
  1753. this.position = [0, 0];
  1754. }
  1755. if (opts.rotation == null) {
  1756. /**
  1757. * 旋转
  1758. * @type {Array.<number>}
  1759. * @default 0
  1760. */
  1761. this.rotation = 0;
  1762. }
  1763. if (!opts.scale) {
  1764. /**
  1765. * 缩放
  1766. * @type {Array.<number>}
  1767. * @default [1, 1]
  1768. */
  1769. this.scale = [1, 1];
  1770. }
  1771. /**
  1772. * 旋转和缩放的原点
  1773. * @type {Array.<number>}
  1774. * @default null
  1775. */
  1776. this.origin = this.origin || null;
  1777. };
  1778. var transformableProto = Transformable.prototype;
  1779. transformableProto.transform = null;
  1780. /**
  1781. * 判断是否需要有坐标变换
  1782. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1783. */
  1784. transformableProto.needLocalTransform = function () {
  1785. return isNotAroundZero(this.rotation)
  1786. || isNotAroundZero(this.position[0])
  1787. || isNotAroundZero(this.position[1])
  1788. || isNotAroundZero(this.scale[0] - 1)
  1789. || isNotAroundZero(this.scale[1] - 1);
  1790. };
  1791. transformableProto.updateTransform = function () {
  1792. var parent = this.parent;
  1793. var parentHasTransform = parent && parent.transform;
  1794. var needLocalTransform = this.needLocalTransform();
  1795. var m = this.transform;
  1796. if (!(needLocalTransform || parentHasTransform)) {
  1797. m && mIdentity(m);
  1798. return;
  1799. }
  1800. m = m || create$1();
  1801. if (needLocalTransform) {
  1802. this.getLocalTransform(m);
  1803. }
  1804. else {
  1805. mIdentity(m);
  1806. }
  1807. // 应用父节点变换
  1808. if (parentHasTransform) {
  1809. if (needLocalTransform) {
  1810. mul$1(m, parent.transform, m);
  1811. }
  1812. else {
  1813. copy$1(m, parent.transform);
  1814. }
  1815. }
  1816. // 保存这个变换矩阵
  1817. this.transform = m;
  1818. this.invTransform = this.invTransform || create$1();
  1819. invert(this.invTransform, m);
  1820. };
  1821. transformableProto.getLocalTransform = function (m) {
  1822. return Transformable.getLocalTransform(this, m);
  1823. };
  1824. /**
  1825. * 将自己的transform应用到context上
  1826. * @param {CanvasRenderingContext2D} ctx
  1827. */
  1828. transformableProto.setTransform = function (ctx) {
  1829. var m = this.transform;
  1830. var dpr = ctx.dpr || 1;
  1831. if (m) {
  1832. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1833. }
  1834. else {
  1835. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1836. }
  1837. };
  1838. transformableProto.restoreTransform = function (ctx) {
  1839. var dpr = ctx.dpr || 1;
  1840. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1841. };
  1842. var tmpTransform = [];
  1843. /**
  1844. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1845. */
  1846. transformableProto.decomposeTransform = function () {
  1847. if (!this.transform) {
  1848. return;
  1849. }
  1850. var parent = this.parent;
  1851. var m = this.transform;
  1852. if (parent && parent.transform) {
  1853. // Get local transform and decompose them to position, scale, rotation
  1854. mul$1(tmpTransform, parent.invTransform, m);
  1855. m = tmpTransform;
  1856. }
  1857. var sx = m[0] * m[0] + m[1] * m[1];
  1858. var sy = m[2] * m[2] + m[3] * m[3];
  1859. var position = this.position;
  1860. var scale$$1 = this.scale;
  1861. if (isNotAroundZero(sx - 1)) {
  1862. sx = Math.sqrt(sx);
  1863. }
  1864. if (isNotAroundZero(sy - 1)) {
  1865. sy = Math.sqrt(sy);
  1866. }
  1867. if (m[0] < 0) {
  1868. sx = -sx;
  1869. }
  1870. if (m[3] < 0) {
  1871. sy = -sy;
  1872. }
  1873. position[0] = m[4];
  1874. position[1] = m[5];
  1875. scale$$1[0] = sx;
  1876. scale$$1[1] = sy;
  1877. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1878. };
  1879. /**
  1880. * Get global scale
  1881. * @return {Array.<number>}
  1882. */
  1883. transformableProto.getGlobalScale = function () {
  1884. var m = this.transform;
  1885. if (!m) {
  1886. return [1, 1];
  1887. }
  1888. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1889. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1890. if (m[0] < 0) {
  1891. sx = -sx;
  1892. }
  1893. if (m[3] < 0) {
  1894. sy = -sy;
  1895. }
  1896. return [sx, sy];
  1897. };
  1898. /**
  1899. * 变换坐标位置到 shape 的局部坐标空间
  1900. * @method
  1901. * @param {number} x
  1902. * @param {number} y
  1903. * @return {Array.<number>}
  1904. */
  1905. transformableProto.transformCoordToLocal = function (x, y) {
  1906. var v2 = [x, y];
  1907. var invTransform = this.invTransform;
  1908. if (invTransform) {
  1909. applyTransform(v2, v2, invTransform);
  1910. }
  1911. return v2;
  1912. };
  1913. /**
  1914. * 变换局部坐标位置到全局坐标空间
  1915. * @method
  1916. * @param {number} x
  1917. * @param {number} y
  1918. * @return {Array.<number>}
  1919. */
  1920. transformableProto.transformCoordToGlobal = function (x, y) {
  1921. var v2 = [x, y];
  1922. var transform = this.transform;
  1923. if (transform) {
  1924. applyTransform(v2, v2, transform);
  1925. }
  1926. return v2;
  1927. };
  1928. /**
  1929. * @static
  1930. * @param {Object} target
  1931. * @param {Array.<number>} target.origin
  1932. * @param {number} target.rotation
  1933. * @param {Array.<number>} target.position
  1934. * @param {Array.<number>} [m]
  1935. */
  1936. Transformable.getLocalTransform = function (target, m) {
  1937. m = m || [];
  1938. mIdentity(m);
  1939. var origin = target.origin;
  1940. var scale$$1 = target.scale || [1, 1];
  1941. var rotation = target.rotation || 0;
  1942. var position = target.position || [0, 0];
  1943. if (origin) {
  1944. // Translate to origin
  1945. m[4] -= origin[0];
  1946. m[5] -= origin[1];
  1947. }
  1948. scale$1(m, m, scale$$1);
  1949. if (rotation) {
  1950. rotate(m, m, rotation);
  1951. }
  1952. if (origin) {
  1953. // Translate back from origin
  1954. m[4] += origin[0];
  1955. m[5] += origin[1];
  1956. }
  1957. m[4] += position[0];
  1958. m[5] += position[1];
  1959. return m;
  1960. };
  1961. /**
  1962. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  1963. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  1964. * @exports zrender/animation/easing
  1965. */
  1966. var easing = {
  1967. /**
  1968. * @param {number} k
  1969. * @return {number}
  1970. */
  1971. linear: function (k) {
  1972. return k;
  1973. },
  1974. /**
  1975. * @param {number} k
  1976. * @return {number}
  1977. */
  1978. quadraticIn: function (k) {
  1979. return k * k;
  1980. },
  1981. /**
  1982. * @param {number} k
  1983. * @return {number}
  1984. */
  1985. quadraticOut: function (k) {
  1986. return k * (2 - k);
  1987. },
  1988. /**
  1989. * @param {number} k
  1990. * @return {number}
  1991. */
  1992. quadraticInOut: function (k) {
  1993. if ((k *= 2) < 1) {
  1994. return 0.5 * k * k;
  1995. }
  1996. return -0.5 * (--k * (k - 2) - 1);
  1997. },
  1998. // 三次方的缓动(t^3)
  1999. /**
  2000. * @param {number} k
  2001. * @return {number}
  2002. */
  2003. cubicIn: function (k) {
  2004. return k * k * k;
  2005. },
  2006. /**
  2007. * @param {number} k
  2008. * @return {number}
  2009. */
  2010. cubicOut: function (k) {
  2011. return --k * k * k + 1;
  2012. },
  2013. /**
  2014. * @param {number} k
  2015. * @return {number}
  2016. */
  2017. cubicInOut: function (k) {
  2018. if ((k *= 2) < 1) {
  2019. return 0.5 * k * k * k;
  2020. }
  2021. return 0.5 * ((k -= 2) * k * k + 2);
  2022. },
  2023. // 四次方的缓动(t^4)
  2024. /**
  2025. * @param {number} k
  2026. * @return {number}
  2027. */
  2028. quarticIn: function (k) {
  2029. return k * k * k * k;
  2030. },
  2031. /**
  2032. * @param {number} k
  2033. * @return {number}
  2034. */
  2035. quarticOut: function (k) {
  2036. return 1 - (--k * k * k * k);
  2037. },
  2038. /**
  2039. * @param {number} k
  2040. * @return {number}
  2041. */
  2042. quarticInOut: function (k) {
  2043. if ((k *= 2) < 1) {
  2044. return 0.5 * k * k * k * k;
  2045. }
  2046. return -0.5 * ((k -= 2) * k * k * k - 2);
  2047. },
  2048. // 五次方的缓动(t^5)
  2049. /**
  2050. * @param {number} k
  2051. * @return {number}
  2052. */
  2053. quinticIn: function (k) {
  2054. return k * k * k * k * k;
  2055. },
  2056. /**
  2057. * @param {number} k
  2058. * @return {number}
  2059. */
  2060. quinticOut: function (k) {
  2061. return --k * k * k * k * k + 1;
  2062. },
  2063. /**
  2064. * @param {number} k
  2065. * @return {number}
  2066. */
  2067. quinticInOut: function (k) {
  2068. if ((k *= 2) < 1) {
  2069. return 0.5 * k * k * k * k * k;
  2070. }
  2071. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2072. },
  2073. // 正弦曲线的缓动(sin(t))
  2074. /**
  2075. * @param {number} k
  2076. * @return {number}
  2077. */
  2078. sinusoidalIn: function (k) {
  2079. return 1 - Math.cos(k * Math.PI / 2);
  2080. },
  2081. /**
  2082. * @param {number} k
  2083. * @return {number}
  2084. */
  2085. sinusoidalOut: function (k) {
  2086. return Math.sin(k * Math.PI / 2);
  2087. },
  2088. /**
  2089. * @param {number} k
  2090. * @return {number}
  2091. */
  2092. sinusoidalInOut: function (k) {
  2093. return 0.5 * (1 - Math.cos(Math.PI * k));
  2094. },
  2095. // 指数曲线的缓动(2^t)
  2096. /**
  2097. * @param {number} k
  2098. * @return {number}
  2099. */
  2100. exponentialIn: function (k) {
  2101. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2102. },
  2103. /**
  2104. * @param {number} k
  2105. * @return {number}
  2106. */
  2107. exponentialOut: function (k) {
  2108. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2109. },
  2110. /**
  2111. * @param {number} k
  2112. * @return {number}
  2113. */
  2114. exponentialInOut: function (k) {
  2115. if (k === 0) {
  2116. return 0;
  2117. }
  2118. if (k === 1) {
  2119. return 1;
  2120. }
  2121. if ((k *= 2) < 1) {
  2122. return 0.5 * Math.pow(1024, k - 1);
  2123. }
  2124. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2125. },
  2126. // 圆形曲线的缓动(sqrt(1-t^2))
  2127. /**
  2128. * @param {number} k
  2129. * @return {number}
  2130. */
  2131. circularIn: function (k) {
  2132. return 1 - Math.sqrt(1 - k * k);
  2133. },
  2134. /**
  2135. * @param {number} k
  2136. * @return {number}
  2137. */
  2138. circularOut: function (k) {
  2139. return Math.sqrt(1 - (--k * k));
  2140. },
  2141. /**
  2142. * @param {number} k
  2143. * @return {number}
  2144. */
  2145. circularInOut: function (k) {
  2146. if ((k *= 2) < 1) {
  2147. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2148. }
  2149. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2150. },
  2151. // 创建类似于弹簧在停止前来回振荡的动画
  2152. /**
  2153. * @param {number} k
  2154. * @return {number}
  2155. */
  2156. elasticIn: function (k) {
  2157. var s;
  2158. var a = 0.1;
  2159. var p = 0.4;
  2160. if (k === 0) {
  2161. return 0;
  2162. }
  2163. if (k === 1) {
  2164. return 1;
  2165. }
  2166. if (!a || a < 1) {
  2167. a = 1; s = p / 4;
  2168. }
  2169. else {
  2170. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2171. }
  2172. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2173. Math.sin((k - s) * (2 * Math.PI) / p));
  2174. },
  2175. /**
  2176. * @param {number} k
  2177. * @return {number}
  2178. */
  2179. elasticOut: function (k) {
  2180. var s;
  2181. var a = 0.1;
  2182. var p = 0.4;
  2183. if (k === 0) {
  2184. return 0;
  2185. }
  2186. if (k === 1) {
  2187. return 1;
  2188. }
  2189. if (!a || a < 1) {
  2190. a = 1; s = p / 4;
  2191. }
  2192. else {
  2193. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2194. }
  2195. return (a * Math.pow(2, -10 * k) *
  2196. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2197. },
  2198. /**
  2199. * @param {number} k
  2200. * @return {number}
  2201. */
  2202. elasticInOut: function (k) {
  2203. var s;
  2204. var a = 0.1;
  2205. var p = 0.4;
  2206. if (k === 0) {
  2207. return 0;
  2208. }
  2209. if (k === 1) {
  2210. return 1;
  2211. }
  2212. if (!a || a < 1) {
  2213. a = 1; s = p / 4;
  2214. }
  2215. else {
  2216. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2217. }
  2218. if ((k *= 2) < 1) {
  2219. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2220. * Math.sin((k - s) * (2 * Math.PI) / p));
  2221. }
  2222. return a * Math.pow(2, -10 * (k -= 1))
  2223. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2224. },
  2225. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2226. /**
  2227. * @param {number} k
  2228. * @return {number}
  2229. */
  2230. backIn: function (k) {
  2231. var s = 1.70158;
  2232. return k * k * ((s + 1) * k - s);
  2233. },
  2234. /**
  2235. * @param {number} k
  2236. * @return {number}
  2237. */
  2238. backOut: function (k) {
  2239. var s = 1.70158;
  2240. return --k * k * ((s + 1) * k + s) + 1;
  2241. },
  2242. /**
  2243. * @param {number} k
  2244. * @return {number}
  2245. */
  2246. backInOut: function (k) {
  2247. var s = 1.70158 * 1.525;
  2248. if ((k *= 2) < 1) {
  2249. return 0.5 * (k * k * ((s + 1) * k - s));
  2250. }
  2251. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2252. },
  2253. // 创建弹跳效果
  2254. /**
  2255. * @param {number} k
  2256. * @return {number}
  2257. */
  2258. bounceIn: function (k) {
  2259. return 1 - easing.bounceOut(1 - k);
  2260. },
  2261. /**
  2262. * @param {number} k
  2263. * @return {number}
  2264. */
  2265. bounceOut: function (k) {
  2266. if (k < (1 / 2.75)) {
  2267. return 7.5625 * k * k;
  2268. }
  2269. else if (k < (2 / 2.75)) {
  2270. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2271. }
  2272. else if (k < (2.5 / 2.75)) {
  2273. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2274. }
  2275. else {
  2276. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2277. }
  2278. },
  2279. /**
  2280. * @param {number} k
  2281. * @return {number}
  2282. */
  2283. bounceInOut: function (k) {
  2284. if (k < 0.5) {
  2285. return easing.bounceIn(k * 2) * 0.5;
  2286. }
  2287. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2288. }
  2289. };
  2290. /**
  2291. * 动画主控制器
  2292. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2293. * @config life(1000) 动画时长
  2294. * @config delay(0) 动画延迟时间
  2295. * @config loop(true)
  2296. * @config gap(0) 循环的间隔时间
  2297. * @config onframe
  2298. * @config easing(optional)
  2299. * @config ondestroy(optional)
  2300. * @config onrestart(optional)
  2301. *
  2302. * TODO pause
  2303. */
  2304. function Clip(options) {
  2305. this._target = options.target;
  2306. // 生命周期
  2307. this._life = options.life || 1000;
  2308. // 延时
  2309. this._delay = options.delay || 0;
  2310. // 开始时间
  2311. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2312. this._initialized = false;
  2313. // 是否循环
  2314. this.loop = options.loop == null ? false : options.loop;
  2315. this.gap = options.gap || 0;
  2316. this.easing = options.easing || 'Linear';
  2317. this.onframe = options.onframe;
  2318. this.ondestroy = options.ondestroy;
  2319. this.onrestart = options.onrestart;
  2320. this._pausedTime = 0;
  2321. this._paused = false;
  2322. }
  2323. Clip.prototype = {
  2324. constructor: Clip,
  2325. step: function (globalTime, deltaTime) {
  2326. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2327. // PENDING
  2328. if (!this._initialized) {
  2329. this._startTime = globalTime + this._delay;
  2330. this._initialized = true;
  2331. }
  2332. if (this._paused) {
  2333. this._pausedTime += deltaTime;
  2334. return;
  2335. }
  2336. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2337. // 还没开始
  2338. if (percent < 0) {
  2339. return;
  2340. }
  2341. percent = Math.min(percent, 1);
  2342. var easing$$1 = this.easing;
  2343. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2344. var schedule = typeof easingFunc === 'function'
  2345. ? easingFunc(percent)
  2346. : percent;
  2347. this.fire('frame', schedule);
  2348. // 结束
  2349. if (percent == 1) {
  2350. if (this.loop) {
  2351. this.restart (globalTime);
  2352. // 重新开始周期
  2353. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2354. return 'restart';
  2355. }
  2356. // 动画完成将这个控制器标识为待删除
  2357. // 在Animation.update中进行批量删除
  2358. this._needsRemove = true;
  2359. return 'destroy';
  2360. }
  2361. return null;
  2362. },
  2363. restart: function (globalTime) {
  2364. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2365. this._startTime = globalTime - remainder + this.gap;
  2366. this._pausedTime = 0;
  2367. this._needsRemove = false;
  2368. },
  2369. fire: function (eventType, arg) {
  2370. eventType = 'on' + eventType;
  2371. if (this[eventType]) {
  2372. this[eventType](this._target, arg);
  2373. }
  2374. },
  2375. pause: function () {
  2376. this._paused = true;
  2377. },
  2378. resume: function () {
  2379. this._paused = false;
  2380. }
  2381. };
  2382. // Simple LRU cache use doubly linked list
  2383. // @module zrender/core/LRU
  2384. /**
  2385. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2386. * @constructor
  2387. */
  2388. var LinkedList = function () {
  2389. /**
  2390. * @type {module:zrender/core/LRU~Entry}
  2391. */
  2392. this.head = null;
  2393. /**
  2394. * @type {module:zrender/core/LRU~Entry}
  2395. */
  2396. this.tail = null;
  2397. this._len = 0;
  2398. };
  2399. var linkedListProto = LinkedList.prototype;
  2400. /**
  2401. * Insert a new value at the tail
  2402. * @param {} val
  2403. * @return {module:zrender/core/LRU~Entry}
  2404. */
  2405. linkedListProto.insert = function (val) {
  2406. var entry = new Entry(val);
  2407. this.insertEntry(entry);
  2408. return entry;
  2409. };
  2410. /**
  2411. * Insert an entry at the tail
  2412. * @param {module:zrender/core/LRU~Entry} entry
  2413. */
  2414. linkedListProto.insertEntry = function (entry) {
  2415. if (!this.head) {
  2416. this.head = this.tail = entry;
  2417. }
  2418. else {
  2419. this.tail.next = entry;
  2420. entry.prev = this.tail;
  2421. entry.next = null;
  2422. this.tail = entry;
  2423. }
  2424. this._len++;
  2425. };
  2426. /**
  2427. * Remove entry.
  2428. * @param {module:zrender/core/LRU~Entry} entry
  2429. */
  2430. linkedListProto.remove = function (entry) {
  2431. var prev = entry.prev;
  2432. var next = entry.next;
  2433. if (prev) {
  2434. prev.next = next;
  2435. }
  2436. else {
  2437. // Is head
  2438. this.head = next;
  2439. }
  2440. if (next) {
  2441. next.prev = prev;
  2442. }
  2443. else {
  2444. // Is tail
  2445. this.tail = prev;
  2446. }
  2447. entry.next = entry.prev = null;
  2448. this._len--;
  2449. };
  2450. /**
  2451. * @return {number}
  2452. */
  2453. linkedListProto.len = function () {
  2454. return this._len;
  2455. };
  2456. /**
  2457. * Clear list
  2458. */
  2459. linkedListProto.clear = function () {
  2460. this.head = this.tail = null;
  2461. this._len = 0;
  2462. };
  2463. /**
  2464. * @constructor
  2465. * @param {} val
  2466. */
  2467. var Entry = function (val) {
  2468. /**
  2469. * @type {}
  2470. */
  2471. this.value = val;
  2472. /**
  2473. * @type {module:zrender/core/LRU~Entry}
  2474. */
  2475. this.next;
  2476. /**
  2477. * @type {module:zrender/core/LRU~Entry}
  2478. */
  2479. this.prev;
  2480. };
  2481. /**
  2482. * LRU Cache
  2483. * @constructor
  2484. * @alias module:zrender/core/LRU
  2485. */
  2486. var LRU = function (maxSize) {
  2487. this._list = new LinkedList();
  2488. this._map = {};
  2489. this._maxSize = maxSize || 10;
  2490. this._lastRemovedEntry = null;
  2491. };
  2492. var LRUProto = LRU.prototype;
  2493. /**
  2494. * @param {string} key
  2495. * @param {} value
  2496. * @return {} Removed value
  2497. */
  2498. LRUProto.put = function (key, value) {
  2499. var list = this._list;
  2500. var map = this._map;
  2501. var removed = null;
  2502. if (map[key] == null) {
  2503. var len = list.len();
  2504. // Reuse last removed entry
  2505. var entry = this._lastRemovedEntry;
  2506. if (len >= this._maxSize && len > 0) {
  2507. // Remove the least recently used
  2508. var leastUsedEntry = list.head;
  2509. list.remove(leastUsedEntry);
  2510. delete map[leastUsedEntry.key];
  2511. removed = leastUsedEntry.value;
  2512. this._lastRemovedEntry = leastUsedEntry;
  2513. }
  2514. if (entry) {
  2515. entry.value = value;
  2516. }
  2517. else {
  2518. entry = new Entry(value);
  2519. }
  2520. entry.key = key;
  2521. list.insertEntry(entry);
  2522. map[key] = entry;
  2523. }
  2524. return removed;
  2525. };
  2526. /**
  2527. * @param {string} key
  2528. * @return {}
  2529. */
  2530. LRUProto.get = function (key) {
  2531. var entry = this._map[key];
  2532. var list = this._list;
  2533. if (entry != null) {
  2534. // Put the latest used entry in the tail
  2535. if (entry !== list.tail) {
  2536. list.remove(entry);
  2537. list.insertEntry(entry);
  2538. }
  2539. return entry.value;
  2540. }
  2541. };
  2542. /**
  2543. * Clear the cache
  2544. */
  2545. LRUProto.clear = function () {
  2546. this._list.clear();
  2547. this._map = {};
  2548. };
  2549. var kCSSColorTable = {
  2550. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2551. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2552. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2553. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2554. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2555. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2556. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2557. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2558. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2559. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2560. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2561. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2562. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2563. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2564. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2565. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2566. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2567. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2568. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2569. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2570. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2571. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2572. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2573. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2574. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2575. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2576. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2577. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2578. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2579. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2580. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2581. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2582. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2583. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2584. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2585. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2586. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2587. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2588. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2589. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2590. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2591. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2592. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2593. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2594. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2595. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2596. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2597. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2598. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2599. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2600. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2601. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2602. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2603. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2604. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2605. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2606. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2607. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2608. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2609. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2610. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2611. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2612. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2613. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2614. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2615. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2616. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2617. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2618. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2619. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2620. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2621. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2622. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2623. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2624. };
  2625. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2626. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2627. return i < 0 ? 0 : i > 255 ? 255 : i;
  2628. }
  2629. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2630. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2631. return i < 0 ? 0 : i > 360 ? 360 : i;
  2632. }
  2633. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2634. return f < 0 ? 0 : f > 1 ? 1 : f;
  2635. }
  2636. function parseCssInt(str) { // int or percentage.
  2637. if (str.length && str.charAt(str.length - 1) === '%') {
  2638. return clampCssByte(parseFloat(str) / 100 * 255);
  2639. }
  2640. return clampCssByte(parseInt(str, 10));
  2641. }
  2642. function parseCssFloat(str) { // float or percentage.
  2643. if (str.length && str.charAt(str.length - 1) === '%') {
  2644. return clampCssFloat(parseFloat(str) / 100);
  2645. }
  2646. return clampCssFloat(parseFloat(str));
  2647. }
  2648. function cssHueToRgb(m1, m2, h) {
  2649. if (h < 0) {
  2650. h += 1;
  2651. }
  2652. else if (h > 1) {
  2653. h -= 1;
  2654. }
  2655. if (h * 6 < 1) {
  2656. return m1 + (m2 - m1) * h * 6;
  2657. }
  2658. if (h * 2 < 1) {
  2659. return m2;
  2660. }
  2661. if (h * 3 < 2) {
  2662. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2663. }
  2664. return m1;
  2665. }
  2666. function lerpNumber(a, b, p) {
  2667. return a + (b - a) * p;
  2668. }
  2669. function setRgba(out, r, g, b, a) {
  2670. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2671. return out;
  2672. }
  2673. function copyRgba(out, a) {
  2674. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2675. return out;
  2676. }
  2677. var colorCache = new LRU(20);
  2678. var lastRemovedArr = null;
  2679. function putToCache(colorStr, rgbaArr) {
  2680. // Reuse removed array
  2681. if (lastRemovedArr) {
  2682. copyRgba(lastRemovedArr, rgbaArr);
  2683. }
  2684. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2685. }
  2686. /**
  2687. * @param {string} colorStr
  2688. * @param {Array.<number>} out
  2689. * @return {Array.<number>}
  2690. * @memberOf module:zrender/util/color
  2691. */
  2692. function parse(colorStr, rgbaArr) {
  2693. if (!colorStr) {
  2694. return;
  2695. }
  2696. rgbaArr = rgbaArr || [];
  2697. var cached = colorCache.get(colorStr);
  2698. if (cached) {
  2699. return copyRgba(rgbaArr, cached);
  2700. }
  2701. // colorStr may be not string
  2702. colorStr = colorStr + '';
  2703. // Remove all whitespace, not compliant, but should just be more accepting.
  2704. var str = colorStr.replace(/ /g, '').toLowerCase();
  2705. // Color keywords (and transparent) lookup.
  2706. if (str in kCSSColorTable) {
  2707. copyRgba(rgbaArr, kCSSColorTable[str]);
  2708. putToCache(colorStr, rgbaArr);
  2709. return rgbaArr;
  2710. }
  2711. // #abc and #abc123 syntax.
  2712. if (str.charAt(0) === '#') {
  2713. if (str.length === 4) {
  2714. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2715. if (!(iv >= 0 && iv <= 0xfff)) {
  2716. setRgba(rgbaArr, 0, 0, 0, 1);
  2717. return; // Covers NaN.
  2718. }
  2719. setRgba(rgbaArr,
  2720. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2721. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2722. (iv & 0xf) | ((iv & 0xf) << 4),
  2723. 1
  2724. );
  2725. putToCache(colorStr, rgbaArr);
  2726. return rgbaArr;
  2727. }
  2728. else if (str.length === 7) {
  2729. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2730. if (!(iv >= 0 && iv <= 0xffffff)) {
  2731. setRgba(rgbaArr, 0, 0, 0, 1);
  2732. return; // Covers NaN.
  2733. }
  2734. setRgba(rgbaArr,
  2735. (iv & 0xff0000) >> 16,
  2736. (iv & 0xff00) >> 8,
  2737. iv & 0xff,
  2738. 1
  2739. );
  2740. putToCache(colorStr, rgbaArr);
  2741. return rgbaArr;
  2742. }
  2743. return;
  2744. }
  2745. var op = str.indexOf('('), ep = str.indexOf(')');
  2746. if (op !== -1 && ep + 1 === str.length) {
  2747. var fname = str.substr(0, op);
  2748. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2749. var alpha = 1; // To allow case fallthrough.
  2750. switch (fname) {
  2751. case 'rgba':
  2752. if (params.length !== 4) {
  2753. setRgba(rgbaArr, 0, 0, 0, 1);
  2754. return;
  2755. }
  2756. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2757. // Fall through.
  2758. case 'rgb':
  2759. if (params.length !== 3) {
  2760. setRgba(rgbaArr, 0, 0, 0, 1);
  2761. return;
  2762. }
  2763. setRgba(rgbaArr,
  2764. parseCssInt(params[0]),
  2765. parseCssInt(params[1]),
  2766. parseCssInt(params[2]),
  2767. alpha
  2768. );
  2769. putToCache(colorStr, rgbaArr);
  2770. return rgbaArr;
  2771. case 'hsla':
  2772. if (params.length !== 4) {
  2773. setRgba(rgbaArr, 0, 0, 0, 1);
  2774. return;
  2775. }
  2776. params[3] = parseCssFloat(params[3]);
  2777. hsla2rgba(params, rgbaArr);
  2778. putToCache(colorStr, rgbaArr);
  2779. return rgbaArr;
  2780. case 'hsl':
  2781. if (params.length !== 3) {
  2782. setRgba(rgbaArr, 0, 0, 0, 1);
  2783. return;
  2784. }
  2785. hsla2rgba(params, rgbaArr);
  2786. putToCache(colorStr, rgbaArr);
  2787. return rgbaArr;
  2788. default:
  2789. return;
  2790. }
  2791. }
  2792. setRgba(rgbaArr, 0, 0, 0, 1);
  2793. return;
  2794. }
  2795. /**
  2796. * @param {Array.<number>} hsla
  2797. * @param {Array.<number>} rgba
  2798. * @return {Array.<number>} rgba
  2799. */
  2800. function hsla2rgba(hsla, rgba) {
  2801. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2802. // NOTE(deanm): According to the CSS spec s/l should only be
  2803. // percentages, but we don't bother and let float or percentage.
  2804. var s = parseCssFloat(hsla[1]);
  2805. var l = parseCssFloat(hsla[2]);
  2806. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2807. var m1 = l * 2 - m2;
  2808. rgba = rgba || [];
  2809. setRgba(rgba,
  2810. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2811. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2812. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2813. 1
  2814. );
  2815. if (hsla.length === 4) {
  2816. rgba[3] = hsla[3];
  2817. }
  2818. return rgba;
  2819. }
  2820. /**
  2821. * @param {Array.<number>} rgba
  2822. * @return {Array.<number>} hsla
  2823. */
  2824. function rgba2hsla(rgba) {
  2825. if (!rgba) {
  2826. return;
  2827. }
  2828. // RGB from 0 to 255
  2829. var R = rgba[0] / 255;
  2830. var G = rgba[1] / 255;
  2831. var B = rgba[2] / 255;
  2832. var vMin = Math.min(R, G, B); // Min. value of RGB
  2833. var vMax = Math.max(R, G, B); // Max. value of RGB
  2834. var delta = vMax - vMin; // Delta RGB value
  2835. var L = (vMax + vMin) / 2;
  2836. var H;
  2837. var S;
  2838. // HSL results from 0 to 1
  2839. if (delta === 0) {
  2840. H = 0;
  2841. S = 0;
  2842. }
  2843. else {
  2844. if (L < 0.5) {
  2845. S = delta / (vMax + vMin);
  2846. }
  2847. else {
  2848. S = delta / (2 - vMax - vMin);
  2849. }
  2850. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2851. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2852. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2853. if (R === vMax) {
  2854. H = deltaB - deltaG;
  2855. }
  2856. else if (G === vMax) {
  2857. H = (1 / 3) + deltaR - deltaB;
  2858. }
  2859. else if (B === vMax) {
  2860. H = (2 / 3) + deltaG - deltaR;
  2861. }
  2862. if (H < 0) {
  2863. H += 1;
  2864. }
  2865. if (H > 1) {
  2866. H -= 1;
  2867. }
  2868. }
  2869. var hsla = [H * 360, S, L];
  2870. if (rgba[3] != null) {
  2871. hsla.push(rgba[3]);
  2872. }
  2873. return hsla;
  2874. }
  2875. /**
  2876. * @param {string} color
  2877. * @param {number} level
  2878. * @return {string}
  2879. * @memberOf module:zrender/util/color
  2880. */
  2881. function lift(color, level) {
  2882. var colorArr = parse(color);
  2883. if (colorArr) {
  2884. for (var i = 0; i < 3; i++) {
  2885. if (level < 0) {
  2886. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2887. }
  2888. else {
  2889. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2890. }
  2891. }
  2892. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2893. }
  2894. }
  2895. /**
  2896. * @param {string} color
  2897. * @return {string}
  2898. * @memberOf module:zrender/util/color
  2899. */
  2900. function toHex(color) {
  2901. var colorArr = parse(color);
  2902. if (colorArr) {
  2903. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2904. }
  2905. }
  2906. /**
  2907. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  2908. * @param {number} normalizedValue A float between 0 and 1.
  2909. * @param {Array.<Array.<number>>} colors List of rgba color array
  2910. * @param {Array.<number>} [out] Mapped gba color array
  2911. * @return {Array.<number>} will be null/undefined if input illegal.
  2912. */
  2913. function fastLerp(normalizedValue, colors, out) {
  2914. if (!(colors && colors.length)
  2915. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2916. ) {
  2917. return;
  2918. }
  2919. out = out || [];
  2920. var value = normalizedValue * (colors.length - 1);
  2921. var leftIndex = Math.floor(value);
  2922. var rightIndex = Math.ceil(value);
  2923. var leftColor = colors[leftIndex];
  2924. var rightColor = colors[rightIndex];
  2925. var dv = value - leftIndex;
  2926. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  2927. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  2928. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  2929. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  2930. return out;
  2931. }
  2932. /**
  2933. * @deprecated
  2934. */
  2935. var fastMapToColor = fastLerp;
  2936. /**
  2937. * @param {number} normalizedValue A float between 0 and 1.
  2938. * @param {Array.<string>} colors Color list.
  2939. * @param {boolean=} fullOutput Default false.
  2940. * @return {(string|Object)} Result color. If fullOutput,
  2941. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  2942. * @memberOf module:zrender/util/color
  2943. */
  2944. function lerp$1(normalizedValue, colors, fullOutput) {
  2945. if (!(colors && colors.length)
  2946. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2947. ) {
  2948. return;
  2949. }
  2950. var value = normalizedValue * (colors.length - 1);
  2951. var leftIndex = Math.floor(value);
  2952. var rightIndex = Math.ceil(value);
  2953. var leftColor = parse(colors[leftIndex]);
  2954. var rightColor = parse(colors[rightIndex]);
  2955. var dv = value - leftIndex;
  2956. var color = stringify(
  2957. [
  2958. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  2959. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  2960. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  2961. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  2962. ],
  2963. 'rgba'
  2964. );
  2965. return fullOutput
  2966. ? {
  2967. color: color,
  2968. leftIndex: leftIndex,
  2969. rightIndex: rightIndex,
  2970. value: value
  2971. }
  2972. : color;
  2973. }
  2974. /**
  2975. * @deprecated
  2976. */
  2977. var mapToColor = lerp$1;
  2978. /**
  2979. * @param {string} color
  2980. * @param {number=} h 0 ~ 360, ignore when null.
  2981. * @param {number=} s 0 ~ 1, ignore when null.
  2982. * @param {number=} l 0 ~ 1, ignore when null.
  2983. * @return {string} Color string in rgba format.
  2984. * @memberOf module:zrender/util/color
  2985. */
  2986. function modifyHSL(color, h, s, l) {
  2987. color = parse(color);
  2988. if (color) {
  2989. color = rgba2hsla(color);
  2990. h != null && (color[0] = clampCssAngle(h));
  2991. s != null && (color[1] = parseCssFloat(s));
  2992. l != null && (color[2] = parseCssFloat(l));
  2993. return stringify(hsla2rgba(color), 'rgba');
  2994. }
  2995. }
  2996. /**
  2997. * @param {string} color
  2998. * @param {number=} alpha 0 ~ 1
  2999. * @return {string} Color string in rgba format.
  3000. * @memberOf module:zrender/util/color
  3001. */
  3002. function modifyAlpha(color, alpha) {
  3003. color = parse(color);
  3004. if (color && alpha != null) {
  3005. color[3] = clampCssFloat(alpha);
  3006. return stringify(color, 'rgba');
  3007. }
  3008. }
  3009. /**
  3010. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3011. * @param {string} type 'rgba', 'hsva', ...
  3012. * @return {string} Result color. (If input illegal, return undefined).
  3013. */
  3014. function stringify(arrColor, type) {
  3015. if (!arrColor || !arrColor.length) {
  3016. return;
  3017. }
  3018. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3019. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3020. colorStr += ',' + arrColor[3];
  3021. }
  3022. return type + '(' + colorStr + ')';
  3023. }
  3024. var color = (Object.freeze || Object)({
  3025. parse: parse,
  3026. lift: lift,
  3027. toHex: toHex,
  3028. fastLerp: fastLerp,
  3029. fastMapToColor: fastMapToColor,
  3030. lerp: lerp$1,
  3031. mapToColor: mapToColor,
  3032. modifyHSL: modifyHSL,
  3033. modifyAlpha: modifyAlpha,
  3034. stringify: stringify
  3035. });
  3036. /**
  3037. * @module echarts/animation/Animator
  3038. */
  3039. var arraySlice = Array.prototype.slice;
  3040. function defaultGetter(target, key) {
  3041. return target[key];
  3042. }
  3043. function defaultSetter(target, key, value) {
  3044. target[key] = value;
  3045. }
  3046. /**
  3047. * @param {number} p0
  3048. * @param {number} p1
  3049. * @param {number} percent
  3050. * @return {number}
  3051. */
  3052. function interpolateNumber(p0, p1, percent) {
  3053. return (p1 - p0) * percent + p0;
  3054. }
  3055. /**
  3056. * @param {string} p0
  3057. * @param {string} p1
  3058. * @param {number} percent
  3059. * @return {string}
  3060. */
  3061. function interpolateString(p0, p1, percent) {
  3062. return percent > 0.5 ? p1 : p0;
  3063. }
  3064. /**
  3065. * @param {Array} p0
  3066. * @param {Array} p1
  3067. * @param {number} percent
  3068. * @param {Array} out
  3069. * @param {number} arrDim
  3070. */
  3071. function interpolateArray(p0, p1, percent, out, arrDim) {
  3072. var len = p0.length;
  3073. if (arrDim == 1) {
  3074. for (var i = 0; i < len; i++) {
  3075. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3076. }
  3077. }
  3078. else {
  3079. var len2 = len && p0[0].length;
  3080. for (var i = 0; i < len; i++) {
  3081. for (var j = 0; j < len2; j++) {
  3082. out[i][j] = interpolateNumber(
  3083. p0[i][j], p1[i][j], percent
  3084. );
  3085. }
  3086. }
  3087. }
  3088. }
  3089. // arr0 is source array, arr1 is target array.
  3090. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3091. function fillArr(arr0, arr1, arrDim) {
  3092. var arr0Len = arr0.length;
  3093. var arr1Len = arr1.length;
  3094. if (arr0Len !== arr1Len) {
  3095. // FIXME Not work for TypedArray
  3096. var isPreviousLarger = arr0Len > arr1Len;
  3097. if (isPreviousLarger) {
  3098. // Cut the previous
  3099. arr0.length = arr1Len;
  3100. }
  3101. else {
  3102. // Fill the previous
  3103. for (var i = arr0Len; i < arr1Len; i++) {
  3104. arr0.push(
  3105. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3106. );
  3107. }
  3108. }
  3109. }
  3110. // Handling NaN value
  3111. var len2 = arr0[0] && arr0[0].length;
  3112. for (var i = 0; i < arr0.length; i++) {
  3113. if (arrDim === 1) {
  3114. if (isNaN(arr0[i])) {
  3115. arr0[i] = arr1[i];
  3116. }
  3117. }
  3118. else {
  3119. for (var j = 0; j < len2; j++) {
  3120. if (isNaN(arr0[i][j])) {
  3121. arr0[i][j] = arr1[i][j];
  3122. }
  3123. }
  3124. }
  3125. }
  3126. }
  3127. /**
  3128. * @param {Array} arr0
  3129. * @param {Array} arr1
  3130. * @param {number} arrDim
  3131. * @return {boolean}
  3132. */
  3133. function isArraySame(arr0, arr1, arrDim) {
  3134. if (arr0 === arr1) {
  3135. return true;
  3136. }
  3137. var len = arr0.length;
  3138. if (len !== arr1.length) {
  3139. return false;
  3140. }
  3141. if (arrDim === 1) {
  3142. for (var i = 0; i < len; i++) {
  3143. if (arr0[i] !== arr1[i]) {
  3144. return false;
  3145. }
  3146. }
  3147. }
  3148. else {
  3149. var len2 = arr0[0].length;
  3150. for (var i = 0; i < len; i++) {
  3151. for (var j = 0; j < len2; j++) {
  3152. if (arr0[i][j] !== arr1[i][j]) {
  3153. return false;
  3154. }
  3155. }
  3156. }
  3157. }
  3158. return true;
  3159. }
  3160. /**
  3161. * Catmull Rom interpolate array
  3162. * @param {Array} p0
  3163. * @param {Array} p1
  3164. * @param {Array} p2
  3165. * @param {Array} p3
  3166. * @param {number} t
  3167. * @param {number} t2
  3168. * @param {number} t3
  3169. * @param {Array} out
  3170. * @param {number} arrDim
  3171. */
  3172. function catmullRomInterpolateArray(
  3173. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3174. ) {
  3175. var len = p0.length;
  3176. if (arrDim == 1) {
  3177. for (var i = 0; i < len; i++) {
  3178. out[i] = catmullRomInterpolate(
  3179. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3180. );
  3181. }
  3182. }
  3183. else {
  3184. var len2 = p0[0].length;
  3185. for (var i = 0; i < len; i++) {
  3186. for (var j = 0; j < len2; j++) {
  3187. out[i][j] = catmullRomInterpolate(
  3188. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3189. t, t2, t3
  3190. );
  3191. }
  3192. }
  3193. }
  3194. }
  3195. /**
  3196. * Catmull Rom interpolate number
  3197. * @param {number} p0
  3198. * @param {number} p1
  3199. * @param {number} p2
  3200. * @param {number} p3
  3201. * @param {number} t
  3202. * @param {number} t2
  3203. * @param {number} t3
  3204. * @return {number}
  3205. */
  3206. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3207. var v0 = (p2 - p0) * 0.5;
  3208. var v1 = (p3 - p1) * 0.5;
  3209. return (2 * (p1 - p2) + v0 + v1) * t3
  3210. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3211. + v0 * t + p1;
  3212. }
  3213. function cloneValue(value) {
  3214. if (isArrayLike(value)) {
  3215. var len = value.length;
  3216. if (isArrayLike(value[0])) {
  3217. var ret = [];
  3218. for (var i = 0; i < len; i++) {
  3219. ret.push(arraySlice.call(value[i]));
  3220. }
  3221. return ret;
  3222. }
  3223. return arraySlice.call(value);
  3224. }
  3225. return value;
  3226. }
  3227. function rgba2String(rgba) {
  3228. rgba[0] = Math.floor(rgba[0]);
  3229. rgba[1] = Math.floor(rgba[1]);
  3230. rgba[2] = Math.floor(rgba[2]);
  3231. return 'rgba(' + rgba.join(',') + ')';
  3232. }
  3233. function getArrayDim(keyframes) {
  3234. var lastValue = keyframes[keyframes.length - 1].value;
  3235. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3236. }
  3237. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3238. var getter = animator._getter;
  3239. var setter = animator._setter;
  3240. var useSpline = easing === 'spline';
  3241. var trackLen = keyframes.length;
  3242. if (!trackLen) {
  3243. return;
  3244. }
  3245. // Guess data type
  3246. var firstVal = keyframes[0].value;
  3247. var isValueArray = isArrayLike(firstVal);
  3248. var isValueColor = false;
  3249. var isValueString = false;
  3250. // For vertices morphing
  3251. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3252. var trackMaxTime;
  3253. // Sort keyframe as ascending
  3254. keyframes.sort(function(a, b) {
  3255. return a.time - b.time;
  3256. });
  3257. trackMaxTime = keyframes[trackLen - 1].time;
  3258. // Percents of each keyframe
  3259. var kfPercents = [];
  3260. // Value of each keyframe
  3261. var kfValues = [];
  3262. var prevValue = keyframes[0].value;
  3263. var isAllValueEqual = true;
  3264. for (var i = 0; i < trackLen; i++) {
  3265. kfPercents.push(keyframes[i].time / trackMaxTime);
  3266. // Assume value is a color when it is a string
  3267. var value = keyframes[i].value;
  3268. // Check if value is equal, deep check if value is array
  3269. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3270. || (!isValueArray && value === prevValue))) {
  3271. isAllValueEqual = false;
  3272. }
  3273. prevValue = value;
  3274. // Try converting a string to a color array
  3275. if (typeof value == 'string') {
  3276. var colorArray = parse(value);
  3277. if (colorArray) {
  3278. value = colorArray;
  3279. isValueColor = true;
  3280. }
  3281. else {
  3282. isValueString = true;
  3283. }
  3284. }
  3285. kfValues.push(value);
  3286. }
  3287. if (!forceAnimate && isAllValueEqual) {
  3288. return;
  3289. }
  3290. var lastValue = kfValues[trackLen - 1];
  3291. // Polyfill array and NaN value
  3292. for (var i = 0; i < trackLen - 1; i++) {
  3293. if (isValueArray) {
  3294. fillArr(kfValues[i], lastValue, arrDim);
  3295. }
  3296. else {
  3297. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3298. kfValues[i] = lastValue;
  3299. }
  3300. }
  3301. }
  3302. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3303. // Cache the key of last frame to speed up when
  3304. // animation playback is sequency
  3305. var lastFrame = 0;
  3306. var lastFramePercent = 0;
  3307. var start;
  3308. var w;
  3309. var p0;
  3310. var p1;
  3311. var p2;
  3312. var p3;
  3313. if (isValueColor) {
  3314. var rgba = [0, 0, 0, 0];
  3315. }
  3316. var onframe = function (target, percent) {
  3317. // Find the range keyframes
  3318. // kf1-----kf2---------current--------kf3
  3319. // find kf2 and kf3 and do interpolation
  3320. var frame;
  3321. // In the easing function like elasticOut, percent may less than 0
  3322. if (percent < 0) {
  3323. frame = 0;
  3324. }
  3325. else if (percent < lastFramePercent) {
  3326. // Start from next key
  3327. // PENDING start from lastFrame ?
  3328. start = Math.min(lastFrame + 1, trackLen - 1);
  3329. for (frame = start; frame >= 0; frame--) {
  3330. if (kfPercents[frame] <= percent) {
  3331. break;
  3332. }
  3333. }
  3334. // PENDING really need to do this ?
  3335. frame = Math.min(frame, trackLen - 2);
  3336. }
  3337. else {
  3338. for (frame = lastFrame; frame < trackLen; frame++) {
  3339. if (kfPercents[frame] > percent) {
  3340. break;
  3341. }
  3342. }
  3343. frame = Math.min(frame - 1, trackLen - 2);
  3344. }
  3345. lastFrame = frame;
  3346. lastFramePercent = percent;
  3347. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3348. if (range === 0) {
  3349. return;
  3350. }
  3351. else {
  3352. w = (percent - kfPercents[frame]) / range;
  3353. }
  3354. if (useSpline) {
  3355. p1 = kfValues[frame];
  3356. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3357. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3358. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3359. if (isValueArray) {
  3360. catmullRomInterpolateArray(
  3361. p0, p1, p2, p3, w, w * w, w * w * w,
  3362. getter(target, propName),
  3363. arrDim
  3364. );
  3365. }
  3366. else {
  3367. var value;
  3368. if (isValueColor) {
  3369. value = catmullRomInterpolateArray(
  3370. p0, p1, p2, p3, w, w * w, w * w * w,
  3371. rgba, 1
  3372. );
  3373. value = rgba2String(rgba);
  3374. }
  3375. else if (isValueString) {
  3376. // String is step(0.5)
  3377. return interpolateString(p1, p2, w);
  3378. }
  3379. else {
  3380. value = catmullRomInterpolate(
  3381. p0, p1, p2, p3, w, w * w, w * w * w
  3382. );
  3383. }
  3384. setter(
  3385. target,
  3386. propName,
  3387. value
  3388. );
  3389. }
  3390. }
  3391. else {
  3392. if (isValueArray) {
  3393. interpolateArray(
  3394. kfValues[frame], kfValues[frame + 1], w,
  3395. getter(target, propName),
  3396. arrDim
  3397. );
  3398. }
  3399. else {
  3400. var value;
  3401. if (isValueColor) {
  3402. interpolateArray(
  3403. kfValues[frame], kfValues[frame + 1], w,
  3404. rgba, 1
  3405. );
  3406. value = rgba2String(rgba);
  3407. }
  3408. else if (isValueString) {
  3409. // String is step(0.5)
  3410. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3411. }
  3412. else {
  3413. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3414. }
  3415. setter(
  3416. target,
  3417. propName,
  3418. value
  3419. );
  3420. }
  3421. }
  3422. };
  3423. var clip = new Clip({
  3424. target: animator._target,
  3425. life: trackMaxTime,
  3426. loop: animator._loop,
  3427. delay: animator._delay,
  3428. onframe: onframe,
  3429. ondestroy: oneTrackDone
  3430. });
  3431. if (easing && easing !== 'spline') {
  3432. clip.easing = easing;
  3433. }
  3434. return clip;
  3435. }
  3436. /**
  3437. * @alias module:zrender/animation/Animator
  3438. * @constructor
  3439. * @param {Object} target
  3440. * @param {boolean} loop
  3441. * @param {Function} getter
  3442. * @param {Function} setter
  3443. */
  3444. var Animator = function(target, loop, getter, setter) {
  3445. this._tracks = {};
  3446. this._target = target;
  3447. this._loop = loop || false;
  3448. this._getter = getter || defaultGetter;
  3449. this._setter = setter || defaultSetter;
  3450. this._clipCount = 0;
  3451. this._delay = 0;
  3452. this._doneList = [];
  3453. this._onframeList = [];
  3454. this._clipList = [];
  3455. };
  3456. Animator.prototype = {
  3457. /**
  3458. * 设置动画关键帧
  3459. * @param {number} time 关键帧时间,单位是ms
  3460. * @param {Object} props 关键帧的属性值,key-value表示
  3461. * @return {module:zrender/animation/Animator}
  3462. */
  3463. when: function(time /* ms */, props) {
  3464. var tracks = this._tracks;
  3465. for (var propName in props) {
  3466. if (!props.hasOwnProperty(propName)) {
  3467. continue;
  3468. }
  3469. if (!tracks[propName]) {
  3470. tracks[propName] = [];
  3471. // Invalid value
  3472. var value = this._getter(this._target, propName);
  3473. if (value == null) {
  3474. // zrLog('Invalid property ' + propName);
  3475. continue;
  3476. }
  3477. // If time is 0
  3478. // Then props is given initialize value
  3479. // Else
  3480. // Initialize value from current prop value
  3481. if (time !== 0) {
  3482. tracks[propName].push({
  3483. time: 0,
  3484. value: cloneValue(value)
  3485. });
  3486. }
  3487. }
  3488. tracks[propName].push({
  3489. time: time,
  3490. value: props[propName]
  3491. });
  3492. }
  3493. return this;
  3494. },
  3495. /**
  3496. * 添加动画每一帧的回调函数
  3497. * @param {Function} callback
  3498. * @return {module:zrender/animation/Animator}
  3499. */
  3500. during: function (callback) {
  3501. this._onframeList.push(callback);
  3502. return this;
  3503. },
  3504. pause: function () {
  3505. for (var i = 0; i < this._clipList.length; i++) {
  3506. this._clipList[i].pause();
  3507. }
  3508. this._paused = true;
  3509. },
  3510. resume: function () {
  3511. for (var i = 0; i < this._clipList.length; i++) {
  3512. this._clipList[i].resume();
  3513. }
  3514. this._paused = false;
  3515. },
  3516. isPaused: function () {
  3517. return !!this._paused;
  3518. },
  3519. _doneCallback: function () {
  3520. // Clear all tracks
  3521. this._tracks = {};
  3522. // Clear all clips
  3523. this._clipList.length = 0;
  3524. var doneList = this._doneList;
  3525. var len = doneList.length;
  3526. for (var i = 0; i < len; i++) {
  3527. doneList[i].call(this);
  3528. }
  3529. },
  3530. /**
  3531. * 开始执行动画
  3532. * @param {string|Function} [easing]
  3533. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3534. * @param {boolean} forceAnimate
  3535. * @return {module:zrender/animation/Animator}
  3536. */
  3537. start: function (easing, forceAnimate) {
  3538. var self = this;
  3539. var clipCount = 0;
  3540. var oneTrackDone = function() {
  3541. clipCount--;
  3542. if (!clipCount) {
  3543. self._doneCallback();
  3544. }
  3545. };
  3546. var lastClip;
  3547. for (var propName in this._tracks) {
  3548. if (!this._tracks.hasOwnProperty(propName)) {
  3549. continue;
  3550. }
  3551. var clip = createTrackClip(
  3552. this, easing, oneTrackDone,
  3553. this._tracks[propName], propName, forceAnimate
  3554. );
  3555. if (clip) {
  3556. this._clipList.push(clip);
  3557. clipCount++;
  3558. // If start after added to animation
  3559. if (this.animation) {
  3560. this.animation.addClip(clip);
  3561. }
  3562. lastClip = clip;
  3563. }
  3564. }
  3565. // Add during callback on the last clip
  3566. if (lastClip) {
  3567. var oldOnFrame = lastClip.onframe;
  3568. lastClip.onframe = function (target, percent) {
  3569. oldOnFrame(target, percent);
  3570. for (var i = 0; i < self._onframeList.length; i++) {
  3571. self._onframeList[i](target, percent);
  3572. }
  3573. };
  3574. }
  3575. // This optimization will help the case that in the upper application
  3576. // the view may be refreshed frequently, where animation will be
  3577. // called repeatly but nothing changed.
  3578. if (!clipCount) {
  3579. this._doneCallback();
  3580. }
  3581. return this;
  3582. },
  3583. /**
  3584. * 停止动画
  3585. * @param {boolean} forwardToLast If move to last frame before stop
  3586. */
  3587. stop: function (forwardToLast) {
  3588. var clipList = this._clipList;
  3589. var animation = this.animation;
  3590. for (var i = 0; i < clipList.length; i++) {
  3591. var clip = clipList[i];
  3592. if (forwardToLast) {
  3593. // Move to last frame before stop
  3594. clip.onframe(this._target, 1);
  3595. }
  3596. animation && animation.removeClip(clip);
  3597. }
  3598. clipList.length = 0;
  3599. },
  3600. /**
  3601. * 设置动画延迟开始的时间
  3602. * @param {number} time 单位ms
  3603. * @return {module:zrender/animation/Animator}
  3604. */
  3605. delay: function (time) {
  3606. this._delay = time;
  3607. return this;
  3608. },
  3609. /**
  3610. * 添加动画结束的回调
  3611. * @param {Function} cb
  3612. * @return {module:zrender/animation/Animator}
  3613. */
  3614. done: function(cb) {
  3615. if (cb) {
  3616. this._doneList.push(cb);
  3617. }
  3618. return this;
  3619. },
  3620. /**
  3621. * @return {Array.<module:zrender/animation/Clip>}
  3622. */
  3623. getClips: function () {
  3624. return this._clipList;
  3625. }
  3626. };
  3627. var dpr = 1;
  3628. // If in browser environment
  3629. if (typeof window !== 'undefined') {
  3630. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3631. }
  3632. /**
  3633. * config默认配置项
  3634. * @exports zrender/config
  3635. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3636. */
  3637. /**
  3638. * debug日志选项:catchBrushException为true下有效
  3639. * 0 : 不生成debug数据,发布用
  3640. * 1 : 异常抛出,调试用
  3641. * 2 : 控制台输出,调试用
  3642. */
  3643. var debugMode = 0;
  3644. // retina 屏幕优化
  3645. var devicePixelRatio = dpr;
  3646. var log = function () {
  3647. };
  3648. if (debugMode === 1) {
  3649. log = function () {
  3650. for (var k in arguments) {
  3651. throw new Error(arguments[k]);
  3652. }
  3653. };
  3654. }
  3655. else if (debugMode > 1) {
  3656. log = function () {
  3657. for (var k in arguments) {
  3658. console.log(arguments[k]);
  3659. }
  3660. };
  3661. }
  3662. var zrLog = log;
  3663. /**
  3664. * @alias modue:zrender/mixin/Animatable
  3665. * @constructor
  3666. */
  3667. var Animatable = function () {
  3668. /**
  3669. * @type {Array.<module:zrender/animation/Animator>}
  3670. * @readOnly
  3671. */
  3672. this.animators = [];
  3673. };
  3674. Animatable.prototype = {
  3675. constructor: Animatable,
  3676. /**
  3677. * 动画
  3678. *
  3679. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3680. * @param {boolean} [loop] Whether to loop animation.
  3681. * @return {module:zrender/animation/Animator}
  3682. * @example:
  3683. * el.animate('style', false)
  3684. * .when(1000, {x: 10} )
  3685. * .done(function(){ // Animation done })
  3686. * .start()
  3687. */
  3688. animate: function (path, loop) {
  3689. var target;
  3690. var animatingShape = false;
  3691. var el = this;
  3692. var zr = this.__zr;
  3693. if (path) {
  3694. var pathSplitted = path.split('.');
  3695. var prop = el;
  3696. // If animating shape
  3697. animatingShape = pathSplitted[0] === 'shape';
  3698. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3699. if (!prop) {
  3700. continue;
  3701. }
  3702. prop = prop[pathSplitted[i]];
  3703. }
  3704. if (prop) {
  3705. target = prop;
  3706. }
  3707. }
  3708. else {
  3709. target = el;
  3710. }
  3711. if (!target) {
  3712. zrLog(
  3713. 'Property "'
  3714. + path
  3715. + '" is not existed in element '
  3716. + el.id
  3717. );
  3718. return;
  3719. }
  3720. var animators = el.animators;
  3721. var animator = new Animator(target, loop);
  3722. animator.during(function (target) {
  3723. el.dirty(animatingShape);
  3724. })
  3725. .done(function () {
  3726. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3727. animators.splice(indexOf(animators, animator), 1);
  3728. });
  3729. animators.push(animator);
  3730. // If animate after added to the zrender
  3731. if (zr) {
  3732. zr.animation.addAnimator(animator);
  3733. }
  3734. return animator;
  3735. },
  3736. /**
  3737. * 停止动画
  3738. * @param {boolean} forwardToLast If move to last frame before stop
  3739. */
  3740. stopAnimation: function (forwardToLast) {
  3741. var animators = this.animators;
  3742. var len = animators.length;
  3743. for (var i = 0; i < len; i++) {
  3744. animators[i].stop(forwardToLast);
  3745. }
  3746. animators.length = 0;
  3747. return this;
  3748. },
  3749. /**
  3750. * Caution: this method will stop previous animation.
  3751. * So do not use this method to one element twice before
  3752. * animation starts, unless you know what you are doing.
  3753. * @param {Object} target
  3754. * @param {number} [time=500] Time in ms
  3755. * @param {string} [easing='linear']
  3756. * @param {number} [delay=0]
  3757. * @param {Function} [callback]
  3758. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3759. * immediently when target values are the same as current values.
  3760. *
  3761. * @example
  3762. * // Animate position
  3763. * el.animateTo({
  3764. * position: [10, 10]
  3765. * }, function () { // done })
  3766. *
  3767. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3768. * el.animateTo({
  3769. * shape: {
  3770. * width: 500
  3771. * },
  3772. * style: {
  3773. * fill: 'red'
  3774. * }
  3775. * position: [10, 10]
  3776. * }, 100, 100, 'cubicOut', function () { // done })
  3777. */
  3778. // TODO Return animation key
  3779. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3780. // animateTo(target, time, easing, callback);
  3781. if (isString(delay)) {
  3782. callback = easing;
  3783. easing = delay;
  3784. delay = 0;
  3785. }
  3786. // animateTo(target, time, delay, callback);
  3787. else if (isFunction(easing)) {
  3788. callback = easing;
  3789. easing = 'linear';
  3790. delay = 0;
  3791. }
  3792. // animateTo(target, time, callback);
  3793. else if (isFunction(delay)) {
  3794. callback = delay;
  3795. delay = 0;
  3796. }
  3797. // animateTo(target, callback)
  3798. else if (isFunction(time)) {
  3799. callback = time;
  3800. time = 500;
  3801. }
  3802. // animateTo(target)
  3803. else if (!time) {
  3804. time = 500;
  3805. }
  3806. // Stop all previous animations
  3807. this.stopAnimation();
  3808. this._animateToShallow('', this, target, time, delay);
  3809. // Animators may be removed immediately after start
  3810. // if there is nothing to animate
  3811. var animators = this.animators.slice();
  3812. var count = animators.length;
  3813. function done() {
  3814. count--;
  3815. if (!count) {
  3816. callback && callback();
  3817. }
  3818. }
  3819. // No animators. This should be checked before animators[i].start(),
  3820. // because 'done' may be executed immediately if no need to animate.
  3821. if (!count) {
  3822. callback && callback();
  3823. }
  3824. // Start after all animators created
  3825. // Incase any animator is done immediately when all animation properties are not changed
  3826. for (var i = 0; i < animators.length; i++) {
  3827. animators[i]
  3828. .done(done)
  3829. .start(easing, forceAnimate);
  3830. }
  3831. },
  3832. /**
  3833. * @private
  3834. * @param {string} path=''
  3835. * @param {Object} source=this
  3836. * @param {Object} target
  3837. * @param {number} [time=500]
  3838. * @param {number} [delay=0]
  3839. *
  3840. * @example
  3841. * // Animate position
  3842. * el._animateToShallow({
  3843. * position: [10, 10]
  3844. * })
  3845. *
  3846. * // Animate shape, style and position in 100ms, delayed 100ms
  3847. * el._animateToShallow({
  3848. * shape: {
  3849. * width: 500
  3850. * },
  3851. * style: {
  3852. * fill: 'red'
  3853. * }
  3854. * position: [10, 10]
  3855. * }, 100, 100)
  3856. */
  3857. _animateToShallow: function (path, source, target, time, delay) {
  3858. var objShallow = {};
  3859. var propertyCount = 0;
  3860. for (var name in target) {
  3861. if (!target.hasOwnProperty(name)) {
  3862. continue;
  3863. }
  3864. if (source[name] != null) {
  3865. if (isObject(target[name]) && !isArrayLike(target[name])) {
  3866. this._animateToShallow(
  3867. path ? path + '.' + name : name,
  3868. source[name],
  3869. target[name],
  3870. time,
  3871. delay
  3872. );
  3873. }
  3874. else {
  3875. objShallow[name] = target[name];
  3876. propertyCount++;
  3877. }
  3878. }
  3879. else if (target[name] != null) {
  3880. // Attr directly if not has property
  3881. // FIXME, if some property not needed for element ?
  3882. if (!path) {
  3883. this.attr(name, target[name]);
  3884. }
  3885. else { // Shape or style
  3886. var props = {};
  3887. props[path] = {};
  3888. props[path][name] = target[name];
  3889. this.attr(props);
  3890. }
  3891. }
  3892. }
  3893. if (propertyCount > 0) {
  3894. this.animate(path, false)
  3895. .when(time == null ? 500 : time, objShallow)
  3896. .delay(delay || 0);
  3897. }
  3898. return this;
  3899. }
  3900. };
  3901. /**
  3902. * @alias module:zrender/Element
  3903. * @constructor
  3904. * @extends {module:zrender/mixin/Animatable}
  3905. * @extends {module:zrender/mixin/Transformable}
  3906. * @extends {module:zrender/mixin/Eventful}
  3907. */
  3908. var Element = function (opts) { // jshint ignore:line
  3909. Transformable.call(this, opts);
  3910. Eventful.call(this, opts);
  3911. Animatable.call(this, opts);
  3912. /**
  3913. * 画布元素ID
  3914. * @type {string}
  3915. */
  3916. this.id = opts.id || guid();
  3917. };
  3918. Element.prototype = {
  3919. /**
  3920. * 元素类型
  3921. * Element type
  3922. * @type {string}
  3923. */
  3924. type: 'element',
  3925. /**
  3926. * 元素名字
  3927. * Element name
  3928. * @type {string}
  3929. */
  3930. name: '',
  3931. /**
  3932. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  3933. * ZRender instance will be assigned when element is associated with zrender
  3934. * @name module:/zrender/Element#__zr
  3935. * @type {module:zrender/ZRender}
  3936. */
  3937. __zr: null,
  3938. /**
  3939. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  3940. * If ignore drawing and events of the element object
  3941. * @name module:/zrender/Element#ignore
  3942. * @type {boolean}
  3943. * @default false
  3944. */
  3945. ignore: false,
  3946. /**
  3947. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  3948. * 该路径会继承被裁减对象的变换
  3949. * @type {module:zrender/graphic/Path}
  3950. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  3951. * @readOnly
  3952. */
  3953. clipPath: null,
  3954. /**
  3955. * Drift element
  3956. * @param {number} dx dx on the global space
  3957. * @param {number} dy dy on the global space
  3958. */
  3959. drift: function (dx, dy) {
  3960. switch (this.draggable) {
  3961. case 'horizontal':
  3962. dy = 0;
  3963. break;
  3964. case 'vertical':
  3965. dx = 0;
  3966. break;
  3967. }
  3968. var m = this.transform;
  3969. if (!m) {
  3970. m = this.transform = [1, 0, 0, 1, 0, 0];
  3971. }
  3972. m[4] += dx;
  3973. m[5] += dy;
  3974. this.decomposeTransform();
  3975. this.dirty(false);
  3976. },
  3977. /**
  3978. * Hook before update
  3979. */
  3980. beforeUpdate: function () {},
  3981. /**
  3982. * Hook after update
  3983. */
  3984. afterUpdate: function () {},
  3985. /**
  3986. * Update each frame
  3987. */
  3988. update: function () {
  3989. this.updateTransform();
  3990. },
  3991. /**
  3992. * @param {Function} cb
  3993. * @param {} context
  3994. */
  3995. traverse: function (cb, context) {},
  3996. /**
  3997. * @protected
  3998. */
  3999. attrKV: function (key, value) {
  4000. if (key === 'position' || key === 'scale' || key === 'origin') {
  4001. // Copy the array
  4002. if (value) {
  4003. var target = this[key];
  4004. if (!target) {
  4005. target = this[key] = [];
  4006. }
  4007. target[0] = value[0];
  4008. target[1] = value[1];
  4009. }
  4010. }
  4011. else {
  4012. this[key] = value;
  4013. }
  4014. },
  4015. /**
  4016. * Hide the element
  4017. */
  4018. hide: function () {
  4019. this.ignore = true;
  4020. this.__zr && this.__zr.refresh();
  4021. },
  4022. /**
  4023. * Show the element
  4024. */
  4025. show: function () {
  4026. this.ignore = false;
  4027. this.__zr && this.__zr.refresh();
  4028. },
  4029. /**
  4030. * @param {string|Object} key
  4031. * @param {*} value
  4032. */
  4033. attr: function (key, value) {
  4034. if (typeof key === 'string') {
  4035. this.attrKV(key, value);
  4036. }
  4037. else if (isObject(key)) {
  4038. for (var name in key) {
  4039. if (key.hasOwnProperty(name)) {
  4040. this.attrKV(name, key[name]);
  4041. }
  4042. }
  4043. }
  4044. this.dirty(false);
  4045. return this;
  4046. },
  4047. /**
  4048. * @param {module:zrender/graphic/Path} clipPath
  4049. */
  4050. setClipPath: function (clipPath) {
  4051. var zr = this.__zr;
  4052. if (zr) {
  4053. clipPath.addSelfToZr(zr);
  4054. }
  4055. // Remove previous clip path
  4056. if (this.clipPath && this.clipPath !== clipPath) {
  4057. this.removeClipPath();
  4058. }
  4059. this.clipPath = clipPath;
  4060. clipPath.__zr = zr;
  4061. clipPath.__clipTarget = this;
  4062. this.dirty(false);
  4063. },
  4064. /**
  4065. */
  4066. removeClipPath: function () {
  4067. var clipPath = this.clipPath;
  4068. if (clipPath) {
  4069. if (clipPath.__zr) {
  4070. clipPath.removeSelfFromZr(clipPath.__zr);
  4071. }
  4072. clipPath.__zr = null;
  4073. clipPath.__clipTarget = null;
  4074. this.clipPath = null;
  4075. this.dirty(false);
  4076. }
  4077. },
  4078. /**
  4079. * Add self from zrender instance.
  4080. * Not recursively because it will be invoked when element added to storage.
  4081. * @param {module:zrender/ZRender} zr
  4082. */
  4083. addSelfToZr: function (zr) {
  4084. this.__zr = zr;
  4085. // 添加动画
  4086. var animators = this.animators;
  4087. if (animators) {
  4088. for (var i = 0; i < animators.length; i++) {
  4089. zr.animation.addAnimator(animators[i]);
  4090. }
  4091. }
  4092. if (this.clipPath) {
  4093. this.clipPath.addSelfToZr(zr);
  4094. }
  4095. },
  4096. /**
  4097. * Remove self from zrender instance.
  4098. * Not recursively because it will be invoked when element added to storage.
  4099. * @param {module:zrender/ZRender} zr
  4100. */
  4101. removeSelfFromZr: function (zr) {
  4102. this.__zr = null;
  4103. // 移除动画
  4104. var animators = this.animators;
  4105. if (animators) {
  4106. for (var i = 0; i < animators.length; i++) {
  4107. zr.animation.removeAnimator(animators[i]);
  4108. }
  4109. }
  4110. if (this.clipPath) {
  4111. this.clipPath.removeSelfFromZr(zr);
  4112. }
  4113. }
  4114. };
  4115. mixin(Element, Animatable);
  4116. mixin(Element, Transformable);
  4117. mixin(Element, Eventful);
  4118. /**
  4119. * @module echarts/core/BoundingRect
  4120. */
  4121. var v2ApplyTransform = applyTransform;
  4122. var mathMin = Math.min;
  4123. var mathMax = Math.max;
  4124. /**
  4125. * @alias module:echarts/core/BoundingRect
  4126. */
  4127. function BoundingRect(x, y, width, height) {
  4128. if (width < 0) {
  4129. x = x + width;
  4130. width = -width;
  4131. }
  4132. if (height < 0) {
  4133. y = y + height;
  4134. height = -height;
  4135. }
  4136. /**
  4137. * @type {number}
  4138. */
  4139. this.x = x;
  4140. /**
  4141. * @type {number}
  4142. */
  4143. this.y = y;
  4144. /**
  4145. * @type {number}
  4146. */
  4147. this.width = width;
  4148. /**
  4149. * @type {number}
  4150. */
  4151. this.height = height;
  4152. }
  4153. BoundingRect.prototype = {
  4154. constructor: BoundingRect,
  4155. /**
  4156. * @param {module:echarts/core/BoundingRect} other
  4157. */
  4158. union: function (other) {
  4159. var x = mathMin(other.x, this.x);
  4160. var y = mathMin(other.y, this.y);
  4161. this.width = mathMax(
  4162. other.x + other.width,
  4163. this.x + this.width
  4164. ) - x;
  4165. this.height = mathMax(
  4166. other.y + other.height,
  4167. this.y + this.height
  4168. ) - y;
  4169. this.x = x;
  4170. this.y = y;
  4171. },
  4172. /**
  4173. * @param {Array.<number>} m
  4174. * @methods
  4175. */
  4176. applyTransform: (function () {
  4177. var lt = [];
  4178. var rb = [];
  4179. var lb = [];
  4180. var rt = [];
  4181. return function (m) {
  4182. // In case usage like this
  4183. // el.getBoundingRect().applyTransform(el.transform)
  4184. // And element has no transform
  4185. if (!m) {
  4186. return;
  4187. }
  4188. lt[0] = lb[0] = this.x;
  4189. lt[1] = rt[1] = this.y;
  4190. rb[0] = rt[0] = this.x + this.width;
  4191. rb[1] = lb[1] = this.y + this.height;
  4192. v2ApplyTransform(lt, lt, m);
  4193. v2ApplyTransform(rb, rb, m);
  4194. v2ApplyTransform(lb, lb, m);
  4195. v2ApplyTransform(rt, rt, m);
  4196. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4197. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4198. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4199. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4200. this.width = maxX - this.x;
  4201. this.height = maxY - this.y;
  4202. };
  4203. })(),
  4204. /**
  4205. * Calculate matrix of transforming from self to target rect
  4206. * @param {module:zrender/core/BoundingRect} b
  4207. * @return {Array.<number>}
  4208. */
  4209. calculateTransform: function (b) {
  4210. var a = this;
  4211. var sx = b.width / a.width;
  4212. var sy = b.height / a.height;
  4213. var m = create$1();
  4214. // 矩阵右乘
  4215. translate(m, m, [-a.x, -a.y]);
  4216. scale$1(m, m, [sx, sy]);
  4217. translate(m, m, [b.x, b.y]);
  4218. return m;
  4219. },
  4220. /**
  4221. * @param {(module:echarts/core/BoundingRect|Object)} b
  4222. * @return {boolean}
  4223. */
  4224. intersect: function (b) {
  4225. if (!b) {
  4226. return false;
  4227. }
  4228. if (!(b instanceof BoundingRect)) {
  4229. // Normalize negative width/height.
  4230. b = BoundingRect.create(b);
  4231. }
  4232. var a = this;
  4233. var ax0 = a.x;
  4234. var ax1 = a.x + a.width;
  4235. var ay0 = a.y;
  4236. var ay1 = a.y + a.height;
  4237. var bx0 = b.x;
  4238. var bx1 = b.x + b.width;
  4239. var by0 = b.y;
  4240. var by1 = b.y + b.height;
  4241. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4242. },
  4243. contain: function (x, y) {
  4244. var rect = this;
  4245. return x >= rect.x
  4246. && x <= (rect.x + rect.width)
  4247. && y >= rect.y
  4248. && y <= (rect.y + rect.height);
  4249. },
  4250. /**
  4251. * @return {module:echarts/core/BoundingRect}
  4252. */
  4253. clone: function () {
  4254. return new BoundingRect(this.x, this.y, this.width, this.height);
  4255. },
  4256. /**
  4257. * Copy from another rect
  4258. */
  4259. copy: function (other) {
  4260. this.x = other.x;
  4261. this.y = other.y;
  4262. this.width = other.width;
  4263. this.height = other.height;
  4264. },
  4265. plain: function () {
  4266. return {
  4267. x: this.x,
  4268. y: this.y,
  4269. width: this.width,
  4270. height: this.height
  4271. };
  4272. }
  4273. };
  4274. /**
  4275. * @param {Object|module:zrender/core/BoundingRect} rect
  4276. * @param {number} rect.x
  4277. * @param {number} rect.y
  4278. * @param {number} rect.width
  4279. * @param {number} rect.height
  4280. * @return {module:zrender/core/BoundingRect}
  4281. */
  4282. BoundingRect.create = function (rect) {
  4283. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4284. };
  4285. /**
  4286. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4287. * @module zrender/graphic/Group
  4288. * @example
  4289. * var Group = require('zrender/container/Group');
  4290. * var Circle = require('zrender/graphic/shape/Circle');
  4291. * var g = new Group();
  4292. * g.position[0] = 100;
  4293. * g.position[1] = 100;
  4294. * g.add(new Circle({
  4295. * style: {
  4296. * x: 100,
  4297. * y: 100,
  4298. * r: 20,
  4299. * }
  4300. * }));
  4301. * zr.add(g);
  4302. */
  4303. /**
  4304. * @alias module:zrender/graphic/Group
  4305. * @constructor
  4306. * @extends module:zrender/mixin/Transformable
  4307. * @extends module:zrender/mixin/Eventful
  4308. */
  4309. var Group = function (opts) {
  4310. opts = opts || {};
  4311. Element.call(this, opts);
  4312. for (var key in opts) {
  4313. if (opts.hasOwnProperty(key)) {
  4314. this[key] = opts[key];
  4315. }
  4316. }
  4317. this._children = [];
  4318. this.__storage = null;
  4319. this.__dirty = true;
  4320. };
  4321. Group.prototype = {
  4322. constructor: Group,
  4323. isGroup: true,
  4324. /**
  4325. * @type {string}
  4326. */
  4327. type: 'group',
  4328. /**
  4329. * 所有子孙元素是否响应鼠标事件
  4330. * @name module:/zrender/container/Group#silent
  4331. * @type {boolean}
  4332. * @default false
  4333. */
  4334. silent: false,
  4335. /**
  4336. * @return {Array.<module:zrender/Element>}
  4337. */
  4338. children: function () {
  4339. return this._children.slice();
  4340. },
  4341. /**
  4342. * 获取指定 index 的儿子节点
  4343. * @param {number} idx
  4344. * @return {module:zrender/Element}
  4345. */
  4346. childAt: function (idx) {
  4347. return this._children[idx];
  4348. },
  4349. /**
  4350. * 获取指定名字的儿子节点
  4351. * @param {string} name
  4352. * @return {module:zrender/Element}
  4353. */
  4354. childOfName: function (name) {
  4355. var children = this._children;
  4356. for (var i = 0; i < children.length; i++) {
  4357. if (children[i].name === name) {
  4358. return children[i];
  4359. }
  4360. }
  4361. },
  4362. /**
  4363. * @return {number}
  4364. */
  4365. childCount: function () {
  4366. return this._children.length;
  4367. },
  4368. /**
  4369. * 添加子节点到最后
  4370. * @param {module:zrender/Element} child
  4371. */
  4372. add: function (child) {
  4373. if (child && child !== this && child.parent !== this) {
  4374. this._children.push(child);
  4375. this._doAdd(child);
  4376. }
  4377. return this;
  4378. },
  4379. /**
  4380. * 添加子节点在 nextSibling 之前
  4381. * @param {module:zrender/Element} child
  4382. * @param {module:zrender/Element} nextSibling
  4383. */
  4384. addBefore: function (child, nextSibling) {
  4385. if (child && child !== this && child.parent !== this
  4386. && nextSibling && nextSibling.parent === this) {
  4387. var children = this._children;
  4388. var idx = children.indexOf(nextSibling);
  4389. if (idx >= 0) {
  4390. children.splice(idx, 0, child);
  4391. this._doAdd(child);
  4392. }
  4393. }
  4394. return this;
  4395. },
  4396. _doAdd: function (child) {
  4397. if (child.parent) {
  4398. child.parent.remove(child);
  4399. }
  4400. child.parent = this;
  4401. var storage = this.__storage;
  4402. var zr = this.__zr;
  4403. if (storage && storage !== child.__storage) {
  4404. storage.addToStorage(child);
  4405. if (child instanceof Group) {
  4406. child.addChildrenToStorage(storage);
  4407. }
  4408. }
  4409. zr && zr.refresh();
  4410. },
  4411. /**
  4412. * 移除子节点
  4413. * @param {module:zrender/Element} child
  4414. */
  4415. remove: function (child) {
  4416. var zr = this.__zr;
  4417. var storage = this.__storage;
  4418. var children = this._children;
  4419. var idx = indexOf(children, child);
  4420. if (idx < 0) {
  4421. return this;
  4422. }
  4423. children.splice(idx, 1);
  4424. child.parent = null;
  4425. if (storage) {
  4426. storage.delFromStorage(child);
  4427. if (child instanceof Group) {
  4428. child.delChildrenFromStorage(storage);
  4429. }
  4430. }
  4431. zr && zr.refresh();
  4432. return this;
  4433. },
  4434. /**
  4435. * 移除所有子节点
  4436. */
  4437. removeAll: function () {
  4438. var children = this._children;
  4439. var storage = this.__storage;
  4440. var child;
  4441. var i;
  4442. for (i = 0; i < children.length; i++) {
  4443. child = children[i];
  4444. if (storage) {
  4445. storage.delFromStorage(child);
  4446. if (child instanceof Group) {
  4447. child.delChildrenFromStorage(storage);
  4448. }
  4449. }
  4450. child.parent = null;
  4451. }
  4452. children.length = 0;
  4453. return this;
  4454. },
  4455. /**
  4456. * 遍历所有子节点
  4457. * @param {Function} cb
  4458. * @param {} context
  4459. */
  4460. eachChild: function (cb, context) {
  4461. var children = this._children;
  4462. for (var i = 0; i < children.length; i++) {
  4463. var child = children[i];
  4464. cb.call(context, child, i);
  4465. }
  4466. return this;
  4467. },
  4468. /**
  4469. * 深度优先遍历所有子孙节点
  4470. * @param {Function} cb
  4471. * @param {} context
  4472. */
  4473. traverse: function (cb, context) {
  4474. for (var i = 0; i < this._children.length; i++) {
  4475. var child = this._children[i];
  4476. cb.call(context, child);
  4477. if (child.type === 'group') {
  4478. child.traverse(cb, context);
  4479. }
  4480. }
  4481. return this;
  4482. },
  4483. addChildrenToStorage: function (storage) {
  4484. for (var i = 0; i < this._children.length; i++) {
  4485. var child = this._children[i];
  4486. storage.addToStorage(child);
  4487. if (child instanceof Group) {
  4488. child.addChildrenToStorage(storage);
  4489. }
  4490. }
  4491. },
  4492. delChildrenFromStorage: function (storage) {
  4493. for (var i = 0; i < this._children.length; i++) {
  4494. var child = this._children[i];
  4495. storage.delFromStorage(child);
  4496. if (child instanceof Group) {
  4497. child.delChildrenFromStorage(storage);
  4498. }
  4499. }
  4500. },
  4501. dirty: function () {
  4502. this.__dirty = true;
  4503. this.__zr && this.__zr.refresh();
  4504. return this;
  4505. },
  4506. /**
  4507. * @return {module:zrender/core/BoundingRect}
  4508. */
  4509. getBoundingRect: function (includeChildren) {
  4510. // TODO Caching
  4511. var rect = null;
  4512. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4513. var children = includeChildren || this._children;
  4514. var tmpMat = [];
  4515. for (var i = 0; i < children.length; i++) {
  4516. var child = children[i];
  4517. if (child.ignore || child.invisible) {
  4518. continue;
  4519. }
  4520. var childRect = child.getBoundingRect();
  4521. var transform = child.getLocalTransform(tmpMat);
  4522. // TODO
  4523. // The boundingRect cacluated by transforming original
  4524. // rect may be bigger than the actual bundingRect when rotation
  4525. // is used. (Consider a circle rotated aginst its center, where
  4526. // the actual boundingRect should be the same as that not be
  4527. // rotated.) But we can not find better approach to calculate
  4528. // actual boundingRect yet, considering performance.
  4529. if (transform) {
  4530. tmpRect.copy(childRect);
  4531. tmpRect.applyTransform(transform);
  4532. rect = rect || tmpRect.clone();
  4533. rect.union(tmpRect);
  4534. }
  4535. else {
  4536. rect = rect || childRect.clone();
  4537. rect.union(childRect);
  4538. }
  4539. }
  4540. return rect || tmpRect;
  4541. }
  4542. };
  4543. inherits(Group, Element);
  4544. // https://github.com/mziccard/node-timsort
  4545. var DEFAULT_MIN_MERGE = 32;
  4546. var DEFAULT_MIN_GALLOPING = 7;
  4547. function minRunLength(n) {
  4548. var r = 0;
  4549. while (n >= DEFAULT_MIN_MERGE) {
  4550. r |= n & 1;
  4551. n >>= 1;
  4552. }
  4553. return n + r;
  4554. }
  4555. function makeAscendingRun(array, lo, hi, compare) {
  4556. var runHi = lo + 1;
  4557. if (runHi === hi) {
  4558. return 1;
  4559. }
  4560. if (compare(array[runHi++], array[lo]) < 0) {
  4561. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4562. runHi++;
  4563. }
  4564. reverseRun(array, lo, runHi);
  4565. }
  4566. else {
  4567. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4568. runHi++;
  4569. }
  4570. }
  4571. return runHi - lo;
  4572. }
  4573. function reverseRun(array, lo, hi) {
  4574. hi--;
  4575. while (lo < hi) {
  4576. var t = array[lo];
  4577. array[lo++] = array[hi];
  4578. array[hi--] = t;
  4579. }
  4580. }
  4581. function binaryInsertionSort(array, lo, hi, start, compare) {
  4582. if (start === lo) {
  4583. start++;
  4584. }
  4585. for (; start < hi; start++) {
  4586. var pivot = array[start];
  4587. var left = lo;
  4588. var right = start;
  4589. var mid;
  4590. while (left < right) {
  4591. mid = left + right >>> 1;
  4592. if (compare(pivot, array[mid]) < 0) {
  4593. right = mid;
  4594. }
  4595. else {
  4596. left = mid + 1;
  4597. }
  4598. }
  4599. var n = start - left;
  4600. switch (n) {
  4601. case 3:
  4602. array[left + 3] = array[left + 2];
  4603. case 2:
  4604. array[left + 2] = array[left + 1];
  4605. case 1:
  4606. array[left + 1] = array[left];
  4607. break;
  4608. default:
  4609. while (n > 0) {
  4610. array[left + n] = array[left + n - 1];
  4611. n--;
  4612. }
  4613. }
  4614. array[left] = pivot;
  4615. }
  4616. }
  4617. function gallopLeft(value, array, start, length, hint, compare) {
  4618. var lastOffset = 0;
  4619. var maxOffset = 0;
  4620. var offset = 1;
  4621. if (compare(value, array[start + hint]) > 0) {
  4622. maxOffset = length - hint;
  4623. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4624. lastOffset = offset;
  4625. offset = (offset << 1) + 1;
  4626. if (offset <= 0) {
  4627. offset = maxOffset;
  4628. }
  4629. }
  4630. if (offset > maxOffset) {
  4631. offset = maxOffset;
  4632. }
  4633. lastOffset += hint;
  4634. offset += hint;
  4635. }
  4636. else {
  4637. maxOffset = hint + 1;
  4638. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4639. lastOffset = offset;
  4640. offset = (offset << 1) + 1;
  4641. if (offset <= 0) {
  4642. offset = maxOffset;
  4643. }
  4644. }
  4645. if (offset > maxOffset) {
  4646. offset = maxOffset;
  4647. }
  4648. var tmp = lastOffset;
  4649. lastOffset = hint - offset;
  4650. offset = hint - tmp;
  4651. }
  4652. lastOffset++;
  4653. while (lastOffset < offset) {
  4654. var m = lastOffset + (offset - lastOffset >>> 1);
  4655. if (compare(value, array[start + m]) > 0) {
  4656. lastOffset = m + 1;
  4657. }
  4658. else {
  4659. offset = m;
  4660. }
  4661. }
  4662. return offset;
  4663. }
  4664. function gallopRight(value, array, start, length, hint, compare) {
  4665. var lastOffset = 0;
  4666. var maxOffset = 0;
  4667. var offset = 1;
  4668. if (compare(value, array[start + hint]) < 0) {
  4669. maxOffset = hint + 1;
  4670. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4671. lastOffset = offset;
  4672. offset = (offset << 1) + 1;
  4673. if (offset <= 0) {
  4674. offset = maxOffset;
  4675. }
  4676. }
  4677. if (offset > maxOffset) {
  4678. offset = maxOffset;
  4679. }
  4680. var tmp = lastOffset;
  4681. lastOffset = hint - offset;
  4682. offset = hint - tmp;
  4683. }
  4684. else {
  4685. maxOffset = length - hint;
  4686. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4687. lastOffset = offset;
  4688. offset = (offset << 1) + 1;
  4689. if (offset <= 0) {
  4690. offset = maxOffset;
  4691. }
  4692. }
  4693. if (offset > maxOffset) {
  4694. offset = maxOffset;
  4695. }
  4696. lastOffset += hint;
  4697. offset += hint;
  4698. }
  4699. lastOffset++;
  4700. while (lastOffset < offset) {
  4701. var m = lastOffset + (offset - lastOffset >>> 1);
  4702. if (compare(value, array[start + m]) < 0) {
  4703. offset = m;
  4704. }
  4705. else {
  4706. lastOffset = m + 1;
  4707. }
  4708. }
  4709. return offset;
  4710. }
  4711. function TimSort(array, compare) {
  4712. var minGallop = DEFAULT_MIN_GALLOPING;
  4713. var runStart;
  4714. var runLength;
  4715. var stackSize = 0;
  4716. var tmp = [];
  4717. runStart = [];
  4718. runLength = [];
  4719. function pushRun(_runStart, _runLength) {
  4720. runStart[stackSize] = _runStart;
  4721. runLength[stackSize] = _runLength;
  4722. stackSize += 1;
  4723. }
  4724. function mergeRuns() {
  4725. while (stackSize > 1) {
  4726. var n = stackSize - 2;
  4727. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4728. if (runLength[n - 1] < runLength[n + 1]) {
  4729. n--;
  4730. }
  4731. }
  4732. else if (runLength[n] > runLength[n + 1]) {
  4733. break;
  4734. }
  4735. mergeAt(n);
  4736. }
  4737. }
  4738. function forceMergeRuns() {
  4739. while (stackSize > 1) {
  4740. var n = stackSize - 2;
  4741. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4742. n--;
  4743. }
  4744. mergeAt(n);
  4745. }
  4746. }
  4747. function mergeAt(i) {
  4748. var start1 = runStart[i];
  4749. var length1 = runLength[i];
  4750. var start2 = runStart[i + 1];
  4751. var length2 = runLength[i + 1];
  4752. runLength[i] = length1 + length2;
  4753. if (i === stackSize - 3) {
  4754. runStart[i + 1] = runStart[i + 2];
  4755. runLength[i + 1] = runLength[i + 2];
  4756. }
  4757. stackSize--;
  4758. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4759. start1 += k;
  4760. length1 -= k;
  4761. if (length1 === 0) {
  4762. return;
  4763. }
  4764. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4765. if (length2 === 0) {
  4766. return;
  4767. }
  4768. if (length1 <= length2) {
  4769. mergeLow(start1, length1, start2, length2);
  4770. }
  4771. else {
  4772. mergeHigh(start1, length1, start2, length2);
  4773. }
  4774. }
  4775. function mergeLow(start1, length1, start2, length2) {
  4776. var i = 0;
  4777. for (i = 0; i < length1; i++) {
  4778. tmp[i] = array[start1 + i];
  4779. }
  4780. var cursor1 = 0;
  4781. var cursor2 = start2;
  4782. var dest = start1;
  4783. array[dest++] = array[cursor2++];
  4784. if (--length2 === 0) {
  4785. for (i = 0; i < length1; i++) {
  4786. array[dest + i] = tmp[cursor1 + i];
  4787. }
  4788. return;
  4789. }
  4790. if (length1 === 1) {
  4791. for (i = 0; i < length2; i++) {
  4792. array[dest + i] = array[cursor2 + i];
  4793. }
  4794. array[dest + length2] = tmp[cursor1];
  4795. return;
  4796. }
  4797. var _minGallop = minGallop;
  4798. var count1, count2, exit;
  4799. while (1) {
  4800. count1 = 0;
  4801. count2 = 0;
  4802. exit = false;
  4803. do {
  4804. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4805. array[dest++] = array[cursor2++];
  4806. count2++;
  4807. count1 = 0;
  4808. if (--length2 === 0) {
  4809. exit = true;
  4810. break;
  4811. }
  4812. }
  4813. else {
  4814. array[dest++] = tmp[cursor1++];
  4815. count1++;
  4816. count2 = 0;
  4817. if (--length1 === 1) {
  4818. exit = true;
  4819. break;
  4820. }
  4821. }
  4822. } while ((count1 | count2) < _minGallop);
  4823. if (exit) {
  4824. break;
  4825. }
  4826. do {
  4827. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4828. if (count1 !== 0) {
  4829. for (i = 0; i < count1; i++) {
  4830. array[dest + i] = tmp[cursor1 + i];
  4831. }
  4832. dest += count1;
  4833. cursor1 += count1;
  4834. length1 -= count1;
  4835. if (length1 <= 1) {
  4836. exit = true;
  4837. break;
  4838. }
  4839. }
  4840. array[dest++] = array[cursor2++];
  4841. if (--length2 === 0) {
  4842. exit = true;
  4843. break;
  4844. }
  4845. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4846. if (count2 !== 0) {
  4847. for (i = 0; i < count2; i++) {
  4848. array[dest + i] = array[cursor2 + i];
  4849. }
  4850. dest += count2;
  4851. cursor2 += count2;
  4852. length2 -= count2;
  4853. if (length2 === 0) {
  4854. exit = true;
  4855. break;
  4856. }
  4857. }
  4858. array[dest++] = tmp[cursor1++];
  4859. if (--length1 === 1) {
  4860. exit = true;
  4861. break;
  4862. }
  4863. _minGallop--;
  4864. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4865. if (exit) {
  4866. break;
  4867. }
  4868. if (_minGallop < 0) {
  4869. _minGallop = 0;
  4870. }
  4871. _minGallop += 2;
  4872. }
  4873. minGallop = _minGallop;
  4874. minGallop < 1 && (minGallop = 1);
  4875. if (length1 === 1) {
  4876. for (i = 0; i < length2; i++) {
  4877. array[dest + i] = array[cursor2 + i];
  4878. }
  4879. array[dest + length2] = tmp[cursor1];
  4880. }
  4881. else if (length1 === 0) {
  4882. throw new Error();
  4883. // throw new Error('mergeLow preconditions were not respected');
  4884. }
  4885. else {
  4886. for (i = 0; i < length1; i++) {
  4887. array[dest + i] = tmp[cursor1 + i];
  4888. }
  4889. }
  4890. }
  4891. function mergeHigh (start1, length1, start2, length2) {
  4892. var i = 0;
  4893. for (i = 0; i < length2; i++) {
  4894. tmp[i] = array[start2 + i];
  4895. }
  4896. var cursor1 = start1 + length1 - 1;
  4897. var cursor2 = length2 - 1;
  4898. var dest = start2 + length2 - 1;
  4899. var customCursor = 0;
  4900. var customDest = 0;
  4901. array[dest--] = array[cursor1--];
  4902. if (--length1 === 0) {
  4903. customCursor = dest - (length2 - 1);
  4904. for (i = 0; i < length2; i++) {
  4905. array[customCursor + i] = tmp[i];
  4906. }
  4907. return;
  4908. }
  4909. if (length2 === 1) {
  4910. dest -= length1;
  4911. cursor1 -= length1;
  4912. customDest = dest + 1;
  4913. customCursor = cursor1 + 1;
  4914. for (i = length1 - 1; i >= 0; i--) {
  4915. array[customDest + i] = array[customCursor + i];
  4916. }
  4917. array[dest] = tmp[cursor2];
  4918. return;
  4919. }
  4920. var _minGallop = minGallop;
  4921. while (true) {
  4922. var count1 = 0;
  4923. var count2 = 0;
  4924. var exit = false;
  4925. do {
  4926. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  4927. array[dest--] = array[cursor1--];
  4928. count1++;
  4929. count2 = 0;
  4930. if (--length1 === 0) {
  4931. exit = true;
  4932. break;
  4933. }
  4934. }
  4935. else {
  4936. array[dest--] = tmp[cursor2--];
  4937. count2++;
  4938. count1 = 0;
  4939. if (--length2 === 1) {
  4940. exit = true;
  4941. break;
  4942. }
  4943. }
  4944. } while ((count1 | count2) < _minGallop);
  4945. if (exit) {
  4946. break;
  4947. }
  4948. do {
  4949. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  4950. if (count1 !== 0) {
  4951. dest -= count1;
  4952. cursor1 -= count1;
  4953. length1 -= count1;
  4954. customDest = dest + 1;
  4955. customCursor = cursor1 + 1;
  4956. for (i = count1 - 1; i >= 0; i--) {
  4957. array[customDest + i] = array[customCursor + i];
  4958. }
  4959. if (length1 === 0) {
  4960. exit = true;
  4961. break;
  4962. }
  4963. }
  4964. array[dest--] = tmp[cursor2--];
  4965. if (--length2 === 1) {
  4966. exit = true;
  4967. break;
  4968. }
  4969. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  4970. if (count2 !== 0) {
  4971. dest -= count2;
  4972. cursor2 -= count2;
  4973. length2 -= count2;
  4974. customDest = dest + 1;
  4975. customCursor = cursor2 + 1;
  4976. for (i = 0; i < count2; i++) {
  4977. array[customDest + i] = tmp[customCursor + i];
  4978. }
  4979. if (length2 <= 1) {
  4980. exit = true;
  4981. break;
  4982. }
  4983. }
  4984. array[dest--] = array[cursor1--];
  4985. if (--length1 === 0) {
  4986. exit = true;
  4987. break;
  4988. }
  4989. _minGallop--;
  4990. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4991. if (exit) {
  4992. break;
  4993. }
  4994. if (_minGallop < 0) {
  4995. _minGallop = 0;
  4996. }
  4997. _minGallop += 2;
  4998. }
  4999. minGallop = _minGallop;
  5000. if (minGallop < 1) {
  5001. minGallop = 1;
  5002. }
  5003. if (length2 === 1) {
  5004. dest -= length1;
  5005. cursor1 -= length1;
  5006. customDest = dest + 1;
  5007. customCursor = cursor1 + 1;
  5008. for (i = length1 - 1; i >= 0; i--) {
  5009. array[customDest + i] = array[customCursor + i];
  5010. }
  5011. array[dest] = tmp[cursor2];
  5012. }
  5013. else if (length2 === 0) {
  5014. throw new Error();
  5015. // throw new Error('mergeHigh preconditions were not respected');
  5016. }
  5017. else {
  5018. customCursor = dest - (length2 - 1);
  5019. for (i = 0; i < length2; i++) {
  5020. array[customCursor + i] = tmp[i];
  5021. }
  5022. }
  5023. }
  5024. this.mergeRuns = mergeRuns;
  5025. this.forceMergeRuns = forceMergeRuns;
  5026. this.pushRun = pushRun;
  5027. }
  5028. function sort(array, compare, lo, hi) {
  5029. if (!lo) {
  5030. lo = 0;
  5031. }
  5032. if (!hi) {
  5033. hi = array.length;
  5034. }
  5035. var remaining = hi - lo;
  5036. if (remaining < 2) {
  5037. return;
  5038. }
  5039. var runLength = 0;
  5040. if (remaining < DEFAULT_MIN_MERGE) {
  5041. runLength = makeAscendingRun(array, lo, hi, compare);
  5042. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5043. return;
  5044. }
  5045. var ts = new TimSort(array, compare);
  5046. var minRun = minRunLength(remaining);
  5047. do {
  5048. runLength = makeAscendingRun(array, lo, hi, compare);
  5049. if (runLength < minRun) {
  5050. var force = remaining;
  5051. if (force > minRun) {
  5052. force = minRun;
  5053. }
  5054. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5055. runLength = force;
  5056. }
  5057. ts.pushRun(lo, runLength);
  5058. ts.mergeRuns();
  5059. remaining -= runLength;
  5060. lo += runLength;
  5061. } while (remaining !== 0);
  5062. ts.forceMergeRuns();
  5063. }
  5064. /**
  5065. * Storage内容仓库模块
  5066. * @module zrender/Storage
  5067. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  5068. * @author errorrik (errorrik@gmail.com)
  5069. * @author pissang (https://github.com/pissang/)
  5070. */
  5071. // Use timsort because in most case elements are partially sorted
  5072. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5073. function shapeCompareFunc(a, b) {
  5074. if (a.zlevel === b.zlevel) {
  5075. if (a.z === b.z) {
  5076. // if (a.z2 === b.z2) {
  5077. // // FIXME Slow has renderidx compare
  5078. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5079. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5080. // return a.__renderidx - b.__renderidx;
  5081. // }
  5082. return a.z2 - b.z2;
  5083. }
  5084. return a.z - b.z;
  5085. }
  5086. return a.zlevel - b.zlevel;
  5087. }
  5088. /**
  5089. * 内容仓库 (M)
  5090. * @alias module:zrender/Storage
  5091. * @constructor
  5092. */
  5093. var Storage = function () { // jshint ignore:line
  5094. this._roots = [];
  5095. this._displayList = [];
  5096. this._displayListLen = 0;
  5097. };
  5098. Storage.prototype = {
  5099. constructor: Storage,
  5100. /**
  5101. * @param {Function} cb
  5102. *
  5103. */
  5104. traverse: function (cb, context) {
  5105. for (var i = 0; i < this._roots.length; i++) {
  5106. this._roots[i].traverse(cb, context);
  5107. }
  5108. },
  5109. /**
  5110. * 返回所有图形的绘制队列
  5111. * @param {boolean} [update=false] 是否在返回前更新该数组
  5112. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5113. *
  5114. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5115. * @return {Array.<module:zrender/graphic/Displayable>}
  5116. */
  5117. getDisplayList: function (update, includeIgnore) {
  5118. includeIgnore = includeIgnore || false;
  5119. if (update) {
  5120. this.updateDisplayList(includeIgnore);
  5121. }
  5122. return this._displayList;
  5123. },
  5124. /**
  5125. * 更新图形的绘制队列。
  5126. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5127. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5128. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5129. */
  5130. updateDisplayList: function (includeIgnore) {
  5131. this._displayListLen = 0;
  5132. var roots = this._roots;
  5133. var displayList = this._displayList;
  5134. for (var i = 0, len = roots.length; i < len; i++) {
  5135. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5136. }
  5137. displayList.length = this._displayListLen;
  5138. // for (var i = 0, len = displayList.length; i < len; i++) {
  5139. // displayList[i].__renderidx = i;
  5140. // }
  5141. // displayList.sort(shapeCompareFunc);
  5142. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5143. },
  5144. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5145. if (el.ignore && !includeIgnore) {
  5146. return;
  5147. }
  5148. el.beforeUpdate();
  5149. if (el.__dirty) {
  5150. el.update();
  5151. }
  5152. el.afterUpdate();
  5153. var userSetClipPath = el.clipPath;
  5154. if (userSetClipPath) {
  5155. // FIXME 效率影响
  5156. if (clipPaths) {
  5157. clipPaths = clipPaths.slice();
  5158. }
  5159. else {
  5160. clipPaths = [];
  5161. }
  5162. var currentClipPath = userSetClipPath;
  5163. var parentClipPath = el;
  5164. // Recursively add clip path
  5165. while (currentClipPath) {
  5166. // clipPath 的变换是基于使用这个 clipPath 的元素
  5167. currentClipPath.parent = parentClipPath;
  5168. currentClipPath.updateTransform();
  5169. clipPaths.push(currentClipPath);
  5170. parentClipPath = currentClipPath;
  5171. currentClipPath = currentClipPath.clipPath;
  5172. }
  5173. }
  5174. if (el.isGroup) {
  5175. var children = el._children;
  5176. for (var i = 0; i < children.length; i++) {
  5177. var child = children[i];
  5178. // Force to mark as dirty if group is dirty
  5179. // FIXME __dirtyPath ?
  5180. if (el.__dirty) {
  5181. child.__dirty = true;
  5182. }
  5183. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5184. }
  5185. // Mark group clean here
  5186. el.__dirty = false;
  5187. }
  5188. else {
  5189. el.__clipPaths = clipPaths;
  5190. this._displayList[this._displayListLen++] = el;
  5191. }
  5192. },
  5193. /**
  5194. * 添加图形(Shape)或者组(Group)到根节点
  5195. * @param {module:zrender/Element} el
  5196. */
  5197. addRoot: function (el) {
  5198. if (el.__storage === this) {
  5199. return;
  5200. }
  5201. if (el instanceof Group) {
  5202. el.addChildrenToStorage(this);
  5203. }
  5204. this.addToStorage(el);
  5205. this._roots.push(el);
  5206. },
  5207. /**
  5208. * 删除指定的图形(Shape)或者组(Group)
  5209. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5210. */
  5211. delRoot: function (el) {
  5212. if (el == null) {
  5213. // 不指定el清空
  5214. for (var i = 0; i < this._roots.length; i++) {
  5215. var root = this._roots[i];
  5216. if (root instanceof Group) {
  5217. root.delChildrenFromStorage(this);
  5218. }
  5219. }
  5220. this._roots = [];
  5221. this._displayList = [];
  5222. this._displayListLen = 0;
  5223. return;
  5224. }
  5225. if (el instanceof Array) {
  5226. for (var i = 0, l = el.length; i < l; i++) {
  5227. this.delRoot(el[i]);
  5228. }
  5229. return;
  5230. }
  5231. var idx = indexOf(this._roots, el);
  5232. if (idx >= 0) {
  5233. this.delFromStorage(el);
  5234. this._roots.splice(idx, 1);
  5235. if (el instanceof Group) {
  5236. el.delChildrenFromStorage(this);
  5237. }
  5238. }
  5239. },
  5240. addToStorage: function (el) {
  5241. el.__storage = this;
  5242. el.dirty(false);
  5243. return this;
  5244. },
  5245. delFromStorage: function (el) {
  5246. if (el) {
  5247. el.__storage = null;
  5248. }
  5249. return this;
  5250. },
  5251. /**
  5252. * 清空并且释放Storage
  5253. */
  5254. dispose: function () {
  5255. this._renderList =
  5256. this._roots = null;
  5257. },
  5258. displayableSortFunc: shapeCompareFunc
  5259. };
  5260. var STYLE_COMMON_PROPS = [
  5261. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5262. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5263. ];
  5264. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5265. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5266. var Style = function (opts, host) {
  5267. this.extendFrom(opts, false);
  5268. this.host = host;
  5269. };
  5270. function createLinearGradient(ctx, obj, rect) {
  5271. var x = obj.x == null ? 0 : obj.x;
  5272. var x2 = obj.x2 == null ? 1 : obj.x2;
  5273. var y = obj.y == null ? 0 : obj.y;
  5274. var y2 = obj.y2 == null ? 0 : obj.y2;
  5275. if (!obj.global) {
  5276. x = x * rect.width + rect.x;
  5277. x2 = x2 * rect.width + rect.x;
  5278. y = y * rect.height + rect.y;
  5279. y2 = y2 * rect.height + rect.y;
  5280. }
  5281. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5282. return canvasGradient;
  5283. }
  5284. function createRadialGradient(ctx, obj, rect) {
  5285. var width = rect.width;
  5286. var height = rect.height;
  5287. var min = Math.min(width, height);
  5288. var x = obj.x == null ? 0.5 : obj.x;
  5289. var y = obj.y == null ? 0.5 : obj.y;
  5290. var r = obj.r == null ? 0.5 : obj.r;
  5291. if (!obj.global) {
  5292. x = x * width + rect.x;
  5293. y = y * height + rect.y;
  5294. r = r * min;
  5295. }
  5296. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5297. return canvasGradient;
  5298. }
  5299. Style.prototype = {
  5300. constructor: Style,
  5301. /**
  5302. * @type {module:zrender/graphic/Displayable}
  5303. */
  5304. host: null,
  5305. /**
  5306. * @type {string}
  5307. */
  5308. fill: '#000',
  5309. /**
  5310. * @type {string}
  5311. */
  5312. stroke: null,
  5313. /**
  5314. * @type {number}
  5315. */
  5316. opacity: 1,
  5317. /**
  5318. * @type {Array.<number>}
  5319. */
  5320. lineDash: null,
  5321. /**
  5322. * @type {number}
  5323. */
  5324. lineDashOffset: 0,
  5325. /**
  5326. * @type {number}
  5327. */
  5328. shadowBlur: 0,
  5329. /**
  5330. * @type {number}
  5331. */
  5332. shadowOffsetX: 0,
  5333. /**
  5334. * @type {number}
  5335. */
  5336. shadowOffsetY: 0,
  5337. /**
  5338. * @type {number}
  5339. */
  5340. lineWidth: 1,
  5341. /**
  5342. * If stroke ignore scale
  5343. * @type {Boolean}
  5344. */
  5345. strokeNoScale: false,
  5346. // Bounding rect text configuration
  5347. // Not affected by element transform
  5348. /**
  5349. * @type {string}
  5350. */
  5351. text: null,
  5352. /**
  5353. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5354. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5355. * So do not visit it directly in upper application (like echarts),
  5356. * but use `contain/text#makeFont` instead.
  5357. * @type {string}
  5358. */
  5359. font: null,
  5360. /**
  5361. * The same as font. Use font please.
  5362. * @deprecated
  5363. * @type {string}
  5364. */
  5365. textFont: null,
  5366. /**
  5367. * It helps merging respectively, rather than parsing an entire font string.
  5368. * @type {string}
  5369. */
  5370. fontStyle: null,
  5371. /**
  5372. * It helps merging respectively, rather than parsing an entire font string.
  5373. * @type {string}
  5374. */
  5375. fontWeight: null,
  5376. /**
  5377. * It helps merging respectively, rather than parsing an entire font string.
  5378. * Should be 12 but not '12px'.
  5379. * @type {number}
  5380. */
  5381. fontSize: null,
  5382. /**
  5383. * It helps merging respectively, rather than parsing an entire font string.
  5384. * @type {string}
  5385. */
  5386. fontFamily: null,
  5387. /**
  5388. * Reserved for special functinality, like 'hr'.
  5389. * @type {string}
  5390. */
  5391. textTag: null,
  5392. /**
  5393. * @type {string}
  5394. */
  5395. textFill: '#000',
  5396. /**
  5397. * @type {string}
  5398. */
  5399. textStroke: null,
  5400. /**
  5401. * @type {number}
  5402. */
  5403. textWidth: null,
  5404. /**
  5405. * Only for textBackground.
  5406. * @type {number}
  5407. */
  5408. textHeight: null,
  5409. /**
  5410. * textStroke may be set as some color as a default
  5411. * value in upper applicaion, where the default value
  5412. * of textStrokeWidth should be 0 to make sure that
  5413. * user can choose to do not use text stroke.
  5414. * @type {number}
  5415. */
  5416. textStrokeWidth: 0,
  5417. /**
  5418. * @type {number}
  5419. */
  5420. textLineHeight: null,
  5421. /**
  5422. * 'inside', 'left', 'right', 'top', 'bottom'
  5423. * [x, y]
  5424. * Based on x, y of rect.
  5425. * @type {string|Array.<number>}
  5426. * @default 'inside'
  5427. */
  5428. textPosition: 'inside',
  5429. /**
  5430. * If not specified, use the boundingRect of a `displayable`.
  5431. * @type {Object}
  5432. */
  5433. textRect: null,
  5434. /**
  5435. * [x, y]
  5436. * @type {Array.<number>}
  5437. */
  5438. textOffset: null,
  5439. /**
  5440. * @type {string}
  5441. */
  5442. textAlign: null,
  5443. /**
  5444. * @type {string}
  5445. */
  5446. textVerticalAlign: null,
  5447. /**
  5448. * @type {number}
  5449. */
  5450. textDistance: 5,
  5451. /**
  5452. * @type {string}
  5453. */
  5454. textShadowColor: 'transparent',
  5455. /**
  5456. * @type {number}
  5457. */
  5458. textShadowBlur: 0,
  5459. /**
  5460. * @type {number}
  5461. */
  5462. textShadowOffsetX: 0,
  5463. /**
  5464. * @type {number}
  5465. */
  5466. textShadowOffsetY: 0,
  5467. /**
  5468. * @type {string}
  5469. */
  5470. textBoxShadowColor: 'transparent',
  5471. /**
  5472. * @type {number}
  5473. */
  5474. textBoxShadowBlur: 0,
  5475. /**
  5476. * @type {number}
  5477. */
  5478. textBoxShadowOffsetX: 0,
  5479. /**
  5480. * @type {number}
  5481. */
  5482. textBoxShadowOffsetY: 0,
  5483. /**
  5484. * Whether transform text.
  5485. * Only useful in Path and Image element
  5486. * @type {boolean}
  5487. */
  5488. transformText: false,
  5489. /**
  5490. * Text rotate around position of Path or Image
  5491. * Only useful in Path and Image element and transformText is false.
  5492. */
  5493. textRotation: 0,
  5494. /**
  5495. * Text origin of text rotation, like [10, 40].
  5496. * Based on x, y of rect.
  5497. * Useful in label rotation of circular symbol.
  5498. * By default, this origin is textPosition.
  5499. * Can be 'center'.
  5500. * @type {string|Array.<number>}
  5501. */
  5502. textOrigin: null,
  5503. /**
  5504. * @type {string}
  5505. */
  5506. textBackgroundColor: null,
  5507. /**
  5508. * @type {string}
  5509. */
  5510. textBorderColor: null,
  5511. /**
  5512. * @type {number}
  5513. */
  5514. textBorderWidth: 0,
  5515. /**
  5516. * @type {number}
  5517. */
  5518. textBorderRadius: 0,
  5519. /**
  5520. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5521. * @type {number|Array.<number>}
  5522. */
  5523. textPadding: null,
  5524. /**
  5525. * Text styles for rich text.
  5526. * @type {Object}
  5527. */
  5528. rich: null,
  5529. /**
  5530. * {outerWidth, outerHeight, ellipsis, placeholder}
  5531. * @type {Object}
  5532. */
  5533. truncate: null,
  5534. /**
  5535. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5536. * @type {string}
  5537. */
  5538. blend: null,
  5539. /**
  5540. * @param {CanvasRenderingContext2D} ctx
  5541. */
  5542. bind: function (ctx, el, prevEl) {
  5543. var style = this;
  5544. var prevStyle = prevEl && prevEl.style;
  5545. var firstDraw = !prevStyle;
  5546. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5547. var prop = STYLE_COMMON_PROPS[i];
  5548. var styleName = prop[0];
  5549. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5550. // FIXME Invalid property value will cause style leak from previous element.
  5551. ctx[styleName] = style[styleName] || prop[1];
  5552. }
  5553. }
  5554. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5555. ctx.fillStyle = style.fill;
  5556. }
  5557. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5558. ctx.strokeStyle = style.stroke;
  5559. }
  5560. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5561. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5562. }
  5563. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5564. ctx.globalCompositeOperation = style.blend || 'source-over';
  5565. }
  5566. if (this.hasStroke()) {
  5567. var lineWidth = style.lineWidth;
  5568. ctx.lineWidth = lineWidth / (
  5569. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5570. );
  5571. }
  5572. },
  5573. hasFill: function () {
  5574. var fill = this.fill;
  5575. return fill != null && fill !== 'none';
  5576. },
  5577. hasStroke: function () {
  5578. var stroke = this.stroke;
  5579. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5580. },
  5581. /**
  5582. * Extend from other style
  5583. * @param {zrender/graphic/Style} otherStyle
  5584. * @param {boolean} overwrite true: overwrirte any way.
  5585. * false: overwrite only when !target.hasOwnProperty
  5586. * others: overwrite when property is not null/undefined.
  5587. */
  5588. extendFrom: function (otherStyle, overwrite) {
  5589. if (otherStyle) {
  5590. for (var name in otherStyle) {
  5591. if (otherStyle.hasOwnProperty(name)
  5592. && (overwrite === true
  5593. || (
  5594. overwrite === false
  5595. ? !this.hasOwnProperty(name)
  5596. : otherStyle[name] != null
  5597. )
  5598. )
  5599. ) {
  5600. this[name] = otherStyle[name];
  5601. }
  5602. }
  5603. }
  5604. },
  5605. /**
  5606. * Batch setting style with a given object
  5607. * @param {Object|string} obj
  5608. * @param {*} [obj]
  5609. */
  5610. set: function (obj, value) {
  5611. if (typeof obj === 'string') {
  5612. this[obj] = value;
  5613. }
  5614. else {
  5615. this.extendFrom(obj, true);
  5616. }
  5617. },
  5618. /**
  5619. * Clone
  5620. * @return {zrender/graphic/Style} [description]
  5621. */
  5622. clone: function () {
  5623. var newStyle = new this.constructor();
  5624. newStyle.extendFrom(this, true);
  5625. return newStyle;
  5626. },
  5627. getGradient: function (ctx, obj, rect) {
  5628. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5629. var canvasGradient = method(ctx, obj, rect);
  5630. var colorStops = obj.colorStops;
  5631. for (var i = 0; i < colorStops.length; i++) {
  5632. canvasGradient.addColorStop(
  5633. colorStops[i].offset, colorStops[i].color
  5634. );
  5635. }
  5636. return canvasGradient;
  5637. }
  5638. };
  5639. var styleProto = Style.prototype;
  5640. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5641. var prop = STYLE_COMMON_PROPS[i];
  5642. if (!(prop[0] in styleProto)) {
  5643. styleProto[prop[0]] = prop[1];
  5644. }
  5645. }
  5646. // Provide for others
  5647. Style.getGradient = styleProto.getGradient;
  5648. var Pattern = function (image, repeat) {
  5649. // Should do nothing more in this constructor. Because gradient can be
  5650. // declard by `color: {image: ...}`, where this constructor will not be called.
  5651. this.image = image;
  5652. this.repeat = repeat;
  5653. // Can be cloned
  5654. this.type = 'pattern';
  5655. };
  5656. Pattern.prototype.getCanvasPattern = function (ctx) {
  5657. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5658. };
  5659. /**
  5660. * @module zrender/Layer
  5661. * @author pissang(https://www.github.com/pissang)
  5662. */
  5663. function returnFalse() {
  5664. return false;
  5665. }
  5666. /**
  5667. * 创建dom
  5668. *
  5669. * @inner
  5670. * @param {string} id dom id 待用
  5671. * @param {Painter} painter painter instance
  5672. * @param {number} number
  5673. */
  5674. function createDom(id, painter, dpr) {
  5675. var newDom = createCanvas();
  5676. var width = painter.getWidth();
  5677. var height = painter.getHeight();
  5678. var newDomStyle = newDom.style;
  5679. // 没append呢,请原谅我这样写,清晰~
  5680. newDomStyle.position = 'absolute';
  5681. newDomStyle.left = 0;
  5682. newDomStyle.top = 0;
  5683. newDomStyle.width = width + 'px';
  5684. newDomStyle.height = height + 'px';
  5685. newDom.width = width * dpr;
  5686. newDom.height = height * dpr;
  5687. // id不作为索引用,避免可能造成的重名,定义为私有属性
  5688. newDom.setAttribute('data-zr-dom-id', id);
  5689. return newDom;
  5690. }
  5691. /**
  5692. * @alias module:zrender/Layer
  5693. * @constructor
  5694. * @extends module:zrender/mixin/Transformable
  5695. * @param {string} id
  5696. * @param {module:zrender/Painter} painter
  5697. * @param {number} [dpr]
  5698. */
  5699. var Layer = function(id, painter, dpr) {
  5700. var dom;
  5701. dpr = dpr || devicePixelRatio;
  5702. if (typeof id === 'string') {
  5703. dom = createDom(id, painter, dpr);
  5704. }
  5705. // Not using isDom because in node it will return false
  5706. else if (isObject(id)) {
  5707. dom = id;
  5708. id = dom.id;
  5709. }
  5710. this.id = id;
  5711. this.dom = dom;
  5712. var domStyle = dom.style;
  5713. if (domStyle) { // Not in node
  5714. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5715. domStyle['-webkit-user-select'] = 'none';
  5716. domStyle['user-select'] = 'none';
  5717. domStyle['-webkit-touch-callout'] = 'none';
  5718. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5719. domStyle['padding'] = 0;
  5720. domStyle['margin'] = 0;
  5721. domStyle['border-width'] = 0;
  5722. }
  5723. this.domBack = null;
  5724. this.ctxBack = null;
  5725. this.painter = painter;
  5726. this.config = null;
  5727. // Configs
  5728. /**
  5729. * 每次清空画布的颜色
  5730. * @type {string}
  5731. * @default 0
  5732. */
  5733. this.clearColor = 0;
  5734. /**
  5735. * 是否开启动态模糊
  5736. * @type {boolean}
  5737. * @default false
  5738. */
  5739. this.motionBlur = false;
  5740. /**
  5741. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5742. * @type {number}
  5743. * @default 0.7
  5744. */
  5745. this.lastFrameAlpha = 0.7;
  5746. /**
  5747. * Layer dpr
  5748. * @type {number}
  5749. */
  5750. this.dpr = dpr;
  5751. };
  5752. Layer.prototype = {
  5753. constructor: Layer,
  5754. elCount: 0,
  5755. __dirty: true,
  5756. initContext: function () {
  5757. this.ctx = this.dom.getContext('2d');
  5758. this.ctx.__currentValues = {};
  5759. this.ctx.dpr = this.dpr;
  5760. },
  5761. createBackBuffer: function () {
  5762. var dpr = this.dpr;
  5763. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5764. this.ctxBack = this.domBack.getContext('2d');
  5765. this.ctxBack.__currentValues = {};
  5766. if (dpr != 1) {
  5767. this.ctxBack.scale(dpr, dpr);
  5768. }
  5769. },
  5770. /**
  5771. * @param {number} width
  5772. * @param {number} height
  5773. */
  5774. resize: function (width, height) {
  5775. var dpr = this.dpr;
  5776. var dom = this.dom;
  5777. var domStyle = dom.style;
  5778. var domBack = this.domBack;
  5779. domStyle.width = width + 'px';
  5780. domStyle.height = height + 'px';
  5781. dom.width = width * dpr;
  5782. dom.height = height * dpr;
  5783. if (domBack) {
  5784. domBack.width = width * dpr;
  5785. domBack.height = height * dpr;
  5786. if (dpr != 1) {
  5787. this.ctxBack.scale(dpr, dpr);
  5788. }
  5789. }
  5790. },
  5791. /**
  5792. * 清空该层画布
  5793. * @param {boolean} clearAll Clear all with out motion blur
  5794. */
  5795. clear: function (clearAll) {
  5796. var dom = this.dom;
  5797. var ctx = this.ctx;
  5798. var width = dom.width;
  5799. var height = dom.height;
  5800. var clearColor = this.clearColor;
  5801. var haveMotionBLur = this.motionBlur && !clearAll;
  5802. var lastFrameAlpha = this.lastFrameAlpha;
  5803. var dpr = this.dpr;
  5804. if (haveMotionBLur) {
  5805. if (!this.domBack) {
  5806. this.createBackBuffer();
  5807. }
  5808. this.ctxBack.globalCompositeOperation = 'copy';
  5809. this.ctxBack.drawImage(
  5810. dom, 0, 0,
  5811. width / dpr,
  5812. height / dpr
  5813. );
  5814. }
  5815. ctx.clearRect(0, 0, width, height);
  5816. if (clearColor) {
  5817. var clearColorGradientOrPattern;
  5818. // Gradient
  5819. if (clearColor.colorStops) {
  5820. // Cache canvas gradient
  5821. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5822. x: 0,
  5823. y: 0,
  5824. width: width,
  5825. height: height
  5826. });
  5827. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5828. }
  5829. // Pattern
  5830. else if (clearColor.image) {
  5831. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5832. }
  5833. ctx.save();
  5834. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5835. ctx.fillRect(0, 0, width, height);
  5836. ctx.restore();
  5837. }
  5838. if (haveMotionBLur) {
  5839. var domBack = this.domBack;
  5840. ctx.save();
  5841. ctx.globalAlpha = lastFrameAlpha;
  5842. ctx.drawImage(domBack, 0, 0, width, height);
  5843. ctx.restore();
  5844. }
  5845. }
  5846. };
  5847. var requestAnimationFrame = (
  5848. typeof window !== 'undefined'
  5849. && (
  5850. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5851. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5852. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5853. || window.mozRequestAnimationFrame
  5854. || window.webkitRequestAnimationFrame
  5855. )
  5856. ) || function (func) {
  5857. setTimeout(func, 16);
  5858. };
  5859. var globalImageCache = new LRU(50);
  5860. /**
  5861. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5862. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5863. */
  5864. function findExistImage(newImageOrSrc) {
  5865. if (typeof newImageOrSrc === 'string') {
  5866. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5867. return cachedImgObj && cachedImgObj.image;
  5868. }
  5869. else {
  5870. return newImageOrSrc;
  5871. }
  5872. }
  5873. /**
  5874. * Caution: User should cache loaded images, but not just count on LRU.
  5875. * Consider if required images more than LRU size, will dead loop occur?
  5876. *
  5877. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5878. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  5879. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  5880. * @param {Function} [cb] params: (image, cbPayload)
  5881. * @param {Object} [cbPayload] Payload on cb calling.
  5882. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5883. */
  5884. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  5885. if (!newImageOrSrc) {
  5886. return image;
  5887. }
  5888. else if (typeof newImageOrSrc === 'string') {
  5889. // Image should not be loaded repeatly.
  5890. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  5891. return image;
  5892. }
  5893. // Only when there is no existent image or existent image src
  5894. // is different, this method is responsible for load.
  5895. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5896. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  5897. if (cachedImgObj) {
  5898. image = cachedImgObj.image;
  5899. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  5900. }
  5901. else {
  5902. !image && (image = new Image());
  5903. image.onload = imageOnLoad;
  5904. globalImageCache.put(
  5905. newImageOrSrc,
  5906. image.__cachedImgObj = {
  5907. image: image,
  5908. pending: [pendingWrap]
  5909. }
  5910. );
  5911. image.src = image.__zrImageSrc = newImageOrSrc;
  5912. }
  5913. return image;
  5914. }
  5915. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  5916. else {
  5917. return newImageOrSrc;
  5918. }
  5919. }
  5920. function imageOnLoad() {
  5921. var cachedImgObj = this.__cachedImgObj;
  5922. this.onload = this.__cachedImgObj = null;
  5923. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  5924. var pendingWrap = cachedImgObj.pending[i];
  5925. var cb = pendingWrap.cb;
  5926. cb && cb(this, pendingWrap.cbPayload);
  5927. pendingWrap.hostEl.dirty();
  5928. }
  5929. cachedImgObj.pending.length = 0;
  5930. }
  5931. function isImageReady(image) {
  5932. return image && image.width && image.height;
  5933. }
  5934. var textWidthCache = {};
  5935. var textWidthCacheCounter = 0;
  5936. var TEXT_CACHE_MAX = 5000;
  5937. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  5938. var DEFAULT_FONT = '12px sans-serif';
  5939. // Avoid assign to an exported variable, for transforming to cjs.
  5940. var methods$1 = {};
  5941. function $override$1(name, fn) {
  5942. methods$1[name] = fn;
  5943. }
  5944. /**
  5945. * @public
  5946. * @param {string} text
  5947. * @param {string} font
  5948. * @return {number} width
  5949. */
  5950. function getWidth(text, font) {
  5951. font = font || DEFAULT_FONT;
  5952. var key = text + ':' + font;
  5953. if (textWidthCache[key]) {
  5954. return textWidthCache[key];
  5955. }
  5956. var textLines = (text + '').split('\n');
  5957. var width = 0;
  5958. for (var i = 0, l = textLines.length; i < l; i++) {
  5959. // textContain.measureText may be overrided in SVG or VML
  5960. width = Math.max(measureText(textLines[i], font).width, width);
  5961. }
  5962. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  5963. textWidthCacheCounter = 0;
  5964. textWidthCache = {};
  5965. }
  5966. textWidthCacheCounter++;
  5967. textWidthCache[key] = width;
  5968. return width;
  5969. }
  5970. /**
  5971. * @public
  5972. * @param {string} text
  5973. * @param {string} font
  5974. * @param {string} [textAlign='left']
  5975. * @param {string} [textVerticalAlign='top']
  5976. * @param {Array.<number>} [textPadding]
  5977. * @param {Object} [rich]
  5978. * @param {Object} [truncate]
  5979. * @return {Object} {x, y, width, height, lineHeight}
  5980. */
  5981. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  5982. return rich
  5983. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  5984. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  5985. }
  5986. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  5987. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  5988. var outerWidth = getWidth(text, font);
  5989. if (textPadding) {
  5990. outerWidth += textPadding[1] + textPadding[3];
  5991. }
  5992. var outerHeight = contentBlock.outerHeight;
  5993. var x = adjustTextX(0, outerWidth, textAlign);
  5994. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  5995. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  5996. rect.lineHeight = contentBlock.lineHeight;
  5997. return rect;
  5998. }
  5999. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6000. var contentBlock = parseRichText(text, {
  6001. rich: rich,
  6002. truncate: truncate,
  6003. font: font,
  6004. textAlign: textAlign,
  6005. textPadding: textPadding
  6006. });
  6007. var outerWidth = contentBlock.outerWidth;
  6008. var outerHeight = contentBlock.outerHeight;
  6009. var x = adjustTextX(0, outerWidth, textAlign);
  6010. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6011. return new BoundingRect(x, y, outerWidth, outerHeight);
  6012. }
  6013. /**
  6014. * @public
  6015. * @param {number} x
  6016. * @param {number} width
  6017. * @param {string} [textAlign='left']
  6018. * @return {number} Adjusted x.
  6019. */
  6020. function adjustTextX(x, width, textAlign) {
  6021. // FIXME Right to left language
  6022. if (textAlign === 'right') {
  6023. x -= width;
  6024. }
  6025. else if (textAlign === 'center') {
  6026. x -= width / 2;
  6027. }
  6028. return x;
  6029. }
  6030. /**
  6031. * @public
  6032. * @param {number} y
  6033. * @param {number} height
  6034. * @param {string} [textVerticalAlign='top']
  6035. * @return {number} Adjusted y.
  6036. */
  6037. function adjustTextY(y, height, textVerticalAlign) {
  6038. if (textVerticalAlign === 'middle') {
  6039. y -= height / 2;
  6040. }
  6041. else if (textVerticalAlign === 'bottom') {
  6042. y -= height;
  6043. }
  6044. return y;
  6045. }
  6046. /**
  6047. * @public
  6048. * @param {stirng} textPosition
  6049. * @param {Object} rect {x, y, width, height}
  6050. * @param {number} distance
  6051. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6052. */
  6053. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6054. var x = rect.x;
  6055. var y = rect.y;
  6056. var height = rect.height;
  6057. var width = rect.width;
  6058. var halfHeight = height / 2;
  6059. var textAlign = 'left';
  6060. var textVerticalAlign = 'top';
  6061. switch (textPosition) {
  6062. case 'left':
  6063. x -= distance;
  6064. y += halfHeight;
  6065. textAlign = 'right';
  6066. textVerticalAlign = 'middle';
  6067. break;
  6068. case 'right':
  6069. x += distance + width;
  6070. y += halfHeight;
  6071. textVerticalAlign = 'middle';
  6072. break;
  6073. case 'top':
  6074. x += width / 2;
  6075. y -= distance;
  6076. textAlign = 'center';
  6077. textVerticalAlign = 'bottom';
  6078. break;
  6079. case 'bottom':
  6080. x += width / 2;
  6081. y += height + distance;
  6082. textAlign = 'center';
  6083. break;
  6084. case 'inside':
  6085. x += width / 2;
  6086. y += halfHeight;
  6087. textAlign = 'center';
  6088. textVerticalAlign = 'middle';
  6089. break;
  6090. case 'insideLeft':
  6091. x += distance;
  6092. y += halfHeight;
  6093. textVerticalAlign = 'middle';
  6094. break;
  6095. case 'insideRight':
  6096. x += width - distance;
  6097. y += halfHeight;
  6098. textAlign = 'right';
  6099. textVerticalAlign = 'middle';
  6100. break;
  6101. case 'insideTop':
  6102. x += width / 2;
  6103. y += distance;
  6104. textAlign = 'center';
  6105. break;
  6106. case 'insideBottom':
  6107. x += width / 2;
  6108. y += height - distance;
  6109. textAlign = 'center';
  6110. textVerticalAlign = 'bottom';
  6111. break;
  6112. case 'insideTopLeft':
  6113. x += distance;
  6114. y += distance;
  6115. break;
  6116. case 'insideTopRight':
  6117. x += width - distance;
  6118. y += distance;
  6119. textAlign = 'right';
  6120. break;
  6121. case 'insideBottomLeft':
  6122. x += distance;
  6123. y += height - distance;
  6124. textVerticalAlign = 'bottom';
  6125. break;
  6126. case 'insideBottomRight':
  6127. x += width - distance;
  6128. y += height - distance;
  6129. textAlign = 'right';
  6130. textVerticalAlign = 'bottom';
  6131. break;
  6132. }
  6133. return {
  6134. x: x,
  6135. y: y,
  6136. textAlign: textAlign,
  6137. textVerticalAlign: textVerticalAlign
  6138. };
  6139. }
  6140. /**
  6141. * Show ellipsis if overflow.
  6142. *
  6143. * @public
  6144. * @param {string} text
  6145. * @param {string} containerWidth
  6146. * @param {string} font
  6147. * @param {number} [ellipsis='...']
  6148. * @param {Object} [options]
  6149. * @param {number} [options.maxIterations=3]
  6150. * @param {number} [options.minChar=0] If truncate result are less
  6151. * then minChar, ellipsis will not show, which is
  6152. * better for user hint in some cases.
  6153. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6154. * @return {string}
  6155. */
  6156. function truncateText(text, containerWidth, font, ellipsis, options) {
  6157. if (!containerWidth) {
  6158. return '';
  6159. }
  6160. var textLines = (text + '').split('\n');
  6161. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6162. // FIXME
  6163. // It is not appropriate that every line has '...' when truncate multiple lines.
  6164. for (var i = 0, len = textLines.length; i < len; i++) {
  6165. textLines[i] = truncateSingleLine(textLines[i], options);
  6166. }
  6167. return textLines.join('\n');
  6168. }
  6169. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6170. options = extend({}, options);
  6171. options.font = font;
  6172. var ellipsis = retrieve2(ellipsis, '...');
  6173. options.maxIterations = retrieve2(options.maxIterations, 2);
  6174. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6175. // FIXME
  6176. // Other languages?
  6177. options.cnCharWidth = getWidth('国', font);
  6178. // FIXME
  6179. // Consider proportional font?
  6180. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6181. options.placeholder = retrieve2(options.placeholder, '');
  6182. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6183. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6184. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6185. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6186. contentWidth -= ascCharWidth;
  6187. }
  6188. var ellipsisWidth = getWidth(ellipsis);
  6189. if (ellipsisWidth > contentWidth) {
  6190. ellipsis = '';
  6191. ellipsisWidth = 0;
  6192. }
  6193. contentWidth = containerWidth - ellipsisWidth;
  6194. options.ellipsis = ellipsis;
  6195. options.ellipsisWidth = ellipsisWidth;
  6196. options.contentWidth = contentWidth;
  6197. options.containerWidth = containerWidth;
  6198. return options;
  6199. }
  6200. function truncateSingleLine(textLine, options) {
  6201. var containerWidth = options.containerWidth;
  6202. var font = options.font;
  6203. var contentWidth = options.contentWidth;
  6204. if (!containerWidth) {
  6205. return '';
  6206. }
  6207. var lineWidth = getWidth(textLine, font);
  6208. if (lineWidth <= containerWidth) {
  6209. return textLine;
  6210. }
  6211. for (var j = 0;; j++) {
  6212. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6213. textLine += options.ellipsis;
  6214. break;
  6215. }
  6216. var subLength = j === 0
  6217. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6218. : lineWidth > 0
  6219. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6220. : 0;
  6221. textLine = textLine.substr(0, subLength);
  6222. lineWidth = getWidth(textLine, font);
  6223. }
  6224. if (textLine === '') {
  6225. textLine = options.placeholder;
  6226. }
  6227. return textLine;
  6228. }
  6229. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6230. var width = 0;
  6231. var i = 0;
  6232. for (var len = text.length; i < len && width < contentWidth; i++) {
  6233. var charCode = text.charCodeAt(i);
  6234. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6235. }
  6236. return i;
  6237. }
  6238. /**
  6239. * @public
  6240. * @param {string} font
  6241. * @return {number} line height
  6242. */
  6243. function getLineHeight(font) {
  6244. // FIXME A rough approach.
  6245. return getWidth('国', font);
  6246. }
  6247. /**
  6248. * @public
  6249. * @param {string} text
  6250. * @param {string} font
  6251. * @return {Object} width
  6252. */
  6253. function measureText(text, font) {
  6254. return methods$1.measureText(text, font);
  6255. }
  6256. // Avoid assign to an exported variable, for transforming to cjs.
  6257. methods$1.measureText = function (text, font) {
  6258. var ctx = getContext();
  6259. ctx.font = font || DEFAULT_FONT;
  6260. return ctx.measureText(text);
  6261. };
  6262. /**
  6263. * @public
  6264. * @param {string} text
  6265. * @param {string} font
  6266. * @param {Object} [truncate]
  6267. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6268. * Notice: for performance, do not calculate outerWidth util needed.
  6269. */
  6270. function parsePlainText(text, font, padding, truncate) {
  6271. text != null && (text += '');
  6272. var lineHeight = getLineHeight(font);
  6273. var lines = text ? text.split('\n') : [];
  6274. var height = lines.length * lineHeight;
  6275. var outerHeight = height;
  6276. if (padding) {
  6277. outerHeight += padding[0] + padding[2];
  6278. }
  6279. if (text && truncate) {
  6280. var truncOuterHeight = truncate.outerHeight;
  6281. var truncOuterWidth = truncate.outerWidth;
  6282. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6283. text = '';
  6284. lines = [];
  6285. }
  6286. else if (truncOuterWidth != null) {
  6287. var options = prepareTruncateOptions(
  6288. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6289. font,
  6290. truncate.ellipsis,
  6291. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6292. );
  6293. // FIXME
  6294. // It is not appropriate that every line has '...' when truncate multiple lines.
  6295. for (var i = 0, len = lines.length; i < len; i++) {
  6296. lines[i] = truncateSingleLine(lines[i], options);
  6297. }
  6298. }
  6299. }
  6300. return {
  6301. lines: lines,
  6302. height: height,
  6303. outerHeight: outerHeight,
  6304. lineHeight: lineHeight
  6305. };
  6306. }
  6307. /**
  6308. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6309. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6310. *
  6311. * @public
  6312. * @param {string} text
  6313. * @param {Object} style
  6314. * @return {Object} block
  6315. * {
  6316. * width,
  6317. * height,
  6318. * lines: [{
  6319. * lineHeight,
  6320. * width,
  6321. * tokens: [[{
  6322. * styleName,
  6323. * text,
  6324. * width, // include textPadding
  6325. * height, // include textPadding
  6326. * textWidth, // pure text width
  6327. * textHeight, // pure text height
  6328. * lineHeihgt,
  6329. * font,
  6330. * textAlign,
  6331. * textVerticalAlign
  6332. * }], [...], ...]
  6333. * }, ...]
  6334. * }
  6335. * If styleName is undefined, it is plain text.
  6336. */
  6337. function parseRichText(text, style) {
  6338. var contentBlock = {lines: [], width: 0, height: 0};
  6339. text != null && (text += '');
  6340. if (!text) {
  6341. return contentBlock;
  6342. }
  6343. var lastIndex = STYLE_REG.lastIndex = 0;
  6344. var result;
  6345. while ((result = STYLE_REG.exec(text)) != null) {
  6346. var matchedIndex = result.index;
  6347. if (matchedIndex > lastIndex) {
  6348. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6349. }
  6350. pushTokens(contentBlock, result[2], result[1]);
  6351. lastIndex = STYLE_REG.lastIndex;
  6352. }
  6353. if (lastIndex < text.length) {
  6354. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6355. }
  6356. var lines = contentBlock.lines;
  6357. var contentHeight = 0;
  6358. var contentWidth = 0;
  6359. // For `textWidth: 100%`
  6360. var pendingList = [];
  6361. var stlPadding = style.textPadding;
  6362. var truncate = style.truncate;
  6363. var truncateWidth = truncate && truncate.outerWidth;
  6364. var truncateHeight = truncate && truncate.outerHeight;
  6365. if (stlPadding) {
  6366. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6367. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6368. }
  6369. // Calculate layout info of tokens.
  6370. for (var i = 0; i < lines.length; i++) {
  6371. var line = lines[i];
  6372. var lineHeight = 0;
  6373. var lineWidth = 0;
  6374. for (var j = 0; j < line.tokens.length; j++) {
  6375. var token = line.tokens[j];
  6376. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6377. // textPadding should not inherit from style.
  6378. var textPadding = token.textPadding = tokenStyle.textPadding;
  6379. // textFont has been asigned to font by `normalizeStyle`.
  6380. var font = token.font = tokenStyle.font || style.font;
  6381. // textHeight can be used when textVerticalAlign is specified in token.
  6382. var tokenHeight = token.textHeight = retrieve2(
  6383. // textHeight should not be inherited, consider it can be specified
  6384. // as box height of the block.
  6385. tokenStyle.textHeight, getLineHeight(font)
  6386. );
  6387. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6388. token.height = tokenHeight;
  6389. token.lineHeight = retrieve3(
  6390. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6391. );
  6392. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6393. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6394. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6395. return {lines: [], width: 0, height: 0};
  6396. }
  6397. token.textWidth = getWidth(token.text, font);
  6398. var tokenWidth = tokenStyle.textWidth;
  6399. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6400. // Percent width, can be `100%`, can be used in drawing separate
  6401. // line when box width is needed to be auto.
  6402. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6403. token.percentWidth = tokenWidth;
  6404. pendingList.push(token);
  6405. tokenWidth = 0;
  6406. // Do not truncate in this case, because there is no user case
  6407. // and it is too complicated.
  6408. }
  6409. else {
  6410. if (tokenWidthNotSpecified) {
  6411. tokenWidth = token.textWidth;
  6412. // FIXME: If image is not loaded and textWidth is not specified, calling
  6413. // `getBoundingRect()` will not get correct result.
  6414. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6415. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6416. // Use cases:
  6417. // (1) If image is not loaded, it will be loaded at render phase and call
  6418. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6419. // image, and then the right size will be calculated here at the next tick.
  6420. // See `graphic/helper/text.js`.
  6421. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6422. // use `imageHelper.findExistImage` to find cached image.
  6423. // `imageHelper.findExistImage` will always be called here before
  6424. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6425. // which ensures that image will not be rendered before correct size calcualted.
  6426. if (bgImg) {
  6427. bgImg = findExistImage(bgImg);
  6428. if (isImageReady(bgImg)) {
  6429. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6430. }
  6431. }
  6432. }
  6433. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6434. tokenWidth += paddingW;
  6435. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6436. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6437. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6438. token.text = '';
  6439. token.textWidth = tokenWidth = 0;
  6440. }
  6441. else {
  6442. token.text = truncateText(
  6443. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6444. {minChar: truncate.minChar}
  6445. );
  6446. token.textWidth = getWidth(token.text, font);
  6447. tokenWidth = token.textWidth + paddingW;
  6448. }
  6449. }
  6450. }
  6451. lineWidth += (token.width = tokenWidth);
  6452. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6453. }
  6454. line.width = lineWidth;
  6455. line.lineHeight = lineHeight;
  6456. contentHeight += lineHeight;
  6457. contentWidth = Math.max(contentWidth, lineWidth);
  6458. }
  6459. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6460. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6461. if (stlPadding) {
  6462. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6463. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6464. }
  6465. for (var i = 0; i < pendingList.length; i++) {
  6466. var token = pendingList[i];
  6467. var percentWidth = token.percentWidth;
  6468. // Should not base on outerWidth, because token can not be placed out of padding.
  6469. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6470. }
  6471. return contentBlock;
  6472. }
  6473. function pushTokens(block, str, styleName) {
  6474. var isEmptyStr = str === '';
  6475. var strs = str.split('\n');
  6476. var lines = block.lines;
  6477. for (var i = 0; i < strs.length; i++) {
  6478. var text = strs[i];
  6479. var token = {
  6480. styleName: styleName,
  6481. text: text,
  6482. isLineHolder: !text && !isEmptyStr
  6483. };
  6484. // The first token should be appended to the last line.
  6485. if (!i) {
  6486. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6487. // Consider cases:
  6488. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6489. // (which is a placeholder) should be replaced by new token.
  6490. // (2) A image backage, where token likes {a|}.
  6491. // (3) A redundant '' will affect textAlign in line.
  6492. // (4) tokens with the same tplName should not be merged, because
  6493. // they should be displayed in different box (with border and padding).
  6494. var tokensLen = tokens.length;
  6495. (tokensLen === 1 && tokens[0].isLineHolder)
  6496. ? (tokens[0] = token)
  6497. // Consider text is '', only insert when it is the "lineHolder" or
  6498. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6499. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6500. }
  6501. // Other tokens always start a new line.
  6502. else {
  6503. // If there is '', insert it as a placeholder.
  6504. lines.push({tokens: [token]});
  6505. }
  6506. }
  6507. }
  6508. function makeFont(style) {
  6509. // FIXME in node-canvas fontWeight is before fontStyle
  6510. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6511. return (style.fontSize || style.fontFamily) && [
  6512. style.fontStyle,
  6513. style.fontWeight,
  6514. (style.fontSize || 12) + 'px',
  6515. // If font properties are defined, `fontFamily` should not be ignored.
  6516. style.fontFamily || 'sans-serif'
  6517. ].join(' ') || style.textFont || style.font;
  6518. }
  6519. function buildPath(ctx, shape) {
  6520. var x = shape.x;
  6521. var y = shape.y;
  6522. var width = shape.width;
  6523. var height = shape.height;
  6524. var r = shape.r;
  6525. var r1;
  6526. var r2;
  6527. var r3;
  6528. var r4;
  6529. // Convert width and height to positive for better borderRadius
  6530. if (width < 0) {
  6531. x = x + width;
  6532. width = -width;
  6533. }
  6534. if (height < 0) {
  6535. y = y + height;
  6536. height = -height;
  6537. }
  6538. if (typeof r === 'number') {
  6539. r1 = r2 = r3 = r4 = r;
  6540. }
  6541. else if (r instanceof Array) {
  6542. if (r.length === 1) {
  6543. r1 = r2 = r3 = r4 = r[0];
  6544. }
  6545. else if (r.length === 2) {
  6546. r1 = r3 = r[0];
  6547. r2 = r4 = r[1];
  6548. }
  6549. else if (r.length === 3) {
  6550. r1 = r[0];
  6551. r2 = r4 = r[1];
  6552. r3 = r[2];
  6553. }
  6554. else {
  6555. r1 = r[0];
  6556. r2 = r[1];
  6557. r3 = r[2];
  6558. r4 = r[3];
  6559. }
  6560. }
  6561. else {
  6562. r1 = r2 = r3 = r4 = 0;
  6563. }
  6564. var total;
  6565. if (r1 + r2 > width) {
  6566. total = r1 + r2;
  6567. r1 *= width / total;
  6568. r2 *= width / total;
  6569. }
  6570. if (r3 + r4 > width) {
  6571. total = r3 + r4;
  6572. r3 *= width / total;
  6573. r4 *= width / total;
  6574. }
  6575. if (r2 + r3 > height) {
  6576. total = r2 + r3;
  6577. r2 *= height / total;
  6578. r3 *= height / total;
  6579. }
  6580. if (r1 + r4 > height) {
  6581. total = r1 + r4;
  6582. r1 *= height / total;
  6583. r4 *= height / total;
  6584. }
  6585. ctx.moveTo(x + r1, y);
  6586. ctx.lineTo(x + width - r2, y);
  6587. r2 !== 0 && ctx.quadraticCurveTo(
  6588. x + width, y, x + width, y + r2
  6589. );
  6590. ctx.lineTo(x + width, y + height - r3);
  6591. r3 !== 0 && ctx.quadraticCurveTo(
  6592. x + width, y + height, x + width - r3, y + height
  6593. );
  6594. ctx.lineTo(x + r4, y + height);
  6595. r4 !== 0 && ctx.quadraticCurveTo(
  6596. x, y + height, x, y + height - r4
  6597. );
  6598. ctx.lineTo(x, y + r1);
  6599. r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y);
  6600. }
  6601. // TODO: Have not support 'start', 'end' yet.
  6602. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6603. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6604. /**
  6605. * @param {module:zrender/graphic/Style} style
  6606. * @return {module:zrender/graphic/Style} The input style.
  6607. */
  6608. function normalizeTextStyle(style) {
  6609. normalizeStyle(style);
  6610. each$1(style.rich, normalizeStyle);
  6611. return style;
  6612. }
  6613. function normalizeStyle(style) {
  6614. if (style) {
  6615. style.font = makeFont(style);
  6616. var textAlign = style.textAlign;
  6617. textAlign === 'middle' && (textAlign = 'center');
  6618. style.textAlign = (
  6619. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6620. ) ? textAlign : 'left';
  6621. // Compatible with textBaseline.
  6622. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6623. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6624. style.textVerticalAlign = (
  6625. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6626. ) ? textVerticalAlign : 'top';
  6627. var textPadding = style.textPadding;
  6628. if (textPadding) {
  6629. style.textPadding = normalizeCssArray(style.textPadding);
  6630. }
  6631. }
  6632. }
  6633. /**
  6634. * @param {CanvasRenderingContext2D} ctx
  6635. * @param {string} text
  6636. * @param {module:zrender/graphic/Style} style
  6637. * @param {Object|boolean} [rect] {x, y, width, height}
  6638. * If set false, rect text is not used.
  6639. */
  6640. function renderText(hostEl, ctx, text, style, rect) {
  6641. style.rich
  6642. ? renderRichText(hostEl, ctx, text, style, rect)
  6643. : renderPlainText(hostEl, ctx, text, style, rect);
  6644. }
  6645. function renderPlainText(hostEl, ctx, text, style, rect) {
  6646. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6647. var textPadding = style.textPadding;
  6648. var contentBlock = hostEl.__textCotentBlock;
  6649. if (!contentBlock || hostEl.__dirty) {
  6650. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6651. text, font, textPadding, style.truncate
  6652. );
  6653. }
  6654. var outerHeight = contentBlock.outerHeight;
  6655. var textLines = contentBlock.lines;
  6656. var lineHeight = contentBlock.lineHeight;
  6657. var boxPos = getBoxPosition(outerHeight, style, rect);
  6658. var baseX = boxPos.baseX;
  6659. var baseY = boxPos.baseY;
  6660. var textAlign = boxPos.textAlign;
  6661. var textVerticalAlign = boxPos.textVerticalAlign;
  6662. // Origin of textRotation should be the base point of text drawing.
  6663. applyTextRotation(ctx, style, rect, baseX, baseY);
  6664. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6665. var textX = baseX;
  6666. var textY = boxY;
  6667. var needDrawBg = needDrawBackground(style);
  6668. if (needDrawBg || textPadding) {
  6669. // Consider performance, do not call getTextWidth util necessary.
  6670. var textWidth = getWidth(text, font);
  6671. var outerWidth = textWidth;
  6672. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6673. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6674. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6675. if (textPadding) {
  6676. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6677. textY += textPadding[0];
  6678. }
  6679. }
  6680. setCtx(ctx, 'textAlign', textAlign || 'left');
  6681. // Force baseline to be "middle". Otherwise, if using "top", the
  6682. // text will offset downward a little bit in font "Microsoft YaHei".
  6683. setCtx(ctx, 'textBaseline', 'middle');
  6684. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6685. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6686. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6687. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6688. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6689. // `textBaseline` is set as 'middle'.
  6690. textY += lineHeight / 2;
  6691. var textStrokeWidth = style.textStrokeWidth;
  6692. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6693. var textFill = getFill(style.textFill);
  6694. if (textStroke) {
  6695. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6696. setCtx(ctx, 'strokeStyle', textStroke);
  6697. }
  6698. if (textFill) {
  6699. setCtx(ctx, 'fillStyle', textFill);
  6700. }
  6701. for (var i = 0; i < textLines.length; i++) {
  6702. // Fill after stroke so the outline will not cover the main part.
  6703. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6704. textFill && ctx.fillText(textLines[i], textX, textY);
  6705. textY += lineHeight;
  6706. }
  6707. }
  6708. function renderRichText(hostEl, ctx, text, style, rect) {
  6709. var contentBlock = hostEl.__textCotentBlock;
  6710. if (!contentBlock || hostEl.__dirty) {
  6711. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6712. }
  6713. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6714. }
  6715. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6716. var contentWidth = contentBlock.width;
  6717. var outerWidth = contentBlock.outerWidth;
  6718. var outerHeight = contentBlock.outerHeight;
  6719. var textPadding = style.textPadding;
  6720. var boxPos = getBoxPosition(outerHeight, style, rect);
  6721. var baseX = boxPos.baseX;
  6722. var baseY = boxPos.baseY;
  6723. var textAlign = boxPos.textAlign;
  6724. var textVerticalAlign = boxPos.textVerticalAlign;
  6725. // Origin of textRotation should be the base point of text drawing.
  6726. applyTextRotation(ctx, style, rect, baseX, baseY);
  6727. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6728. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6729. var xLeft = boxX;
  6730. var lineTop = boxY;
  6731. if (textPadding) {
  6732. xLeft += textPadding[3];
  6733. lineTop += textPadding[0];
  6734. }
  6735. var xRight = xLeft + contentWidth;
  6736. needDrawBackground(style) && drawBackground(
  6737. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6738. );
  6739. for (var i = 0; i < contentBlock.lines.length; i++) {
  6740. var line = contentBlock.lines[i];
  6741. var tokens = line.tokens;
  6742. var tokenCount = tokens.length;
  6743. var lineHeight = line.lineHeight;
  6744. var usedWidth = line.width;
  6745. var leftIndex = 0;
  6746. var lineXLeft = xLeft;
  6747. var lineXRight = xRight;
  6748. var rightIndex = tokenCount - 1;
  6749. var token;
  6750. while (
  6751. leftIndex < tokenCount
  6752. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6753. ) {
  6754. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6755. usedWidth -= token.width;
  6756. lineXLeft += token.width;
  6757. leftIndex++;
  6758. }
  6759. while (
  6760. rightIndex >= 0
  6761. && (token = tokens[rightIndex], token.textAlign === 'right')
  6762. ) {
  6763. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6764. usedWidth -= token.width;
  6765. lineXRight -= token.width;
  6766. rightIndex--;
  6767. }
  6768. // The other tokens are placed as textAlign 'center' if there is enough space.
  6769. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6770. while (leftIndex <= rightIndex) {
  6771. token = tokens[leftIndex];
  6772. // Consider width specified by user, use 'center' rather than 'left'.
  6773. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6774. lineXLeft += token.width;
  6775. leftIndex++;
  6776. }
  6777. lineTop += lineHeight;
  6778. }
  6779. }
  6780. function applyTextRotation(ctx, style, rect, x, y) {
  6781. // textRotation only apply in RectText.
  6782. if (rect && style.textRotation) {
  6783. var origin = style.textOrigin;
  6784. if (origin === 'center') {
  6785. x = rect.width / 2 + rect.x;
  6786. y = rect.height / 2 + rect.y;
  6787. }
  6788. else if (origin) {
  6789. x = origin[0] + rect.x;
  6790. y = origin[1] + rect.y;
  6791. }
  6792. ctx.translate(x, y);
  6793. // Positive: anticlockwise
  6794. ctx.rotate(-style.textRotation);
  6795. ctx.translate(-x, -y);
  6796. }
  6797. }
  6798. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6799. var tokenStyle = style.rich[token.styleName] || {};
  6800. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6801. // the bias of "Microsoft YaHei".
  6802. var textVerticalAlign = token.textVerticalAlign;
  6803. var y = lineTop + lineHeight / 2;
  6804. if (textVerticalAlign === 'top') {
  6805. y = lineTop + token.height / 2;
  6806. }
  6807. else if (textVerticalAlign === 'bottom') {
  6808. y = lineTop + lineHeight - token.height / 2;
  6809. }
  6810. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6811. hostEl,
  6812. ctx,
  6813. tokenStyle,
  6814. textAlign === 'right'
  6815. ? x - token.width
  6816. : textAlign === 'center'
  6817. ? x - token.width / 2
  6818. : x,
  6819. y - token.height / 2,
  6820. token.width,
  6821. token.height
  6822. );
  6823. var textPadding = token.textPadding;
  6824. if (textPadding) {
  6825. x = getTextXForPadding(x, textAlign, textPadding);
  6826. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6827. }
  6828. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6829. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6830. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6831. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6832. setCtx(ctx, 'textAlign', textAlign);
  6833. // Force baseline to be "middle". Otherwise, if using "top", the
  6834. // text will offset downward a little bit in font "Microsoft YaHei".
  6835. setCtx(ctx, 'textBaseline', 'middle');
  6836. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6837. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6838. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6839. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6840. // Fill after stroke so the outline will not cover the main part.
  6841. if (textStroke) {
  6842. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6843. setCtx(ctx, 'strokeStyle', textStroke);
  6844. ctx.strokeText(token.text, x, y);
  6845. }
  6846. if (textFill) {
  6847. setCtx(ctx, 'fillStyle', textFill);
  6848. ctx.fillText(token.text, x, y);
  6849. }
  6850. }
  6851. function needDrawBackground(style) {
  6852. return style.textBackgroundColor
  6853. || (style.textBorderWidth && style.textBorderColor);
  6854. }
  6855. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6856. // shape: {x, y, width, height}
  6857. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6858. var textBackgroundColor = style.textBackgroundColor;
  6859. var textBorderWidth = style.textBorderWidth;
  6860. var textBorderColor = style.textBorderColor;
  6861. var isPlainBg = isString(textBackgroundColor);
  6862. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6863. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6864. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6865. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6866. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6867. ctx.beginPath();
  6868. var textBorderRadius = style.textBorderRadius;
  6869. if (!textBorderRadius) {
  6870. ctx.rect(x, y, width, height);
  6871. }
  6872. else {
  6873. buildPath(ctx, {
  6874. x: x, y: y, width: width, height: height, r: textBorderRadius
  6875. });
  6876. }
  6877. ctx.closePath();
  6878. }
  6879. if (isPlainBg) {
  6880. setCtx(ctx, 'fillStyle', textBackgroundColor);
  6881. ctx.fill();
  6882. }
  6883. else if (isObject(textBackgroundColor)) {
  6884. var image = textBackgroundColor.image;
  6885. image = createOrUpdateImage(
  6886. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  6887. );
  6888. if (image && isImageReady(image)) {
  6889. ctx.drawImage(image, x, y, width, height);
  6890. }
  6891. }
  6892. if (textBorderWidth && textBorderColor) {
  6893. setCtx(ctx, 'lineWidth', textBorderWidth);
  6894. setCtx(ctx, 'strokeStyle', textBorderColor);
  6895. ctx.stroke();
  6896. }
  6897. }
  6898. function onBgImageLoaded(image, textBackgroundColor) {
  6899. // Replace image, so that `contain/text.js#parseRichText`
  6900. // will get correct result in next tick.
  6901. textBackgroundColor.image = image;
  6902. }
  6903. function getBoxPosition(blockHeiht, style, rect) {
  6904. var baseX = style.x || 0;
  6905. var baseY = style.y || 0;
  6906. var textAlign = style.textAlign;
  6907. var textVerticalAlign = style.textVerticalAlign;
  6908. // Text position represented by coord
  6909. if (rect) {
  6910. var textPosition = style.textPosition;
  6911. if (textPosition instanceof Array) {
  6912. // Percent
  6913. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  6914. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  6915. }
  6916. else {
  6917. var res = adjustTextPositionOnRect(
  6918. textPosition, rect, style.textDistance
  6919. );
  6920. baseX = res.x;
  6921. baseY = res.y;
  6922. // Default align and baseline when has textPosition
  6923. textAlign = textAlign || res.textAlign;
  6924. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  6925. }
  6926. // textOffset is only support in RectText, otherwise
  6927. // we have to adjust boundingRect for textOffset.
  6928. var textOffset = style.textOffset;
  6929. if (textOffset) {
  6930. baseX += textOffset[0];
  6931. baseY += textOffset[1];
  6932. }
  6933. }
  6934. return {
  6935. baseX: baseX,
  6936. baseY: baseY,
  6937. textAlign: textAlign,
  6938. textVerticalAlign: textVerticalAlign
  6939. };
  6940. }
  6941. function setCtx(ctx, prop, value) {
  6942. // FIXME ??? performance try
  6943. // if (ctx.__currentValues[prop] !== value) {
  6944. // ctx[prop] = ctx.__currentValues[prop] = value;
  6945. ctx[prop] = value;
  6946. // }
  6947. return ctx[prop];
  6948. }
  6949. /**
  6950. * @param {string} [stroke] If specified, do not check style.textStroke.
  6951. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  6952. * @param {number} style
  6953. */
  6954. function getStroke(stroke, lineWidth) {
  6955. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  6956. ? null
  6957. // TODO pattern and gradient?
  6958. : (stroke.image || stroke.colorStops)
  6959. ? '#000'
  6960. : stroke;
  6961. }
  6962. function getFill(fill) {
  6963. return (fill == null || fill === 'none')
  6964. ? null
  6965. // TODO pattern and gradient?
  6966. : (fill.image || fill.colorStops)
  6967. ? '#000'
  6968. : fill;
  6969. }
  6970. function parsePercent(value, maxValue) {
  6971. if (typeof value === 'string') {
  6972. if (value.lastIndexOf('%') >= 0) {
  6973. return parseFloat(value) / 100 * maxValue;
  6974. }
  6975. return parseFloat(value);
  6976. }
  6977. return value;
  6978. }
  6979. function getTextXForPadding(x, textAlign, textPadding) {
  6980. return textAlign === 'right'
  6981. ? (x - textPadding[1])
  6982. : textAlign === 'center'
  6983. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  6984. : (x + textPadding[3]);
  6985. }
  6986. /**
  6987. * @param {string} text
  6988. * @param {module:zrender/Style} style
  6989. * @return {boolean}
  6990. */
  6991. function needDrawText(text, style) {
  6992. return text != null
  6993. && (text
  6994. || style.textBackgroundColor
  6995. || (style.textBorderWidth && style.textBorderColor)
  6996. || style.textPadding
  6997. );
  6998. }
  6999. /**
  7000. * Mixin for drawing text in a element bounding rect
  7001. * @module zrender/mixin/RectText
  7002. */
  7003. var tmpRect$1 = new BoundingRect();
  7004. var RectText = function () {};
  7005. RectText.prototype = {
  7006. constructor: RectText,
  7007. /**
  7008. * Draw text in a rect with specified position.
  7009. * @param {CanvasRenderingContext2D} ctx
  7010. * @param {Object} rect Displayable rect
  7011. */
  7012. drawRectText: function (ctx, rect) {
  7013. var style = this.style;
  7014. rect = style.textRect || rect;
  7015. // Optimize, avoid normalize every time.
  7016. this.__dirty && normalizeTextStyle(style, true);
  7017. var text = style.text;
  7018. // Convert to string
  7019. text != null && (text += '');
  7020. if (!needDrawText(text, style)) {
  7021. return;
  7022. }
  7023. // FIXME
  7024. ctx.save();
  7025. // Transform rect to view space
  7026. var transform = this.transform;
  7027. if (!style.transformText) {
  7028. if (transform) {
  7029. tmpRect$1.copy(rect);
  7030. tmpRect$1.applyTransform(transform);
  7031. rect = tmpRect$1;
  7032. }
  7033. }
  7034. else {
  7035. this.setTransform(ctx);
  7036. }
  7037. // transformText and textRotation can not be used at the same time.
  7038. renderText(this, ctx, text, style, rect);
  7039. ctx.restore();
  7040. }
  7041. };
  7042. /**
  7043. * 可绘制的图形基类
  7044. * Base class of all displayable graphic objects
  7045. * @module zrender/graphic/Displayable
  7046. */
  7047. /**
  7048. * @alias module:zrender/graphic/Displayable
  7049. * @extends module:zrender/Element
  7050. * @extends module:zrender/graphic/mixin/RectText
  7051. */
  7052. function Displayable(opts) {
  7053. opts = opts || {};
  7054. Element.call(this, opts);
  7055. // Extend properties
  7056. for (var name in opts) {
  7057. if (
  7058. opts.hasOwnProperty(name) &&
  7059. name !== 'style'
  7060. ) {
  7061. this[name] = opts[name];
  7062. }
  7063. }
  7064. /**
  7065. * @type {module:zrender/graphic/Style}
  7066. */
  7067. this.style = new Style(opts.style, this);
  7068. this._rect = null;
  7069. // Shapes for cascade clipping.
  7070. this.__clipPaths = [];
  7071. // FIXME Stateful must be mixined after style is setted
  7072. // Stateful.call(this, opts);
  7073. }
  7074. Displayable.prototype = {
  7075. constructor: Displayable,
  7076. type: 'displayable',
  7077. /**
  7078. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7079. * Dirty flag. From which painter will determine if this displayable object needs brush
  7080. * @name module:zrender/graphic/Displayable#__dirty
  7081. * @type {boolean}
  7082. */
  7083. __dirty: true,
  7084. /**
  7085. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7086. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7087. * @name module:/zrender/graphic/Displayable#invisible
  7088. * @type {boolean}
  7089. * @default false
  7090. */
  7091. invisible: false,
  7092. /**
  7093. * @name module:/zrender/graphic/Displayable#z
  7094. * @type {number}
  7095. * @default 0
  7096. */
  7097. z: 0,
  7098. /**
  7099. * @name module:/zrender/graphic/Displayable#z
  7100. * @type {number}
  7101. * @default 0
  7102. */
  7103. z2: 0,
  7104. /**
  7105. * z层level,决定绘画在哪层canvas中
  7106. * @name module:/zrender/graphic/Displayable#zlevel
  7107. * @type {number}
  7108. * @default 0
  7109. */
  7110. zlevel: 0,
  7111. /**
  7112. * 是否可拖拽
  7113. * @name module:/zrender/graphic/Displayable#draggable
  7114. * @type {boolean}
  7115. * @default false
  7116. */
  7117. draggable: false,
  7118. /**
  7119. * 是否正在拖拽
  7120. * @name module:/zrender/graphic/Displayable#draggable
  7121. * @type {boolean}
  7122. * @default false
  7123. */
  7124. dragging: false,
  7125. /**
  7126. * 是否相应鼠标事件
  7127. * @name module:/zrender/graphic/Displayable#silent
  7128. * @type {boolean}
  7129. * @default false
  7130. */
  7131. silent: false,
  7132. /**
  7133. * If enable culling
  7134. * @type {boolean}
  7135. * @default false
  7136. */
  7137. culling: false,
  7138. /**
  7139. * Mouse cursor when hovered
  7140. * @name module:/zrender/graphic/Displayable#cursor
  7141. * @type {string}
  7142. */
  7143. cursor: 'pointer',
  7144. /**
  7145. * If hover area is bounding rect
  7146. * @name module:/zrender/graphic/Displayable#rectHover
  7147. * @type {string}
  7148. */
  7149. rectHover: false,
  7150. /**
  7151. * Render the element progressively when the value >= 0,
  7152. * usefull for large data.
  7153. * @type {number}
  7154. */
  7155. progressive: -1,
  7156. beforeBrush: function (ctx) {},
  7157. afterBrush: function (ctx) {},
  7158. /**
  7159. * 图形绘制方法
  7160. * @param {CanvasRenderingContext2D} ctx
  7161. */
  7162. // Interface
  7163. brush: function (ctx, prevEl) {},
  7164. /**
  7165. * 获取最小包围盒
  7166. * @return {module:zrender/core/BoundingRect}
  7167. */
  7168. // Interface
  7169. getBoundingRect: function () {},
  7170. /**
  7171. * 判断坐标 x, y 是否在图形上
  7172. * If displayable element contain coord x, y
  7173. * @param {number} x
  7174. * @param {number} y
  7175. * @return {boolean}
  7176. */
  7177. contain: function (x, y) {
  7178. return this.rectContain(x, y);
  7179. },
  7180. /**
  7181. * @param {Function} cb
  7182. * @param {} context
  7183. */
  7184. traverse: function (cb, context) {
  7185. cb.call(context, this);
  7186. },
  7187. /**
  7188. * 判断坐标 x, y 是否在图形的包围盒上
  7189. * If bounding rect of element contain coord x, y
  7190. * @param {number} x
  7191. * @param {number} y
  7192. * @return {boolean}
  7193. */
  7194. rectContain: function (x, y) {
  7195. var coord = this.transformCoordToLocal(x, y);
  7196. var rect = this.getBoundingRect();
  7197. return rect.contain(coord[0], coord[1]);
  7198. },
  7199. /**
  7200. * 标记图形元素为脏,并且在下一帧重绘
  7201. * Mark displayable element dirty and refresh next frame
  7202. */
  7203. dirty: function () {
  7204. this.__dirty = true;
  7205. this._rect = null;
  7206. this.__zr && this.__zr.refresh();
  7207. },
  7208. /**
  7209. * 图形是否会触发事件
  7210. * If displayable object binded any event
  7211. * @return {boolean}
  7212. */
  7213. // TODO, 通过 bind 绑定的事件
  7214. // isSilent: function () {
  7215. // return !(
  7216. // this.hoverable || this.draggable
  7217. // || this.onmousemove || this.onmouseover || this.onmouseout
  7218. // || this.onmousedown || this.onmouseup || this.onclick
  7219. // || this.ondragenter || this.ondragover || this.ondragleave
  7220. // || this.ondrop
  7221. // );
  7222. // },
  7223. /**
  7224. * Alias for animate('style')
  7225. * @param {boolean} loop
  7226. */
  7227. animateStyle: function (loop) {
  7228. return this.animate('style', loop);
  7229. },
  7230. attrKV: function (key, value) {
  7231. if (key !== 'style') {
  7232. Element.prototype.attrKV.call(this, key, value);
  7233. }
  7234. else {
  7235. this.style.set(value);
  7236. }
  7237. },
  7238. /**
  7239. * @param {Object|string} key
  7240. * @param {*} value
  7241. */
  7242. setStyle: function (key, value) {
  7243. this.style.set(key, value);
  7244. this.dirty(false);
  7245. return this;
  7246. },
  7247. /**
  7248. * Use given style object
  7249. * @param {Object} obj
  7250. */
  7251. useStyle: function (obj) {
  7252. this.style = new Style(obj, this);
  7253. this.dirty(false);
  7254. return this;
  7255. }
  7256. };
  7257. inherits(Displayable, Element);
  7258. mixin(Displayable, RectText);
  7259. /**
  7260. * @alias zrender/graphic/Image
  7261. * @extends module:zrender/graphic/Displayable
  7262. * @constructor
  7263. * @param {Object} opts
  7264. */
  7265. function ZImage(opts) {
  7266. Displayable.call(this, opts);
  7267. }
  7268. ZImage.prototype = {
  7269. constructor: ZImage,
  7270. type: 'image',
  7271. brush: function (ctx, prevEl) {
  7272. var style = this.style;
  7273. var src = style.image;
  7274. // Must bind each time
  7275. style.bind(ctx, this, prevEl);
  7276. var image = this._image = createOrUpdateImage(
  7277. src,
  7278. this._image,
  7279. this,
  7280. this.onload
  7281. );
  7282. if (!image || !isImageReady(image)) {
  7283. return;
  7284. }
  7285. // 图片已经加载完成
  7286. // if (image.nodeName.toUpperCase() == 'IMG') {
  7287. // if (!image.complete) {
  7288. // return;
  7289. // }
  7290. // }
  7291. // Else is canvas
  7292. var x = style.x || 0;
  7293. var y = style.y || 0;
  7294. var width = style.width;
  7295. var height = style.height;
  7296. var aspect = image.width / image.height;
  7297. if (width == null && height != null) {
  7298. // Keep image/height ratio
  7299. width = height * aspect;
  7300. }
  7301. else if (height == null && width != null) {
  7302. height = width / aspect;
  7303. }
  7304. else if (width == null && height == null) {
  7305. width = image.width;
  7306. height = image.height;
  7307. }
  7308. // 设置transform
  7309. this.setTransform(ctx);
  7310. if (style.sWidth && style.sHeight) {
  7311. var sx = style.sx || 0;
  7312. var sy = style.sy || 0;
  7313. ctx.drawImage(
  7314. image,
  7315. sx, sy, style.sWidth, style.sHeight,
  7316. x, y, width, height
  7317. );
  7318. }
  7319. else if (style.sx && style.sy) {
  7320. var sx = style.sx;
  7321. var sy = style.sy;
  7322. var sWidth = width - sx;
  7323. var sHeight = height - sy;
  7324. ctx.drawImage(
  7325. image,
  7326. sx, sy, sWidth, sHeight,
  7327. x, y, width, height
  7328. );
  7329. }
  7330. else {
  7331. ctx.drawImage(image, x, y, width, height);
  7332. }
  7333. this.restoreTransform(ctx);
  7334. // Draw rect text
  7335. if (style.text != null) {
  7336. this.drawRectText(ctx, this.getBoundingRect());
  7337. }
  7338. },
  7339. getBoundingRect: function () {
  7340. var style = this.style;
  7341. if (! this._rect) {
  7342. this._rect = new BoundingRect(
  7343. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7344. );
  7345. }
  7346. return this._rect;
  7347. }
  7348. };
  7349. inherits(ZImage, Displayable);
  7350. /**
  7351. * Default canvas painter
  7352. * @module zrender/Painter
  7353. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  7354. * errorrik (errorrik@gmail.com)
  7355. * pissang (https://www.github.com/pissang)
  7356. */
  7357. // PENDIGN
  7358. // Layer exceeds MAX_PROGRESSIVE_LAYER_NUMBER may have some problem when flush directly second time.
  7359. //
  7360. // Maximum progressive layer. When exceeding this number. All elements will be drawed in the last layer.
  7361. var MAX_PROGRESSIVE_LAYER_NUMBER = 5;
  7362. function parseInt10(val) {
  7363. return parseInt(val, 10);
  7364. }
  7365. function isLayerValid(layer) {
  7366. if (!layer) {
  7367. return false;
  7368. }
  7369. if (layer.__builtin__) {
  7370. return true;
  7371. }
  7372. if (typeof(layer.resize) !== 'function'
  7373. || typeof(layer.refresh) !== 'function'
  7374. ) {
  7375. return false;
  7376. }
  7377. return true;
  7378. }
  7379. function preProcessLayer(layer) {
  7380. layer.__unusedCount++;
  7381. }
  7382. function postProcessLayer(layer) {
  7383. if (layer.__unusedCount == 1) {
  7384. layer.clear();
  7385. }
  7386. }
  7387. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7388. var viewRect = new BoundingRect(0, 0, 0, 0);
  7389. function isDisplayableCulled(el, width, height) {
  7390. tmpRect.copy(el.getBoundingRect());
  7391. if (el.transform) {
  7392. tmpRect.applyTransform(el.transform);
  7393. }
  7394. viewRect.width = width;
  7395. viewRect.height = height;
  7396. return !tmpRect.intersect(viewRect);
  7397. }
  7398. function isClipPathChanged(clipPaths, prevClipPaths) {
  7399. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7400. return false;
  7401. }
  7402. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7403. return true;
  7404. }
  7405. for (var i = 0; i < clipPaths.length; i++) {
  7406. if (clipPaths[i] !== prevClipPaths[i]) {
  7407. return true;
  7408. }
  7409. }
  7410. }
  7411. function doClip(clipPaths, ctx) {
  7412. for (var i = 0; i < clipPaths.length; i++) {
  7413. var clipPath = clipPaths[i];
  7414. clipPath.setTransform(ctx);
  7415. ctx.beginPath();
  7416. clipPath.buildPath(ctx, clipPath.shape);
  7417. ctx.clip();
  7418. // Transform back
  7419. clipPath.restoreTransform(ctx);
  7420. }
  7421. }
  7422. function createRoot(width, height) {
  7423. var domRoot = document.createElement('div');
  7424. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7425. domRoot.style.cssText = [
  7426. 'position:relative',
  7427. 'overflow:hidden',
  7428. 'width:' + width + 'px',
  7429. 'height:' + height + 'px',
  7430. 'padding:0',
  7431. 'margin:0',
  7432. 'border-width:0'
  7433. ].join(';') + ';';
  7434. return domRoot;
  7435. }
  7436. /**
  7437. * @alias module:zrender/Painter
  7438. * @constructor
  7439. * @param {HTMLElement} root 绘图容器
  7440. * @param {module:zrender/Storage} storage
  7441. * @param {Object} opts
  7442. */
  7443. var Painter = function (root, storage, opts) {
  7444. this.type = 'canvas';
  7445. // In node environment using node-canvas
  7446. var singleCanvas = !root.nodeName // In node ?
  7447. || root.nodeName.toUpperCase() === 'CANVAS';
  7448. this._opts = opts = extend({}, opts || {});
  7449. /**
  7450. * @type {number}
  7451. */
  7452. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7453. /**
  7454. * @type {boolean}
  7455. * @private
  7456. */
  7457. this._singleCanvas = singleCanvas;
  7458. /**
  7459. * 绘图容器
  7460. * @type {HTMLElement}
  7461. */
  7462. this.root = root;
  7463. var rootStyle = root.style;
  7464. if (rootStyle) {
  7465. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7466. rootStyle['-webkit-user-select'] =
  7467. rootStyle['user-select'] =
  7468. rootStyle['-webkit-touch-callout'] = 'none';
  7469. root.innerHTML = '';
  7470. }
  7471. /**
  7472. * @type {module:zrender/Storage}
  7473. */
  7474. this.storage = storage;
  7475. /**
  7476. * @type {Array.<number>}
  7477. * @private
  7478. */
  7479. var zlevelList = this._zlevelList = [];
  7480. /**
  7481. * @type {Object.<string, module:zrender/Layer>}
  7482. * @private
  7483. */
  7484. var layers = this._layers = {};
  7485. /**
  7486. * @type {Object.<string, Object>}
  7487. * @type {private}
  7488. */
  7489. this._layerConfig = {};
  7490. if (!singleCanvas) {
  7491. this._width = this._getSize(0);
  7492. this._height = this._getSize(1);
  7493. var domRoot = this._domRoot = createRoot(
  7494. this._width, this._height
  7495. );
  7496. root.appendChild(domRoot);
  7497. }
  7498. else {
  7499. if (opts.width != null) {
  7500. root.width = opts.width;
  7501. }
  7502. if (opts.height != null) {
  7503. root.height = opts.height;
  7504. }
  7505. // Use canvas width and height directly
  7506. var width = root.width;
  7507. var height = root.height;
  7508. this._width = width;
  7509. this._height = height;
  7510. // Create layer if only one given canvas
  7511. // Device pixel ratio is fixed to 1 because given canvas has its specified width and height
  7512. var mainLayer = new Layer(root, this, 1);
  7513. mainLayer.initContext();
  7514. // FIXME Use canvas width and height
  7515. // mainLayer.resize(width, height);
  7516. layers[0] = mainLayer;
  7517. zlevelList.push(0);
  7518. this._domRoot = root;
  7519. }
  7520. // Layers for progressive rendering
  7521. this._progressiveLayers = [];
  7522. /**
  7523. * @type {module:zrender/Layer}
  7524. * @private
  7525. */
  7526. this._hoverlayer;
  7527. this._hoverElements = [];
  7528. };
  7529. Painter.prototype = {
  7530. constructor: Painter,
  7531. getType: function () {
  7532. return 'canvas';
  7533. },
  7534. /**
  7535. * If painter use a single canvas
  7536. * @return {boolean}
  7537. */
  7538. isSingleCanvas: function () {
  7539. return this._singleCanvas;
  7540. },
  7541. /**
  7542. * @return {HTMLDivElement}
  7543. */
  7544. getViewportRoot: function () {
  7545. return this._domRoot;
  7546. },
  7547. getViewportRootOffset: function () {
  7548. var viewportRoot = this.getViewportRoot();
  7549. if (viewportRoot) {
  7550. return {
  7551. offsetLeft: viewportRoot.offsetLeft || 0,
  7552. offsetTop: viewportRoot.offsetTop || 0
  7553. };
  7554. }
  7555. },
  7556. /**
  7557. * 刷新
  7558. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7559. */
  7560. refresh: function (paintAll) {
  7561. var list = this.storage.getDisplayList(true);
  7562. var zlevelList = this._zlevelList;
  7563. this._paintList(list, paintAll);
  7564. // Paint custum layers
  7565. for (var i = 0; i < zlevelList.length; i++) {
  7566. var z = zlevelList[i];
  7567. var layer = this._layers[z];
  7568. if (!layer.__builtin__ && layer.refresh) {
  7569. layer.refresh();
  7570. }
  7571. }
  7572. this.refreshHover();
  7573. if (this._progressiveLayers.length) {
  7574. this._startProgessive();
  7575. }
  7576. return this;
  7577. },
  7578. addHover: function (el, hoverStyle) {
  7579. if (el.__hoverMir) {
  7580. return;
  7581. }
  7582. var elMirror = new el.constructor({
  7583. style: el.style,
  7584. shape: el.shape
  7585. });
  7586. elMirror.__from = el;
  7587. el.__hoverMir = elMirror;
  7588. elMirror.setStyle(hoverStyle);
  7589. this._hoverElements.push(elMirror);
  7590. },
  7591. removeHover: function (el) {
  7592. var elMirror = el.__hoverMir;
  7593. var hoverElements = this._hoverElements;
  7594. var idx = indexOf(hoverElements, elMirror);
  7595. if (idx >= 0) {
  7596. hoverElements.splice(idx, 1);
  7597. }
  7598. el.__hoverMir = null;
  7599. },
  7600. clearHover: function (el) {
  7601. var hoverElements = this._hoverElements;
  7602. for (var i = 0; i < hoverElements.length; i++) {
  7603. var from = hoverElements[i].__from;
  7604. if (from) {
  7605. from.__hoverMir = null;
  7606. }
  7607. }
  7608. hoverElements.length = 0;
  7609. },
  7610. refreshHover: function () {
  7611. var hoverElements = this._hoverElements;
  7612. var len = hoverElements.length;
  7613. var hoverLayer = this._hoverlayer;
  7614. hoverLayer && hoverLayer.clear();
  7615. if (!len) {
  7616. return;
  7617. }
  7618. sort(hoverElements, this.storage.displayableSortFunc);
  7619. // Use a extream large zlevel
  7620. // FIXME?
  7621. if (!hoverLayer) {
  7622. hoverLayer = this._hoverlayer = this.getLayer(1e5);
  7623. }
  7624. var scope = {};
  7625. hoverLayer.ctx.save();
  7626. for (var i = 0; i < len;) {
  7627. var el = hoverElements[i];
  7628. var originalEl = el.__from;
  7629. // Original el is removed
  7630. // PENDING
  7631. if (!(originalEl && originalEl.__zr)) {
  7632. hoverElements.splice(i, 1);
  7633. originalEl.__hoverMir = null;
  7634. len--;
  7635. continue;
  7636. }
  7637. i++;
  7638. // Use transform
  7639. // FIXME style and shape ?
  7640. if (!originalEl.invisible) {
  7641. el.transform = originalEl.transform;
  7642. el.invTransform = originalEl.invTransform;
  7643. el.__clipPaths = originalEl.__clipPaths;
  7644. // el.
  7645. this._doPaintEl(el, hoverLayer, true, scope);
  7646. }
  7647. }
  7648. hoverLayer.ctx.restore();
  7649. },
  7650. _startProgessive: function () {
  7651. var self = this;
  7652. if (!self._furtherProgressive) {
  7653. return;
  7654. }
  7655. // Use a token to stop progress steps triggered by
  7656. // previous zr.refresh calling.
  7657. var token = self._progressiveToken = +new Date();
  7658. self._progress++;
  7659. requestAnimationFrame(step);
  7660. function step() {
  7661. // In case refreshed or disposed
  7662. if (token === self._progressiveToken && self.storage) {
  7663. self._doPaintList(self.storage.getDisplayList());
  7664. if (self._furtherProgressive) {
  7665. self._progress++;
  7666. requestAnimationFrame(step);
  7667. }
  7668. else {
  7669. self._progressiveToken = -1;
  7670. }
  7671. }
  7672. }
  7673. },
  7674. _clearProgressive: function () {
  7675. this._progressiveToken = -1;
  7676. this._progress = 0;
  7677. each$1(this._progressiveLayers, function (layer) {
  7678. layer.__dirty && layer.clear();
  7679. });
  7680. },
  7681. _paintList: function (list, paintAll) {
  7682. if (paintAll == null) {
  7683. paintAll = false;
  7684. }
  7685. this._updateLayerStatus(list);
  7686. this._clearProgressive();
  7687. this.eachBuiltinLayer(preProcessLayer);
  7688. this._doPaintList(list, paintAll);
  7689. this.eachBuiltinLayer(postProcessLayer);
  7690. },
  7691. _doPaintList: function (list, paintAll) {
  7692. var currentLayer;
  7693. var currentZLevel;
  7694. var ctx;
  7695. // var invTransform = [];
  7696. var scope;
  7697. var progressiveLayerIdx = 0;
  7698. var currentProgressiveLayer;
  7699. var width = this._width;
  7700. var height = this._height;
  7701. var layerProgress;
  7702. var frame = this._progress;
  7703. function flushProgressiveLayer(layer) {
  7704. var dpr = ctx.dpr || 1;
  7705. ctx.save();
  7706. ctx.globalAlpha = 1;
  7707. ctx.shadowBlur = 0;
  7708. // Avoid layer don't clear in next progressive frame
  7709. currentLayer.__dirty = true;
  7710. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7711. ctx.drawImage(layer.dom, 0, 0, width * dpr, height * dpr);
  7712. ctx.restore();
  7713. }
  7714. for (var i = 0, l = list.length; i < l; i++) {
  7715. var el = list[i];
  7716. var elZLevel = this._singleCanvas ? 0 : el.zlevel;
  7717. var elFrame = el.__frame;
  7718. // Flush at current context
  7719. // PENDING
  7720. if (elFrame < 0 && currentProgressiveLayer) {
  7721. flushProgressiveLayer(currentProgressiveLayer);
  7722. currentProgressiveLayer = null;
  7723. }
  7724. // Change draw layer
  7725. if (currentZLevel !== elZLevel) {
  7726. if (ctx) {
  7727. ctx.restore();
  7728. }
  7729. // Reset scope
  7730. scope = {};
  7731. // Only 0 zlevel if only has one canvas
  7732. currentZLevel = elZLevel;
  7733. currentLayer = this.getLayer(currentZLevel);
  7734. if (!currentLayer.__builtin__) {
  7735. zrLog(
  7736. 'ZLevel ' + currentZLevel
  7737. + ' has been used by unkown layer ' + currentLayer.id
  7738. );
  7739. }
  7740. ctx = currentLayer.ctx;
  7741. ctx.save();
  7742. // Reset the count
  7743. currentLayer.__unusedCount = 0;
  7744. if (currentLayer.__dirty || paintAll) {
  7745. currentLayer.clear();
  7746. }
  7747. }
  7748. if (!(currentLayer.__dirty || paintAll)) {
  7749. continue;
  7750. }
  7751. if (elFrame >= 0) {
  7752. // Progressive layer changed
  7753. if (!currentProgressiveLayer) {
  7754. currentProgressiveLayer = this._progressiveLayers[
  7755. Math.min(progressiveLayerIdx++, MAX_PROGRESSIVE_LAYER_NUMBER - 1)
  7756. ];
  7757. currentProgressiveLayer.ctx.save();
  7758. currentProgressiveLayer.renderScope = {};
  7759. if (currentProgressiveLayer
  7760. && (currentProgressiveLayer.__progress > currentProgressiveLayer.__maxProgress)
  7761. ) {
  7762. // flushProgressiveLayer(currentProgressiveLayer);
  7763. // Quick jump all progressive elements
  7764. // All progressive element are not dirty, jump over and flush directly
  7765. i = currentProgressiveLayer.__nextIdxNotProg - 1;
  7766. // currentProgressiveLayer = null;
  7767. continue;
  7768. }
  7769. layerProgress = currentProgressiveLayer.__progress;
  7770. if (!currentProgressiveLayer.__dirty) {
  7771. // Keep rendering
  7772. frame = layerProgress;
  7773. }
  7774. currentProgressiveLayer.__progress = frame + 1;
  7775. }
  7776. if (elFrame === frame) {
  7777. this._doPaintEl(el, currentProgressiveLayer, true, currentProgressiveLayer.renderScope);
  7778. }
  7779. }
  7780. else {
  7781. this._doPaintEl(el, currentLayer, paintAll, scope);
  7782. }
  7783. el.__dirty = false;
  7784. }
  7785. if (currentProgressiveLayer) {
  7786. flushProgressiveLayer(currentProgressiveLayer);
  7787. }
  7788. // Restore the lastLayer ctx
  7789. ctx && ctx.restore();
  7790. // If still has clipping state
  7791. // if (scope.prevElClipPaths) {
  7792. // ctx.restore();
  7793. // }
  7794. this._furtherProgressive = false;
  7795. each$1(this._progressiveLayers, function (layer) {
  7796. if (layer.__maxProgress >= layer.__progress) {
  7797. this._furtherProgressive = true;
  7798. }
  7799. }, this);
  7800. },
  7801. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7802. var ctx = currentLayer.ctx;
  7803. var m = el.transform;
  7804. if (
  7805. (currentLayer.__dirty || forcePaint)
  7806. // Ignore invisible element
  7807. && !el.invisible
  7808. // Ignore transparent element
  7809. && el.style.opacity !== 0
  7810. // Ignore scale 0 element, in some environment like node-canvas
  7811. // Draw a scale 0 element can cause all following draw wrong
  7812. // And setTransform with scale 0 will cause set back transform failed.
  7813. && !(m && !m[0] && !m[3])
  7814. // Ignore culled element
  7815. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7816. ) {
  7817. var clipPaths = el.__clipPaths;
  7818. // Optimize when clipping on group with several elements
  7819. if (scope.prevClipLayer !== currentLayer
  7820. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7821. ) {
  7822. // If has previous clipping state, restore from it
  7823. if (scope.prevElClipPaths) {
  7824. scope.prevClipLayer.ctx.restore();
  7825. scope.prevClipLayer = scope.prevElClipPaths = null;
  7826. // Reset prevEl since context has been restored
  7827. scope.prevEl = null;
  7828. }
  7829. // New clipping state
  7830. if (clipPaths) {
  7831. ctx.save();
  7832. doClip(clipPaths, ctx);
  7833. scope.prevClipLayer = currentLayer;
  7834. scope.prevElClipPaths = clipPaths;
  7835. }
  7836. }
  7837. el.beforeBrush && el.beforeBrush(ctx);
  7838. el.brush(ctx, scope.prevEl || null);
  7839. scope.prevEl = el;
  7840. el.afterBrush && el.afterBrush(ctx);
  7841. }
  7842. },
  7843. /**
  7844. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7845. * @param {number} zlevel
  7846. * @return {module:zrender/Layer}
  7847. */
  7848. getLayer: function (zlevel) {
  7849. if (this._singleCanvas) {
  7850. return this._layers[0];
  7851. }
  7852. var layer = this._layers[zlevel];
  7853. if (!layer) {
  7854. // Create a new layer
  7855. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7856. layer.__builtin__ = true;
  7857. if (this._layerConfig[zlevel]) {
  7858. merge(layer, this._layerConfig[zlevel], true);
  7859. }
  7860. this.insertLayer(zlevel, layer);
  7861. // Context is created after dom inserted to document
  7862. // Or excanvas will get 0px clientWidth and clientHeight
  7863. layer.initContext();
  7864. }
  7865. return layer;
  7866. },
  7867. insertLayer: function (zlevel, layer) {
  7868. var layersMap = this._layers;
  7869. var zlevelList = this._zlevelList;
  7870. var len = zlevelList.length;
  7871. var prevLayer = null;
  7872. var i = -1;
  7873. var domRoot = this._domRoot;
  7874. if (layersMap[zlevel]) {
  7875. zrLog('ZLevel ' + zlevel + ' has been used already');
  7876. return;
  7877. }
  7878. // Check if is a valid layer
  7879. if (!isLayerValid(layer)) {
  7880. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7881. return;
  7882. }
  7883. if (len > 0 && zlevel > zlevelList[0]) {
  7884. for (i = 0; i < len - 1; i++) {
  7885. if (
  7886. zlevelList[i] < zlevel
  7887. && zlevelList[i + 1] > zlevel
  7888. ) {
  7889. break;
  7890. }
  7891. }
  7892. prevLayer = layersMap[zlevelList[i]];
  7893. }
  7894. zlevelList.splice(i + 1, 0, zlevel);
  7895. layersMap[zlevel] = layer;
  7896. // Vitual layer will not directly show on the screen.
  7897. // (It can be a WebGL layer and assigned to a ZImage element)
  7898. // But it still under management of zrender.
  7899. if (!layer.virtual) {
  7900. if (prevLayer) {
  7901. var prevDom = prevLayer.dom;
  7902. if (prevDom.nextSibling) {
  7903. domRoot.insertBefore(
  7904. layer.dom,
  7905. prevDom.nextSibling
  7906. );
  7907. }
  7908. else {
  7909. domRoot.appendChild(layer.dom);
  7910. }
  7911. }
  7912. else {
  7913. if (domRoot.firstChild) {
  7914. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7915. }
  7916. else {
  7917. domRoot.appendChild(layer.dom);
  7918. }
  7919. }
  7920. }
  7921. },
  7922. // Iterate each layer
  7923. eachLayer: function (cb, context) {
  7924. var zlevelList = this._zlevelList;
  7925. var z;
  7926. var i;
  7927. for (i = 0; i < zlevelList.length; i++) {
  7928. z = zlevelList[i];
  7929. cb.call(context, this._layers[z], z);
  7930. }
  7931. },
  7932. // Iterate each buildin layer
  7933. eachBuiltinLayer: function (cb, context) {
  7934. var zlevelList = this._zlevelList;
  7935. var layer;
  7936. var z;
  7937. var i;
  7938. for (i = 0; i < zlevelList.length; i++) {
  7939. z = zlevelList[i];
  7940. layer = this._layers[z];
  7941. if (layer.__builtin__) {
  7942. cb.call(context, layer, z);
  7943. }
  7944. }
  7945. },
  7946. // Iterate each other layer except buildin layer
  7947. eachOtherLayer: function (cb, context) {
  7948. var zlevelList = this._zlevelList;
  7949. var layer;
  7950. var z;
  7951. var i;
  7952. for (i = 0; i < zlevelList.length; i++) {
  7953. z = zlevelList[i];
  7954. layer = this._layers[z];
  7955. if (!layer.__builtin__) {
  7956. cb.call(context, layer, z);
  7957. }
  7958. }
  7959. },
  7960. /**
  7961. * 获取所有已创建的层
  7962. * @param {Array.<module:zrender/Layer>} [prevLayer]
  7963. */
  7964. getLayers: function () {
  7965. return this._layers;
  7966. },
  7967. _updateLayerStatus: function (list) {
  7968. var layers = this._layers;
  7969. var progressiveLayers = this._progressiveLayers;
  7970. var elCountsLastFrame = {};
  7971. var progressiveElCountsLastFrame = {};
  7972. this.eachBuiltinLayer(function (layer, z) {
  7973. elCountsLastFrame[z] = layer.elCount;
  7974. layer.elCount = 0;
  7975. layer.__dirty = false;
  7976. });
  7977. each$1(progressiveLayers, function (layer, idx) {
  7978. progressiveElCountsLastFrame[idx] = layer.elCount;
  7979. layer.elCount = 0;
  7980. layer.__dirty = false;
  7981. });
  7982. var progressiveLayerCount = 0;
  7983. var currentProgressiveLayer;
  7984. var lastProgressiveKey;
  7985. var frameCount = 0;
  7986. for (var i = 0, l = list.length; i < l; i++) {
  7987. var el = list[i];
  7988. var zlevel = this._singleCanvas ? 0 : el.zlevel;
  7989. var layer = layers[zlevel];
  7990. var elProgress = el.progressive;
  7991. if (layer) {
  7992. layer.elCount++;
  7993. layer.__dirty = layer.__dirty || el.__dirty;
  7994. }
  7995. /////// Update progressive
  7996. if (elProgress >= 0) {
  7997. // Fix wrong progressive sequence problem.
  7998. if (lastProgressiveKey !== elProgress) {
  7999. lastProgressiveKey = elProgress;
  8000. frameCount++;
  8001. }
  8002. var elFrame = el.__frame = frameCount - 1;
  8003. if (!currentProgressiveLayer) {
  8004. var idx = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER - 1);
  8005. currentProgressiveLayer = progressiveLayers[idx];
  8006. if (!currentProgressiveLayer) {
  8007. currentProgressiveLayer = progressiveLayers[idx] = new Layer(
  8008. 'progressive', this, this.dpr
  8009. );
  8010. currentProgressiveLayer.initContext();
  8011. }
  8012. currentProgressiveLayer.__maxProgress = 0;
  8013. }
  8014. currentProgressiveLayer.__dirty = currentProgressiveLayer.__dirty || el.__dirty;
  8015. currentProgressiveLayer.elCount++;
  8016. currentProgressiveLayer.__maxProgress = Math.max(
  8017. currentProgressiveLayer.__maxProgress, elFrame
  8018. );
  8019. if (currentProgressiveLayer.__maxProgress >= currentProgressiveLayer.__progress) {
  8020. // Should keep rendering this layer because progressive rendering is not finished yet
  8021. layer.__dirty = true;
  8022. }
  8023. }
  8024. else {
  8025. el.__frame = -1;
  8026. if (currentProgressiveLayer) {
  8027. currentProgressiveLayer.__nextIdxNotProg = i;
  8028. progressiveLayerCount++;
  8029. currentProgressiveLayer = null;
  8030. }
  8031. }
  8032. }
  8033. if (currentProgressiveLayer) {
  8034. progressiveLayerCount++;
  8035. currentProgressiveLayer.__nextIdxNotProg = i;
  8036. }
  8037. // 层中的元素数量有发生变化
  8038. this.eachBuiltinLayer(function (layer, z) {
  8039. if (elCountsLastFrame[z] !== layer.elCount) {
  8040. layer.__dirty = true;
  8041. }
  8042. });
  8043. progressiveLayers.length = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER);
  8044. each$1(progressiveLayers, function (layer, idx) {
  8045. if (progressiveElCountsLastFrame[idx] !== layer.elCount) {
  8046. el.__dirty = true;
  8047. }
  8048. if (layer.__dirty) {
  8049. layer.__progress = 0;
  8050. }
  8051. });
  8052. },
  8053. /**
  8054. * 清除hover层外所有内容
  8055. */
  8056. clear: function () {
  8057. this.eachBuiltinLayer(this._clearLayer);
  8058. return this;
  8059. },
  8060. _clearLayer: function (layer) {
  8061. layer.clear();
  8062. },
  8063. /**
  8064. * 修改指定zlevel的绘制参数
  8065. *
  8066. * @param {string} zlevel
  8067. * @param {Object} config 配置对象
  8068. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8069. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8070. * @param {number} [config.lastFrameAlpha=0.7]
  8071. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8072. */
  8073. configLayer: function (zlevel, config) {
  8074. if (config) {
  8075. var layerConfig = this._layerConfig;
  8076. if (!layerConfig[zlevel]) {
  8077. layerConfig[zlevel] = config;
  8078. }
  8079. else {
  8080. merge(layerConfig[zlevel], config, true);
  8081. }
  8082. var layer = this._layers[zlevel];
  8083. if (layer) {
  8084. merge(layer, layerConfig[zlevel], true);
  8085. }
  8086. }
  8087. },
  8088. /**
  8089. * 删除指定层
  8090. * @param {number} zlevel 层所在的zlevel
  8091. */
  8092. delLayer: function (zlevel) {
  8093. var layers = this._layers;
  8094. var zlevelList = this._zlevelList;
  8095. var layer = layers[zlevel];
  8096. if (!layer) {
  8097. return;
  8098. }
  8099. layer.dom.parentNode.removeChild(layer.dom);
  8100. delete layers[zlevel];
  8101. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8102. },
  8103. /**
  8104. * 区域大小变化后重绘
  8105. */
  8106. resize: function (width, height) {
  8107. var domRoot = this._domRoot;
  8108. // FIXME Why ?
  8109. domRoot.style.display = 'none';
  8110. // Save input w/h
  8111. var opts = this._opts;
  8112. width != null && (opts.width = width);
  8113. height != null && (opts.height = height);
  8114. width = this._getSize(0);
  8115. height = this._getSize(1);
  8116. domRoot.style.display = '';
  8117. // 优化没有实际改变的resize
  8118. if (this._width != width || height != this._height) {
  8119. domRoot.style.width = width + 'px';
  8120. domRoot.style.height = height + 'px';
  8121. for (var id in this._layers) {
  8122. if (this._layers.hasOwnProperty(id)) {
  8123. this._layers[id].resize(width, height);
  8124. }
  8125. }
  8126. each$1(this._progressiveLayers, function (layer) {
  8127. layer.resize(width, height);
  8128. });
  8129. this.refresh(true);
  8130. }
  8131. this._width = width;
  8132. this._height = height;
  8133. return this;
  8134. },
  8135. /**
  8136. * 清除单独的一个层
  8137. * @param {number} zlevel
  8138. */
  8139. clearLayer: function (zlevel) {
  8140. var layer = this._layers[zlevel];
  8141. if (layer) {
  8142. layer.clear();
  8143. }
  8144. },
  8145. /**
  8146. * 释放
  8147. */
  8148. dispose: function () {
  8149. this.root.innerHTML = '';
  8150. this.root =
  8151. this.storage =
  8152. this._domRoot =
  8153. this._layers = null;
  8154. },
  8155. /**
  8156. * Get canvas which has all thing rendered
  8157. * @param {Object} opts
  8158. * @param {string} [opts.backgroundColor]
  8159. * @param {number} [opts.pixelRatio]
  8160. */
  8161. getRenderedCanvas: function (opts) {
  8162. opts = opts || {};
  8163. if (this._singleCanvas) {
  8164. return this._layers[0].dom;
  8165. }
  8166. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8167. imageLayer.initContext();
  8168. imageLayer.clearColor = opts.backgroundColor;
  8169. imageLayer.clear();
  8170. var displayList = this.storage.getDisplayList(true);
  8171. var scope = {};
  8172. var zlevel;
  8173. var self = this;
  8174. function findAndDrawOtherLayer(smaller, larger) {
  8175. var zlevelList = self._zlevelList;
  8176. if (smaller == null) {
  8177. smaller = -Infinity;
  8178. }
  8179. var intermediateLayer;
  8180. for (var i = 0; i < zlevelList.length; i++) {
  8181. var z = zlevelList[i];
  8182. var layer = self._layers[z];
  8183. if (!layer.__builtin__ && z > smaller && z < larger) {
  8184. intermediateLayer = layer;
  8185. break;
  8186. }
  8187. }
  8188. if (intermediateLayer && intermediateLayer.renderToCanvas) {
  8189. imageLayer.ctx.save();
  8190. intermediateLayer.renderToCanvas(imageLayer.ctx);
  8191. imageLayer.ctx.restore();
  8192. }
  8193. }
  8194. for (var i = 0; i < displayList.length; i++) {
  8195. var el = displayList[i];
  8196. if (el.zlevel !== zlevel) {
  8197. findAndDrawOtherLayer(zlevel, el.zlevel);
  8198. zlevel = el.zlevel;
  8199. }
  8200. this._doPaintEl(el, imageLayer, true, scope);
  8201. }
  8202. findAndDrawOtherLayer(zlevel, Infinity);
  8203. return imageLayer.dom;
  8204. },
  8205. /**
  8206. * 获取绘图区域宽度
  8207. */
  8208. getWidth: function () {
  8209. return this._width;
  8210. },
  8211. /**
  8212. * 获取绘图区域高度
  8213. */
  8214. getHeight: function () {
  8215. return this._height;
  8216. },
  8217. _getSize: function (whIdx) {
  8218. var opts = this._opts;
  8219. var wh = ['width', 'height'][whIdx];
  8220. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8221. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8222. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8223. if (opts[wh] != null && opts[wh] !== 'auto') {
  8224. return parseFloat(opts[wh]);
  8225. }
  8226. var root = this.root;
  8227. // IE8 does not support getComputedStyle, but it use VML.
  8228. var stl = document.defaultView.getComputedStyle(root);
  8229. return (
  8230. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8231. - (parseInt10(stl[plt]) || 0)
  8232. - (parseInt10(stl[prb]) || 0)
  8233. ) | 0;
  8234. },
  8235. pathToImage: function (path, dpr) {
  8236. dpr = dpr || this.dpr;
  8237. var canvas = document.createElement('canvas');
  8238. var ctx = canvas.getContext('2d');
  8239. var rect = path.getBoundingRect();
  8240. var style = path.style;
  8241. var shadowBlurSize = style.shadowBlur;
  8242. var shadowOffsetX = style.shadowOffsetX;
  8243. var shadowOffsetY = style.shadowOffsetY;
  8244. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8245. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8246. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8247. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8248. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8249. var width = rect.width + leftMargin + rightMargin;
  8250. var height = rect.height + topMargin + bottomMargin;
  8251. canvas.width = width * dpr;
  8252. canvas.height = height * dpr;
  8253. ctx.scale(dpr, dpr);
  8254. ctx.clearRect(0, 0, width, height);
  8255. ctx.dpr = dpr;
  8256. var pathTransform = {
  8257. position: path.position,
  8258. rotation: path.rotation,
  8259. scale: path.scale
  8260. };
  8261. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8262. path.rotation = 0;
  8263. path.scale = [1, 1];
  8264. path.updateTransform();
  8265. if (path) {
  8266. path.brush(ctx);
  8267. }
  8268. var ImageShape = ZImage;
  8269. var imgShape = new ImageShape({
  8270. style: {
  8271. x: 0,
  8272. y: 0,
  8273. image: canvas
  8274. }
  8275. });
  8276. if (pathTransform.position != null) {
  8277. imgShape.position = path.position = pathTransform.position;
  8278. }
  8279. if (pathTransform.rotation != null) {
  8280. imgShape.rotation = path.rotation = pathTransform.rotation;
  8281. }
  8282. if (pathTransform.scale != null) {
  8283. imgShape.scale = path.scale = pathTransform.scale;
  8284. }
  8285. return imgShape;
  8286. }
  8287. };
  8288. /**
  8289. * 事件辅助类
  8290. * @module zrender/core/event
  8291. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8292. */
  8293. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8294. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8295. function getBoundingClientRect(el) {
  8296. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8297. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8298. }
  8299. // `calculate` is optional, default false
  8300. function clientToLocal(el, e, out, calculate) {
  8301. out = out || {};
  8302. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8303. // to the padding edge of the target element. The only browser using this convention
  8304. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8305. // not support the properties.
  8306. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8307. // In zr painter.dom, padding edge equals to border edge.
  8308. // FIXME
  8309. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8310. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8311. // is too complex. So css-transfrom dont support in this case temporarily.
  8312. if (calculate || !env$1.canvasSupported) {
  8313. defaultGetZrXY(el, e, out);
  8314. }
  8315. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8316. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8317. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8318. // zoom-factor, overflow / opacity layers, transforms ...)
  8319. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8320. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8321. // BTW3, In ff, offsetX/offsetY is always 0.
  8322. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8323. out.zrX = e.layerX;
  8324. out.zrY = e.layerY;
  8325. }
  8326. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8327. else if (e.offsetX != null) {
  8328. out.zrX = e.offsetX;
  8329. out.zrY = e.offsetY;
  8330. }
  8331. // For some other device, e.g., IOS safari.
  8332. else {
  8333. defaultGetZrXY(el, e, out);
  8334. }
  8335. return out;
  8336. }
  8337. function defaultGetZrXY(el, e, out) {
  8338. // This well-known method below does not support css transform.
  8339. var box = getBoundingClientRect(el);
  8340. out.zrX = e.clientX - box.left;
  8341. out.zrY = e.clientY - box.top;
  8342. }
  8343. /**
  8344. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8345. * `calculate` is optional, default false.
  8346. */
  8347. function normalizeEvent(el, e, calculate) {
  8348. e = e || window.event;
  8349. if (e.zrX != null) {
  8350. return e;
  8351. }
  8352. var eventType = e.type;
  8353. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8354. if (!isTouch) {
  8355. clientToLocal(el, e, e, calculate);
  8356. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8357. }
  8358. else {
  8359. var touch = eventType != 'touchend'
  8360. ? e.targetTouches[0]
  8361. : e.changedTouches[0];
  8362. touch && clientToLocal(el, touch, e, calculate);
  8363. }
  8364. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8365. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8366. // If e.which has been defined, if may be readonly,
  8367. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8368. var button = e.button;
  8369. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8370. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8371. }
  8372. return e;
  8373. }
  8374. function addEventListener(el, name, handler) {
  8375. if (isDomLevel2) {
  8376. el.addEventListener(name, handler);
  8377. }
  8378. else {
  8379. el.attachEvent('on' + name, handler);
  8380. }
  8381. }
  8382. function removeEventListener(el, name, handler) {
  8383. if (isDomLevel2) {
  8384. el.removeEventListener(name, handler);
  8385. }
  8386. else {
  8387. el.detachEvent('on' + name, handler);
  8388. }
  8389. }
  8390. /**
  8391. * preventDefault and stopPropagation.
  8392. * Notice: do not do that in zrender. Upper application
  8393. * do that if necessary.
  8394. *
  8395. * @memberOf module:zrender/core/event
  8396. * @method
  8397. * @param {Event} e : event对象
  8398. */
  8399. var stop = isDomLevel2
  8400. ? function (e) {
  8401. e.preventDefault();
  8402. e.stopPropagation();
  8403. e.cancelBubble = true;
  8404. }
  8405. : function (e) {
  8406. e.returnValue = false;
  8407. e.cancelBubble = true;
  8408. };
  8409. function notLeftMouse(e) {
  8410. // If e.which is undefined, considered as left mouse event.
  8411. return e.which > 1;
  8412. }
  8413. /**
  8414. * 动画主类, 调度和管理所有动画控制器
  8415. *
  8416. * @module zrender/animation/Animation
  8417. * @author pissang(https://github.com/pissang)
  8418. */
  8419. // TODO Additive animation
  8420. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8421. // https://developer.apple.com/videos/wwdc2014/#236
  8422. /**
  8423. * @typedef {Object} IZRenderStage
  8424. * @property {Function} update
  8425. */
  8426. /**
  8427. * @alias module:zrender/animation/Animation
  8428. * @constructor
  8429. * @param {Object} [options]
  8430. * @param {Function} [options.onframe]
  8431. * @param {IZRenderStage} [options.stage]
  8432. * @example
  8433. * var animation = new Animation();
  8434. * var obj = {
  8435. * x: 100,
  8436. * y: 100
  8437. * };
  8438. * animation.animate(node.position)
  8439. * .when(1000, {
  8440. * x: 500,
  8441. * y: 500
  8442. * })
  8443. * .when(2000, {
  8444. * x: 100,
  8445. * y: 100
  8446. * })
  8447. * .start('spline');
  8448. */
  8449. var Animation = function (options) {
  8450. options = options || {};
  8451. this.stage = options.stage || {};
  8452. this.onframe = options.onframe || function() {};
  8453. // private properties
  8454. this._clips = [];
  8455. this._running = false;
  8456. this._time;
  8457. this._pausedTime;
  8458. this._pauseStart;
  8459. this._paused = false;
  8460. Eventful.call(this);
  8461. };
  8462. Animation.prototype = {
  8463. constructor: Animation,
  8464. /**
  8465. * 添加 clip
  8466. * @param {module:zrender/animation/Clip} clip
  8467. */
  8468. addClip: function (clip) {
  8469. this._clips.push(clip);
  8470. },
  8471. /**
  8472. * 添加 animator
  8473. * @param {module:zrender/animation/Animator} animator
  8474. */
  8475. addAnimator: function (animator) {
  8476. animator.animation = this;
  8477. var clips = animator.getClips();
  8478. for (var i = 0; i < clips.length; i++) {
  8479. this.addClip(clips[i]);
  8480. }
  8481. },
  8482. /**
  8483. * 删除动画片段
  8484. * @param {module:zrender/animation/Clip} clip
  8485. */
  8486. removeClip: function(clip) {
  8487. var idx = indexOf(this._clips, clip);
  8488. if (idx >= 0) {
  8489. this._clips.splice(idx, 1);
  8490. }
  8491. },
  8492. /**
  8493. * 删除动画片段
  8494. * @param {module:zrender/animation/Animator} animator
  8495. */
  8496. removeAnimator: function (animator) {
  8497. var clips = animator.getClips();
  8498. for (var i = 0; i < clips.length; i++) {
  8499. this.removeClip(clips[i]);
  8500. }
  8501. animator.animation = null;
  8502. },
  8503. _update: function() {
  8504. var time = new Date().getTime() - this._pausedTime;
  8505. var delta = time - this._time;
  8506. var clips = this._clips;
  8507. var len = clips.length;
  8508. var deferredEvents = [];
  8509. var deferredClips = [];
  8510. for (var i = 0; i < len; i++) {
  8511. var clip = clips[i];
  8512. var e = clip.step(time, delta);
  8513. // Throw out the events need to be called after
  8514. // stage.update, like destroy
  8515. if (e) {
  8516. deferredEvents.push(e);
  8517. deferredClips.push(clip);
  8518. }
  8519. }
  8520. // Remove the finished clip
  8521. for (var i = 0; i < len;) {
  8522. if (clips[i]._needsRemove) {
  8523. clips[i] = clips[len - 1];
  8524. clips.pop();
  8525. len--;
  8526. }
  8527. else {
  8528. i++;
  8529. }
  8530. }
  8531. len = deferredEvents.length;
  8532. for (var i = 0; i < len; i++) {
  8533. deferredClips[i].fire(deferredEvents[i]);
  8534. }
  8535. this._time = time;
  8536. this.onframe(delta);
  8537. this.trigger('frame', delta);
  8538. if (this.stage.update) {
  8539. this.stage.update();
  8540. }
  8541. },
  8542. _startLoop: function () {
  8543. var self = this;
  8544. this._running = true;
  8545. function step() {
  8546. if (self._running) {
  8547. requestAnimationFrame(step);
  8548. !self._paused && self._update();
  8549. }
  8550. }
  8551. requestAnimationFrame(step);
  8552. },
  8553. /**
  8554. * 开始运行动画
  8555. */
  8556. start: function () {
  8557. this._time = new Date().getTime();
  8558. this._pausedTime = 0;
  8559. this._startLoop();
  8560. },
  8561. /**
  8562. * 停止运行动画
  8563. */
  8564. stop: function () {
  8565. this._running = false;
  8566. },
  8567. /**
  8568. * Pause
  8569. */
  8570. pause: function () {
  8571. if (!this._paused) {
  8572. this._pauseStart = new Date().getTime();
  8573. this._paused = true;
  8574. }
  8575. },
  8576. /**
  8577. * Resume
  8578. */
  8579. resume: function () {
  8580. if (this._paused) {
  8581. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8582. this._paused = false;
  8583. }
  8584. },
  8585. /**
  8586. * 清除所有动画片段
  8587. */
  8588. clear: function () {
  8589. this._clips = [];
  8590. },
  8591. /**
  8592. * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画
  8593. * @param {Object} target
  8594. * @param {Object} options
  8595. * @param {boolean} [options.loop=false] 是否循环播放动画
  8596. * @param {Function} [options.getter=null]
  8597. * 如果指定getter函数,会通过getter函数取属性值
  8598. * @param {Function} [options.setter=null]
  8599. * 如果指定setter函数,会通过setter函数设置属性值
  8600. * @return {module:zrender/animation/Animation~Animator}
  8601. */
  8602. // TODO Gap
  8603. animate: function (target, options) {
  8604. options = options || {};
  8605. var animator = new Animator(
  8606. target,
  8607. options.loop,
  8608. options.getter,
  8609. options.setter
  8610. );
  8611. this.addAnimator(animator);
  8612. return animator;
  8613. }
  8614. };
  8615. mixin(Animation, Eventful);
  8616. /**
  8617. * Only implements needed gestures for mobile.
  8618. */
  8619. var GestureMgr = function () {
  8620. /**
  8621. * @private
  8622. * @type {Array.<Object>}
  8623. */
  8624. this._track = [];
  8625. };
  8626. GestureMgr.prototype = {
  8627. constructor: GestureMgr,
  8628. recognize: function (event, target, root) {
  8629. this._doTrack(event, target, root);
  8630. return this._recognize(event);
  8631. },
  8632. clear: function () {
  8633. this._track.length = 0;
  8634. return this;
  8635. },
  8636. _doTrack: function (event, target, root) {
  8637. var touches = event.touches;
  8638. if (!touches) {
  8639. return;
  8640. }
  8641. var trackItem = {
  8642. points: [],
  8643. touches: [],
  8644. target: target,
  8645. event: event
  8646. };
  8647. for (var i = 0, len = touches.length; i < len; i++) {
  8648. var touch = touches[i];
  8649. var pos = clientToLocal(root, touch, {});
  8650. trackItem.points.push([pos.zrX, pos.zrY]);
  8651. trackItem.touches.push(touch);
  8652. }
  8653. this._track.push(trackItem);
  8654. },
  8655. _recognize: function (event) {
  8656. for (var eventName in recognizers) {
  8657. if (recognizers.hasOwnProperty(eventName)) {
  8658. var gestureInfo = recognizers[eventName](this._track, event);
  8659. if (gestureInfo) {
  8660. return gestureInfo;
  8661. }
  8662. }
  8663. }
  8664. }
  8665. };
  8666. function dist$1(pointPair) {
  8667. var dx = pointPair[1][0] - pointPair[0][0];
  8668. var dy = pointPair[1][1] - pointPair[0][1];
  8669. return Math.sqrt(dx * dx + dy * dy);
  8670. }
  8671. function center(pointPair) {
  8672. return [
  8673. (pointPair[0][0] + pointPair[1][0]) / 2,
  8674. (pointPair[0][1] + pointPair[1][1]) / 2
  8675. ];
  8676. }
  8677. var recognizers = {
  8678. pinch: function (track, event) {
  8679. var trackLen = track.length;
  8680. if (!trackLen) {
  8681. return;
  8682. }
  8683. var pinchEnd = (track[trackLen - 1] || {}).points;
  8684. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8685. if (pinchPre
  8686. && pinchPre.length > 1
  8687. && pinchEnd
  8688. && pinchEnd.length > 1
  8689. ) {
  8690. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8691. !isFinite(pinchScale) && (pinchScale = 1);
  8692. event.pinchScale = pinchScale;
  8693. var pinchCenter = center(pinchEnd);
  8694. event.pinchX = pinchCenter[0];
  8695. event.pinchY = pinchCenter[1];
  8696. return {
  8697. type: 'pinch',
  8698. target: track[0].target,
  8699. event: event
  8700. };
  8701. }
  8702. }
  8703. // Only pinch currently.
  8704. };
  8705. var TOUCH_CLICK_DELAY = 300;
  8706. var mouseHandlerNames = [
  8707. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8708. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8709. ];
  8710. var touchHandlerNames = [
  8711. 'touchstart', 'touchend', 'touchmove'
  8712. ];
  8713. var pointerEventNames = {
  8714. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8715. };
  8716. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8717. var nm = name.replace('mouse', 'pointer');
  8718. return pointerEventNames[nm] ? nm : name;
  8719. });
  8720. function eventNameFix(name) {
  8721. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8722. }
  8723. function processGesture(proxy, event, stage) {
  8724. var gestureMgr = proxy._gestureMgr;
  8725. stage === 'start' && gestureMgr.clear();
  8726. var gestureInfo = gestureMgr.recognize(
  8727. event,
  8728. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8729. proxy.dom
  8730. );
  8731. stage === 'end' && gestureMgr.clear();
  8732. // Do not do any preventDefault here. Upper application do that if necessary.
  8733. if (gestureInfo) {
  8734. var type = gestureInfo.type;
  8735. event.gestureEvent = type;
  8736. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8737. }
  8738. }
  8739. // function onMSGestureChange(proxy, event) {
  8740. // if (event.translationX || event.translationY) {
  8741. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8742. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8743. // }
  8744. // if (event.scale !== 1) {
  8745. // event.pinchX = event.offsetX;
  8746. // event.pinchY = event.offsetY;
  8747. // event.pinchScale = event.scale;
  8748. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8749. // }
  8750. // }
  8751. /**
  8752. * Prevent mouse event from being dispatched after Touch Events action
  8753. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8754. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8755. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8756. * Result: Blocking Mouse Events for 700ms.
  8757. */
  8758. function setTouchTimer(instance) {
  8759. instance._touching = true;
  8760. clearTimeout(instance._touchTimer);
  8761. instance._touchTimer = setTimeout(function () {
  8762. instance._touching = false;
  8763. }, 700);
  8764. }
  8765. var domHandlers = {
  8766. /**
  8767. * Mouse move handler
  8768. * @inner
  8769. * @param {Event} event
  8770. */
  8771. mousemove: function (event) {
  8772. event = normalizeEvent(this.dom, event);
  8773. this.trigger('mousemove', event);
  8774. },
  8775. /**
  8776. * Mouse out handler
  8777. * @inner
  8778. * @param {Event} event
  8779. */
  8780. mouseout: function (event) {
  8781. event = normalizeEvent(this.dom, event);
  8782. var element = event.toElement || event.relatedTarget;
  8783. if (element != this.dom) {
  8784. while (element && element.nodeType != 9) {
  8785. // 忽略包含在root中的dom引起的mouseOut
  8786. if (element === this.dom) {
  8787. return;
  8788. }
  8789. element = element.parentNode;
  8790. }
  8791. }
  8792. this.trigger('mouseout', event);
  8793. },
  8794. /**
  8795. * Touch开始响应函数
  8796. * @inner
  8797. * @param {Event} event
  8798. */
  8799. touchstart: function (event) {
  8800. // Default mouse behaviour should not be disabled here.
  8801. // For example, page may needs to be slided.
  8802. event = normalizeEvent(this.dom, event);
  8803. // Mark touch, which is useful in distinguish touch and
  8804. // mouse event in upper applicatoin.
  8805. event.zrByTouch = true;
  8806. this._lastTouchMoment = new Date();
  8807. processGesture(this, event, 'start');
  8808. // In touch device, trigger `mousemove`(`mouseover`) should
  8809. // be triggered, and must before `mousedown` triggered.
  8810. domHandlers.mousemove.call(this, event);
  8811. domHandlers.mousedown.call(this, event);
  8812. setTouchTimer(this);
  8813. },
  8814. /**
  8815. * Touch移动响应函数
  8816. * @inner
  8817. * @param {Event} event
  8818. */
  8819. touchmove: function (event) {
  8820. event = normalizeEvent(this.dom, event);
  8821. // Mark touch, which is useful in distinguish touch and
  8822. // mouse event in upper applicatoin.
  8823. event.zrByTouch = true;
  8824. processGesture(this, event, 'change');
  8825. // Mouse move should always be triggered no matter whether
  8826. // there is gestrue event, because mouse move and pinch may
  8827. // be used at the same time.
  8828. domHandlers.mousemove.call(this, event);
  8829. setTouchTimer(this);
  8830. },
  8831. /**
  8832. * Touch结束响应函数
  8833. * @inner
  8834. * @param {Event} event
  8835. */
  8836. touchend: function (event) {
  8837. event = normalizeEvent(this.dom, event);
  8838. // Mark touch, which is useful in distinguish touch and
  8839. // mouse event in upper applicatoin.
  8840. event.zrByTouch = true;
  8841. processGesture(this, event, 'end');
  8842. domHandlers.mouseup.call(this, event);
  8843. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8844. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8845. // we can conveniently implement "hover style" in both PC and touch device just
  8846. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8847. // to remove "hover style" on an element, without any additional code for
  8848. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8849. // style" will remain for user view)
  8850. // click event should always be triggered no matter whether
  8851. // there is gestrue event. System click can not be prevented.
  8852. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8853. domHandlers.click.call(this, event);
  8854. }
  8855. setTouchTimer(this);
  8856. },
  8857. pointerdown: function (event) {
  8858. domHandlers.mousedown.call(this, event);
  8859. // if (useMSGuesture(this, event)) {
  8860. // this._msGesture.addPointer(event.pointerId);
  8861. // }
  8862. },
  8863. pointermove: function (event) {
  8864. // FIXME
  8865. // pointermove is so sensitive that it always triggered when
  8866. // tap(click) on touch screen, which affect some judgement in
  8867. // upper application. So, we dont support mousemove on MS touch
  8868. // device yet.
  8869. if (!isPointerFromTouch(event)) {
  8870. domHandlers.mousemove.call(this, event);
  8871. }
  8872. },
  8873. pointerup: function (event) {
  8874. domHandlers.mouseup.call(this, event);
  8875. },
  8876. pointerout: function (event) {
  8877. // pointerout will be triggered when tap on touch screen
  8878. // (IE11+/Edge on MS Surface) after click event triggered,
  8879. // which is inconsistent with the mousout behavior we defined
  8880. // in touchend. So we unify them.
  8881. // (check domHandlers.touchend for detailed explanation)
  8882. if (!isPointerFromTouch(event)) {
  8883. domHandlers.mouseout.call(this, event);
  8884. }
  8885. }
  8886. };
  8887. function isPointerFromTouch(event) {
  8888. var pointerType = event.pointerType;
  8889. return pointerType === 'pen' || pointerType === 'touch';
  8890. }
  8891. // function useMSGuesture(handlerProxy, event) {
  8892. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8893. // }
  8894. // Common handlers
  8895. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8896. domHandlers[name] = function (event) {
  8897. event = normalizeEvent(this.dom, event);
  8898. this.trigger(name, event);
  8899. };
  8900. });
  8901. /**
  8902. * 为控制类实例初始化dom 事件处理函数
  8903. *
  8904. * @inner
  8905. * @param {module:zrender/Handler} instance 控制类实例
  8906. */
  8907. function initDomHandler(instance) {
  8908. each$1(touchHandlerNames, function (name) {
  8909. instance._handlers[name] = bind(domHandlers[name], instance);
  8910. });
  8911. each$1(pointerHandlerNames, function (name) {
  8912. instance._handlers[name] = bind(domHandlers[name], instance);
  8913. });
  8914. each$1(mouseHandlerNames, function (name) {
  8915. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  8916. });
  8917. function makeMouseHandler(fn, instance) {
  8918. return function () {
  8919. if (instance._touching) {
  8920. return;
  8921. }
  8922. return fn.apply(instance, arguments);
  8923. };
  8924. }
  8925. }
  8926. function HandlerDomProxy(dom) {
  8927. Eventful.call(this);
  8928. this.dom = dom;
  8929. /**
  8930. * @private
  8931. * @type {boolean}
  8932. */
  8933. this._touching = false;
  8934. /**
  8935. * @private
  8936. * @type {number}
  8937. */
  8938. this._touchTimer;
  8939. /**
  8940. * @private
  8941. * @type {module:zrender/core/GestureMgr}
  8942. */
  8943. this._gestureMgr = new GestureMgr();
  8944. this._handlers = {};
  8945. initDomHandler(this);
  8946. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  8947. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  8948. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  8949. // at the same time.
  8950. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  8951. // screen, which do not occurs in pointer event.
  8952. // So we use pointer event to both detect touch gesture and mouse behavior.
  8953. mountHandlers(pointerHandlerNames, this);
  8954. // FIXME
  8955. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  8956. // which does not prevent defuault behavior occasionally (which may cause view port
  8957. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  8958. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  8959. // touch screen. And we only support click behavior on MS touch screen now.
  8960. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  8961. // We dont support touch on IE on win7.
  8962. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  8963. // if (typeof MSGesture === 'function') {
  8964. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  8965. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  8966. // }
  8967. }
  8968. else {
  8969. if (env$1.touchEventsSupported) {
  8970. mountHandlers(touchHandlerNames, this);
  8971. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  8972. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  8973. }
  8974. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  8975. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  8976. // mouse event can not be handle in those devices.
  8977. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  8978. // mouseevent after touch event triggered, see `setTouchTimer`.
  8979. mountHandlers(mouseHandlerNames, this);
  8980. }
  8981. function mountHandlers(handlerNames, instance) {
  8982. each$1(handlerNames, function (name) {
  8983. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  8984. }, instance);
  8985. }
  8986. }
  8987. var handlerDomProxyProto = HandlerDomProxy.prototype;
  8988. handlerDomProxyProto.dispose = function () {
  8989. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  8990. for (var i = 0; i < handlerNames.length; i++) {
  8991. var name = handlerNames[i];
  8992. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  8993. }
  8994. };
  8995. handlerDomProxyProto.setCursor = function (cursorStyle) {
  8996. this.dom.style.cursor = cursorStyle || 'default';
  8997. };
  8998. mixin(HandlerDomProxy, Eventful);
  8999. /*!
  9000. * ZRender, a high performance 2d drawing library.
  9001. *
  9002. * Copyright (c) 2013, Baidu Inc.
  9003. * All rights reserved.
  9004. *
  9005. * LICENSE
  9006. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9007. */
  9008. var useVML = !env$1.canvasSupported;
  9009. var painterCtors = {
  9010. canvas: Painter
  9011. };
  9012. var instances$1 = {}; // ZRender实例map索引
  9013. /**
  9014. * @type {string}
  9015. */
  9016. var version$1 = '3.7.4';
  9017. /**
  9018. * Initializing a zrender instance
  9019. * @param {HTMLElement} dom
  9020. * @param {Object} opts
  9021. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9022. * @param {number} [opts.devicePixelRatio]
  9023. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9024. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9025. * @return {module:zrender/ZRender}
  9026. */
  9027. function init$1(dom, opts) {
  9028. var zr = new ZRender(guid(), dom, opts);
  9029. instances$1[zr.id] = zr;
  9030. return zr;
  9031. }
  9032. /**
  9033. * Dispose zrender instance
  9034. * @param {module:zrender/ZRender} zr
  9035. */
  9036. function dispose$1(zr) {
  9037. if (zr) {
  9038. zr.dispose();
  9039. }
  9040. else {
  9041. for (var key in instances$1) {
  9042. if (instances$1.hasOwnProperty(key)) {
  9043. instances$1[key].dispose();
  9044. }
  9045. }
  9046. instances$1 = {};
  9047. }
  9048. return this;
  9049. }
  9050. /**
  9051. * Get zrender instance by id
  9052. * @param {string} id zrender instance id
  9053. * @return {module:zrender/ZRender}
  9054. */
  9055. function getInstance(id) {
  9056. return instances$1[id];
  9057. }
  9058. function registerPainter(name, Ctor) {
  9059. painterCtors[name] = Ctor;
  9060. }
  9061. function delInstance(id) {
  9062. delete instances$1[id];
  9063. }
  9064. /**
  9065. * @module zrender/ZRender
  9066. */
  9067. /**
  9068. * @constructor
  9069. * @alias module:zrender/ZRender
  9070. * @param {string} id
  9071. * @param {HTMLElement} dom
  9072. * @param {Object} opts
  9073. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9074. * @param {number} [opts.devicePixelRatio]
  9075. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9076. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9077. */
  9078. var ZRender = function (id, dom, opts) {
  9079. opts = opts || {};
  9080. /**
  9081. * @type {HTMLDomElement}
  9082. */
  9083. this.dom = dom;
  9084. /**
  9085. * @type {string}
  9086. */
  9087. this.id = id;
  9088. var self = this;
  9089. var storage = new Storage();
  9090. var rendererType = opts.renderer;
  9091. // TODO WebGL
  9092. if (useVML) {
  9093. if (!painterCtors.vml) {
  9094. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9095. }
  9096. rendererType = 'vml';
  9097. }
  9098. else if (!rendererType || !painterCtors[rendererType]) {
  9099. rendererType = 'canvas';
  9100. }
  9101. var painter = new painterCtors[rendererType](dom, storage, opts);
  9102. this.storage = storage;
  9103. this.painter = painter;
  9104. var handerProxy = !env$1.node ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9105. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9106. /**
  9107. * @type {module:zrender/animation/Animation}
  9108. */
  9109. this.animation = new Animation({
  9110. stage: {
  9111. update: bind(this.flush, this)
  9112. }
  9113. });
  9114. this.animation.start();
  9115. /**
  9116. * @type {boolean}
  9117. * @private
  9118. */
  9119. this._needsRefresh;
  9120. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9121. // FIXME 有点ugly
  9122. var oldDelFromStorage = storage.delFromStorage;
  9123. var oldAddToStorage = storage.addToStorage;
  9124. storage.delFromStorage = function (el) {
  9125. oldDelFromStorage.call(storage, el);
  9126. el && el.removeSelfFromZr(self);
  9127. };
  9128. storage.addToStorage = function (el) {
  9129. oldAddToStorage.call(storage, el);
  9130. el.addSelfToZr(self);
  9131. };
  9132. };
  9133. ZRender.prototype = {
  9134. constructor: ZRender,
  9135. /**
  9136. * 获取实例唯一标识
  9137. * @return {string}
  9138. */
  9139. getId: function () {
  9140. return this.id;
  9141. },
  9142. /**
  9143. * 添加元素
  9144. * @param {module:zrender/Element} el
  9145. */
  9146. add: function (el) {
  9147. this.storage.addRoot(el);
  9148. this._needsRefresh = true;
  9149. },
  9150. /**
  9151. * 删除元素
  9152. * @param {module:zrender/Element} el
  9153. */
  9154. remove: function (el) {
  9155. this.storage.delRoot(el);
  9156. this._needsRefresh = true;
  9157. },
  9158. /**
  9159. * Change configuration of layer
  9160. * @param {string} zLevel
  9161. * @param {Object} config
  9162. * @param {string} [config.clearColor=0] Clear color
  9163. * @param {string} [config.motionBlur=false] If enable motion blur
  9164. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9165. */
  9166. configLayer: function (zLevel, config) {
  9167. this.painter.configLayer(zLevel, config);
  9168. this._needsRefresh = true;
  9169. },
  9170. /**
  9171. * Repaint the canvas immediately
  9172. */
  9173. refreshImmediately: function () {
  9174. // var start = new Date();
  9175. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9176. // Or it will cause zrender refreshes again and again.
  9177. this._needsRefresh = false;
  9178. this.painter.refresh();
  9179. /**
  9180. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9181. */
  9182. this._needsRefresh = false;
  9183. // var end = new Date();
  9184. // var log = document.getElementById('log');
  9185. // if (log) {
  9186. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9187. // }
  9188. },
  9189. /**
  9190. * Mark and repaint the canvas in the next frame of browser
  9191. */
  9192. refresh: function() {
  9193. this._needsRefresh = true;
  9194. },
  9195. /**
  9196. * Perform all refresh
  9197. */
  9198. flush: function () {
  9199. if (this._needsRefresh) {
  9200. this.refreshImmediately();
  9201. }
  9202. if (this._needsRefreshHover) {
  9203. this.refreshHoverImmediately();
  9204. }
  9205. },
  9206. /**
  9207. * Add element to hover layer
  9208. * @param {module:zrender/Element} el
  9209. * @param {Object} style
  9210. */
  9211. addHover: function (el, style) {
  9212. if (this.painter.addHover) {
  9213. this.painter.addHover(el, style);
  9214. this.refreshHover();
  9215. }
  9216. },
  9217. /**
  9218. * Add element from hover layer
  9219. * @param {module:zrender/Element} el
  9220. */
  9221. removeHover: function (el) {
  9222. if (this.painter.removeHover) {
  9223. this.painter.removeHover(el);
  9224. this.refreshHover();
  9225. }
  9226. },
  9227. /**
  9228. * Clear all hover elements in hover layer
  9229. * @param {module:zrender/Element} el
  9230. */
  9231. clearHover: function () {
  9232. if (this.painter.clearHover) {
  9233. this.painter.clearHover();
  9234. this.refreshHover();
  9235. }
  9236. },
  9237. /**
  9238. * Refresh hover in next frame
  9239. */
  9240. refreshHover: function () {
  9241. this._needsRefreshHover = true;
  9242. },
  9243. /**
  9244. * Refresh hover immediately
  9245. */
  9246. refreshHoverImmediately: function () {
  9247. this._needsRefreshHover = false;
  9248. this.painter.refreshHover && this.painter.refreshHover();
  9249. },
  9250. /**
  9251. * Resize the canvas.
  9252. * Should be invoked when container size is changed
  9253. * @param {Object} [opts]
  9254. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9255. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9256. */
  9257. resize: function(opts) {
  9258. opts = opts || {};
  9259. this.painter.resize(opts.width, opts.height);
  9260. this.handler.resize();
  9261. },
  9262. /**
  9263. * Stop and clear all animation immediately
  9264. */
  9265. clearAnimation: function () {
  9266. this.animation.clear();
  9267. },
  9268. /**
  9269. * Get container width
  9270. */
  9271. getWidth: function() {
  9272. return this.painter.getWidth();
  9273. },
  9274. /**
  9275. * Get container height
  9276. */
  9277. getHeight: function() {
  9278. return this.painter.getHeight();
  9279. },
  9280. /**
  9281. * Export the canvas as Base64 URL
  9282. * @param {string} type
  9283. * @param {string} [backgroundColor='#fff']
  9284. * @return {string} Base64 URL
  9285. */
  9286. // toDataURL: function(type, backgroundColor) {
  9287. // return this.painter.getRenderedCanvas({
  9288. // backgroundColor: backgroundColor
  9289. // }).toDataURL(type);
  9290. // },
  9291. /**
  9292. * Converting a path to image.
  9293. * It has much better performance of drawing image rather than drawing a vector path.
  9294. * @param {module:zrender/graphic/Path} e
  9295. * @param {number} width
  9296. * @param {number} height
  9297. */
  9298. pathToImage: function(e, dpr) {
  9299. return this.painter.pathToImage(e, dpr);
  9300. },
  9301. /**
  9302. * Set default cursor
  9303. * @param {string} [cursorStyle='default'] 例如 crosshair
  9304. */
  9305. setCursorStyle: function (cursorStyle) {
  9306. this.handler.setCursorStyle(cursorStyle);
  9307. },
  9308. /**
  9309. * Find hovered element
  9310. * @param {number} x
  9311. * @param {number} y
  9312. * @return {Object} {target, topTarget}
  9313. */
  9314. findHover: function (x, y) {
  9315. return this.handler.findHover(x, y);
  9316. },
  9317. /**
  9318. * Bind event
  9319. *
  9320. * @param {string} eventName Event name
  9321. * @param {Function} eventHandler Handler function
  9322. * @param {Object} [context] Context object
  9323. */
  9324. on: function(eventName, eventHandler, context) {
  9325. this.handler.on(eventName, eventHandler, context);
  9326. },
  9327. /**
  9328. * Unbind event
  9329. * @param {string} eventName Event name
  9330. * @param {Function} [eventHandler] Handler function
  9331. */
  9332. off: function(eventName, eventHandler) {
  9333. this.handler.off(eventName, eventHandler);
  9334. },
  9335. /**
  9336. * Trigger event manually
  9337. *
  9338. * @param {string} eventName Event name
  9339. * @param {event=} event Event object
  9340. */
  9341. trigger: function (eventName, event) {
  9342. this.handler.trigger(eventName, event);
  9343. },
  9344. /**
  9345. * Clear all objects and the canvas.
  9346. */
  9347. clear: function () {
  9348. this.storage.delRoot();
  9349. this.painter.clear();
  9350. },
  9351. /**
  9352. * Dispose self.
  9353. */
  9354. dispose: function () {
  9355. this.animation.stop();
  9356. this.clear();
  9357. this.storage.dispose();
  9358. this.painter.dispose();
  9359. this.handler.dispose();
  9360. this.animation =
  9361. this.storage =
  9362. this.painter =
  9363. this.handler = null;
  9364. delInstance(this.id);
  9365. }
  9366. };
  9367. var zrender = (Object.freeze || Object)({
  9368. version: version$1,
  9369. init: init$1,
  9370. dispose: dispose$1,
  9371. getInstance: getInstance,
  9372. registerPainter: registerPainter
  9373. });
  9374. var RADIAN_EPSILON = 1e-4;
  9375. function _trim(str) {
  9376. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  9377. }
  9378. /**
  9379. * Linear mapping a value from domain to range
  9380. * @memberOf module:echarts/util/number
  9381. * @param {(number|Array.<number>)} val
  9382. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  9383. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  9384. * @param {boolean} clamp
  9385. * @return {(number|Array.<number>}
  9386. */
  9387. function linearMap(val, domain, range, clamp) {
  9388. var subDomain = domain[1] - domain[0];
  9389. var subRange = range[1] - range[0];
  9390. if (subDomain === 0) {
  9391. return subRange === 0
  9392. ? range[0]
  9393. : (range[0] + range[1]) / 2;
  9394. }
  9395. // Avoid accuracy problem in edge, such as
  9396. // 146.39 - 62.83 === 83.55999999999999.
  9397. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  9398. // It is a little verbose for efficiency considering this method
  9399. // is a hotspot.
  9400. if (clamp) {
  9401. if (subDomain > 0) {
  9402. if (val <= domain[0]) {
  9403. return range[0];
  9404. }
  9405. else if (val >= domain[1]) {
  9406. return range[1];
  9407. }
  9408. }
  9409. else {
  9410. if (val >= domain[0]) {
  9411. return range[0];
  9412. }
  9413. else if (val <= domain[1]) {
  9414. return range[1];
  9415. }
  9416. }
  9417. }
  9418. else {
  9419. if (val === domain[0]) {
  9420. return range[0];
  9421. }
  9422. if (val === domain[1]) {
  9423. return range[1];
  9424. }
  9425. }
  9426. return (val - domain[0]) / subDomain * subRange + range[0];
  9427. }
  9428. /**
  9429. * Convert a percent string to absolute number.
  9430. * Returns NaN if percent is not a valid string or number
  9431. * @memberOf module:echarts/util/number
  9432. * @param {string|number} percent
  9433. * @param {number} all
  9434. * @return {number}
  9435. */
  9436. function parsePercent$1(percent, all) {
  9437. switch (percent) {
  9438. case 'center':
  9439. case 'middle':
  9440. percent = '50%';
  9441. break;
  9442. case 'left':
  9443. case 'top':
  9444. percent = '0%';
  9445. break;
  9446. case 'right':
  9447. case 'bottom':
  9448. percent = '100%';
  9449. break;
  9450. }
  9451. if (typeof percent === 'string') {
  9452. if (_trim(percent).match(/%$/)) {
  9453. return parseFloat(percent) / 100 * all;
  9454. }
  9455. return parseFloat(percent);
  9456. }
  9457. return percent == null ? NaN : +percent;
  9458. }
  9459. /**
  9460. * (1) Fix rounding error of float numbers.
  9461. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  9462. *
  9463. * @param {number} x
  9464. * @param {number} [precision]
  9465. * @param {boolean} [returnStr]
  9466. * @return {number|string}
  9467. */
  9468. function round(x, precision, returnStr) {
  9469. if (precision == null) {
  9470. precision = 10;
  9471. }
  9472. // Avoid range error
  9473. precision = Math.min(Math.max(0, precision), 20);
  9474. x = (+x).toFixed(precision);
  9475. return returnStr ? x : +x;
  9476. }
  9477. function asc(arr) {
  9478. arr.sort(function (a, b) {
  9479. return a - b;
  9480. });
  9481. return arr;
  9482. }
  9483. /**
  9484. * Get precision
  9485. * @param {number} val
  9486. */
  9487. function getPrecision(val) {
  9488. val = +val;
  9489. if (isNaN(val)) {
  9490. return 0;
  9491. }
  9492. // It is much faster than methods converting number to string as follows
  9493. // var tmp = val.toString();
  9494. // return tmp.length - 1 - tmp.indexOf('.');
  9495. // especially when precision is low
  9496. var e = 1;
  9497. var count = 0;
  9498. while (Math.round(val * e) / e !== val) {
  9499. e *= 10;
  9500. count++;
  9501. }
  9502. return count;
  9503. }
  9504. /**
  9505. * @param {string|number} val
  9506. * @return {number}
  9507. */
  9508. function getPrecisionSafe(val) {
  9509. var str = val.toString();
  9510. // Consider scientific notation: '3.4e-12' '3.4e+12'
  9511. var eIndex = str.indexOf('e');
  9512. if (eIndex > 0) {
  9513. var precision = +str.slice(eIndex + 1);
  9514. return precision < 0 ? -precision : 0;
  9515. }
  9516. else {
  9517. var dotIndex = str.indexOf('.');
  9518. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  9519. }
  9520. }
  9521. /**
  9522. * Minimal dicernible data precisioin according to a single pixel.
  9523. *
  9524. * @param {Array.<number>} dataExtent
  9525. * @param {Array.<number>} pixelExtent
  9526. * @return {number} precision
  9527. */
  9528. function getPixelPrecision(dataExtent, pixelExtent) {
  9529. var log = Math.log;
  9530. var LN10 = Math.LN10;
  9531. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  9532. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  9533. // toFixed() digits argument must be between 0 and 20.
  9534. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  9535. return !isFinite(precision) ? 20 : precision;
  9536. }
  9537. /**
  9538. * Get a data of given precision, assuring the sum of percentages
  9539. * in valueList is 1.
  9540. * The largest remainer method is used.
  9541. * https://en.wikipedia.org/wiki/Largest_remainder_method
  9542. *
  9543. * @param {Array.<number>} valueList a list of all data
  9544. * @param {number} idx index of the data to be processed in valueList
  9545. * @param {number} precision integer number showing digits of precision
  9546. * @return {number} percent ranging from 0 to 100
  9547. */
  9548. function getPercentWithPrecision(valueList, idx, precision) {
  9549. if (!valueList[idx]) {
  9550. return 0;
  9551. }
  9552. var sum = reduce(valueList, function (acc, val) {
  9553. return acc + (isNaN(val) ? 0 : val);
  9554. }, 0);
  9555. if (sum === 0) {
  9556. return 0;
  9557. }
  9558. var digits = Math.pow(10, precision);
  9559. var votesPerQuota = map(valueList, function (val) {
  9560. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  9561. });
  9562. var targetSeats = digits * 100;
  9563. var seats = map(votesPerQuota, function (votes) {
  9564. // Assign automatic seats.
  9565. return Math.floor(votes);
  9566. });
  9567. var currentSum = reduce(seats, function (acc, val) {
  9568. return acc + val;
  9569. }, 0);
  9570. var remainder = map(votesPerQuota, function (votes, idx) {
  9571. return votes - seats[idx];
  9572. });
  9573. // Has remainding votes.
  9574. while (currentSum < targetSeats) {
  9575. // Find next largest remainder.
  9576. var max = Number.NEGATIVE_INFINITY;
  9577. var maxId = null;
  9578. for (var i = 0, len = remainder.length; i < len; ++i) {
  9579. if (remainder[i] > max) {
  9580. max = remainder[i];
  9581. maxId = i;
  9582. }
  9583. }
  9584. // Add a vote to max remainder.
  9585. ++seats[maxId];
  9586. remainder[maxId] = 0;
  9587. ++currentSum;
  9588. }
  9589. return seats[idx] / digits;
  9590. }
  9591. // Number.MAX_SAFE_INTEGER, ie do not support.
  9592. var MAX_SAFE_INTEGER = 9007199254740991;
  9593. /**
  9594. * To 0 - 2 * PI, considering negative radian.
  9595. * @param {number} radian
  9596. * @return {number}
  9597. */
  9598. function remRadian(radian) {
  9599. var pi2 = Math.PI * 2;
  9600. return (radian % pi2 + pi2) % pi2;
  9601. }
  9602. /**
  9603. * @param {type} radian
  9604. * @return {boolean}
  9605. */
  9606. function isRadianAroundZero(val) {
  9607. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  9608. }
  9609. 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
  9610. /**
  9611. * @param {string|Date|number} value These values can be accepted:
  9612. * + An instance of Date, represent a time in its own time zone.
  9613. * + Or string in a subset of ISO 8601, only including:
  9614. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  9615. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  9616. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  9617. * all of which will be treated as local time if time zone is not specified
  9618. * (see <https://momentjs.com/>).
  9619. * + Or other string format, including (all of which will be treated as loacal time):
  9620. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  9621. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  9622. * + a timestamp, which represent a time in UTC.
  9623. * @return {Date} date
  9624. */
  9625. function parseDate(value) {
  9626. if (value instanceof Date) {
  9627. return value;
  9628. }
  9629. else if (typeof value === 'string') {
  9630. // Different browsers parse date in different way, so we parse it manually.
  9631. // Some other issues:
  9632. // new Date('1970-01-01') is UTC,
  9633. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  9634. // See issue #3623
  9635. var match = TIME_REG.exec(value);
  9636. if (!match) {
  9637. // return Invalid Date.
  9638. return new Date(NaN);
  9639. }
  9640. // Use local time when no timezone offset specifed.
  9641. if (!match[8]) {
  9642. // match[n] can only be string or undefined.
  9643. // But take care of '12' + 1 => '121'.
  9644. return new Date(
  9645. +match[1],
  9646. +(match[2] || 1) - 1,
  9647. +match[3] || 1,
  9648. +match[4] || 0,
  9649. +(match[5] || 0),
  9650. +match[6] || 0,
  9651. +match[7] || 0
  9652. );
  9653. }
  9654. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  9655. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  9656. // For example, system timezone is set as "Time Zone: America/Toronto",
  9657. // then these code will get different result:
  9658. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  9659. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  9660. // So we should not use `new Date`, but use `Date.UTC`.
  9661. else {
  9662. var hour = +match[4] || 0;
  9663. if (match[8].toUpperCase() !== 'Z') {
  9664. hour -= match[8].slice(0, 3);
  9665. }
  9666. return new Date(Date.UTC(
  9667. +match[1],
  9668. +(match[2] || 1) - 1,
  9669. +match[3] || 1,
  9670. hour,
  9671. +(match[5] || 0),
  9672. +match[6] || 0,
  9673. +match[7] || 0
  9674. ));
  9675. }
  9676. }
  9677. else if (value == null) {
  9678. return new Date(NaN);
  9679. }
  9680. return new Date(Math.round(value));
  9681. }
  9682. /**
  9683. * Quantity of a number. e.g. 0.1, 1, 10, 100
  9684. *
  9685. * @param {number} val
  9686. * @return {number}
  9687. */
  9688. function quantity(val) {
  9689. return Math.pow(10, quantityExponent(val));
  9690. }
  9691. function quantityExponent(val) {
  9692. return Math.floor(Math.log(val) / Math.LN10);
  9693. }
  9694. /**
  9695. * find a “nice” number approximately equal to x. Round the number if round = true,
  9696. * take ceiling if round = false. The primary observation is that the “nicest”
  9697. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  9698. *
  9699. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  9700. *
  9701. * @param {number} val Non-negative value.
  9702. * @param {boolean} round
  9703. * @return {number}
  9704. */
  9705. function nice(val, round) {
  9706. var exponent = quantityExponent(val);
  9707. var exp10 = Math.pow(10, exponent);
  9708. var f = val / exp10; // 1 <= f < 10
  9709. var nf;
  9710. if (round) {
  9711. if (f < 1.5) { nf = 1; }
  9712. else if (f < 2.5) { nf = 2; }
  9713. else if (f < 4) { nf = 3; }
  9714. else if (f < 7) { nf = 5; }
  9715. else { nf = 10; }
  9716. }
  9717. else {
  9718. if (f < 1) { nf = 1; }
  9719. else if (f < 2) { nf = 2; }
  9720. else if (f < 3) { nf = 3; }
  9721. else if (f < 5) { nf = 5; }
  9722. else { nf = 10; }
  9723. }
  9724. val = nf * exp10;
  9725. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  9726. // 20 is the uppper bound of toFixed.
  9727. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  9728. }
  9729. /**
  9730. * Order intervals asc, and split them when overlap.
  9731. * expect(numberUtil.reformIntervals([
  9732. * {interval: [18, 62], close: [1, 1]},
  9733. * {interval: [-Infinity, -70], close: [0, 0]},
  9734. * {interval: [-70, -26], close: [1, 1]},
  9735. * {interval: [-26, 18], close: [1, 1]},
  9736. * {interval: [62, 150], close: [1, 1]},
  9737. * {interval: [106, 150], close: [1, 1]},
  9738. * {interval: [150, Infinity], close: [0, 0]}
  9739. * ])).toEqual([
  9740. * {interval: [-Infinity, -70], close: [0, 0]},
  9741. * {interval: [-70, -26], close: [1, 1]},
  9742. * {interval: [-26, 18], close: [0, 1]},
  9743. * {interval: [18, 62], close: [0, 1]},
  9744. * {interval: [62, 150], close: [0, 1]},
  9745. * {interval: [150, Infinity], close: [0, 0]}
  9746. * ]);
  9747. * @param {Array.<Object>} list, where `close` mean open or close
  9748. * of the interval, and Infinity can be used.
  9749. * @return {Array.<Object>} The origin list, which has been reformed.
  9750. */
  9751. function reformIntervals(list) {
  9752. list.sort(function (a, b) {
  9753. return littleThan(a, b, 0) ? -1 : 1;
  9754. });
  9755. var curr = -Infinity;
  9756. var currClose = 1;
  9757. for (var i = 0; i < list.length;) {
  9758. var interval = list[i].interval;
  9759. var close = list[i].close;
  9760. for (var lg = 0; lg < 2; lg++) {
  9761. if (interval[lg] <= curr) {
  9762. interval[lg] = curr;
  9763. close[lg] = !lg ? 1 - currClose : 1;
  9764. }
  9765. curr = interval[lg];
  9766. currClose = close[lg];
  9767. }
  9768. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  9769. list.splice(i, 1);
  9770. }
  9771. else {
  9772. i++;
  9773. }
  9774. }
  9775. return list;
  9776. function littleThan(a, b, lg) {
  9777. return a.interval[lg] < b.interval[lg]
  9778. || (
  9779. a.interval[lg] === b.interval[lg]
  9780. && (
  9781. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  9782. || (!lg && littleThan(a, b, 1))
  9783. )
  9784. );
  9785. }
  9786. }
  9787. /**
  9788. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  9789. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  9790. * subtraction forces infinities to NaN
  9791. *
  9792. * @param {*} v
  9793. * @return {boolean}
  9794. */
  9795. function isNumeric(v) {
  9796. return v - parseFloat(v) >= 0;
  9797. }
  9798. var number = (Object.freeze || Object)({
  9799. linearMap: linearMap,
  9800. parsePercent: parsePercent$1,
  9801. round: round,
  9802. asc: asc,
  9803. getPrecision: getPrecision,
  9804. getPrecisionSafe: getPrecisionSafe,
  9805. getPixelPrecision: getPixelPrecision,
  9806. getPercentWithPrecision: getPercentWithPrecision,
  9807. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  9808. remRadian: remRadian,
  9809. isRadianAroundZero: isRadianAroundZero,
  9810. parseDate: parseDate,
  9811. quantity: quantity,
  9812. nice: nice,
  9813. reformIntervals: reformIntervals,
  9814. isNumeric: isNumeric
  9815. });
  9816. /**
  9817. * 每三位默认加,格式化
  9818. * @param {string|number} x
  9819. * @return {string}
  9820. */
  9821. function addCommas(x) {
  9822. if (isNaN(x)) {
  9823. return '-';
  9824. }
  9825. x = (x + '').split('.');
  9826. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  9827. + (x.length > 1 ? ('.' + x[1]) : '');
  9828. }
  9829. /**
  9830. * @param {string} str
  9831. * @param {boolean} [upperCaseFirst=false]
  9832. * @return {string} str
  9833. */
  9834. function toCamelCase(str, upperCaseFirst) {
  9835. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  9836. return group1.toUpperCase();
  9837. });
  9838. if (upperCaseFirst && str) {
  9839. str = str.charAt(0).toUpperCase() + str.slice(1);
  9840. }
  9841. return str;
  9842. }
  9843. var normalizeCssArray$1 = normalizeCssArray;
  9844. function encodeHTML(source) {
  9845. return String(source)
  9846. .replace(/&/g, '&amp;')
  9847. .replace(/</g, '&lt;')
  9848. .replace(/>/g, '&gt;')
  9849. .replace(/"/g, '&quot;')
  9850. .replace(/'/g, '&#39;');
  9851. }
  9852. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  9853. var wrapVar = function (varName, seriesIdx) {
  9854. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  9855. };
  9856. /**
  9857. * Template formatter
  9858. * @param {string} tpl
  9859. * @param {Array.<Object>|Object} paramsList
  9860. * @param {boolean} [encode=false]
  9861. * @return {string}
  9862. */
  9863. function formatTpl(tpl, paramsList, encode) {
  9864. if (!isArray(paramsList)) {
  9865. paramsList = [paramsList];
  9866. }
  9867. var seriesLen = paramsList.length;
  9868. if (!seriesLen) {
  9869. return '';
  9870. }
  9871. var $vars = paramsList[0].$vars || [];
  9872. for (var i = 0; i < $vars.length; i++) {
  9873. var alias = TPL_VAR_ALIAS[i];
  9874. var val = wrapVar(alias, 0);
  9875. tpl = tpl.replace(wrapVar(alias), encode ? encodeHTML(val) : val);
  9876. }
  9877. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  9878. for (var k = 0; k < $vars.length; k++) {
  9879. var val = paramsList[seriesIdx][$vars[k]];
  9880. tpl = tpl.replace(
  9881. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  9882. encode ? encodeHTML(val) : val
  9883. );
  9884. }
  9885. }
  9886. return tpl;
  9887. }
  9888. /**
  9889. * simple Template formatter
  9890. *
  9891. * @param {string} tpl
  9892. * @param {Object} param
  9893. * @param {boolean} [encode=false]
  9894. * @return {string}
  9895. */
  9896. function formatTplSimple(tpl, param, encode) {
  9897. each$1(param, function (value, key) {
  9898. tpl = tpl.replace(
  9899. '{' + key + '}',
  9900. encode ? encodeHTML(value) : value
  9901. );
  9902. });
  9903. return tpl;
  9904. }
  9905. /**
  9906. * @param {string} color
  9907. * @param {string} [extraCssText]
  9908. * @return {string}
  9909. */
  9910. function getTooltipMarker(color, extraCssText) {
  9911. return color
  9912. ? '<span style="display:inline-block;margin-right:5px;'
  9913. + 'border-radius:10px;width:9px;height:9px;background-color:'
  9914. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  9915. : '';
  9916. }
  9917. /**
  9918. * @param {string} str
  9919. * @return {string}
  9920. * @inner
  9921. */
  9922. var s2d = function (str) {
  9923. return str < 10 ? ('0' + str) : str;
  9924. };
  9925. /**
  9926. * ISO Date format
  9927. * @param {string} tpl
  9928. * @param {number} value
  9929. * @param {boolean} [isUTC=false] Default in local time.
  9930. * see `module:echarts/scale/Time`
  9931. * and `module:echarts/util/number#parseDate`.
  9932. * @inner
  9933. */
  9934. function formatTime(tpl, value, isUTC) {
  9935. if (tpl === 'week'
  9936. || tpl === 'month'
  9937. || tpl === 'quarter'
  9938. || tpl === 'half-year'
  9939. || tpl === 'year'
  9940. ) {
  9941. tpl = 'MM-dd\nyyyy';
  9942. }
  9943. var date = parseDate(value);
  9944. var utc = isUTC ? 'UTC' : '';
  9945. var y = date['get' + utc + 'FullYear']();
  9946. var M = date['get' + utc + 'Month']() + 1;
  9947. var d = date['get' + utc + 'Date']();
  9948. var h = date['get' + utc + 'Hours']();
  9949. var m = date['get' + utc + 'Minutes']();
  9950. var s = date['get' + utc + 'Seconds']();
  9951. tpl = tpl.replace('MM', s2d(M))
  9952. .replace('M', M)
  9953. .replace('yyyy', y)
  9954. .replace('yy', y % 100)
  9955. .replace('dd', s2d(d))
  9956. .replace('d', d)
  9957. .replace('hh', s2d(h))
  9958. .replace('h', h)
  9959. .replace('mm', s2d(m))
  9960. .replace('m', m)
  9961. .replace('ss', s2d(s))
  9962. .replace('s', s);
  9963. return tpl;
  9964. }
  9965. /**
  9966. * Capital first
  9967. * @param {string} str
  9968. * @return {string}
  9969. */
  9970. function capitalFirst(str) {
  9971. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  9972. }
  9973. var truncateText$1 = truncateText;
  9974. var getTextRect = getBoundingRect;
  9975. var format = (Object.freeze || Object)({
  9976. addCommas: addCommas,
  9977. toCamelCase: toCamelCase,
  9978. normalizeCssArray: normalizeCssArray$1,
  9979. encodeHTML: encodeHTML,
  9980. formatTpl: formatTpl,
  9981. formatTplSimple: formatTplSimple,
  9982. getTooltipMarker: getTooltipMarker,
  9983. formatTime: formatTime,
  9984. capitalFirst: capitalFirst,
  9985. truncateText: truncateText$1,
  9986. getTextRect: getTextRect
  9987. });
  9988. var TYPE_DELIMITER = '.';
  9989. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9990. var MEMBER_PRIFIX = '\0ec_\0';
  9991. /**
  9992. * Hide private class member.
  9993. * The same behavior as `host[name] = value;` (can be right-value)
  9994. * @public
  9995. */
  9996. function set$1(host, name, value) {
  9997. return (host[MEMBER_PRIFIX + name] = value);
  9998. }
  9999. /**
  10000. * Hide private class member.
  10001. * The same behavior as `host[name];`
  10002. * @public
  10003. */
  10004. function get(host, name) {
  10005. return host[MEMBER_PRIFIX + name];
  10006. }
  10007. /**
  10008. * For hidden private class member.
  10009. * The same behavior as `host.hasOwnProperty(name);`
  10010. * @public
  10011. */
  10012. function hasOwn(host, name) {
  10013. return host.hasOwnProperty(MEMBER_PRIFIX + name);
  10014. }
  10015. /**
  10016. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10017. * @public
  10018. */
  10019. function parseClassType$1(componentType) {
  10020. var ret = {main: '', sub: ''};
  10021. if (componentType) {
  10022. componentType = componentType.split(TYPE_DELIMITER);
  10023. ret.main = componentType[0] || '';
  10024. ret.sub = componentType[1] || '';
  10025. }
  10026. return ret;
  10027. }
  10028. /**
  10029. * @public
  10030. */
  10031. function checkClassType(componentType) {
  10032. assert(
  10033. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10034. 'componentType "' + componentType + '" illegal'
  10035. );
  10036. }
  10037. /**
  10038. * @public
  10039. */
  10040. function enableClassExtend(RootClass, mandatoryMethods) {
  10041. RootClass.$constructor = RootClass;
  10042. RootClass.extend = function (proto) {
  10043. if (__DEV__) {
  10044. each$1(mandatoryMethods, function (method) {
  10045. if (!proto[method]) {
  10046. console.warn(
  10047. 'Method `' + method + '` should be implemented'
  10048. + (proto.type ? ' in ' + proto.type : '') + '.'
  10049. );
  10050. }
  10051. });
  10052. }
  10053. var superClass = this;
  10054. var ExtendedClass = function () {
  10055. if (!proto.$constructor) {
  10056. superClass.apply(this, arguments);
  10057. }
  10058. else {
  10059. proto.$constructor.apply(this, arguments);
  10060. }
  10061. };
  10062. extend(ExtendedClass.prototype, proto);
  10063. ExtendedClass.extend = this.extend;
  10064. ExtendedClass.superCall = superCall;
  10065. ExtendedClass.superApply = superApply;
  10066. inherits(ExtendedClass, this);
  10067. ExtendedClass.superClass = superClass;
  10068. return ExtendedClass;
  10069. };
  10070. }
  10071. // superCall should have class info, which can not be fetch from 'this'.
  10072. // Consider this case:
  10073. // class A has method f,
  10074. // class B inherits class A, overrides method f, f call superApply('f'),
  10075. // class C inherits class B, do not overrides method f,
  10076. // then when method of class C is called, dead loop occured.
  10077. function superCall(context, methodName) {
  10078. var args = slice(arguments, 2);
  10079. return this.superClass.prototype[methodName].apply(context, args);
  10080. }
  10081. function superApply(context, methodName, args) {
  10082. return this.superClass.prototype[methodName].apply(context, args);
  10083. }
  10084. /**
  10085. * @param {Object} entity
  10086. * @param {Object} options
  10087. * @param {boolean} [options.registerWhenExtend]
  10088. * @public
  10089. */
  10090. function enableClassManagement(entity, options) {
  10091. options = options || {};
  10092. /**
  10093. * Component model classes
  10094. * key: componentType,
  10095. * value:
  10096. * componentClass, when componentType is 'xxx'
  10097. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10098. * @type {Object}
  10099. */
  10100. var storage = {};
  10101. entity.registerClass = function (Clazz, componentType) {
  10102. if (componentType) {
  10103. checkClassType(componentType);
  10104. componentType = parseClassType$1(componentType);
  10105. if (!componentType.sub) {
  10106. if (__DEV__) {
  10107. if (storage[componentType.main]) {
  10108. console.warn(componentType.main + ' exists.');
  10109. }
  10110. }
  10111. storage[componentType.main] = Clazz;
  10112. }
  10113. else if (componentType.sub !== IS_CONTAINER) {
  10114. var container = makeContainer(componentType);
  10115. container[componentType.sub] = Clazz;
  10116. }
  10117. }
  10118. return Clazz;
  10119. };
  10120. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10121. var Clazz = storage[componentMainType];
  10122. if (Clazz && Clazz[IS_CONTAINER]) {
  10123. Clazz = subType ? Clazz[subType] : null;
  10124. }
  10125. if (throwWhenNotFound && !Clazz) {
  10126. throw new Error(
  10127. !subType
  10128. ? componentMainType + '.' + 'type should be specified.'
  10129. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10130. );
  10131. }
  10132. return Clazz;
  10133. };
  10134. entity.getClassesByMainType = function (componentType) {
  10135. componentType = parseClassType$1(componentType);
  10136. var result = [];
  10137. var obj = storage[componentType.main];
  10138. if (obj && obj[IS_CONTAINER]) {
  10139. each$1(obj, function (o, type) {
  10140. type !== IS_CONTAINER && result.push(o);
  10141. });
  10142. }
  10143. else {
  10144. result.push(obj);
  10145. }
  10146. return result;
  10147. };
  10148. entity.hasClass = function (componentType) {
  10149. // Just consider componentType.main.
  10150. componentType = parseClassType$1(componentType);
  10151. return !!storage[componentType.main];
  10152. };
  10153. /**
  10154. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10155. */
  10156. entity.getAllClassMainTypes = function () {
  10157. var types = [];
  10158. each$1(storage, function (obj, type) {
  10159. types.push(type);
  10160. });
  10161. return types;
  10162. };
  10163. /**
  10164. * If a main type is container and has sub types
  10165. * @param {string} mainType
  10166. * @return {boolean}
  10167. */
  10168. entity.hasSubTypes = function (componentType) {
  10169. componentType = parseClassType$1(componentType);
  10170. var obj = storage[componentType.main];
  10171. return obj && obj[IS_CONTAINER];
  10172. };
  10173. entity.parseClassType = parseClassType$1;
  10174. function makeContainer(componentType) {
  10175. var container = storage[componentType.main];
  10176. if (!container || !container[IS_CONTAINER]) {
  10177. container = storage[componentType.main] = {};
  10178. container[IS_CONTAINER] = true;
  10179. }
  10180. return container;
  10181. }
  10182. if (options.registerWhenExtend) {
  10183. var originalExtend = entity.extend;
  10184. if (originalExtend) {
  10185. entity.extend = function (proto) {
  10186. var ExtendedClass = originalExtend.call(this, proto);
  10187. return entity.registerClass(ExtendedClass, proto.type);
  10188. };
  10189. }
  10190. }
  10191. return entity;
  10192. }
  10193. /**
  10194. * @param {string|Array.<string>} properties
  10195. */
  10196. // TODO Parse shadow style
  10197. // TODO Only shallow path support
  10198. var makeStyleMapper = function (properties) {
  10199. // Normalize
  10200. for (var i = 0; i < properties.length; i++) {
  10201. if (!properties[i][1]) {
  10202. properties[i][1] = properties[i][0];
  10203. }
  10204. }
  10205. return function (model, excludes, includes) {
  10206. var style = {};
  10207. for (var i = 0; i < properties.length; i++) {
  10208. var propName = properties[i][1];
  10209. if ((excludes && indexOf(excludes, propName) >= 0)
  10210. || (includes && indexOf(includes, propName) < 0)
  10211. ) {
  10212. continue;
  10213. }
  10214. var val = model.getShallow(propName);
  10215. if (val != null) {
  10216. style[properties[i][0]] = val;
  10217. }
  10218. }
  10219. return style;
  10220. };
  10221. };
  10222. var getLineStyle = makeStyleMapper(
  10223. [
  10224. ['lineWidth', 'width'],
  10225. ['stroke', 'color'],
  10226. ['opacity'],
  10227. ['shadowBlur'],
  10228. ['shadowOffsetX'],
  10229. ['shadowOffsetY'],
  10230. ['shadowColor']
  10231. ]
  10232. );
  10233. var lineStyleMixin = {
  10234. getLineStyle: function (excludes) {
  10235. var style = getLineStyle(this, excludes);
  10236. var lineDash = this.getLineDash(style.lineWidth);
  10237. lineDash && (style.lineDash = lineDash);
  10238. return style;
  10239. },
  10240. getLineDash: function (lineWidth) {
  10241. if (lineWidth == null) {
  10242. lineWidth = 1;
  10243. }
  10244. var lineType = this.get('type');
  10245. var dotSize = Math.max(lineWidth, 2);
  10246. var dashSize = lineWidth * 4;
  10247. return (lineType === 'solid' || lineType == null) ? null
  10248. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10249. }
  10250. };
  10251. var getAreaStyle = makeStyleMapper(
  10252. [
  10253. ['fill', 'color'],
  10254. ['shadowBlur'],
  10255. ['shadowOffsetX'],
  10256. ['shadowOffsetY'],
  10257. ['opacity'],
  10258. ['shadowColor']
  10259. ]
  10260. );
  10261. var areaStyleMixin = {
  10262. getAreaStyle: function (excludes, includes) {
  10263. return getAreaStyle(this, excludes, includes);
  10264. }
  10265. };
  10266. /**
  10267. * 曲线辅助模块
  10268. * @module zrender/core/curve
  10269. * @author pissang(https://www.github.com/pissang)
  10270. */
  10271. var mathPow = Math.pow;
  10272. var mathSqrt$2 = Math.sqrt;
  10273. var EPSILON$1 = 1e-8;
  10274. var EPSILON_NUMERIC = 1e-4;
  10275. var THREE_SQRT = mathSqrt$2(3);
  10276. var ONE_THIRD = 1 / 3;
  10277. // 临时变量
  10278. var _v0 = create();
  10279. var _v1 = create();
  10280. var _v2 = create();
  10281. function isAroundZero(val) {
  10282. return val > -EPSILON$1 && val < EPSILON$1;
  10283. }
  10284. function isNotAroundZero$1(val) {
  10285. return val > EPSILON$1 || val < -EPSILON$1;
  10286. }
  10287. /**
  10288. * 计算三次贝塞尔值
  10289. * @memberOf module:zrender/core/curve
  10290. * @param {number} p0
  10291. * @param {number} p1
  10292. * @param {number} p2
  10293. * @param {number} p3
  10294. * @param {number} t
  10295. * @return {number}
  10296. */
  10297. function cubicAt(p0, p1, p2, p3, t) {
  10298. var onet = 1 - t;
  10299. return onet * onet * (onet * p0 + 3 * t * p1)
  10300. + t * t * (t * p3 + 3 * onet * p2);
  10301. }
  10302. /**
  10303. * 计算三次贝塞尔导数值
  10304. * @memberOf module:zrender/core/curve
  10305. * @param {number} p0
  10306. * @param {number} p1
  10307. * @param {number} p2
  10308. * @param {number} p3
  10309. * @param {number} t
  10310. * @return {number}
  10311. */
  10312. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10313. var onet = 1 - t;
  10314. return 3 * (
  10315. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10316. + (p3 - p2) * t * t
  10317. );
  10318. }
  10319. /**
  10320. * 计算三次贝塞尔方程根,使用盛金公式
  10321. * @memberOf module:zrender/core/curve
  10322. * @param {number} p0
  10323. * @param {number} p1
  10324. * @param {number} p2
  10325. * @param {number} p3
  10326. * @param {number} val
  10327. * @param {Array.<number>} roots
  10328. * @return {number} 有效根数目
  10329. */
  10330. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10331. // Evaluate roots of cubic functions
  10332. var a = p3 + 3 * (p1 - p2) - p0;
  10333. var b = 3 * (p2 - p1 * 2 + p0);
  10334. var c = 3 * (p1 - p0);
  10335. var d = p0 - val;
  10336. var A = b * b - 3 * a * c;
  10337. var B = b * c - 9 * a * d;
  10338. var C = c * c - 3 * b * d;
  10339. var n = 0;
  10340. if (isAroundZero(A) && isAroundZero(B)) {
  10341. if (isAroundZero(b)) {
  10342. roots[0] = 0;
  10343. }
  10344. else {
  10345. var t1 = -c / b; //t1, t2, t3, b is not zero
  10346. if (t1 >= 0 && t1 <= 1) {
  10347. roots[n++] = t1;
  10348. }
  10349. }
  10350. }
  10351. else {
  10352. var disc = B * B - 4 * A * C;
  10353. if (isAroundZero(disc)) {
  10354. var K = B / A;
  10355. var t1 = -b / a + K; // t1, a is not zero
  10356. var t2 = -K / 2; // t2, t3
  10357. if (t1 >= 0 && t1 <= 1) {
  10358. roots[n++] = t1;
  10359. }
  10360. if (t2 >= 0 && t2 <= 1) {
  10361. roots[n++] = t2;
  10362. }
  10363. }
  10364. else if (disc > 0) {
  10365. var discSqrt = mathSqrt$2(disc);
  10366. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10367. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10368. if (Y1 < 0) {
  10369. Y1 = -mathPow(-Y1, ONE_THIRD);
  10370. }
  10371. else {
  10372. Y1 = mathPow(Y1, ONE_THIRD);
  10373. }
  10374. if (Y2 < 0) {
  10375. Y2 = -mathPow(-Y2, ONE_THIRD);
  10376. }
  10377. else {
  10378. Y2 = mathPow(Y2, ONE_THIRD);
  10379. }
  10380. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10381. if (t1 >= 0 && t1 <= 1) {
  10382. roots[n++] = t1;
  10383. }
  10384. }
  10385. else {
  10386. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10387. var theta = Math.acos(T) / 3;
  10388. var ASqrt = mathSqrt$2(A);
  10389. var tmp = Math.cos(theta);
  10390. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10391. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10392. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10393. if (t1 >= 0 && t1 <= 1) {
  10394. roots[n++] = t1;
  10395. }
  10396. if (t2 >= 0 && t2 <= 1) {
  10397. roots[n++] = t2;
  10398. }
  10399. if (t3 >= 0 && t3 <= 1) {
  10400. roots[n++] = t3;
  10401. }
  10402. }
  10403. }
  10404. return n;
  10405. }
  10406. /**
  10407. * 计算三次贝塞尔方程极限值的位置
  10408. * @memberOf module:zrender/core/curve
  10409. * @param {number} p0
  10410. * @param {number} p1
  10411. * @param {number} p2
  10412. * @param {number} p3
  10413. * @param {Array.<number>} extrema
  10414. * @return {number} 有效数目
  10415. */
  10416. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10417. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10418. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10419. var c = 3 * p1 - 3 * p0;
  10420. var n = 0;
  10421. if (isAroundZero(a)) {
  10422. if (isNotAroundZero$1(b)) {
  10423. var t1 = -c / b;
  10424. if (t1 >= 0 && t1 <=1) {
  10425. extrema[n++] = t1;
  10426. }
  10427. }
  10428. }
  10429. else {
  10430. var disc = b * b - 4 * a * c;
  10431. if (isAroundZero(disc)) {
  10432. extrema[0] = -b / (2 * a);
  10433. }
  10434. else if (disc > 0) {
  10435. var discSqrt = mathSqrt$2(disc);
  10436. var t1 = (-b + discSqrt) / (2 * a);
  10437. var t2 = (-b - discSqrt) / (2 * a);
  10438. if (t1 >= 0 && t1 <= 1) {
  10439. extrema[n++] = t1;
  10440. }
  10441. if (t2 >= 0 && t2 <= 1) {
  10442. extrema[n++] = t2;
  10443. }
  10444. }
  10445. }
  10446. return n;
  10447. }
  10448. /**
  10449. * 细分三次贝塞尔曲线
  10450. * @memberOf module:zrender/core/curve
  10451. * @param {number} p0
  10452. * @param {number} p1
  10453. * @param {number} p2
  10454. * @param {number} p3
  10455. * @param {number} t
  10456. * @param {Array.<number>} out
  10457. */
  10458. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10459. var p01 = (p1 - p0) * t + p0;
  10460. var p12 = (p2 - p1) * t + p1;
  10461. var p23 = (p3 - p2) * t + p2;
  10462. var p012 = (p12 - p01) * t + p01;
  10463. var p123 = (p23 - p12) * t + p12;
  10464. var p0123 = (p123 - p012) * t + p012;
  10465. // Seg0
  10466. out[0] = p0;
  10467. out[1] = p01;
  10468. out[2] = p012;
  10469. out[3] = p0123;
  10470. // Seg1
  10471. out[4] = p0123;
  10472. out[5] = p123;
  10473. out[6] = p23;
  10474. out[7] = p3;
  10475. }
  10476. /**
  10477. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10478. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10479. * @param {number} x0
  10480. * @param {number} y0
  10481. * @param {number} x1
  10482. * @param {number} y1
  10483. * @param {number} x2
  10484. * @param {number} y2
  10485. * @param {number} x3
  10486. * @param {number} y3
  10487. * @param {number} x
  10488. * @param {number} y
  10489. * @param {Array.<number>} [out] 投射点
  10490. * @return {number}
  10491. */
  10492. function cubicProjectPoint(
  10493. x0, y0, x1, y1, x2, y2, x3, y3,
  10494. x, y, out
  10495. ) {
  10496. // http://pomax.github.io/bezierinfo/#projections
  10497. var t;
  10498. var interval = 0.005;
  10499. var d = Infinity;
  10500. var prev;
  10501. var next;
  10502. var d1;
  10503. var d2;
  10504. _v0[0] = x;
  10505. _v0[1] = y;
  10506. // 先粗略估计一下可能的最小距离的 t 值
  10507. // PENDING
  10508. for (var _t = 0; _t < 1; _t += 0.05) {
  10509. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10510. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10511. d1 = distSquare(_v0, _v1);
  10512. if (d1 < d) {
  10513. t = _t;
  10514. d = d1;
  10515. }
  10516. }
  10517. d = Infinity;
  10518. // At most 32 iteration
  10519. for (var i = 0; i < 32; i++) {
  10520. if (interval < EPSILON_NUMERIC) {
  10521. break;
  10522. }
  10523. prev = t - interval;
  10524. next = t + interval;
  10525. // t - interval
  10526. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10527. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10528. d1 = distSquare(_v1, _v0);
  10529. if (prev >= 0 && d1 < d) {
  10530. t = prev;
  10531. d = d1;
  10532. }
  10533. else {
  10534. // t + interval
  10535. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10536. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10537. d2 = distSquare(_v2, _v0);
  10538. if (next <= 1 && d2 < d) {
  10539. t = next;
  10540. d = d2;
  10541. }
  10542. else {
  10543. interval *= 0.5;
  10544. }
  10545. }
  10546. }
  10547. // t
  10548. if (out) {
  10549. out[0] = cubicAt(x0, x1, x2, x3, t);
  10550. out[1] = cubicAt(y0, y1, y2, y3, t);
  10551. }
  10552. // console.log(interval, i);
  10553. return mathSqrt$2(d);
  10554. }
  10555. /**
  10556. * 计算二次方贝塞尔值
  10557. * @param {number} p0
  10558. * @param {number} p1
  10559. * @param {number} p2
  10560. * @param {number} t
  10561. * @return {number}
  10562. */
  10563. function quadraticAt(p0, p1, p2, t) {
  10564. var onet = 1 - t;
  10565. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10566. }
  10567. /**
  10568. * 计算二次方贝塞尔导数值
  10569. * @param {number} p0
  10570. * @param {number} p1
  10571. * @param {number} p2
  10572. * @param {number} t
  10573. * @return {number}
  10574. */
  10575. function quadraticDerivativeAt(p0, p1, p2, t) {
  10576. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10577. }
  10578. /**
  10579. * 计算二次方贝塞尔方程根
  10580. * @param {number} p0
  10581. * @param {number} p1
  10582. * @param {number} p2
  10583. * @param {number} t
  10584. * @param {Array.<number>} roots
  10585. * @return {number} 有效根数目
  10586. */
  10587. function quadraticRootAt(p0, p1, p2, val, roots) {
  10588. var a = p0 - 2 * p1 + p2;
  10589. var b = 2 * (p1 - p0);
  10590. var c = p0 - val;
  10591. var n = 0;
  10592. if (isAroundZero(a)) {
  10593. if (isNotAroundZero$1(b)) {
  10594. var t1 = -c / b;
  10595. if (t1 >= 0 && t1 <= 1) {
  10596. roots[n++] = t1;
  10597. }
  10598. }
  10599. }
  10600. else {
  10601. var disc = b * b - 4 * a * c;
  10602. if (isAroundZero(disc)) {
  10603. var t1 = -b / (2 * a);
  10604. if (t1 >= 0 && t1 <= 1) {
  10605. roots[n++] = t1;
  10606. }
  10607. }
  10608. else if (disc > 0) {
  10609. var discSqrt = mathSqrt$2(disc);
  10610. var t1 = (-b + discSqrt) / (2 * a);
  10611. var t2 = (-b - discSqrt) / (2 * a);
  10612. if (t1 >= 0 && t1 <= 1) {
  10613. roots[n++] = t1;
  10614. }
  10615. if (t2 >= 0 && t2 <= 1) {
  10616. roots[n++] = t2;
  10617. }
  10618. }
  10619. }
  10620. return n;
  10621. }
  10622. /**
  10623. * 计算二次贝塞尔方程极限值
  10624. * @memberOf module:zrender/core/curve
  10625. * @param {number} p0
  10626. * @param {number} p1
  10627. * @param {number} p2
  10628. * @return {number}
  10629. */
  10630. function quadraticExtremum(p0, p1, p2) {
  10631. var divider = p0 + p2 - 2 * p1;
  10632. if (divider === 0) {
  10633. // p1 is center of p0 and p2
  10634. return 0.5;
  10635. }
  10636. else {
  10637. return (p0 - p1) / divider;
  10638. }
  10639. }
  10640. /**
  10641. * 细分二次贝塞尔曲线
  10642. * @memberOf module:zrender/core/curve
  10643. * @param {number} p0
  10644. * @param {number} p1
  10645. * @param {number} p2
  10646. * @param {number} t
  10647. * @param {Array.<number>} out
  10648. */
  10649. function quadraticSubdivide(p0, p1, p2, t, out) {
  10650. var p01 = (p1 - p0) * t + p0;
  10651. var p12 = (p2 - p1) * t + p1;
  10652. var p012 = (p12 - p01) * t + p01;
  10653. // Seg0
  10654. out[0] = p0;
  10655. out[1] = p01;
  10656. out[2] = p012;
  10657. // Seg1
  10658. out[3] = p012;
  10659. out[4] = p12;
  10660. out[5] = p2;
  10661. }
  10662. /**
  10663. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10664. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10665. * @param {number} x0
  10666. * @param {number} y0
  10667. * @param {number} x1
  10668. * @param {number} y1
  10669. * @param {number} x2
  10670. * @param {number} y2
  10671. * @param {number} x
  10672. * @param {number} y
  10673. * @param {Array.<number>} out 投射点
  10674. * @return {number}
  10675. */
  10676. function quadraticProjectPoint(
  10677. x0, y0, x1, y1, x2, y2,
  10678. x, y, out
  10679. ) {
  10680. // http://pomax.github.io/bezierinfo/#projections
  10681. var t;
  10682. var interval = 0.005;
  10683. var d = Infinity;
  10684. _v0[0] = x;
  10685. _v0[1] = y;
  10686. // 先粗略估计一下可能的最小距离的 t 值
  10687. // PENDING
  10688. for (var _t = 0; _t < 1; _t += 0.05) {
  10689. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10690. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10691. var d1 = distSquare(_v0, _v1);
  10692. if (d1 < d) {
  10693. t = _t;
  10694. d = d1;
  10695. }
  10696. }
  10697. d = Infinity;
  10698. // At most 32 iteration
  10699. for (var i = 0; i < 32; i++) {
  10700. if (interval < EPSILON_NUMERIC) {
  10701. break;
  10702. }
  10703. var prev = t - interval;
  10704. var next = t + interval;
  10705. // t - interval
  10706. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10707. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10708. var d1 = distSquare(_v1, _v0);
  10709. if (prev >= 0 && d1 < d) {
  10710. t = prev;
  10711. d = d1;
  10712. }
  10713. else {
  10714. // t + interval
  10715. _v2[0] = quadraticAt(x0, x1, x2, next);
  10716. _v2[1] = quadraticAt(y0, y1, y2, next);
  10717. var d2 = distSquare(_v2, _v0);
  10718. if (next <= 1 && d2 < d) {
  10719. t = next;
  10720. d = d2;
  10721. }
  10722. else {
  10723. interval *= 0.5;
  10724. }
  10725. }
  10726. }
  10727. // t
  10728. if (out) {
  10729. out[0] = quadraticAt(x0, x1, x2, t);
  10730. out[1] = quadraticAt(y0, y1, y2, t);
  10731. }
  10732. // console.log(interval, i);
  10733. return mathSqrt$2(d);
  10734. }
  10735. /**
  10736. * @author Yi Shen(https://github.com/pissang)
  10737. */
  10738. var mathMin$3 = Math.min;
  10739. var mathMax$3 = Math.max;
  10740. var mathSin$2 = Math.sin;
  10741. var mathCos$2 = Math.cos;
  10742. var PI2 = Math.PI * 2;
  10743. var start = create();
  10744. var end = create();
  10745. var extremity = create();
  10746. /**
  10747. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10748. * @module zrender/core/bbox
  10749. * @param {Array<Object>} points 顶点数组
  10750. * @param {number} min
  10751. * @param {number} max
  10752. */
  10753. function fromPoints(points, min$$1, max$$1) {
  10754. if (points.length === 0) {
  10755. return;
  10756. }
  10757. var p = points[0];
  10758. var left = p[0];
  10759. var right = p[0];
  10760. var top = p[1];
  10761. var bottom = p[1];
  10762. var i;
  10763. for (i = 1; i < points.length; i++) {
  10764. p = points[i];
  10765. left = mathMin$3(left, p[0]);
  10766. right = mathMax$3(right, p[0]);
  10767. top = mathMin$3(top, p[1]);
  10768. bottom = mathMax$3(bottom, p[1]);
  10769. }
  10770. min$$1[0] = left;
  10771. min$$1[1] = top;
  10772. max$$1[0] = right;
  10773. max$$1[1] = bottom;
  10774. }
  10775. /**
  10776. * @memberOf module:zrender/core/bbox
  10777. * @param {number} x0
  10778. * @param {number} y0
  10779. * @param {number} x1
  10780. * @param {number} y1
  10781. * @param {Array.<number>} min
  10782. * @param {Array.<number>} max
  10783. */
  10784. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10785. min$$1[0] = mathMin$3(x0, x1);
  10786. min$$1[1] = mathMin$3(y0, y1);
  10787. max$$1[0] = mathMax$3(x0, x1);
  10788. max$$1[1] = mathMax$3(y0, y1);
  10789. }
  10790. var xDim = [];
  10791. var yDim = [];
  10792. /**
  10793. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10794. * @memberOf module:zrender/core/bbox
  10795. * @param {number} x0
  10796. * @param {number} y0
  10797. * @param {number} x1
  10798. * @param {number} y1
  10799. * @param {number} x2
  10800. * @param {number} y2
  10801. * @param {number} x3
  10802. * @param {number} y3
  10803. * @param {Array.<number>} min
  10804. * @param {Array.<number>} max
  10805. */
  10806. function fromCubic(
  10807. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10808. ) {
  10809. var cubicExtrema$$1 = cubicExtrema;
  10810. var cubicAt$$1 = cubicAt;
  10811. var i;
  10812. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10813. min$$1[0] = Infinity;
  10814. min$$1[1] = Infinity;
  10815. max$$1[0] = -Infinity;
  10816. max$$1[1] = -Infinity;
  10817. for (i = 0; i < n; i++) {
  10818. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10819. min$$1[0] = mathMin$3(x, min$$1[0]);
  10820. max$$1[0] = mathMax$3(x, max$$1[0]);
  10821. }
  10822. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10823. for (i = 0; i < n; i++) {
  10824. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10825. min$$1[1] = mathMin$3(y, min$$1[1]);
  10826. max$$1[1] = mathMax$3(y, max$$1[1]);
  10827. }
  10828. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10829. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10830. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10831. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10832. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10833. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10834. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10835. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10836. }
  10837. /**
  10838. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10839. * @memberOf module:zrender/core/bbox
  10840. * @param {number} x0
  10841. * @param {number} y0
  10842. * @param {number} x1
  10843. * @param {number} y1
  10844. * @param {number} x2
  10845. * @param {number} y2
  10846. * @param {Array.<number>} min
  10847. * @param {Array.<number>} max
  10848. */
  10849. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10850. var quadraticExtremum$$1 = quadraticExtremum;
  10851. var quadraticAt$$1 = quadraticAt;
  10852. // Find extremities, where derivative in x dim or y dim is zero
  10853. var tx =
  10854. mathMax$3(
  10855. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10856. );
  10857. var ty =
  10858. mathMax$3(
  10859. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10860. );
  10861. var x = quadraticAt$$1(x0, x1, x2, tx);
  10862. var y = quadraticAt$$1(y0, y1, y2, ty);
  10863. min$$1[0] = mathMin$3(x0, x2, x);
  10864. min$$1[1] = mathMin$3(y0, y2, y);
  10865. max$$1[0] = mathMax$3(x0, x2, x);
  10866. max$$1[1] = mathMax$3(y0, y2, y);
  10867. }
  10868. /**
  10869. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10870. * @method
  10871. * @memberOf module:zrender/core/bbox
  10872. * @param {number} x
  10873. * @param {number} y
  10874. * @param {number} rx
  10875. * @param {number} ry
  10876. * @param {number} startAngle
  10877. * @param {number} endAngle
  10878. * @param {number} anticlockwise
  10879. * @param {Array.<number>} min
  10880. * @param {Array.<number>} max
  10881. */
  10882. function fromArc(
  10883. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10884. ) {
  10885. var vec2Min = min;
  10886. var vec2Max = max;
  10887. var diff = Math.abs(startAngle - endAngle);
  10888. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10889. // Is a circle
  10890. min$$1[0] = x - rx;
  10891. min$$1[1] = y - ry;
  10892. max$$1[0] = x + rx;
  10893. max$$1[1] = y + ry;
  10894. return;
  10895. }
  10896. start[0] = mathCos$2(startAngle) * rx + x;
  10897. start[1] = mathSin$2(startAngle) * ry + y;
  10898. end[0] = mathCos$2(endAngle) * rx + x;
  10899. end[1] = mathSin$2(endAngle) * ry + y;
  10900. vec2Min(min$$1, start, end);
  10901. vec2Max(max$$1, start, end);
  10902. // Thresh to [0, Math.PI * 2]
  10903. startAngle = startAngle % (PI2);
  10904. if (startAngle < 0) {
  10905. startAngle = startAngle + PI2;
  10906. }
  10907. endAngle = endAngle % (PI2);
  10908. if (endAngle < 0) {
  10909. endAngle = endAngle + PI2;
  10910. }
  10911. if (startAngle > endAngle && !anticlockwise) {
  10912. endAngle += PI2;
  10913. }
  10914. else if (startAngle < endAngle && anticlockwise) {
  10915. startAngle += PI2;
  10916. }
  10917. if (anticlockwise) {
  10918. var tmp = endAngle;
  10919. endAngle = startAngle;
  10920. startAngle = tmp;
  10921. }
  10922. // var number = 0;
  10923. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10924. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10925. if (angle > startAngle) {
  10926. extremity[0] = mathCos$2(angle) * rx + x;
  10927. extremity[1] = mathSin$2(angle) * ry + y;
  10928. vec2Min(min$$1, extremity, min$$1);
  10929. vec2Max(max$$1, extremity, max$$1);
  10930. }
  10931. }
  10932. }
  10933. /**
  10934. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10935. * 可以用于 isInsidePath 判断以及获取boundingRect
  10936. *
  10937. * @module zrender/core/PathProxy
  10938. * @author Yi Shen (http://www.github.com/pissang)
  10939. */
  10940. // TODO getTotalLength, getPointAtLength
  10941. var CMD = {
  10942. M: 1,
  10943. L: 2,
  10944. C: 3,
  10945. Q: 4,
  10946. A: 5,
  10947. Z: 6,
  10948. // Rect
  10949. R: 7
  10950. };
  10951. // var CMD_MEM_SIZE = {
  10952. // M: 3,
  10953. // L: 3,
  10954. // C: 7,
  10955. // Q: 5,
  10956. // A: 9,
  10957. // R: 5,
  10958. // Z: 1
  10959. // };
  10960. var min$1 = [];
  10961. var max$1 = [];
  10962. var min2 = [];
  10963. var max2 = [];
  10964. var mathMin$2 = Math.min;
  10965. var mathMax$2 = Math.max;
  10966. var mathCos$1 = Math.cos;
  10967. var mathSin$1 = Math.sin;
  10968. var mathSqrt$1 = Math.sqrt;
  10969. var mathAbs = Math.abs;
  10970. var hasTypedArray = typeof Float32Array != 'undefined';
  10971. /**
  10972. * @alias module:zrender/core/PathProxy
  10973. * @constructor
  10974. */
  10975. var PathProxy = function (notSaveData) {
  10976. this._saveData = !(notSaveData || false);
  10977. if (this._saveData) {
  10978. /**
  10979. * Path data. Stored as flat array
  10980. * @type {Array.<Object>}
  10981. */
  10982. this.data = [];
  10983. }
  10984. this._ctx = null;
  10985. };
  10986. /**
  10987. * 快速计算Path包围盒(并不是最小包围盒)
  10988. * @return {Object}
  10989. */
  10990. PathProxy.prototype = {
  10991. constructor: PathProxy,
  10992. _xi: 0,
  10993. _yi: 0,
  10994. _x0: 0,
  10995. _y0: 0,
  10996. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10997. _ux: 0,
  10998. _uy: 0,
  10999. _len: 0,
  11000. _lineDash: null,
  11001. _dashOffset: 0,
  11002. _dashIdx: 0,
  11003. _dashSum: 0,
  11004. /**
  11005. * @readOnly
  11006. */
  11007. setScale: function (sx, sy) {
  11008. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11009. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11010. },
  11011. getContext: function () {
  11012. return this._ctx;
  11013. },
  11014. /**
  11015. * @param {CanvasRenderingContext2D} ctx
  11016. * @return {module:zrender/core/PathProxy}
  11017. */
  11018. beginPath: function (ctx) {
  11019. this._ctx = ctx;
  11020. ctx && ctx.beginPath();
  11021. ctx && (this.dpr = ctx.dpr);
  11022. // Reset
  11023. if (this._saveData) {
  11024. this._len = 0;
  11025. }
  11026. if (this._lineDash) {
  11027. this._lineDash = null;
  11028. this._dashOffset = 0;
  11029. }
  11030. return this;
  11031. },
  11032. /**
  11033. * @param {number} x
  11034. * @param {number} y
  11035. * @return {module:zrender/core/PathProxy}
  11036. */
  11037. moveTo: function (x, y) {
  11038. this.addData(CMD.M, x, y);
  11039. this._ctx && this._ctx.moveTo(x, y);
  11040. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11041. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11042. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11043. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11044. this._x0 = x;
  11045. this._y0 = y;
  11046. this._xi = x;
  11047. this._yi = y;
  11048. return this;
  11049. },
  11050. /**
  11051. * @param {number} x
  11052. * @param {number} y
  11053. * @return {module:zrender/core/PathProxy}
  11054. */
  11055. lineTo: function (x, y) {
  11056. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11057. || mathAbs(y - this._yi) > this._uy
  11058. // Force draw the first segment
  11059. || this._len < 5;
  11060. this.addData(CMD.L, x, y);
  11061. if (this._ctx && exceedUnit) {
  11062. this._needsDash() ? this._dashedLineTo(x, y)
  11063. : this._ctx.lineTo(x, y);
  11064. }
  11065. if (exceedUnit) {
  11066. this._xi = x;
  11067. this._yi = y;
  11068. }
  11069. return this;
  11070. },
  11071. /**
  11072. * @param {number} x1
  11073. * @param {number} y1
  11074. * @param {number} x2
  11075. * @param {number} y2
  11076. * @param {number} x3
  11077. * @param {number} y3
  11078. * @return {module:zrender/core/PathProxy}
  11079. */
  11080. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11081. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11082. if (this._ctx) {
  11083. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11084. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11085. }
  11086. this._xi = x3;
  11087. this._yi = y3;
  11088. return this;
  11089. },
  11090. /**
  11091. * @param {number} x1
  11092. * @param {number} y1
  11093. * @param {number} x2
  11094. * @param {number} y2
  11095. * @return {module:zrender/core/PathProxy}
  11096. */
  11097. quadraticCurveTo: function (x1, y1, x2, y2) {
  11098. this.addData(CMD.Q, x1, y1, x2, y2);
  11099. if (this._ctx) {
  11100. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11101. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11102. }
  11103. this._xi = x2;
  11104. this._yi = y2;
  11105. return this;
  11106. },
  11107. /**
  11108. * @param {number} cx
  11109. * @param {number} cy
  11110. * @param {number} r
  11111. * @param {number} startAngle
  11112. * @param {number} endAngle
  11113. * @param {boolean} anticlockwise
  11114. * @return {module:zrender/core/PathProxy}
  11115. */
  11116. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11117. this.addData(
  11118. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11119. );
  11120. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11121. this._xi = mathCos$1(endAngle) * r + cx;
  11122. this._yi = mathSin$1(endAngle) * r + cx;
  11123. return this;
  11124. },
  11125. // TODO
  11126. arcTo: function (x1, y1, x2, y2, radius) {
  11127. if (this._ctx) {
  11128. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11129. }
  11130. return this;
  11131. },
  11132. // TODO
  11133. rect: function (x, y, w, h) {
  11134. this._ctx && this._ctx.rect(x, y, w, h);
  11135. this.addData(CMD.R, x, y, w, h);
  11136. return this;
  11137. },
  11138. /**
  11139. * @return {module:zrender/core/PathProxy}
  11140. */
  11141. closePath: function () {
  11142. this.addData(CMD.Z);
  11143. var ctx = this._ctx;
  11144. var x0 = this._x0;
  11145. var y0 = this._y0;
  11146. if (ctx) {
  11147. this._needsDash() && this._dashedLineTo(x0, y0);
  11148. ctx.closePath();
  11149. }
  11150. this._xi = x0;
  11151. this._yi = y0;
  11152. return this;
  11153. },
  11154. /**
  11155. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11156. * stroke 同样
  11157. * @param {CanvasRenderingContext2D} ctx
  11158. * @return {module:zrender/core/PathProxy}
  11159. */
  11160. fill: function (ctx) {
  11161. ctx && ctx.fill();
  11162. this.toStatic();
  11163. },
  11164. /**
  11165. * @param {CanvasRenderingContext2D} ctx
  11166. * @return {module:zrender/core/PathProxy}
  11167. */
  11168. stroke: function (ctx) {
  11169. ctx && ctx.stroke();
  11170. this.toStatic();
  11171. },
  11172. /**
  11173. * 必须在其它绘制命令前调用
  11174. * Must be invoked before all other path drawing methods
  11175. * @return {module:zrender/core/PathProxy}
  11176. */
  11177. setLineDash: function (lineDash) {
  11178. if (lineDash instanceof Array) {
  11179. this._lineDash = lineDash;
  11180. this._dashIdx = 0;
  11181. var lineDashSum = 0;
  11182. for (var i = 0; i < lineDash.length; i++) {
  11183. lineDashSum += lineDash[i];
  11184. }
  11185. this._dashSum = lineDashSum;
  11186. }
  11187. return this;
  11188. },
  11189. /**
  11190. * 必须在其它绘制命令前调用
  11191. * Must be invoked before all other path drawing methods
  11192. * @return {module:zrender/core/PathProxy}
  11193. */
  11194. setLineDashOffset: function (offset) {
  11195. this._dashOffset = offset;
  11196. return this;
  11197. },
  11198. /**
  11199. *
  11200. * @return {boolean}
  11201. */
  11202. len: function () {
  11203. return this._len;
  11204. },
  11205. /**
  11206. * 直接设置 Path 数据
  11207. */
  11208. setData: function (data) {
  11209. var len$$1 = data.length;
  11210. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11211. this.data = new Float32Array(len$$1);
  11212. }
  11213. for (var i = 0; i < len$$1; i++) {
  11214. this.data[i] = data[i];
  11215. }
  11216. this._len = len$$1;
  11217. },
  11218. /**
  11219. * 添加子路径
  11220. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11221. */
  11222. appendPath: function (path) {
  11223. if (!(path instanceof Array)) {
  11224. path = [path];
  11225. }
  11226. var len$$1 = path.length;
  11227. var appendSize = 0;
  11228. var offset = this._len;
  11229. for (var i = 0; i < len$$1; i++) {
  11230. appendSize += path[i].len();
  11231. }
  11232. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11233. this.data = new Float32Array(offset + appendSize);
  11234. }
  11235. for (var i = 0; i < len$$1; i++) {
  11236. var appendPathData = path[i].data;
  11237. for (var k = 0; k < appendPathData.length; k++) {
  11238. this.data[offset++] = appendPathData[k];
  11239. }
  11240. }
  11241. this._len = offset;
  11242. },
  11243. /**
  11244. * 填充 Path 数据。
  11245. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11246. */
  11247. addData: function (cmd) {
  11248. if (!this._saveData) {
  11249. return;
  11250. }
  11251. var data = this.data;
  11252. if (this._len + arguments.length > data.length) {
  11253. // 因为之前的数组已经转换成静态的 Float32Array
  11254. // 所以不够用时需要扩展一个新的动态数组
  11255. this._expandData();
  11256. data = this.data;
  11257. }
  11258. for (var i = 0; i < arguments.length; i++) {
  11259. data[this._len++] = arguments[i];
  11260. }
  11261. this._prevCmd = cmd;
  11262. },
  11263. _expandData: function () {
  11264. // Only if data is Float32Array
  11265. if (!(this.data instanceof Array)) {
  11266. var newData = [];
  11267. for (var i = 0; i < this._len; i++) {
  11268. newData[i] = this.data[i];
  11269. }
  11270. this.data = newData;
  11271. }
  11272. },
  11273. /**
  11274. * If needs js implemented dashed line
  11275. * @return {boolean}
  11276. * @private
  11277. */
  11278. _needsDash: function () {
  11279. return this._lineDash;
  11280. },
  11281. _dashedLineTo: function (x1, y1) {
  11282. var dashSum = this._dashSum;
  11283. var offset = this._dashOffset;
  11284. var lineDash = this._lineDash;
  11285. var ctx = this._ctx;
  11286. var x0 = this._xi;
  11287. var y0 = this._yi;
  11288. var dx = x1 - x0;
  11289. var dy = y1 - y0;
  11290. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11291. var x = x0;
  11292. var y = y0;
  11293. var dash;
  11294. var nDash = lineDash.length;
  11295. var idx;
  11296. dx /= dist$$1;
  11297. dy /= dist$$1;
  11298. if (offset < 0) {
  11299. // Convert to positive offset
  11300. offset = dashSum + offset;
  11301. }
  11302. offset %= dashSum;
  11303. x -= offset * dx;
  11304. y -= offset * dy;
  11305. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11306. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11307. idx = this._dashIdx;
  11308. dash = lineDash[idx];
  11309. x += dx * dash;
  11310. y += dy * dash;
  11311. this._dashIdx = (idx + 1) % nDash;
  11312. // Skip positive offset
  11313. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11314. continue;
  11315. }
  11316. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11317. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11318. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11319. );
  11320. }
  11321. // Offset for next lineTo
  11322. dx = x - x1;
  11323. dy = y - y1;
  11324. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11325. },
  11326. // Not accurate dashed line to
  11327. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11328. var dashSum = this._dashSum;
  11329. var offset = this._dashOffset;
  11330. var lineDash = this._lineDash;
  11331. var ctx = this._ctx;
  11332. var x0 = this._xi;
  11333. var y0 = this._yi;
  11334. var t;
  11335. var dx;
  11336. var dy;
  11337. var cubicAt$$1 = cubicAt;
  11338. var bezierLen = 0;
  11339. var idx = this._dashIdx;
  11340. var nDash = lineDash.length;
  11341. var x;
  11342. var y;
  11343. var tmpLen = 0;
  11344. if (offset < 0) {
  11345. // Convert to positive offset
  11346. offset = dashSum + offset;
  11347. }
  11348. offset %= dashSum;
  11349. // Bezier approx length
  11350. for (t = 0; t < 1; t += 0.1) {
  11351. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11352. - cubicAt$$1(x0, x1, x2, x3, t);
  11353. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11354. - cubicAt$$1(y0, y1, y2, y3, t);
  11355. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11356. }
  11357. // Find idx after add offset
  11358. for (; idx < nDash; idx++) {
  11359. tmpLen += lineDash[idx];
  11360. if (tmpLen > offset) {
  11361. break;
  11362. }
  11363. }
  11364. t = (tmpLen - offset) / bezierLen;
  11365. while (t <= 1) {
  11366. x = cubicAt$$1(x0, x1, x2, x3, t);
  11367. y = cubicAt$$1(y0, y1, y2, y3, t);
  11368. // Use line to approximate dashed bezier
  11369. // Bad result if dash is long
  11370. idx % 2 ? ctx.moveTo(x, y)
  11371. : ctx.lineTo(x, y);
  11372. t += lineDash[idx] / bezierLen;
  11373. idx = (idx + 1) % nDash;
  11374. }
  11375. // Finish the last segment and calculate the new offset
  11376. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11377. dx = x3 - x;
  11378. dy = y3 - y;
  11379. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11380. },
  11381. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11382. // Convert quadratic to cubic using degree elevation
  11383. var x3 = x2;
  11384. var y3 = y2;
  11385. x2 = (x2 + 2 * x1) / 3;
  11386. y2 = (y2 + 2 * y1) / 3;
  11387. x1 = (this._xi + 2 * x1) / 3;
  11388. y1 = (this._yi + 2 * y1) / 3;
  11389. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11390. },
  11391. /**
  11392. * 转成静态的 Float32Array 减少堆内存占用
  11393. * Convert dynamic array to static Float32Array
  11394. */
  11395. toStatic: function () {
  11396. var data = this.data;
  11397. if (data instanceof Array) {
  11398. data.length = this._len;
  11399. if (hasTypedArray) {
  11400. this.data = new Float32Array(data);
  11401. }
  11402. }
  11403. },
  11404. /**
  11405. * @return {module:zrender/core/BoundingRect}
  11406. */
  11407. getBoundingRect: function () {
  11408. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11409. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11410. var data = this.data;
  11411. var xi = 0;
  11412. var yi = 0;
  11413. var x0 = 0;
  11414. var y0 = 0;
  11415. for (var i = 0; i < data.length;) {
  11416. var cmd = data[i++];
  11417. if (i == 1) {
  11418. // 如果第一个命令是 L, C, Q
  11419. // 则 previous point 同绘制命令的第一个 point
  11420. //
  11421. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11422. xi = data[i];
  11423. yi = data[i + 1];
  11424. x0 = xi;
  11425. y0 = yi;
  11426. }
  11427. switch (cmd) {
  11428. case CMD.M:
  11429. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11430. // 在 closePath 的时候使用
  11431. x0 = data[i++];
  11432. y0 = data[i++];
  11433. xi = x0;
  11434. yi = y0;
  11435. min2[0] = x0;
  11436. min2[1] = y0;
  11437. max2[0] = x0;
  11438. max2[1] = y0;
  11439. break;
  11440. case CMD.L:
  11441. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11442. xi = data[i++];
  11443. yi = data[i++];
  11444. break;
  11445. case CMD.C:
  11446. fromCubic(
  11447. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11448. min2, max2
  11449. );
  11450. xi = data[i++];
  11451. yi = data[i++];
  11452. break;
  11453. case CMD.Q:
  11454. fromQuadratic(
  11455. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11456. min2, max2
  11457. );
  11458. xi = data[i++];
  11459. yi = data[i++];
  11460. break;
  11461. case CMD.A:
  11462. // TODO Arc 判断的开销比较大
  11463. var cx = data[i++];
  11464. var cy = data[i++];
  11465. var rx = data[i++];
  11466. var ry = data[i++];
  11467. var startAngle = data[i++];
  11468. var endAngle = data[i++] + startAngle;
  11469. // TODO Arc 旋转
  11470. var psi = data[i++];
  11471. var anticlockwise = 1 - data[i++];
  11472. if (i == 1) {
  11473. // 直接使用 arc 命令
  11474. // 第一个命令起点还未定义
  11475. x0 = mathCos$1(startAngle) * rx + cx;
  11476. y0 = mathSin$1(startAngle) * ry + cy;
  11477. }
  11478. fromArc(
  11479. cx, cy, rx, ry, startAngle, endAngle,
  11480. anticlockwise, min2, max2
  11481. );
  11482. xi = mathCos$1(endAngle) * rx + cx;
  11483. yi = mathSin$1(endAngle) * ry + cy;
  11484. break;
  11485. case CMD.R:
  11486. x0 = xi = data[i++];
  11487. y0 = yi = data[i++];
  11488. var width = data[i++];
  11489. var height = data[i++];
  11490. // Use fromLine
  11491. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11492. break;
  11493. case CMD.Z:
  11494. xi = x0;
  11495. yi = y0;
  11496. break;
  11497. }
  11498. // Union
  11499. min(min$1, min$1, min2);
  11500. max(max$1, max$1, max2);
  11501. }
  11502. // No data
  11503. if (i === 0) {
  11504. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11505. }
  11506. return new BoundingRect(
  11507. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11508. );
  11509. },
  11510. /**
  11511. * Rebuild path from current data
  11512. * Rebuild path will not consider javascript implemented line dash.
  11513. * @param {CanvasRenderingContext2D} ctx
  11514. */
  11515. rebuildPath: function (ctx) {
  11516. var d = this.data;
  11517. var x0, y0;
  11518. var xi, yi;
  11519. var x, y;
  11520. var ux = this._ux;
  11521. var uy = this._uy;
  11522. var len$$1 = this._len;
  11523. for (var i = 0; i < len$$1;) {
  11524. var cmd = d[i++];
  11525. if (i == 1) {
  11526. // 如果第一个命令是 L, C, Q
  11527. // 则 previous point 同绘制命令的第一个 point
  11528. //
  11529. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11530. xi = d[i];
  11531. yi = d[i + 1];
  11532. x0 = xi;
  11533. y0 = yi;
  11534. }
  11535. switch (cmd) {
  11536. case CMD.M:
  11537. x0 = xi = d[i++];
  11538. y0 = yi = d[i++];
  11539. ctx.moveTo(xi, yi);
  11540. break;
  11541. case CMD.L:
  11542. x = d[i++];
  11543. y = d[i++];
  11544. // Not draw too small seg between
  11545. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11546. ctx.lineTo(x, y);
  11547. xi = x;
  11548. yi = y;
  11549. }
  11550. break;
  11551. case CMD.C:
  11552. ctx.bezierCurveTo(
  11553. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11554. );
  11555. xi = d[i - 2];
  11556. yi = d[i - 1];
  11557. break;
  11558. case CMD.Q:
  11559. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11560. xi = d[i - 2];
  11561. yi = d[i - 1];
  11562. break;
  11563. case CMD.A:
  11564. var cx = d[i++];
  11565. var cy = d[i++];
  11566. var rx = d[i++];
  11567. var ry = d[i++];
  11568. var theta = d[i++];
  11569. var dTheta = d[i++];
  11570. var psi = d[i++];
  11571. var fs = d[i++];
  11572. var r = (rx > ry) ? rx : ry;
  11573. var scaleX = (rx > ry) ? 1 : rx / ry;
  11574. var scaleY = (rx > ry) ? ry / rx : 1;
  11575. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11576. var endAngle = theta + dTheta;
  11577. if (isEllipse) {
  11578. ctx.translate(cx, cy);
  11579. ctx.rotate(psi);
  11580. ctx.scale(scaleX, scaleY);
  11581. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11582. ctx.scale(1 / scaleX, 1 / scaleY);
  11583. ctx.rotate(-psi);
  11584. ctx.translate(-cx, -cy);
  11585. }
  11586. else {
  11587. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11588. }
  11589. if (i == 1) {
  11590. // 直接使用 arc 命令
  11591. // 第一个命令起点还未定义
  11592. x0 = mathCos$1(theta) * rx + cx;
  11593. y0 = mathSin$1(theta) * ry + cy;
  11594. }
  11595. xi = mathCos$1(endAngle) * rx + cx;
  11596. yi = mathSin$1(endAngle) * ry + cy;
  11597. break;
  11598. case CMD.R:
  11599. x0 = xi = d[i];
  11600. y0 = yi = d[i + 1];
  11601. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11602. break;
  11603. case CMD.Z:
  11604. ctx.closePath();
  11605. xi = x0;
  11606. yi = y0;
  11607. }
  11608. }
  11609. }
  11610. };
  11611. PathProxy.CMD = CMD;
  11612. /**
  11613. * 线段包含判断
  11614. * @param {number} x0
  11615. * @param {number} y0
  11616. * @param {number} x1
  11617. * @param {number} y1
  11618. * @param {number} lineWidth
  11619. * @param {number} x
  11620. * @param {number} y
  11621. * @return {boolean}
  11622. */
  11623. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11624. if (lineWidth === 0) {
  11625. return false;
  11626. }
  11627. var _l = lineWidth;
  11628. var _a = 0;
  11629. var _b = x0;
  11630. // Quick reject
  11631. if (
  11632. (y > y0 + _l && y > y1 + _l)
  11633. || (y < y0 - _l && y < y1 - _l)
  11634. || (x > x0 + _l && x > x1 + _l)
  11635. || (x < x0 - _l && x < x1 - _l)
  11636. ) {
  11637. return false;
  11638. }
  11639. if (x0 !== x1) {
  11640. _a = (y0 - y1) / (x0 - x1);
  11641. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11642. }
  11643. else {
  11644. return Math.abs(x - x0) <= _l / 2;
  11645. }
  11646. var tmp = _a * x - y + _b;
  11647. var _s = tmp * tmp / (_a * _a + 1);
  11648. return _s <= _l / 2 * _l / 2;
  11649. }
  11650. /**
  11651. * 三次贝塞尔曲线描边包含判断
  11652. * @param {number} x0
  11653. * @param {number} y0
  11654. * @param {number} x1
  11655. * @param {number} y1
  11656. * @param {number} x2
  11657. * @param {number} y2
  11658. * @param {number} x3
  11659. * @param {number} y3
  11660. * @param {number} lineWidth
  11661. * @param {number} x
  11662. * @param {number} y
  11663. * @return {boolean}
  11664. */
  11665. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11666. if (lineWidth === 0) {
  11667. return false;
  11668. }
  11669. var _l = lineWidth;
  11670. // Quick reject
  11671. if (
  11672. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11673. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11674. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11675. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11676. ) {
  11677. return false;
  11678. }
  11679. var d = cubicProjectPoint(
  11680. x0, y0, x1, y1, x2, y2, x3, y3,
  11681. x, y, null
  11682. );
  11683. return d <= _l / 2;
  11684. }
  11685. /**
  11686. * 二次贝塞尔曲线描边包含判断
  11687. * @param {number} x0
  11688. * @param {number} y0
  11689. * @param {number} x1
  11690. * @param {number} y1
  11691. * @param {number} x2
  11692. * @param {number} y2
  11693. * @param {number} lineWidth
  11694. * @param {number} x
  11695. * @param {number} y
  11696. * @return {boolean}
  11697. */
  11698. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11699. if (lineWidth === 0) {
  11700. return false;
  11701. }
  11702. var _l = lineWidth;
  11703. // Quick reject
  11704. if (
  11705. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11706. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11707. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11708. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11709. ) {
  11710. return false;
  11711. }
  11712. var d = quadraticProjectPoint(
  11713. x0, y0, x1, y1, x2, y2,
  11714. x, y, null
  11715. );
  11716. return d <= _l / 2;
  11717. }
  11718. var PI2$3 = Math.PI * 2;
  11719. function normalizeRadian(angle) {
  11720. angle %= PI2$3;
  11721. if (angle < 0) {
  11722. angle += PI2$3;
  11723. }
  11724. return angle;
  11725. }
  11726. var PI2$2 = Math.PI * 2;
  11727. /**
  11728. * 圆弧描边包含判断
  11729. * @param {number} cx
  11730. * @param {number} cy
  11731. * @param {number} r
  11732. * @param {number} startAngle
  11733. * @param {number} endAngle
  11734. * @param {boolean} anticlockwise
  11735. * @param {number} lineWidth
  11736. * @param {number} x
  11737. * @param {number} y
  11738. * @return {Boolean}
  11739. */
  11740. function containStroke$4(
  11741. cx, cy, r, startAngle, endAngle, anticlockwise,
  11742. lineWidth, x, y
  11743. ) {
  11744. if (lineWidth === 0) {
  11745. return false;
  11746. }
  11747. var _l = lineWidth;
  11748. x -= cx;
  11749. y -= cy;
  11750. var d = Math.sqrt(x * x + y * y);
  11751. if ((d - _l > r) || (d + _l < r)) {
  11752. return false;
  11753. }
  11754. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11755. // Is a circle
  11756. return true;
  11757. }
  11758. if (anticlockwise) {
  11759. var tmp = startAngle;
  11760. startAngle = normalizeRadian(endAngle);
  11761. endAngle = normalizeRadian(tmp);
  11762. } else {
  11763. startAngle = normalizeRadian(startAngle);
  11764. endAngle = normalizeRadian(endAngle);
  11765. }
  11766. if (startAngle > endAngle) {
  11767. endAngle += PI2$2;
  11768. }
  11769. var angle = Math.atan2(y, x);
  11770. if (angle < 0) {
  11771. angle += PI2$2;
  11772. }
  11773. return (angle >= startAngle && angle <= endAngle)
  11774. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11775. }
  11776. function windingLine(x0, y0, x1, y1, x, y) {
  11777. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11778. return 0;
  11779. }
  11780. // Ignore horizontal line
  11781. if (y1 === y0) {
  11782. return 0;
  11783. }
  11784. var dir = y1 < y0 ? 1 : -1;
  11785. var t = (y - y0) / (y1 - y0);
  11786. // Avoid winding error when intersection point is the connect point of two line of polygon
  11787. if (t === 1 || t === 0) {
  11788. dir = y1 < y0 ? 0.5 : -0.5;
  11789. }
  11790. var x_ = t * (x1 - x0) + x0;
  11791. return x_ > x ? dir : 0;
  11792. }
  11793. var CMD$1 = PathProxy.CMD;
  11794. var PI2$1 = Math.PI * 2;
  11795. var EPSILON$2 = 1e-4;
  11796. function isAroundEqual(a, b) {
  11797. return Math.abs(a - b) < EPSILON$2;
  11798. }
  11799. // 临时数组
  11800. var roots = [-1, -1, -1];
  11801. var extrema = [-1, -1];
  11802. function swapExtrema() {
  11803. var tmp = extrema[0];
  11804. extrema[0] = extrema[1];
  11805. extrema[1] = tmp;
  11806. }
  11807. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11808. // Quick reject
  11809. if (
  11810. (y > y0 && y > y1 && y > y2 && y > y3)
  11811. || (y < y0 && y < y1 && y < y2 && y < y3)
  11812. ) {
  11813. return 0;
  11814. }
  11815. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11816. if (nRoots === 0) {
  11817. return 0;
  11818. }
  11819. else {
  11820. var w = 0;
  11821. var nExtrema = -1;
  11822. var y0_, y1_;
  11823. for (var i = 0; i < nRoots; i++) {
  11824. var t = roots[i];
  11825. // Avoid winding error when intersection point is the connect point of two line of polygon
  11826. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11827. var x_ = cubicAt(x0, x1, x2, x3, t);
  11828. if (x_ < x) { // Quick reject
  11829. continue;
  11830. }
  11831. if (nExtrema < 0) {
  11832. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11833. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11834. swapExtrema();
  11835. }
  11836. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11837. if (nExtrema > 1) {
  11838. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11839. }
  11840. }
  11841. if (nExtrema == 2) {
  11842. // 分成三段单调函数
  11843. if (t < extrema[0]) {
  11844. w += y0_ < y0 ? unit : -unit;
  11845. }
  11846. else if (t < extrema[1]) {
  11847. w += y1_ < y0_ ? unit : -unit;
  11848. }
  11849. else {
  11850. w += y3 < y1_ ? unit : -unit;
  11851. }
  11852. }
  11853. else {
  11854. // 分成两段单调函数
  11855. if (t < extrema[0]) {
  11856. w += y0_ < y0 ? unit : -unit;
  11857. }
  11858. else {
  11859. w += y3 < y0_ ? unit : -unit;
  11860. }
  11861. }
  11862. }
  11863. return w;
  11864. }
  11865. }
  11866. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11867. // Quick reject
  11868. if (
  11869. (y > y0 && y > y1 && y > y2)
  11870. || (y < y0 && y < y1 && y < y2)
  11871. ) {
  11872. return 0;
  11873. }
  11874. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11875. if (nRoots === 0) {
  11876. return 0;
  11877. }
  11878. else {
  11879. var t = quadraticExtremum(y0, y1, y2);
  11880. if (t >= 0 && t <= 1) {
  11881. var w = 0;
  11882. var y_ = quadraticAt(y0, y1, y2, t);
  11883. for (var i = 0; i < nRoots; i++) {
  11884. // Remove one endpoint.
  11885. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11886. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11887. if (x_ < x) { // Quick reject
  11888. continue;
  11889. }
  11890. if (roots[i] < t) {
  11891. w += y_ < y0 ? unit : -unit;
  11892. }
  11893. else {
  11894. w += y2 < y_ ? unit : -unit;
  11895. }
  11896. }
  11897. return w;
  11898. }
  11899. else {
  11900. // Remove one endpoint.
  11901. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11902. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11903. if (x_ < x) { // Quick reject
  11904. return 0;
  11905. }
  11906. return y2 < y0 ? unit : -unit;
  11907. }
  11908. }
  11909. }
  11910. // TODO
  11911. // Arc 旋转
  11912. function windingArc(
  11913. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11914. ) {
  11915. y -= cy;
  11916. if (y > r || y < -r) {
  11917. return 0;
  11918. }
  11919. var tmp = Math.sqrt(r * r - y * y);
  11920. roots[0] = -tmp;
  11921. roots[1] = tmp;
  11922. var diff = Math.abs(startAngle - endAngle);
  11923. if (diff < 1e-4) {
  11924. return 0;
  11925. }
  11926. if (diff % PI2$1 < 1e-4) {
  11927. // Is a circle
  11928. startAngle = 0;
  11929. endAngle = PI2$1;
  11930. var dir = anticlockwise ? 1 : -1;
  11931. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11932. return dir;
  11933. } else {
  11934. return 0;
  11935. }
  11936. }
  11937. if (anticlockwise) {
  11938. var tmp = startAngle;
  11939. startAngle = normalizeRadian(endAngle);
  11940. endAngle = normalizeRadian(tmp);
  11941. }
  11942. else {
  11943. startAngle = normalizeRadian(startAngle);
  11944. endAngle = normalizeRadian(endAngle);
  11945. }
  11946. if (startAngle > endAngle) {
  11947. endAngle += PI2$1;
  11948. }
  11949. var w = 0;
  11950. for (var i = 0; i < 2; i++) {
  11951. var x_ = roots[i];
  11952. if (x_ + cx > x) {
  11953. var angle = Math.atan2(y, x_);
  11954. var dir = anticlockwise ? 1 : -1;
  11955. if (angle < 0) {
  11956. angle = PI2$1 + angle;
  11957. }
  11958. if (
  11959. (angle >= startAngle && angle <= endAngle)
  11960. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11961. ) {
  11962. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11963. dir = -dir;
  11964. }
  11965. w += dir;
  11966. }
  11967. }
  11968. }
  11969. return w;
  11970. }
  11971. function containPath(data, lineWidth, isStroke, x, y) {
  11972. var w = 0;
  11973. var xi = 0;
  11974. var yi = 0;
  11975. var x0 = 0;
  11976. var y0 = 0;
  11977. for (var i = 0; i < data.length;) {
  11978. var cmd = data[i++];
  11979. // Begin a new subpath
  11980. if (cmd === CMD$1.M && i > 1) {
  11981. // Close previous subpath
  11982. if (!isStroke) {
  11983. w += windingLine(xi, yi, x0, y0, x, y);
  11984. }
  11985. // 如果被任何一个 subpath 包含
  11986. // if (w !== 0) {
  11987. // return true;
  11988. // }
  11989. }
  11990. if (i == 1) {
  11991. // 如果第一个命令是 L, C, Q
  11992. // 则 previous point 同绘制命令的第一个 point
  11993. //
  11994. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11995. xi = data[i];
  11996. yi = data[i + 1];
  11997. x0 = xi;
  11998. y0 = yi;
  11999. }
  12000. switch (cmd) {
  12001. case CMD$1.M:
  12002. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12003. // 在 closePath 的时候使用
  12004. x0 = data[i++];
  12005. y0 = data[i++];
  12006. xi = x0;
  12007. yi = y0;
  12008. break;
  12009. case CMD$1.L:
  12010. if (isStroke) {
  12011. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12012. return true;
  12013. }
  12014. }
  12015. else {
  12016. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12017. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12018. }
  12019. xi = data[i++];
  12020. yi = data[i++];
  12021. break;
  12022. case CMD$1.C:
  12023. if (isStroke) {
  12024. if (containStroke$2(xi, yi,
  12025. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12026. lineWidth, x, y
  12027. )) {
  12028. return true;
  12029. }
  12030. }
  12031. else {
  12032. w += windingCubic(
  12033. xi, yi,
  12034. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12035. x, y
  12036. ) || 0;
  12037. }
  12038. xi = data[i++];
  12039. yi = data[i++];
  12040. break;
  12041. case CMD$1.Q:
  12042. if (isStroke) {
  12043. if (containStroke$3(xi, yi,
  12044. data[i++], data[i++], data[i], data[i + 1],
  12045. lineWidth, x, y
  12046. )) {
  12047. return true;
  12048. }
  12049. }
  12050. else {
  12051. w += windingQuadratic(
  12052. xi, yi,
  12053. data[i++], data[i++], data[i], data[i + 1],
  12054. x, y
  12055. ) || 0;
  12056. }
  12057. xi = data[i++];
  12058. yi = data[i++];
  12059. break;
  12060. case CMD$1.A:
  12061. // TODO Arc 判断的开销比较大
  12062. var cx = data[i++];
  12063. var cy = data[i++];
  12064. var rx = data[i++];
  12065. var ry = data[i++];
  12066. var theta = data[i++];
  12067. var dTheta = data[i++];
  12068. // TODO Arc 旋转
  12069. var psi = data[i++];
  12070. var anticlockwise = 1 - data[i++];
  12071. var x1 = Math.cos(theta) * rx + cx;
  12072. var y1 = Math.sin(theta) * ry + cy;
  12073. // 不是直接使用 arc 命令
  12074. if (i > 1) {
  12075. w += windingLine(xi, yi, x1, y1, x, y);
  12076. }
  12077. else {
  12078. // 第一个命令起点还未定义
  12079. x0 = x1;
  12080. y0 = y1;
  12081. }
  12082. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12083. var _x = (x - cx) * ry / rx + cx;
  12084. if (isStroke) {
  12085. if (containStroke$4(
  12086. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12087. lineWidth, _x, y
  12088. )) {
  12089. return true;
  12090. }
  12091. }
  12092. else {
  12093. w += windingArc(
  12094. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12095. _x, y
  12096. );
  12097. }
  12098. xi = Math.cos(theta + dTheta) * rx + cx;
  12099. yi = Math.sin(theta + dTheta) * ry + cy;
  12100. break;
  12101. case CMD$1.R:
  12102. x0 = xi = data[i++];
  12103. y0 = yi = data[i++];
  12104. var width = data[i++];
  12105. var height = data[i++];
  12106. var x1 = x0 + width;
  12107. var y1 = y0 + height;
  12108. if (isStroke) {
  12109. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12110. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12111. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12112. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12113. ) {
  12114. return true;
  12115. }
  12116. }
  12117. else {
  12118. // FIXME Clockwise ?
  12119. w += windingLine(x1, y0, x1, y1, x, y);
  12120. w += windingLine(x0, y1, x0, y0, x, y);
  12121. }
  12122. break;
  12123. case CMD$1.Z:
  12124. if (isStroke) {
  12125. if (containStroke$1(
  12126. xi, yi, x0, y0, lineWidth, x, y
  12127. )) {
  12128. return true;
  12129. }
  12130. }
  12131. else {
  12132. // Close a subpath
  12133. w += windingLine(xi, yi, x0, y0, x, y);
  12134. // 如果被任何一个 subpath 包含
  12135. // FIXME subpaths may overlap
  12136. // if (w !== 0) {
  12137. // return true;
  12138. // }
  12139. }
  12140. xi = x0;
  12141. yi = y0;
  12142. break;
  12143. }
  12144. }
  12145. if (!isStroke && !isAroundEqual(yi, y0)) {
  12146. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12147. }
  12148. return w !== 0;
  12149. }
  12150. function contain(pathData, x, y) {
  12151. return containPath(pathData, 0, false, x, y);
  12152. }
  12153. function containStroke(pathData, lineWidth, x, y) {
  12154. return containPath(pathData, lineWidth, true, x, y);
  12155. }
  12156. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12157. var abs = Math.abs;
  12158. var pathProxyForDraw = new PathProxy(true);
  12159. /**
  12160. * @alias module:zrender/graphic/Path
  12161. * @extends module:zrender/graphic/Displayable
  12162. * @constructor
  12163. * @param {Object} opts
  12164. */
  12165. function Path(opts) {
  12166. Displayable.call(this, opts);
  12167. /**
  12168. * @type {module:zrender/core/PathProxy}
  12169. * @readOnly
  12170. */
  12171. this.path = null;
  12172. }
  12173. Path.prototype = {
  12174. constructor: Path,
  12175. type: 'path',
  12176. __dirtyPath: true,
  12177. strokeContainThreshold: 5,
  12178. brush: function (ctx, prevEl) {
  12179. var style = this.style;
  12180. var path = this.path || pathProxyForDraw;
  12181. var hasStroke = style.hasStroke();
  12182. var hasFill = style.hasFill();
  12183. var fill = style.fill;
  12184. var stroke = style.stroke;
  12185. var hasFillGradient = hasFill && !!(fill.colorStops);
  12186. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12187. var hasFillPattern = hasFill && !!(fill.image);
  12188. var hasStrokePattern = hasStroke && !!(stroke.image);
  12189. style.bind(ctx, this, prevEl);
  12190. this.setTransform(ctx);
  12191. if (this.__dirty) {
  12192. var rect;
  12193. // Update gradient because bounding rect may changed
  12194. if (hasFillGradient) {
  12195. rect = rect || this.getBoundingRect();
  12196. this._fillGradient = style.getGradient(ctx, fill, rect);
  12197. }
  12198. if (hasStrokeGradient) {
  12199. rect = rect || this.getBoundingRect();
  12200. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12201. }
  12202. }
  12203. // Use the gradient or pattern
  12204. if (hasFillGradient) {
  12205. // PENDING If may have affect the state
  12206. ctx.fillStyle = this._fillGradient;
  12207. }
  12208. else if (hasFillPattern) {
  12209. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12210. }
  12211. if (hasStrokeGradient) {
  12212. ctx.strokeStyle = this._strokeGradient;
  12213. }
  12214. else if (hasStrokePattern) {
  12215. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12216. }
  12217. var lineDash = style.lineDash;
  12218. var lineDashOffset = style.lineDashOffset;
  12219. var ctxLineDash = !!ctx.setLineDash;
  12220. // Update path sx, sy
  12221. var scale = this.getGlobalScale();
  12222. path.setScale(scale[0], scale[1]);
  12223. // Proxy context
  12224. // Rebuild path in following 2 cases
  12225. // 1. Path is dirty
  12226. // 2. Path needs javascript implemented lineDash stroking.
  12227. // In this case, lineDash information will not be saved in PathProxy
  12228. if (this.__dirtyPath
  12229. || (lineDash && !ctxLineDash && hasStroke)
  12230. ) {
  12231. path.beginPath(ctx);
  12232. // Setting line dash before build path
  12233. if (lineDash && !ctxLineDash) {
  12234. path.setLineDash(lineDash);
  12235. path.setLineDashOffset(lineDashOffset);
  12236. }
  12237. this.buildPath(path, this.shape, false);
  12238. // Clear path dirty flag
  12239. if (this.path) {
  12240. this.__dirtyPath = false;
  12241. }
  12242. }
  12243. else {
  12244. // Replay path building
  12245. ctx.beginPath();
  12246. this.path.rebuildPath(ctx);
  12247. }
  12248. hasFill && path.fill(ctx);
  12249. if (lineDash && ctxLineDash) {
  12250. ctx.setLineDash(lineDash);
  12251. ctx.lineDashOffset = lineDashOffset;
  12252. }
  12253. hasStroke && path.stroke(ctx);
  12254. if (lineDash && ctxLineDash) {
  12255. // PENDING
  12256. // Remove lineDash
  12257. ctx.setLineDash([]);
  12258. }
  12259. this.restoreTransform(ctx);
  12260. // Draw rect text
  12261. if (style.text != null) {
  12262. this.drawRectText(ctx, this.getBoundingRect());
  12263. }
  12264. },
  12265. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12266. // Like in circle
  12267. buildPath: function (ctx, shapeCfg, inBundle) {},
  12268. createPathProxy: function () {
  12269. this.path = new PathProxy();
  12270. },
  12271. getBoundingRect: function () {
  12272. var rect = this._rect;
  12273. var style = this.style;
  12274. var needsUpdateRect = !rect;
  12275. if (needsUpdateRect) {
  12276. var path = this.path;
  12277. if (!path) {
  12278. // Create path on demand.
  12279. path = this.path = new PathProxy();
  12280. }
  12281. if (this.__dirtyPath) {
  12282. path.beginPath();
  12283. this.buildPath(path, this.shape, false);
  12284. }
  12285. rect = path.getBoundingRect();
  12286. }
  12287. this._rect = rect;
  12288. if (style.hasStroke()) {
  12289. // Needs update rect with stroke lineWidth when
  12290. // 1. Element changes scale or lineWidth
  12291. // 2. Shape is changed
  12292. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12293. if (this.__dirty || needsUpdateRect) {
  12294. rectWithStroke.copy(rect);
  12295. // FIXME Must after updateTransform
  12296. var w = style.lineWidth;
  12297. // PENDING, Min line width is needed when line is horizontal or vertical
  12298. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12299. // Only add extra hover lineWidth when there are no fill
  12300. if (!style.hasFill()) {
  12301. w = Math.max(w, this.strokeContainThreshold || 4);
  12302. }
  12303. // Consider line width
  12304. // Line scale can't be 0;
  12305. if (lineScale > 1e-10) {
  12306. rectWithStroke.width += w / lineScale;
  12307. rectWithStroke.height += w / lineScale;
  12308. rectWithStroke.x -= w / lineScale / 2;
  12309. rectWithStroke.y -= w / lineScale / 2;
  12310. }
  12311. }
  12312. // Return rect with stroke
  12313. return rectWithStroke;
  12314. }
  12315. return rect;
  12316. },
  12317. contain: function (x, y) {
  12318. var localPos = this.transformCoordToLocal(x, y);
  12319. var rect = this.getBoundingRect();
  12320. var style = this.style;
  12321. x = localPos[0];
  12322. y = localPos[1];
  12323. if (rect.contain(x, y)) {
  12324. var pathData = this.path.data;
  12325. if (style.hasStroke()) {
  12326. var lineWidth = style.lineWidth;
  12327. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12328. // Line scale can't be 0;
  12329. if (lineScale > 1e-10) {
  12330. // Only add extra hover lineWidth when there are no fill
  12331. if (!style.hasFill()) {
  12332. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12333. }
  12334. if (containStroke(
  12335. pathData, lineWidth / lineScale, x, y
  12336. )) {
  12337. return true;
  12338. }
  12339. }
  12340. }
  12341. if (style.hasFill()) {
  12342. return contain(pathData, x, y);
  12343. }
  12344. }
  12345. return false;
  12346. },
  12347. /**
  12348. * @param {boolean} dirtyPath
  12349. */
  12350. dirty: function (dirtyPath) {
  12351. if (dirtyPath == null) {
  12352. dirtyPath = true;
  12353. }
  12354. // Only mark dirty, not mark clean
  12355. if (dirtyPath) {
  12356. this.__dirtyPath = dirtyPath;
  12357. this._rect = null;
  12358. }
  12359. this.__dirty = true;
  12360. this.__zr && this.__zr.refresh();
  12361. // Used as a clipping path
  12362. if (this.__clipTarget) {
  12363. this.__clipTarget.dirty();
  12364. }
  12365. },
  12366. /**
  12367. * Alias for animate('shape')
  12368. * @param {boolean} loop
  12369. */
  12370. animateShape: function (loop) {
  12371. return this.animate('shape', loop);
  12372. },
  12373. // Overwrite attrKV
  12374. attrKV: function (key, value) {
  12375. // FIXME
  12376. if (key === 'shape') {
  12377. this.setShape(value);
  12378. this.__dirtyPath = true;
  12379. this._rect = null;
  12380. }
  12381. else {
  12382. Displayable.prototype.attrKV.call(this, key, value);
  12383. }
  12384. },
  12385. /**
  12386. * @param {Object|string} key
  12387. * @param {*} value
  12388. */
  12389. setShape: function (key, value) {
  12390. var shape = this.shape;
  12391. // Path from string may not have shape
  12392. if (shape) {
  12393. if (isObject(key)) {
  12394. for (var name in key) {
  12395. if (key.hasOwnProperty(name)) {
  12396. shape[name] = key[name];
  12397. }
  12398. }
  12399. }
  12400. else {
  12401. shape[key] = value;
  12402. }
  12403. this.dirty(true);
  12404. }
  12405. return this;
  12406. },
  12407. getLineScale: function () {
  12408. var m = this.transform;
  12409. // Get the line scale.
  12410. // Determinant of `m` means how much the area is enlarged by the
  12411. // transformation. So its square root can be used as a scale factor
  12412. // for width.
  12413. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12414. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12415. : 1;
  12416. }
  12417. };
  12418. /**
  12419. * 扩展一个 Path element, 比如星形,圆等。
  12420. * Extend a path element
  12421. * @param {Object} props
  12422. * @param {string} props.type Path type
  12423. * @param {Function} props.init Initialize
  12424. * @param {Function} props.buildPath Overwrite buildPath method
  12425. * @param {Object} [props.style] Extended default style config
  12426. * @param {Object} [props.shape] Extended default shape config
  12427. */
  12428. Path.extend = function (defaults$$1) {
  12429. var Sub = function (opts) {
  12430. Path.call(this, opts);
  12431. if (defaults$$1.style) {
  12432. // Extend default style
  12433. this.style.extendFrom(defaults$$1.style, false);
  12434. }
  12435. // Extend default shape
  12436. var defaultShape = defaults$$1.shape;
  12437. if (defaultShape) {
  12438. this.shape = this.shape || {};
  12439. var thisShape = this.shape;
  12440. for (var name in defaultShape) {
  12441. if (
  12442. ! thisShape.hasOwnProperty(name)
  12443. && defaultShape.hasOwnProperty(name)
  12444. ) {
  12445. thisShape[name] = defaultShape[name];
  12446. }
  12447. }
  12448. }
  12449. defaults$$1.init && defaults$$1.init.call(this, opts);
  12450. };
  12451. inherits(Sub, Path);
  12452. // FIXME 不能 extend position, rotation 等引用对象
  12453. for (var name in defaults$$1) {
  12454. // Extending prototype values and methods
  12455. if (name !== 'style' && name !== 'shape') {
  12456. Sub.prototype[name] = defaults$$1[name];
  12457. }
  12458. }
  12459. return Sub;
  12460. };
  12461. inherits(Path, Displayable);
  12462. var CMD$2 = PathProxy.CMD;
  12463. var points = [[], [], []];
  12464. var mathSqrt$3 = Math.sqrt;
  12465. var mathAtan2 = Math.atan2;
  12466. var transformPath = function (path, m) {
  12467. var data = path.data;
  12468. var cmd;
  12469. var nPoint;
  12470. var i;
  12471. var j;
  12472. var k;
  12473. var p;
  12474. var M = CMD$2.M;
  12475. var C = CMD$2.C;
  12476. var L = CMD$2.L;
  12477. var R = CMD$2.R;
  12478. var A = CMD$2.A;
  12479. var Q = CMD$2.Q;
  12480. for (i = 0, j = 0; i < data.length;) {
  12481. cmd = data[i++];
  12482. j = i;
  12483. nPoint = 0;
  12484. switch (cmd) {
  12485. case M:
  12486. nPoint = 1;
  12487. break;
  12488. case L:
  12489. nPoint = 1;
  12490. break;
  12491. case C:
  12492. nPoint = 3;
  12493. break;
  12494. case Q:
  12495. nPoint = 2;
  12496. break;
  12497. case A:
  12498. var x = m[4];
  12499. var y = m[5];
  12500. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12501. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12502. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12503. // cx
  12504. data[i] *= sx;
  12505. data[i++] += x;
  12506. // cy
  12507. data[i] *= sy;
  12508. data[i++] += y;
  12509. // Scale rx and ry
  12510. // FIXME Assume psi is 0 here
  12511. data[i++] *= sx;
  12512. data[i++] *= sy;
  12513. // Start angle
  12514. data[i++] += angle;
  12515. // end angle
  12516. data[i++] += angle;
  12517. // FIXME psi
  12518. i += 2;
  12519. j = i;
  12520. break;
  12521. case R:
  12522. // x0, y0
  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. // x1, y1
  12529. p[0] += data[i++];
  12530. p[1] += data[i++];
  12531. applyTransform(p, p, m);
  12532. data[j++] = p[0];
  12533. data[j++] = p[1];
  12534. }
  12535. for (k = 0; k < nPoint; k++) {
  12536. var p = points[k];
  12537. p[0] = data[i++];
  12538. p[1] = data[i++];
  12539. applyTransform(p, p, m);
  12540. // Write back
  12541. data[j++] = p[0];
  12542. data[j++] = p[1];
  12543. }
  12544. }
  12545. };
  12546. // command chars
  12547. var cc = [
  12548. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12549. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12550. ];
  12551. var mathSqrt = Math.sqrt;
  12552. var mathSin = Math.sin;
  12553. var mathCos = Math.cos;
  12554. var PI = Math.PI;
  12555. var vMag = function(v) {
  12556. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12557. };
  12558. var vRatio = function(u, v) {
  12559. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12560. };
  12561. var vAngle = function(u, v) {
  12562. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12563. * Math.acos(vRatio(u, v));
  12564. };
  12565. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12566. var psi = psiDeg * (PI / 180.0);
  12567. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12568. + mathSin(psi) * (y1 - y2) / 2.0;
  12569. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12570. + mathCos(psi) * (y1 - y2) / 2.0;
  12571. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12572. if (lambda > 1) {
  12573. rx *= mathSqrt(lambda);
  12574. ry *= mathSqrt(lambda);
  12575. }
  12576. var f = (fa === fs ? -1 : 1)
  12577. * mathSqrt((((rx * rx) * (ry * ry))
  12578. - ((rx * rx) * (yp * yp))
  12579. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12580. + (ry * ry) * (xp * xp))
  12581. ) || 0;
  12582. var cxp = f * rx * yp / ry;
  12583. var cyp = f * -ry * xp / rx;
  12584. var cx = (x1 + x2) / 2.0
  12585. + mathCos(psi) * cxp
  12586. - mathSin(psi) * cyp;
  12587. var cy = (y1 + y2) / 2.0
  12588. + mathSin(psi) * cxp
  12589. + mathCos(psi) * cyp;
  12590. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12591. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12592. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12593. var dTheta = vAngle(u, v);
  12594. if (vRatio(u, v) <= -1) {
  12595. dTheta = PI;
  12596. }
  12597. if (vRatio(u, v) >= 1) {
  12598. dTheta = 0;
  12599. }
  12600. if (fs === 0 && dTheta > 0) {
  12601. dTheta = dTheta - 2 * PI;
  12602. }
  12603. if (fs === 1 && dTheta < 0) {
  12604. dTheta = dTheta + 2 * PI;
  12605. }
  12606. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12607. }
  12608. function createPathProxyFromString(data) {
  12609. if (!data) {
  12610. return [];
  12611. }
  12612. // command string
  12613. var cs = data.replace(/-/g, ' -')
  12614. .replace(/ /g, ' ')
  12615. .replace(/ /g, ',')
  12616. .replace(/,,/g, ',');
  12617. var n;
  12618. // create pipes so that we can split the data
  12619. for (n = 0; n < cc.length; n++) {
  12620. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12621. }
  12622. // create array
  12623. var arr = cs.split('|');
  12624. // init context point
  12625. var cpx = 0;
  12626. var cpy = 0;
  12627. var path = new PathProxy();
  12628. var CMD = PathProxy.CMD;
  12629. var prevCmd;
  12630. for (n = 1; n < arr.length; n++) {
  12631. var str = arr[n];
  12632. var c = str.charAt(0);
  12633. var off = 0;
  12634. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12635. var cmd;
  12636. if (p.length > 0 && p[0] === '') {
  12637. p.shift();
  12638. }
  12639. for (var i = 0; i < p.length; i++) {
  12640. p[i] = parseFloat(p[i]);
  12641. }
  12642. while (off < p.length && !isNaN(p[off])) {
  12643. if (isNaN(p[0])) {
  12644. break;
  12645. }
  12646. var ctlPtx;
  12647. var ctlPty;
  12648. var rx;
  12649. var ry;
  12650. var psi;
  12651. var fa;
  12652. var fs;
  12653. var x1 = cpx;
  12654. var y1 = cpy;
  12655. // convert l, H, h, V, and v to L
  12656. switch (c) {
  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 'L':
  12664. cpx = p[off++];
  12665. cpy = p[off++];
  12666. cmd = CMD.L;
  12667. path.addData(cmd, cpx, cpy);
  12668. break;
  12669. case 'm':
  12670. cpx += p[off++];
  12671. cpy += p[off++];
  12672. cmd = CMD.M;
  12673. path.addData(cmd, cpx, cpy);
  12674. c = 'l';
  12675. break;
  12676. case 'M':
  12677. cpx = p[off++];
  12678. cpy = p[off++];
  12679. cmd = CMD.M;
  12680. path.addData(cmd, cpx, cpy);
  12681. c = 'L';
  12682. break;
  12683. case 'h':
  12684. cpx += p[off++];
  12685. cmd = CMD.L;
  12686. path.addData(cmd, cpx, cpy);
  12687. break;
  12688. case 'H':
  12689. cpx = p[off++];
  12690. cmd = CMD.L;
  12691. path.addData(cmd, cpx, cpy);
  12692. break;
  12693. case 'v':
  12694. cpy += p[off++];
  12695. cmd = CMD.L;
  12696. path.addData(cmd, cpx, cpy);
  12697. break;
  12698. case 'V':
  12699. cpy = p[off++];
  12700. cmd = CMD.L;
  12701. path.addData(cmd, cpx, cpy);
  12702. break;
  12703. case 'C':
  12704. cmd = CMD.C;
  12705. path.addData(
  12706. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12707. );
  12708. cpx = p[off - 2];
  12709. cpy = p[off - 1];
  12710. break;
  12711. case 'c':
  12712. cmd = CMD.C;
  12713. path.addData(
  12714. cmd,
  12715. p[off++] + cpx, p[off++] + cpy,
  12716. p[off++] + cpx, p[off++] + cpy,
  12717. p[off++] + cpx, p[off++] + cpy
  12718. );
  12719. cpx += p[off - 2];
  12720. cpy += p[off - 1];
  12721. break;
  12722. case 'S':
  12723. ctlPtx = cpx;
  12724. ctlPty = cpy;
  12725. var len = path.len();
  12726. var pathData = path.data;
  12727. if (prevCmd === CMD.C) {
  12728. ctlPtx += cpx - pathData[len - 4];
  12729. ctlPty += cpy - pathData[len - 3];
  12730. }
  12731. cmd = CMD.C;
  12732. x1 = p[off++];
  12733. y1 = p[off++];
  12734. cpx = p[off++];
  12735. cpy = p[off++];
  12736. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12737. break;
  12738. case 's':
  12739. ctlPtx = cpx;
  12740. ctlPty = cpy;
  12741. var len = path.len();
  12742. var pathData = path.data;
  12743. if (prevCmd === CMD.C) {
  12744. ctlPtx += cpx - pathData[len - 4];
  12745. ctlPty += cpy - pathData[len - 3];
  12746. }
  12747. cmd = CMD.C;
  12748. x1 = cpx + p[off++];
  12749. y1 = cpy + p[off++];
  12750. cpx += p[off++];
  12751. cpy += p[off++];
  12752. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12753. break;
  12754. case 'Q':
  12755. x1 = p[off++];
  12756. y1 = p[off++];
  12757. cpx = p[off++];
  12758. cpy = p[off++];
  12759. cmd = CMD.Q;
  12760. path.addData(cmd, x1, y1, cpx, cpy);
  12761. break;
  12762. case 'q':
  12763. x1 = p[off++] + cpx;
  12764. y1 = p[off++] + cpy;
  12765. cpx += p[off++];
  12766. cpy += p[off++];
  12767. cmd = CMD.Q;
  12768. path.addData(cmd, x1, y1, cpx, cpy);
  12769. break;
  12770. case 'T':
  12771. ctlPtx = cpx;
  12772. ctlPty = cpy;
  12773. var len = path.len();
  12774. var pathData = path.data;
  12775. if (prevCmd === CMD.Q) {
  12776. ctlPtx += cpx - pathData[len - 4];
  12777. ctlPty += cpy - pathData[len - 3];
  12778. }
  12779. cpx = p[off++];
  12780. cpy = p[off++];
  12781. cmd = CMD.Q;
  12782. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12783. break;
  12784. case 't':
  12785. ctlPtx = cpx;
  12786. ctlPty = cpy;
  12787. var len = path.len();
  12788. var pathData = path.data;
  12789. if (prevCmd === CMD.Q) {
  12790. ctlPtx += cpx - pathData[len - 4];
  12791. ctlPty += cpy - pathData[len - 3];
  12792. }
  12793. cpx += p[off++];
  12794. cpy += p[off++];
  12795. cmd = CMD.Q;
  12796. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12797. break;
  12798. case 'A':
  12799. rx = p[off++];
  12800. ry = p[off++];
  12801. psi = p[off++];
  12802. fa = p[off++];
  12803. fs = p[off++];
  12804. x1 = cpx, y1 = cpy;
  12805. cpx = p[off++];
  12806. cpy = p[off++];
  12807. cmd = CMD.A;
  12808. processArc(
  12809. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12810. );
  12811. break;
  12812. case 'a':
  12813. rx = p[off++];
  12814. ry = p[off++];
  12815. psi = p[off++];
  12816. fa = p[off++];
  12817. fs = p[off++];
  12818. x1 = cpx, y1 = cpy;
  12819. cpx += p[off++];
  12820. cpy += p[off++];
  12821. cmd = CMD.A;
  12822. processArc(
  12823. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12824. );
  12825. break;
  12826. }
  12827. }
  12828. if (c === 'z' || c === 'Z') {
  12829. cmd = CMD.Z;
  12830. path.addData(cmd);
  12831. }
  12832. prevCmd = cmd;
  12833. }
  12834. path.toStatic();
  12835. return path;
  12836. }
  12837. // TODO Optimize double memory cost problem
  12838. function createPathOptions(str, opts) {
  12839. var pathProxy = createPathProxyFromString(str);
  12840. opts = opts || {};
  12841. opts.buildPath = function (path) {
  12842. if (path.setData) {
  12843. path.setData(pathProxy.data);
  12844. // Svg and vml renderer don't have context
  12845. var ctx = path.getContext();
  12846. if (ctx) {
  12847. path.rebuildPath(ctx);
  12848. }
  12849. }
  12850. else {
  12851. var ctx = path;
  12852. pathProxy.rebuildPath(ctx);
  12853. }
  12854. };
  12855. opts.applyTransform = function (m) {
  12856. transformPath(pathProxy, m);
  12857. this.dirty(true);
  12858. };
  12859. return opts;
  12860. }
  12861. /**
  12862. * Create a Path object from path string data
  12863. * http://www.w3.org/TR/SVG/paths.html#PathData
  12864. * @param {Object} opts Other options
  12865. */
  12866. function createFromString(str, opts) {
  12867. return new Path(createPathOptions(str, opts));
  12868. }
  12869. /**
  12870. * Create a Path class from path string data
  12871. * @param {string} str
  12872. * @param {Object} opts Other options
  12873. */
  12874. function extendFromString(str, opts) {
  12875. return Path.extend(createPathOptions(str, opts));
  12876. }
  12877. /**
  12878. * Merge multiple paths
  12879. */
  12880. // TODO Apply transform
  12881. // TODO stroke dash
  12882. // TODO Optimize double memory cost problem
  12883. function mergePath$1(pathEls, opts) {
  12884. var pathList = [];
  12885. var len = pathEls.length;
  12886. for (var i = 0; i < len; i++) {
  12887. var pathEl = pathEls[i];
  12888. if (!pathEl.path) {
  12889. pathEl.createPathProxy();
  12890. }
  12891. if (pathEl.__dirtyPath) {
  12892. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12893. }
  12894. pathList.push(pathEl.path);
  12895. }
  12896. var pathBundle = new Path(opts);
  12897. // Need path proxy.
  12898. pathBundle.createPathProxy();
  12899. pathBundle.buildPath = function (path) {
  12900. path.appendPath(pathList);
  12901. // Svg and vml renderer don't have context
  12902. var ctx = path.getContext();
  12903. if (ctx) {
  12904. path.rebuildPath(ctx);
  12905. }
  12906. };
  12907. return pathBundle;
  12908. }
  12909. /**
  12910. * @alias zrender/graphic/Text
  12911. * @extends module:zrender/graphic/Displayable
  12912. * @constructor
  12913. * @param {Object} opts
  12914. */
  12915. var Text = function (opts) { // jshint ignore:line
  12916. Displayable.call(this, opts);
  12917. };
  12918. Text.prototype = {
  12919. constructor: Text,
  12920. type: 'text',
  12921. brush: function (ctx, prevEl) {
  12922. var style = this.style;
  12923. // Optimize, avoid normalize every time.
  12924. this.__dirty && normalizeTextStyle(style, true);
  12925. // Use props with prefix 'text'.
  12926. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12927. style.shadowOffsetX = style.shadowOffsetY = null;
  12928. var text = style.text;
  12929. // Convert to string
  12930. text != null && (text += '');
  12931. // Always bind style
  12932. style.bind(ctx, this, prevEl);
  12933. if (!needDrawText(text, style)) {
  12934. return;
  12935. }
  12936. this.setTransform(ctx);
  12937. renderText(this, ctx, text, style);
  12938. this.restoreTransform(ctx);
  12939. },
  12940. getBoundingRect: function () {
  12941. var style = this.style;
  12942. // Optimize, avoid normalize every time.
  12943. this.__dirty && normalizeTextStyle(style, true);
  12944. if (!this._rect) {
  12945. var text = style.text;
  12946. text != null ? (text += '') : (text = '');
  12947. var rect = getBoundingRect(
  12948. style.text + '',
  12949. style.font,
  12950. style.textAlign,
  12951. style.textVerticalAlign,
  12952. style.textPadding,
  12953. style.rich
  12954. );
  12955. rect.x += style.x || 0;
  12956. rect.y += style.y || 0;
  12957. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12958. var w = style.textStrokeWidth;
  12959. rect.x -= w / 2;
  12960. rect.y -= w / 2;
  12961. rect.width += w;
  12962. rect.height += w;
  12963. }
  12964. this._rect = rect;
  12965. }
  12966. return this._rect;
  12967. }
  12968. };
  12969. inherits(Text, Displayable);
  12970. /**
  12971. * 圆形
  12972. * @module zrender/shape/Circle
  12973. */
  12974. var Circle = Path.extend({
  12975. type: 'circle',
  12976. shape: {
  12977. cx: 0,
  12978. cy: 0,
  12979. r: 0
  12980. },
  12981. buildPath : function (ctx, shape, inBundle) {
  12982. // Better stroking in ShapeBundle
  12983. // Always do it may have performence issue ( fill may be 2x more cost)
  12984. if (inBundle) {
  12985. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12986. }
  12987. // else {
  12988. // if (ctx.allocate && !ctx.data.length) {
  12989. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12990. // }
  12991. // }
  12992. // Better stroking in ShapeBundle
  12993. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12994. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12995. }
  12996. });
  12997. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12998. // where exception "unexpected call to method or property access"
  12999. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13000. // whose area size is zero is drawn and ctx.clip() is called and
  13001. // shadowBlur is set. See #4572, #3112, #5777.
  13002. // (e.g.,
  13003. // ctx.moveTo(10, 10);
  13004. // ctx.lineTo(20, 10);
  13005. // ctx.closePath();
  13006. // ctx.clip();
  13007. // ctx.shadowBlur = 10;
  13008. // ...
  13009. // ctx.fill();
  13010. // )
  13011. var shadowTemp = [
  13012. ['shadowBlur', 0],
  13013. ['shadowColor', '#000'],
  13014. ['shadowOffsetX', 0],
  13015. ['shadowOffsetY', 0]
  13016. ];
  13017. var fixClipWithShadow = function (orignalBrush) {
  13018. // version string can be: '11.0'
  13019. return (env$1.browser.ie && env$1.browser.version >= 11)
  13020. ? function () {
  13021. var clipPaths = this.__clipPaths;
  13022. var style = this.style;
  13023. var modified;
  13024. if (clipPaths) {
  13025. for (var i = 0; i < clipPaths.length; i++) {
  13026. var clipPath = clipPaths[i];
  13027. var shape = clipPath && clipPath.shape;
  13028. var type = clipPath && clipPath.type;
  13029. if (shape && (
  13030. (type === 'sector' && shape.startAngle === shape.endAngle)
  13031. || (type === 'rect' && (!shape.width || !shape.height))
  13032. )) {
  13033. for (var j = 0; j < shadowTemp.length; j++) {
  13034. // It is save to put shadowTemp static, because shadowTemp
  13035. // will be all modified each item brush called.
  13036. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13037. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13038. }
  13039. modified = true;
  13040. break;
  13041. }
  13042. }
  13043. }
  13044. orignalBrush.apply(this, arguments);
  13045. if (modified) {
  13046. for (var j = 0; j < shadowTemp.length; j++) {
  13047. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13048. }
  13049. }
  13050. }
  13051. : orignalBrush;
  13052. };
  13053. /**
  13054. * 扇形
  13055. * @module zrender/graphic/shape/Sector
  13056. */
  13057. var Sector = Path.extend({
  13058. type: 'sector',
  13059. shape: {
  13060. cx: 0,
  13061. cy: 0,
  13062. r0: 0,
  13063. r: 0,
  13064. startAngle: 0,
  13065. endAngle: Math.PI * 2,
  13066. clockwise: true
  13067. },
  13068. brush: fixClipWithShadow(Path.prototype.brush),
  13069. buildPath: function (ctx, shape) {
  13070. var x = shape.cx;
  13071. var y = shape.cy;
  13072. var r0 = Math.max(shape.r0 || 0, 0);
  13073. var r = Math.max(shape.r, 0);
  13074. var startAngle = shape.startAngle;
  13075. var endAngle = shape.endAngle;
  13076. var clockwise = shape.clockwise;
  13077. var unitX = Math.cos(startAngle);
  13078. var unitY = Math.sin(startAngle);
  13079. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13080. ctx.lineTo(unitX * r + x, unitY * r + y);
  13081. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13082. ctx.lineTo(
  13083. Math.cos(endAngle) * r0 + x,
  13084. Math.sin(endAngle) * r0 + y
  13085. );
  13086. if (r0 !== 0) {
  13087. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13088. }
  13089. ctx.closePath();
  13090. }
  13091. });
  13092. /**
  13093. * 圆环
  13094. * @module zrender/graphic/shape/Ring
  13095. */
  13096. var Ring = Path.extend({
  13097. type: 'ring',
  13098. shape: {
  13099. cx: 0,
  13100. cy: 0,
  13101. r: 0,
  13102. r0: 0
  13103. },
  13104. buildPath: function (ctx, shape) {
  13105. var x = shape.cx;
  13106. var y = shape.cy;
  13107. var PI2 = Math.PI * 2;
  13108. ctx.moveTo(x + shape.r, y);
  13109. ctx.arc(x, y, shape.r, 0, PI2, false);
  13110. ctx.moveTo(x + shape.r0, y);
  13111. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13112. }
  13113. });
  13114. /**
  13115. * Catmull-Rom spline 插值折线
  13116. * @module zrender/shape/util/smoothSpline
  13117. * @author pissang (https://www.github.com/pissang)
  13118. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13119. * errorrik (errorrik@gmail.com)
  13120. */
  13121. /**
  13122. * @inner
  13123. */
  13124. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13125. var v0 = (p2 - p0) * 0.5;
  13126. var v1 = (p3 - p1) * 0.5;
  13127. return (2 * (p1 - p2) + v0 + v1) * t3
  13128. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13129. + v0 * t + p1;
  13130. }
  13131. /**
  13132. * @alias module:zrender/shape/util/smoothSpline
  13133. * @param {Array} points 线段顶点数组
  13134. * @param {boolean} isLoop
  13135. * @return {Array}
  13136. */
  13137. var smoothSpline = function (points, isLoop) {
  13138. var len$$1 = points.length;
  13139. var ret = [];
  13140. var distance$$1 = 0;
  13141. for (var i = 1; i < len$$1; i++) {
  13142. distance$$1 += distance(points[i - 1], points[i]);
  13143. }
  13144. var segs = distance$$1 / 2;
  13145. segs = segs < len$$1 ? len$$1 : segs;
  13146. for (var i = 0; i < segs; i++) {
  13147. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13148. var idx = Math.floor(pos);
  13149. var w = pos - idx;
  13150. var p0;
  13151. var p1 = points[idx % len$$1];
  13152. var p2;
  13153. var p3;
  13154. if (!isLoop) {
  13155. p0 = points[idx === 0 ? idx : idx - 1];
  13156. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13157. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13158. }
  13159. else {
  13160. p0 = points[(idx - 1 + len$$1) % len$$1];
  13161. p2 = points[(idx + 1) % len$$1];
  13162. p3 = points[(idx + 2) % len$$1];
  13163. }
  13164. var w2 = w * w;
  13165. var w3 = w * w2;
  13166. ret.push([
  13167. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13168. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13169. ]);
  13170. }
  13171. return ret;
  13172. };
  13173. /**
  13174. * 贝塞尔平滑曲线
  13175. * @module zrender/shape/util/smoothBezier
  13176. * @author pissang (https://www.github.com/pissang)
  13177. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13178. * errorrik (errorrik@gmail.com)
  13179. */
  13180. /**
  13181. * 贝塞尔平滑曲线
  13182. * @alias module:zrender/shape/util/smoothBezier
  13183. * @param {Array} points 线段顶点数组
  13184. * @param {number} smooth 平滑等级, 0-1
  13185. * @param {boolean} isLoop
  13186. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13187. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13188. * 整个折线的包围盒做一个并集用来约束控制点。
  13189. * @param {Array} 计算出来的控制点数组
  13190. */
  13191. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13192. var cps = [];
  13193. var v = [];
  13194. var v1 = [];
  13195. var v2 = [];
  13196. var prevPoint;
  13197. var nextPoint;
  13198. var min$$1, max$$1;
  13199. if (constraint) {
  13200. min$$1 = [Infinity, Infinity];
  13201. max$$1 = [-Infinity, -Infinity];
  13202. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13203. min(min$$1, min$$1, points[i]);
  13204. max(max$$1, max$$1, points[i]);
  13205. }
  13206. // 与指定的包围盒做并集
  13207. min(min$$1, min$$1, constraint[0]);
  13208. max(max$$1, max$$1, constraint[1]);
  13209. }
  13210. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13211. var point = points[i];
  13212. if (isLoop) {
  13213. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13214. nextPoint = points[(i + 1) % len$$1];
  13215. }
  13216. else {
  13217. if (i === 0 || i === len$$1 - 1) {
  13218. cps.push(clone$1(points[i]));
  13219. continue;
  13220. }
  13221. else {
  13222. prevPoint = points[i - 1];
  13223. nextPoint = points[i + 1];
  13224. }
  13225. }
  13226. sub(v, nextPoint, prevPoint);
  13227. // use degree to scale the handle length
  13228. scale(v, v, smooth);
  13229. var d0 = distance(point, prevPoint);
  13230. var d1 = distance(point, nextPoint);
  13231. var sum = d0 + d1;
  13232. if (sum !== 0) {
  13233. d0 /= sum;
  13234. d1 /= sum;
  13235. }
  13236. scale(v1, v, -d0);
  13237. scale(v2, v, d1);
  13238. var cp0 = add([], point, v1);
  13239. var cp1 = add([], point, v2);
  13240. if (constraint) {
  13241. max(cp0, cp0, min$$1);
  13242. min(cp0, cp0, max$$1);
  13243. max(cp1, cp1, min$$1);
  13244. min(cp1, cp1, max$$1);
  13245. }
  13246. cps.push(cp0);
  13247. cps.push(cp1);
  13248. }
  13249. if (isLoop) {
  13250. cps.push(cps.shift());
  13251. }
  13252. return cps;
  13253. };
  13254. function buildPath$1(ctx, shape, closePath) {
  13255. var points = shape.points;
  13256. var smooth = shape.smooth;
  13257. if (points && points.length >= 2) {
  13258. if (smooth && smooth !== 'spline') {
  13259. var controlPoints = smoothBezier(
  13260. points, smooth, closePath, shape.smoothConstraint
  13261. );
  13262. ctx.moveTo(points[0][0], points[0][1]);
  13263. var len = points.length;
  13264. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13265. var cp1 = controlPoints[i * 2];
  13266. var cp2 = controlPoints[i * 2 + 1];
  13267. var p = points[(i + 1) % len];
  13268. ctx.bezierCurveTo(
  13269. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13270. );
  13271. }
  13272. }
  13273. else {
  13274. if (smooth === 'spline') {
  13275. points = smoothSpline(points, closePath);
  13276. }
  13277. ctx.moveTo(points[0][0], points[0][1]);
  13278. for (var i = 1, l = points.length; i < l; i++) {
  13279. ctx.lineTo(points[i][0], points[i][1]);
  13280. }
  13281. }
  13282. closePath && ctx.closePath();
  13283. }
  13284. }
  13285. /**
  13286. * 多边形
  13287. * @module zrender/shape/Polygon
  13288. */
  13289. var Polygon = Path.extend({
  13290. type: 'polygon',
  13291. shape: {
  13292. points: null,
  13293. smooth: false,
  13294. smoothConstraint: null
  13295. },
  13296. buildPath: function (ctx, shape) {
  13297. buildPath$1(ctx, shape, true);
  13298. }
  13299. });
  13300. /**
  13301. * @module zrender/graphic/shape/Polyline
  13302. */
  13303. var Polyline = Path.extend({
  13304. type: 'polyline',
  13305. shape: {
  13306. points: null,
  13307. smooth: false,
  13308. smoothConstraint: null
  13309. },
  13310. style: {
  13311. stroke: '#000',
  13312. fill: null
  13313. },
  13314. buildPath: function (ctx, shape) {
  13315. buildPath$1(ctx, shape, false);
  13316. }
  13317. });
  13318. /**
  13319. * 矩形
  13320. * @module zrender/graphic/shape/Rect
  13321. */
  13322. var Rect = Path.extend({
  13323. type: 'rect',
  13324. shape: {
  13325. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13326. // r缩写为1 相当于 [1, 1, 1, 1]
  13327. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13328. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13329. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13330. r: 0,
  13331. x: 0,
  13332. y: 0,
  13333. width: 0,
  13334. height: 0
  13335. },
  13336. buildPath: function (ctx, shape) {
  13337. var x = shape.x;
  13338. var y = shape.y;
  13339. var width = shape.width;
  13340. var height = shape.height;
  13341. if (!shape.r) {
  13342. ctx.rect(x, y, width, height);
  13343. }
  13344. else {
  13345. buildPath(ctx, shape);
  13346. }
  13347. ctx.closePath();
  13348. return;
  13349. }
  13350. });
  13351. /**
  13352. * 直线
  13353. * @module zrender/graphic/shape/Line
  13354. */
  13355. var Line = Path.extend({
  13356. type: 'line',
  13357. shape: {
  13358. // Start point
  13359. x1: 0,
  13360. y1: 0,
  13361. // End point
  13362. x2: 0,
  13363. y2: 0,
  13364. percent: 1
  13365. },
  13366. style: {
  13367. stroke: '#000',
  13368. fill: null
  13369. },
  13370. buildPath: function (ctx, shape) {
  13371. var x1 = shape.x1;
  13372. var y1 = shape.y1;
  13373. var x2 = shape.x2;
  13374. var y2 = shape.y2;
  13375. var percent = shape.percent;
  13376. if (percent === 0) {
  13377. return;
  13378. }
  13379. ctx.moveTo(x1, y1);
  13380. if (percent < 1) {
  13381. x2 = x1 * (1 - percent) + x2 * percent;
  13382. y2 = y1 * (1 - percent) + y2 * percent;
  13383. }
  13384. ctx.lineTo(x2, y2);
  13385. },
  13386. /**
  13387. * Get point at percent
  13388. * @param {number} percent
  13389. * @return {Array.<number>}
  13390. */
  13391. pointAt: function (p) {
  13392. var shape = this.shape;
  13393. return [
  13394. shape.x1 * (1 - p) + shape.x2 * p,
  13395. shape.y1 * (1 - p) + shape.y2 * p
  13396. ];
  13397. }
  13398. });
  13399. /**
  13400. * 贝塞尔曲线
  13401. * @module zrender/shape/BezierCurve
  13402. */
  13403. var out = [];
  13404. function someVectorAt(shape, t, isTangent) {
  13405. var cpx2 = shape.cpx2;
  13406. var cpy2 = shape.cpy2;
  13407. if (cpx2 === null || cpy2 === null) {
  13408. return [
  13409. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13410. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13411. ];
  13412. }
  13413. else {
  13414. return [
  13415. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13416. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13417. ];
  13418. }
  13419. }
  13420. var BezierCurve = Path.extend({
  13421. type: 'bezier-curve',
  13422. shape: {
  13423. x1: 0,
  13424. y1: 0,
  13425. x2: 0,
  13426. y2: 0,
  13427. cpx1: 0,
  13428. cpy1: 0,
  13429. // cpx2: 0,
  13430. // cpy2: 0
  13431. // Curve show percent, for animating
  13432. percent: 1
  13433. },
  13434. style: {
  13435. stroke: '#000',
  13436. fill: null
  13437. },
  13438. buildPath: function (ctx, shape) {
  13439. var x1 = shape.x1;
  13440. var y1 = shape.y1;
  13441. var x2 = shape.x2;
  13442. var y2 = shape.y2;
  13443. var cpx1 = shape.cpx1;
  13444. var cpy1 = shape.cpy1;
  13445. var cpx2 = shape.cpx2;
  13446. var cpy2 = shape.cpy2;
  13447. var percent = shape.percent;
  13448. if (percent === 0) {
  13449. return;
  13450. }
  13451. ctx.moveTo(x1, y1);
  13452. if (cpx2 == null || cpy2 == null) {
  13453. if (percent < 1) {
  13454. quadraticSubdivide(
  13455. x1, cpx1, x2, percent, out
  13456. );
  13457. cpx1 = out[1];
  13458. x2 = out[2];
  13459. quadraticSubdivide(
  13460. y1, cpy1, y2, percent, out
  13461. );
  13462. cpy1 = out[1];
  13463. y2 = out[2];
  13464. }
  13465. ctx.quadraticCurveTo(
  13466. cpx1, cpy1,
  13467. x2, y2
  13468. );
  13469. }
  13470. else {
  13471. if (percent < 1) {
  13472. cubicSubdivide(
  13473. x1, cpx1, cpx2, x2, percent, out
  13474. );
  13475. cpx1 = out[1];
  13476. cpx2 = out[2];
  13477. x2 = out[3];
  13478. cubicSubdivide(
  13479. y1, cpy1, cpy2, y2, percent, out
  13480. );
  13481. cpy1 = out[1];
  13482. cpy2 = out[2];
  13483. y2 = out[3];
  13484. }
  13485. ctx.bezierCurveTo(
  13486. cpx1, cpy1,
  13487. cpx2, cpy2,
  13488. x2, y2
  13489. );
  13490. }
  13491. },
  13492. /**
  13493. * Get point at percent
  13494. * @param {number} t
  13495. * @return {Array.<number>}
  13496. */
  13497. pointAt: function (t) {
  13498. return someVectorAt(this.shape, t, false);
  13499. },
  13500. /**
  13501. * Get tangent at percent
  13502. * @param {number} t
  13503. * @return {Array.<number>}
  13504. */
  13505. tangentAt: function (t) {
  13506. var p = someVectorAt(this.shape, t, true);
  13507. return normalize(p, p);
  13508. }
  13509. });
  13510. /**
  13511. * 圆弧
  13512. * @module zrender/graphic/shape/Arc
  13513. */
  13514. var Arc = Path.extend({
  13515. type: 'arc',
  13516. shape: {
  13517. cx: 0,
  13518. cy: 0,
  13519. r: 0,
  13520. startAngle: 0,
  13521. endAngle: Math.PI * 2,
  13522. clockwise: true
  13523. },
  13524. style: {
  13525. stroke: '#000',
  13526. fill: null
  13527. },
  13528. buildPath: function (ctx, shape) {
  13529. var x = shape.cx;
  13530. var y = shape.cy;
  13531. var r = Math.max(shape.r, 0);
  13532. var startAngle = shape.startAngle;
  13533. var endAngle = shape.endAngle;
  13534. var clockwise = shape.clockwise;
  13535. var unitX = Math.cos(startAngle);
  13536. var unitY = Math.sin(startAngle);
  13537. ctx.moveTo(unitX * r + x, unitY * r + y);
  13538. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13539. }
  13540. });
  13541. // CompoundPath to improve performance
  13542. var CompoundPath = Path.extend({
  13543. type: 'compound',
  13544. shape: {
  13545. paths: null
  13546. },
  13547. _updatePathDirty: function () {
  13548. var dirtyPath = this.__dirtyPath;
  13549. var paths = this.shape.paths;
  13550. for (var i = 0; i < paths.length; i++) {
  13551. // Mark as dirty if any subpath is dirty
  13552. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13553. }
  13554. this.__dirtyPath = dirtyPath;
  13555. this.__dirty = this.__dirty || dirtyPath;
  13556. },
  13557. beforeBrush: function () {
  13558. this._updatePathDirty();
  13559. var paths = this.shape.paths || [];
  13560. var scale = this.getGlobalScale();
  13561. // Update path scale
  13562. for (var i = 0; i < paths.length; i++) {
  13563. if (!paths[i].path) {
  13564. paths[i].createPathProxy();
  13565. }
  13566. paths[i].path.setScale(scale[0], scale[1]);
  13567. }
  13568. },
  13569. buildPath: function (ctx, shape) {
  13570. var paths = shape.paths || [];
  13571. for (var i = 0; i < paths.length; i++) {
  13572. paths[i].buildPath(ctx, paths[i].shape, true);
  13573. }
  13574. },
  13575. afterBrush: function () {
  13576. var paths = this.shape.paths || [];
  13577. for (var i = 0; i < paths.length; i++) {
  13578. paths[i].__dirtyPath = false;
  13579. }
  13580. },
  13581. getBoundingRect: function () {
  13582. this._updatePathDirty();
  13583. return Path.prototype.getBoundingRect.call(this);
  13584. }
  13585. });
  13586. /**
  13587. * @param {Array.<Object>} colorStops
  13588. */
  13589. var Gradient = function (colorStops) {
  13590. this.colorStops = colorStops || [];
  13591. };
  13592. Gradient.prototype = {
  13593. constructor: Gradient,
  13594. addColorStop: function (offset, color) {
  13595. this.colorStops.push({
  13596. offset: offset,
  13597. color: color
  13598. });
  13599. }
  13600. };
  13601. /**
  13602. * x, y, x2, y2 are all percent from 0 to 1
  13603. * @param {number} [x=0]
  13604. * @param {number} [y=0]
  13605. * @param {number} [x2=1]
  13606. * @param {number} [y2=0]
  13607. * @param {Array.<Object>} colorStops
  13608. * @param {boolean} [globalCoord=false]
  13609. */
  13610. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13611. // Should do nothing more in this constructor. Because gradient can be
  13612. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13613. // this constructor will not be called.
  13614. this.x = x == null ? 0 : x;
  13615. this.y = y == null ? 0 : y;
  13616. this.x2 = x2 == null ? 1 : x2;
  13617. this.y2 = y2 == null ? 0 : y2;
  13618. // Can be cloned
  13619. this.type = 'linear';
  13620. // If use global coord
  13621. this.global = globalCoord || false;
  13622. Gradient.call(this, colorStops);
  13623. };
  13624. LinearGradient.prototype = {
  13625. constructor: LinearGradient
  13626. };
  13627. inherits(LinearGradient, Gradient);
  13628. /**
  13629. * x, y, r are all percent from 0 to 1
  13630. * @param {number} [x=0.5]
  13631. * @param {number} [y=0.5]
  13632. * @param {number} [r=0.5]
  13633. * @param {Array.<Object>} [colorStops]
  13634. * @param {boolean} [globalCoord=false]
  13635. */
  13636. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13637. // Should do nothing more in this constructor. Because gradient can be
  13638. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13639. // this constructor will not be called.
  13640. this.x = x == null ? 0.5 : x;
  13641. this.y = y == null ? 0.5 : y;
  13642. this.r = r == null ? 0.5 : r;
  13643. // Can be cloned
  13644. this.type = 'radial';
  13645. // If use global coord
  13646. this.global = globalCoord || false;
  13647. Gradient.call(this, colorStops);
  13648. };
  13649. RadialGradient.prototype = {
  13650. constructor: RadialGradient
  13651. };
  13652. inherits(RadialGradient, Gradient);
  13653. var round$1 = Math.round;
  13654. var mathMax$1 = Math.max;
  13655. var mathMin$1 = Math.min;
  13656. var EMPTY_OBJ = {};
  13657. /**
  13658. * Extend shape with parameters
  13659. */
  13660. function extendShape(opts) {
  13661. return Path.extend(opts);
  13662. }
  13663. /**
  13664. * Extend path
  13665. */
  13666. function extendPath(pathData, opts) {
  13667. return extendFromString(pathData, opts);
  13668. }
  13669. /**
  13670. * Create a path element from path data string
  13671. * @param {string} pathData
  13672. * @param {Object} opts
  13673. * @param {module:zrender/core/BoundingRect} rect
  13674. * @param {string} [layout=cover] 'center' or 'cover'
  13675. */
  13676. function makePath(pathData, opts, rect, layout) {
  13677. var path = createFromString(pathData, opts);
  13678. var boundingRect = path.getBoundingRect();
  13679. if (rect) {
  13680. if (layout === 'center') {
  13681. rect = centerGraphic(rect, boundingRect);
  13682. }
  13683. resizePath(path, rect);
  13684. }
  13685. return path;
  13686. }
  13687. /**
  13688. * Create a image element from image url
  13689. * @param {string} imageUrl image url
  13690. * @param {Object} opts options
  13691. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13692. * @param {string} [layout=cover] 'center' or 'cover'
  13693. */
  13694. function makeImage(imageUrl, rect, layout) {
  13695. var path = new ZImage({
  13696. style: {
  13697. image: imageUrl,
  13698. x: rect.x,
  13699. y: rect.y,
  13700. width: rect.width,
  13701. height: rect.height
  13702. },
  13703. onload: function (img) {
  13704. if (layout === 'center') {
  13705. var boundingRect = {
  13706. width: img.width,
  13707. height: img.height
  13708. };
  13709. path.setStyle(centerGraphic(rect, boundingRect));
  13710. }
  13711. }
  13712. });
  13713. return path;
  13714. }
  13715. /**
  13716. * Get position of centered element in bounding box.
  13717. *
  13718. * @param {Object} rect element local bounding box
  13719. * @param {Object} boundingRect constraint bounding box
  13720. * @return {Object} element position containing x, y, width, and height
  13721. */
  13722. function centerGraphic(rect, boundingRect) {
  13723. // Set rect to center, keep width / height ratio.
  13724. var aspect = boundingRect.width / boundingRect.height;
  13725. var width = rect.height * aspect;
  13726. var height;
  13727. if (width <= rect.width) {
  13728. height = rect.height;
  13729. }
  13730. else {
  13731. width = rect.width;
  13732. height = width / aspect;
  13733. }
  13734. var cx = rect.x + rect.width / 2;
  13735. var cy = rect.y + rect.height / 2;
  13736. return {
  13737. x: cx - width / 2,
  13738. y: cy - height / 2,
  13739. width: width,
  13740. height: height
  13741. };
  13742. }
  13743. var mergePath = mergePath$1;
  13744. /**
  13745. * Resize a path to fit the rect
  13746. * @param {module:zrender/graphic/Path} path
  13747. * @param {Object} rect
  13748. */
  13749. function resizePath(path, rect) {
  13750. if (!path.applyTransform) {
  13751. return;
  13752. }
  13753. var pathRect = path.getBoundingRect();
  13754. var m = pathRect.calculateTransform(rect);
  13755. path.applyTransform(m);
  13756. }
  13757. /**
  13758. * Sub pixel optimize line for canvas
  13759. *
  13760. * @param {Object} param
  13761. * @param {Object} [param.shape]
  13762. * @param {number} [param.shape.x1]
  13763. * @param {number} [param.shape.y1]
  13764. * @param {number} [param.shape.x2]
  13765. * @param {number} [param.shape.y2]
  13766. * @param {Object} [param.style]
  13767. * @param {number} [param.style.lineWidth]
  13768. * @return {Object} Modified param
  13769. */
  13770. function subPixelOptimizeLine(param) {
  13771. var shape = param.shape;
  13772. var lineWidth = param.style.lineWidth;
  13773. if (round$1(shape.x1 * 2) === round$1(shape.x2 * 2)) {
  13774. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13775. }
  13776. if (round$1(shape.y1 * 2) === round$1(shape.y2 * 2)) {
  13777. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13778. }
  13779. return param;
  13780. }
  13781. /**
  13782. * Sub pixel optimize rect for canvas
  13783. *
  13784. * @param {Object} param
  13785. * @param {Object} [param.shape]
  13786. * @param {number} [param.shape.x]
  13787. * @param {number} [param.shape.y]
  13788. * @param {number} [param.shape.width]
  13789. * @param {number} [param.shape.height]
  13790. * @param {Object} [param.style]
  13791. * @param {number} [param.style.lineWidth]
  13792. * @return {Object} Modified param
  13793. */
  13794. function subPixelOptimizeRect(param) {
  13795. var shape = param.shape;
  13796. var lineWidth = param.style.lineWidth;
  13797. var originX = shape.x;
  13798. var originY = shape.y;
  13799. var originWidth = shape.width;
  13800. var originHeight = shape.height;
  13801. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13802. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13803. shape.width = Math.max(
  13804. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13805. originWidth === 0 ? 0 : 1
  13806. );
  13807. shape.height = Math.max(
  13808. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13809. originHeight === 0 ? 0 : 1
  13810. );
  13811. return param;
  13812. }
  13813. /**
  13814. * Sub pixel optimize for canvas
  13815. *
  13816. * @param {number} position Coordinate, such as x, y
  13817. * @param {number} lineWidth Should be nonnegative integer.
  13818. * @param {boolean=} positiveOrNegative Default false (negative).
  13819. * @return {number} Optimized position.
  13820. */
  13821. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13822. // Assure that (position + lineWidth / 2) is near integer edge,
  13823. // otherwise line will be fuzzy in canvas.
  13824. var doubledPosition = round$1(position * 2);
  13825. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13826. ? doubledPosition / 2
  13827. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13828. }
  13829. function hasFillOrStroke(fillOrStroke) {
  13830. return fillOrStroke != null && fillOrStroke != 'none';
  13831. }
  13832. function liftColor(color) {
  13833. return typeof color === 'string' ? lift(color, -0.1) : color;
  13834. }
  13835. /**
  13836. * @private
  13837. */
  13838. function cacheElementStl(el) {
  13839. if (el.__hoverStlDirty) {
  13840. var stroke = el.style.stroke;
  13841. var fill = el.style.fill;
  13842. // Create hoverStyle on mouseover
  13843. var hoverStyle = el.__hoverStl;
  13844. hoverStyle.fill = hoverStyle.fill
  13845. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13846. hoverStyle.stroke = hoverStyle.stroke
  13847. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13848. var normalStyle = {};
  13849. for (var name in hoverStyle) {
  13850. // See comment in `doSingleEnterHover`.
  13851. if (hoverStyle[name] != null) {
  13852. normalStyle[name] = el.style[name];
  13853. }
  13854. }
  13855. el.__normalStl = normalStyle;
  13856. el.__hoverStlDirty = false;
  13857. }
  13858. }
  13859. /**
  13860. * @private
  13861. */
  13862. function doSingleEnterHover(el) {
  13863. if (el.__isHover) {
  13864. return;
  13865. }
  13866. cacheElementStl(el);
  13867. if (el.useHoverLayer) {
  13868. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13869. }
  13870. else {
  13871. var style = el.style;
  13872. var insideRollbackOpt = style.insideRollbackOpt;
  13873. // Consider case: only `position: 'top'` is set on emphasis, then text
  13874. // color should be returned to `autoColor`, rather than remain '#fff'.
  13875. // So we should rollback then apply again after style merging.
  13876. insideRollbackOpt && rollbackInsideStyle(style);
  13877. // styles can be:
  13878. // {
  13879. // label: {
  13880. // normal: {
  13881. // show: false,
  13882. // position: 'outside',
  13883. // fontSize: 18
  13884. // },
  13885. // emphasis: {
  13886. // show: true
  13887. // }
  13888. // }
  13889. // },
  13890. // where properties of `emphasis` may not appear in `normal`. We previously use
  13891. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13892. // But consider rich text and setOption in merge mode, it is impossible to cover
  13893. // all properties in merge. So we use merge mode when setting style here, where
  13894. // only properties that is not `null/undefined` can be set. The disadventage:
  13895. // null/undefined can not be used to remove style any more in `emphasis`.
  13896. style.extendFrom(el.__hoverStl);
  13897. // Do not save `insideRollback`.
  13898. if (insideRollbackOpt) {
  13899. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13900. // textFill may be rollbacked to null.
  13901. if (style.textFill == null) {
  13902. style.textFill = insideRollbackOpt.autoColor;
  13903. }
  13904. }
  13905. el.dirty(false);
  13906. el.z2 += 1;
  13907. }
  13908. el.__isHover = true;
  13909. }
  13910. /**
  13911. * @inner
  13912. */
  13913. function doSingleLeaveHover(el) {
  13914. if (!el.__isHover) {
  13915. return;
  13916. }
  13917. var normalStl = el.__normalStl;
  13918. if (el.useHoverLayer) {
  13919. el.__zr && el.__zr.removeHover(el);
  13920. }
  13921. else {
  13922. // Consider null/undefined value, should use
  13923. // `setStyle` but not `extendFrom(stl, true)`.
  13924. normalStl && el.setStyle(normalStl);
  13925. el.z2 -= 1;
  13926. }
  13927. el.__isHover = false;
  13928. }
  13929. /**
  13930. * @inner
  13931. */
  13932. function doEnterHover(el) {
  13933. el.type === 'group'
  13934. ? el.traverse(function (child) {
  13935. if (child.type !== 'group') {
  13936. doSingleEnterHover(child);
  13937. }
  13938. })
  13939. : doSingleEnterHover(el);
  13940. }
  13941. function doLeaveHover(el) {
  13942. el.type === 'group'
  13943. ? el.traverse(function (child) {
  13944. if (child.type !== 'group') {
  13945. doSingleLeaveHover(child);
  13946. }
  13947. })
  13948. : doSingleLeaveHover(el);
  13949. }
  13950. /**
  13951. * @inner
  13952. */
  13953. function setElementHoverStl(el, hoverStl) {
  13954. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13955. // Often used when item group has a label element and it's hoverStyle is different
  13956. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13957. el.__hoverStlDirty = true;
  13958. if (el.__isHover) {
  13959. cacheElementStl(el);
  13960. }
  13961. }
  13962. /**
  13963. * @inner
  13964. */
  13965. function onElementMouseOver(e) {
  13966. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13967. return;
  13968. }
  13969. // Only if element is not in emphasis status
  13970. !this.__isEmphasis && doEnterHover(this);
  13971. }
  13972. /**
  13973. * @inner
  13974. */
  13975. function onElementMouseOut(e) {
  13976. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13977. return;
  13978. }
  13979. // Only if element is not in emphasis status
  13980. !this.__isEmphasis && doLeaveHover(this);
  13981. }
  13982. /**
  13983. * @inner
  13984. */
  13985. function enterEmphasis() {
  13986. this.__isEmphasis = true;
  13987. doEnterHover(this);
  13988. }
  13989. /**
  13990. * @inner
  13991. */
  13992. function leaveEmphasis() {
  13993. this.__isEmphasis = false;
  13994. doLeaveHover(this);
  13995. }
  13996. /**
  13997. * Set hover style of element.
  13998. * This method can be called repeatly without side-effects.
  13999. * @param {module:zrender/Element} el
  14000. * @param {Object} [hoverStyle]
  14001. * @param {Object} [opt]
  14002. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14003. * In touch device, mouseover event will be trigger on touchstart event
  14004. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14005. * conviniently use hoverStyle when tap on touch screen without additional
  14006. * code for compatibility.
  14007. * But if the chart/component has select feature, which usually also use
  14008. * hoverStyle, there might be conflict between 'select-highlight' and
  14009. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14010. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14011. * on touch device.
  14012. */
  14013. function setHoverStyle(el, hoverStyle, opt) {
  14014. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14015. el.type === 'group'
  14016. ? el.traverse(function (child) {
  14017. if (child.type !== 'group') {
  14018. setElementHoverStl(child, hoverStyle);
  14019. }
  14020. })
  14021. : setElementHoverStl(el, hoverStyle);
  14022. // Duplicated function will be auto-ignored, see Eventful.js.
  14023. el.on('mouseover', onElementMouseOver)
  14024. .on('mouseout', onElementMouseOut);
  14025. // Emphasis, normal can be triggered manually
  14026. el.on('emphasis', enterEmphasis)
  14027. .on('normal', leaveEmphasis);
  14028. }
  14029. /**
  14030. * @param {Object|module:zrender/graphic/Style} normalStyle
  14031. * @param {Object} emphasisStyle
  14032. * @param {module:echarts/model/Model} normalModel
  14033. * @param {module:echarts/model/Model} emphasisModel
  14034. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14035. * @param {Object} [opt.defaultText]
  14036. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14037. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14038. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14039. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14040. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14041. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14042. * @param {Object} [normalSpecified]
  14043. * @param {Object} [emphasisSpecified]
  14044. */
  14045. function setLabelStyle(
  14046. normalStyle, emphasisStyle,
  14047. normalModel, emphasisModel,
  14048. opt,
  14049. normalSpecified, emphasisSpecified
  14050. ) {
  14051. opt = opt || EMPTY_OBJ;
  14052. var labelFetcher = opt.labelFetcher;
  14053. var labelDataIndex = opt.labelDataIndex;
  14054. var labelDimIndex = opt.labelDimIndex;
  14055. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14056. // is not supported util someone requests.
  14057. var showNormal = normalModel.getShallow('show');
  14058. var showEmphasis = emphasisModel.getShallow('show');
  14059. // Consider performance, only fetch label when necessary.
  14060. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14061. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14062. var baseText = (showNormal || showEmphasis)
  14063. ? retrieve2(
  14064. labelFetcher
  14065. ? labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex)
  14066. : null,
  14067. opt.defaultText
  14068. )
  14069. : null;
  14070. var normalStyleText = showNormal ? baseText : null;
  14071. var emphasisStyleText = showEmphasis
  14072. ? retrieve2(
  14073. labelFetcher
  14074. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14075. : null,
  14076. baseText
  14077. )
  14078. : null;
  14079. // Optimize: If style.text is null, text will not be drawn.
  14080. if (normalStyleText != null || emphasisStyleText != null) {
  14081. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14082. // values have to be set on `normalStyle`.
  14083. // If we set default values on `emphasisStyle`, consider case:
  14084. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14085. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14086. // Then the 'red' will not work on emphasis.
  14087. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14088. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14089. }
  14090. normalStyle.text = normalStyleText;
  14091. emphasisStyle.text = emphasisStyleText;
  14092. }
  14093. /**
  14094. * Set basic textStyle properties.
  14095. * @param {Object|module:zrender/graphic/Style} textStyle
  14096. * @param {module:echarts/model/Model} model
  14097. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14098. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14099. * @param {boolean} [isEmphasis]
  14100. */
  14101. function setTextStyle(
  14102. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14103. ) {
  14104. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14105. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14106. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14107. return textStyle;
  14108. }
  14109. /**
  14110. * Set text option in the style.
  14111. * @deprecated
  14112. * @param {Object} textStyle
  14113. * @param {module:echarts/model/Model} labelModel
  14114. * @param {string|boolean} defaultColor Default text color.
  14115. * If set as false, it will be processed as a emphasis style.
  14116. */
  14117. function setText(textStyle, labelModel, defaultColor) {
  14118. var opt = {isRectText: true};
  14119. var isEmphasis;
  14120. if (defaultColor === false) {
  14121. isEmphasis = true;
  14122. }
  14123. else {
  14124. // Support setting color as 'auto' to get visual color.
  14125. opt.autoColor = defaultColor;
  14126. }
  14127. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14128. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14129. }
  14130. /**
  14131. * {
  14132. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14133. * isRectText: boolean,
  14134. * autoColor: string, specify a color when color is 'auto',
  14135. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14136. * If autoColor specified, it is used as default textFill.
  14137. * useInsideStyle:
  14138. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14139. * if `textFill` is not specified.
  14140. * `false`: Do not use inside style.
  14141. * `null/undefined`: use inside style if `isRectText` is true and
  14142. * `textFill` is not specified and textPosition contains `'inside'`.
  14143. * forceRich: boolean
  14144. * }
  14145. */
  14146. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14147. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14148. opt = opt || EMPTY_OBJ;
  14149. if (opt.isRectText) {
  14150. var textPosition = textStyleModel.getShallow('position')
  14151. || (isEmphasis ? null : 'inside');
  14152. // 'outside' is not a valid zr textPostion value, but used
  14153. // in bar series, and magric type should be considered.
  14154. textPosition === 'outside' && (textPosition = 'top');
  14155. textStyle.textPosition = textPosition;
  14156. textStyle.textOffset = textStyleModel.getShallow('offset');
  14157. var labelRotate = textStyleModel.getShallow('rotate');
  14158. labelRotate != null && (labelRotate *= Math.PI / 180);
  14159. textStyle.textRotation = labelRotate;
  14160. textStyle.textDistance = retrieve2(
  14161. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14162. );
  14163. }
  14164. var ecModel = textStyleModel.ecModel;
  14165. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14166. // Consider case:
  14167. // {
  14168. // data: [{
  14169. // value: 12,
  14170. // label: {
  14171. // normal: {
  14172. // rich: {
  14173. // // no 'a' here but using parent 'a'.
  14174. // }
  14175. // }
  14176. // }
  14177. // }],
  14178. // rich: {
  14179. // a: { ... }
  14180. // }
  14181. // }
  14182. var richItemNames = getRichItemNames(textStyleModel);
  14183. var richResult;
  14184. if (richItemNames) {
  14185. richResult = {};
  14186. for (var name in richItemNames) {
  14187. if (richItemNames.hasOwnProperty(name)) {
  14188. // Cascade is supported in rich.
  14189. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14190. // In rich, never `disableBox`.
  14191. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14192. }
  14193. }
  14194. }
  14195. textStyle.rich = richResult;
  14196. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14197. if (opt.forceRich && !opt.textStyle) {
  14198. opt.textStyle = {};
  14199. }
  14200. return textStyle;
  14201. }
  14202. // Consider case:
  14203. // {
  14204. // data: [{
  14205. // value: 12,
  14206. // label: {
  14207. // normal: {
  14208. // rich: {
  14209. // // no 'a' here but using parent 'a'.
  14210. // }
  14211. // }
  14212. // }
  14213. // }],
  14214. // rich: {
  14215. // a: { ... }
  14216. // }
  14217. // }
  14218. function getRichItemNames(textStyleModel) {
  14219. // Use object to remove duplicated names.
  14220. var richItemNameMap;
  14221. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14222. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14223. if (rich) {
  14224. richItemNameMap = richItemNameMap || {};
  14225. for (var name in rich) {
  14226. if (rich.hasOwnProperty(name)) {
  14227. richItemNameMap[name] = 1;
  14228. }
  14229. }
  14230. }
  14231. textStyleModel = textStyleModel.parentModel;
  14232. }
  14233. return richItemNameMap;
  14234. }
  14235. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14236. // In merge mode, default value should not be given.
  14237. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14238. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14239. || globalTextStyle.color;
  14240. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14241. || globalTextStyle.textBorderColor;
  14242. textStyle.textStrokeWidth = retrieve2(
  14243. textStyleModel.getShallow('textBorderWidth'),
  14244. globalTextStyle.textBorderWidth
  14245. );
  14246. if (!isEmphasis) {
  14247. if (isBlock) {
  14248. // Always set `insideRollback`, for clearing previous.
  14249. var originalTextPosition = textStyle.textPosition;
  14250. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14251. // Save original textPosition, because style.textPosition will be repalced by
  14252. // real location (like [10, 30]) in zrender.
  14253. textStyle.insideOriginalTextPosition = originalTextPosition;
  14254. textStyle.insideRollbackOpt = opt;
  14255. }
  14256. // Set default finally.
  14257. if (textStyle.textFill == null) {
  14258. textStyle.textFill = opt.autoColor;
  14259. }
  14260. }
  14261. // Do not use `getFont` here, because merge should be supported, where
  14262. // part of these properties may be changed in emphasis style, and the
  14263. // others should remain their original value got from normal style.
  14264. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14265. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14266. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14267. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14268. textStyle.textAlign = textStyleModel.getShallow('align');
  14269. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14270. || textStyleModel.getShallow('baseline');
  14271. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14272. textStyle.textWidth = textStyleModel.getShallow('width');
  14273. textStyle.textHeight = textStyleModel.getShallow('height');
  14274. textStyle.textTag = textStyleModel.getShallow('tag');
  14275. if (!isBlock || !opt.disableBox) {
  14276. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14277. textStyle.textPadding = textStyleModel.getShallow('padding');
  14278. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14279. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14280. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14281. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14282. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14283. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14284. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14285. }
  14286. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14287. || globalTextStyle.textShadowColor;
  14288. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14289. || globalTextStyle.textShadowBlur;
  14290. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14291. || globalTextStyle.textShadowOffsetX;
  14292. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14293. || globalTextStyle.textShadowOffsetY;
  14294. }
  14295. function getAutoColor(color, opt) {
  14296. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14297. }
  14298. function applyInsideStyle(textStyle, textPosition, opt) {
  14299. var useInsideStyle = opt.useInsideStyle;
  14300. var insideRollback;
  14301. if (textStyle.textFill == null
  14302. && useInsideStyle !== false
  14303. && (useInsideStyle === true
  14304. || (opt.isRectText
  14305. && textPosition
  14306. // textPosition can be [10, 30]
  14307. && typeof textPosition === 'string'
  14308. && textPosition.indexOf('inside') >= 0
  14309. )
  14310. )
  14311. ) {
  14312. insideRollback = {
  14313. textFill: null,
  14314. textStroke: textStyle.textStroke,
  14315. textStrokeWidth: textStyle.textStrokeWidth
  14316. };
  14317. textStyle.textFill = '#fff';
  14318. // Consider text with #fff overflow its container.
  14319. if (textStyle.textStroke == null) {
  14320. textStyle.textStroke = opt.autoColor;
  14321. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14322. }
  14323. }
  14324. return insideRollback;
  14325. }
  14326. function rollbackInsideStyle(style) {
  14327. var insideRollback = style.insideRollback;
  14328. if (insideRollback) {
  14329. style.textFill = insideRollback.textFill;
  14330. style.textStroke = insideRollback.textStroke;
  14331. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14332. }
  14333. }
  14334. function getFont(opt, ecModel) {
  14335. // ecModel or default text style model.
  14336. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14337. return [
  14338. // FIXME in node-canvas fontWeight is before fontStyle
  14339. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14340. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14341. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14342. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14343. ].join(' ');
  14344. }
  14345. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14346. if (typeof dataIndex === 'function') {
  14347. cb = dataIndex;
  14348. dataIndex = null;
  14349. }
  14350. // Do not check 'animation' property directly here. Consider this case:
  14351. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14352. // but its parent model (`seriesModel`) does.
  14353. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14354. if (animationEnabled) {
  14355. var postfix = isUpdate ? 'Update' : '';
  14356. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14357. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14358. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14359. if (typeof animationDelay === 'function') {
  14360. animationDelay = animationDelay(
  14361. dataIndex,
  14362. animatableModel.getAnimationDelayParams
  14363. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14364. : null
  14365. );
  14366. }
  14367. if (typeof duration === 'function') {
  14368. duration = duration(dataIndex);
  14369. }
  14370. duration > 0
  14371. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14372. : (el.stopAnimation(), el.attr(props), cb && cb());
  14373. }
  14374. else {
  14375. el.stopAnimation();
  14376. el.attr(props);
  14377. cb && cb();
  14378. }
  14379. }
  14380. /**
  14381. * Update graphic element properties with or without animation according to the
  14382. * configuration in series.
  14383. *
  14384. * Caution: this method will stop previous animation.
  14385. * So if do not use this method to one element twice before
  14386. * animation starts, unless you know what you are doing.
  14387. *
  14388. * @param {module:zrender/Element} el
  14389. * @param {Object} props
  14390. * @param {module:echarts/model/Model} [animatableModel]
  14391. * @param {number} [dataIndex]
  14392. * @param {Function} [cb]
  14393. * @example
  14394. * graphic.updateProps(el, {
  14395. * position: [100, 100]
  14396. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14397. * // Or
  14398. * graphic.updateProps(el, {
  14399. * position: [100, 100]
  14400. * }, seriesModel, function () { console.log('Animation done!'); });
  14401. */
  14402. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14403. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14404. }
  14405. /**
  14406. * Init graphic element properties with or without animation according to the
  14407. * configuration in series.
  14408. *
  14409. * Caution: this method will stop previous animation.
  14410. * So if do not use this method to one element twice before
  14411. * animation starts, unless you know what you are doing.
  14412. *
  14413. * @param {module:zrender/Element} el
  14414. * @param {Object} props
  14415. * @param {module:echarts/model/Model} [animatableModel]
  14416. * @param {number} [dataIndex]
  14417. * @param {Function} cb
  14418. */
  14419. function initProps(el, props, animatableModel, dataIndex, cb) {
  14420. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14421. }
  14422. /**
  14423. * Get transform matrix of target (param target),
  14424. * in coordinate of its ancestor (param ancestor)
  14425. *
  14426. * @param {module:zrender/mixin/Transformable} target
  14427. * @param {module:zrender/mixin/Transformable} [ancestor]
  14428. */
  14429. function getTransform(target, ancestor) {
  14430. var mat = identity([]);
  14431. while (target && target !== ancestor) {
  14432. mul$1(mat, target.getLocalTransform(), mat);
  14433. target = target.parent;
  14434. }
  14435. return mat;
  14436. }
  14437. /**
  14438. * Apply transform to an vertex.
  14439. * @param {Array.<number>} target [x, y]
  14440. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14441. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14442. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14443. * @param {boolean=} invert Whether use invert matrix.
  14444. * @return {Array.<number>} [x, y]
  14445. */
  14446. function applyTransform$1(target, transform, invert$$1) {
  14447. if (transform && !isArrayLike(transform)) {
  14448. transform = Transformable.getLocalTransform(transform);
  14449. }
  14450. if (invert$$1) {
  14451. transform = invert([], transform);
  14452. }
  14453. return applyTransform([], target, transform);
  14454. }
  14455. /**
  14456. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14457. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14458. * @param {boolean=} invert Whether use invert matrix.
  14459. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14460. */
  14461. function transformDirection(direction, transform, invert$$1) {
  14462. // Pick a base, ensure that transform result will not be (0, 0).
  14463. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14464. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14465. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14466. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14467. var vertex = [
  14468. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14469. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14470. ];
  14471. vertex = applyTransform$1(vertex, transform, invert$$1);
  14472. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14473. ? (vertex[0] > 0 ? 'right' : 'left')
  14474. : (vertex[1] > 0 ? 'bottom' : 'top');
  14475. }
  14476. /**
  14477. * Apply group transition animation from g1 to g2.
  14478. * If no animatableModel, no animation.
  14479. */
  14480. function groupTransition(g1, g2, animatableModel, cb) {
  14481. if (!g1 || !g2) {
  14482. return;
  14483. }
  14484. function getElMap(g) {
  14485. var elMap = {};
  14486. g.traverse(function (el) {
  14487. if (!el.isGroup && el.anid) {
  14488. elMap[el.anid] = el;
  14489. }
  14490. });
  14491. return elMap;
  14492. }
  14493. function getAnimatableProps(el) {
  14494. var obj = {
  14495. position: clone$1(el.position),
  14496. rotation: el.rotation
  14497. };
  14498. if (el.shape) {
  14499. obj.shape = extend({}, el.shape);
  14500. }
  14501. return obj;
  14502. }
  14503. var elMap1 = getElMap(g1);
  14504. g2.traverse(function (el) {
  14505. if (!el.isGroup && el.anid) {
  14506. var oldEl = elMap1[el.anid];
  14507. if (oldEl) {
  14508. var newProp = getAnimatableProps(el);
  14509. el.attr(getAnimatableProps(oldEl));
  14510. updateProps(el, newProp, animatableModel, el.dataIndex);
  14511. }
  14512. // else {
  14513. // if (el.previousProps) {
  14514. // graphic.updateProps
  14515. // }
  14516. // }
  14517. }
  14518. });
  14519. }
  14520. /**
  14521. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14522. * @param {Object} rect {x, y, width, height}
  14523. * @return {Array.<Array.<number>>} A new clipped points.
  14524. */
  14525. function clipPointsByRect(points, rect) {
  14526. return map(points, function (point) {
  14527. var x = point[0];
  14528. x = mathMax$1(x, rect.x);
  14529. x = mathMin$1(x, rect.x + rect.width);
  14530. var y = point[1];
  14531. y = mathMax$1(y, rect.y);
  14532. y = mathMin$1(y, rect.y + rect.height);
  14533. return [x, y];
  14534. });
  14535. }
  14536. /**
  14537. * @param {Object} targetRect {x, y, width, height}
  14538. * @param {Object} rect {x, y, width, height}
  14539. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14540. */
  14541. function clipRectByRect(targetRect, rect) {
  14542. var x = mathMax$1(targetRect.x, rect.x);
  14543. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14544. var y = mathMax$1(targetRect.y, rect.y);
  14545. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14546. if (x2 >= x && y2 >= y) {
  14547. return {
  14548. x: x,
  14549. y: y,
  14550. width: x2 - x,
  14551. height: y2 - y
  14552. };
  14553. }
  14554. }
  14555. /**
  14556. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14557. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14558. * @param {Object} [rect] {x, y, width, height}
  14559. * @return {module:zrender/Element} Icon path or image element.
  14560. */
  14561. function createIcon(iconStr, opt, rect) {
  14562. opt = extend({rectHover: true}, opt);
  14563. var style = opt.style = {strokeNoScale: true};
  14564. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14565. if (iconStr) {
  14566. return iconStr.indexOf('image://') === 0
  14567. ? (
  14568. style.image = iconStr.slice(8),
  14569. defaults(style, rect),
  14570. new ZImage(opt)
  14571. )
  14572. : (
  14573. makePath(
  14574. iconStr.replace('path://', ''),
  14575. opt,
  14576. rect,
  14577. 'center'
  14578. )
  14579. );
  14580. }
  14581. }
  14582. var graphic = (Object.freeze || Object)({
  14583. extendShape: extendShape,
  14584. extendPath: extendPath,
  14585. makePath: makePath,
  14586. makeImage: makeImage,
  14587. mergePath: mergePath,
  14588. resizePath: resizePath,
  14589. subPixelOptimizeLine: subPixelOptimizeLine,
  14590. subPixelOptimizeRect: subPixelOptimizeRect,
  14591. subPixelOptimize: subPixelOptimize,
  14592. setHoverStyle: setHoverStyle,
  14593. setLabelStyle: setLabelStyle,
  14594. setTextStyle: setTextStyle,
  14595. setText: setText,
  14596. getFont: getFont,
  14597. updateProps: updateProps,
  14598. initProps: initProps,
  14599. getTransform: getTransform,
  14600. applyTransform: applyTransform$1,
  14601. transformDirection: transformDirection,
  14602. groupTransition: groupTransition,
  14603. clipPointsByRect: clipPointsByRect,
  14604. clipRectByRect: clipRectByRect,
  14605. createIcon: createIcon,
  14606. Group: Group,
  14607. Image: ZImage,
  14608. Text: Text,
  14609. Circle: Circle,
  14610. Sector: Sector,
  14611. Ring: Ring,
  14612. Polygon: Polygon,
  14613. Polyline: Polyline,
  14614. Rect: Rect,
  14615. Line: Line,
  14616. BezierCurve: BezierCurve,
  14617. Arc: Arc,
  14618. CompoundPath: CompoundPath,
  14619. LinearGradient: LinearGradient,
  14620. RadialGradient: RadialGradient,
  14621. BoundingRect: BoundingRect
  14622. });
  14623. var PATH_COLOR = ['textStyle', 'color'];
  14624. var textStyleMixin = {
  14625. /**
  14626. * Get color property or get color from option.textStyle.color
  14627. * @param {boolean} [isEmphasis]
  14628. * @return {string}
  14629. */
  14630. getTextColor: function (isEmphasis) {
  14631. var ecModel = this.ecModel;
  14632. return this.getShallow('color')
  14633. || (
  14634. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14635. );
  14636. },
  14637. /**
  14638. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14639. * @return {string}
  14640. */
  14641. getFont: function () {
  14642. return getFont({
  14643. fontStyle: this.getShallow('fontStyle'),
  14644. fontWeight: this.getShallow('fontWeight'),
  14645. fontSize: this.getShallow('fontSize'),
  14646. fontFamily: this.getShallow('fontFamily')
  14647. }, this.ecModel);
  14648. },
  14649. getTextRect: function (text) {
  14650. return getBoundingRect(
  14651. text,
  14652. this.getFont(),
  14653. this.getShallow('align'),
  14654. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14655. this.getShallow('padding'),
  14656. this.getShallow('rich'),
  14657. this.getShallow('truncateText')
  14658. );
  14659. }
  14660. };
  14661. var getItemStyle = makeStyleMapper(
  14662. [
  14663. ['fill', 'color'],
  14664. ['stroke', 'borderColor'],
  14665. ['lineWidth', 'borderWidth'],
  14666. ['opacity'],
  14667. ['shadowBlur'],
  14668. ['shadowOffsetX'],
  14669. ['shadowOffsetY'],
  14670. ['shadowColor'],
  14671. ['textPosition'],
  14672. ['textAlign']
  14673. ]
  14674. );
  14675. var itemStyleMixin = {
  14676. getItemStyle: function (excludes, includes) {
  14677. var style = getItemStyle(this, excludes, includes);
  14678. var lineDash = this.getBorderLineDash();
  14679. lineDash && (style.lineDash = lineDash);
  14680. return style;
  14681. },
  14682. getBorderLineDash: function () {
  14683. var lineType = this.get('borderType');
  14684. return (lineType === 'solid' || lineType == null) ? null
  14685. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14686. }
  14687. };
  14688. /**
  14689. * @module echarts/model/Model
  14690. */
  14691. var mixin$1 = mixin;
  14692. /**
  14693. * @alias module:echarts/model/Model
  14694. * @constructor
  14695. * @param {Object} option
  14696. * @param {module:echarts/model/Model} [parentModel]
  14697. * @param {module:echarts/model/Global} [ecModel]
  14698. */
  14699. function Model(option, parentModel, ecModel) {
  14700. /**
  14701. * @type {module:echarts/model/Model}
  14702. * @readOnly
  14703. */
  14704. this.parentModel = parentModel;
  14705. /**
  14706. * @type {module:echarts/model/Global}
  14707. * @readOnly
  14708. */
  14709. this.ecModel = ecModel;
  14710. /**
  14711. * @type {Object}
  14712. * @protected
  14713. */
  14714. this.option = option;
  14715. // Simple optimization
  14716. // if (this.init) {
  14717. // if (arguments.length <= 4) {
  14718. // this.init(option, parentModel, ecModel, extraOpt);
  14719. // }
  14720. // else {
  14721. // this.init.apply(this, arguments);
  14722. // }
  14723. // }
  14724. }
  14725. Model.prototype = {
  14726. constructor: Model,
  14727. /**
  14728. * Model 的初始化函数
  14729. * @param {Object} option
  14730. */
  14731. init: null,
  14732. /**
  14733. * 从新的 Option merge
  14734. */
  14735. mergeOption: function (option) {
  14736. merge(this.option, option, true);
  14737. },
  14738. /**
  14739. * @param {string|Array.<string>} path
  14740. * @param {boolean} [ignoreParent=false]
  14741. * @return {*}
  14742. */
  14743. get: function (path, ignoreParent) {
  14744. if (path == null) {
  14745. return this.option;
  14746. }
  14747. return doGet(
  14748. this.option,
  14749. this.parsePath(path),
  14750. !ignoreParent && getParent(this, path)
  14751. );
  14752. },
  14753. /**
  14754. * @param {string} key
  14755. * @param {boolean} [ignoreParent=false]
  14756. * @return {*}
  14757. */
  14758. getShallow: function (key, ignoreParent) {
  14759. var option = this.option;
  14760. var val = option == null ? option : option[key];
  14761. var parentModel = !ignoreParent && getParent(this, key);
  14762. if (val == null && parentModel) {
  14763. val = parentModel.getShallow(key);
  14764. }
  14765. return val;
  14766. },
  14767. /**
  14768. * @param {string|Array.<string>} [path]
  14769. * @param {module:echarts/model/Model} [parentModel]
  14770. * @return {module:echarts/model/Model}
  14771. */
  14772. getModel: function (path, parentModel) {
  14773. var obj = path == null
  14774. ? this.option
  14775. : doGet(this.option, path = this.parsePath(path));
  14776. var thisParentModel;
  14777. parentModel = parentModel || (
  14778. (thisParentModel = getParent(this, path))
  14779. && thisParentModel.getModel(path)
  14780. );
  14781. return new Model(obj, parentModel, this.ecModel);
  14782. },
  14783. /**
  14784. * If model has option
  14785. */
  14786. isEmpty: function () {
  14787. return this.option == null;
  14788. },
  14789. restoreData: function () {},
  14790. // Pending
  14791. clone: function () {
  14792. var Ctor = this.constructor;
  14793. return new Ctor(clone(this.option));
  14794. },
  14795. setReadOnly: function (properties) {
  14796. },
  14797. // If path is null/undefined, return null/undefined.
  14798. parsePath: function(path) {
  14799. if (typeof path === 'string') {
  14800. path = path.split('.');
  14801. }
  14802. return path;
  14803. },
  14804. /**
  14805. * @param {Function} getParentMethod
  14806. * param {Array.<string>|string} path
  14807. * return {module:echarts/model/Model}
  14808. */
  14809. customizeGetParent: function (getParentMethod) {
  14810. set$1(this, 'getParent', getParentMethod);
  14811. },
  14812. isAnimationEnabled: function () {
  14813. if (!env$1.node) {
  14814. if (this.option.animation != null) {
  14815. return !!this.option.animation;
  14816. }
  14817. else if (this.parentModel) {
  14818. return this.parentModel.isAnimationEnabled();
  14819. }
  14820. }
  14821. }
  14822. };
  14823. function doGet(obj, pathArr, parentModel) {
  14824. for (var i = 0; i < pathArr.length; i++) {
  14825. // Ignore empty
  14826. if (!pathArr[i]) {
  14827. continue;
  14828. }
  14829. // obj could be number/string/... (like 0)
  14830. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14831. if (obj == null) {
  14832. break;
  14833. }
  14834. }
  14835. if (obj == null && parentModel) {
  14836. obj = parentModel.get(pathArr);
  14837. }
  14838. return obj;
  14839. }
  14840. // `path` can be null/undefined
  14841. function getParent(model, path) {
  14842. var getParentMethod = get(model, 'getParent');
  14843. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14844. }
  14845. // Enable Model.extend.
  14846. enableClassExtend(Model);
  14847. mixin$1(Model, lineStyleMixin);
  14848. mixin$1(Model, areaStyleMixin);
  14849. mixin$1(Model, textStyleMixin);
  14850. mixin$1(Model, itemStyleMixin);
  14851. var each$3 = each$1;
  14852. var isObject$2 = isObject;
  14853. /**
  14854. * If value is not array, then translate it to array.
  14855. * @param {*} value
  14856. * @return {Array} [value] or value
  14857. */
  14858. function normalizeToArray(value) {
  14859. return value instanceof Array
  14860. ? value
  14861. : value == null
  14862. ? []
  14863. : [value];
  14864. }
  14865. /**
  14866. * Sync default option between normal and emphasis like `position` and `show`
  14867. * In case some one will write code like
  14868. * label: {
  14869. * normal: {
  14870. * show: false,
  14871. * position: 'outside',
  14872. * fontSize: 18
  14873. * },
  14874. * emphasis: {
  14875. * show: true
  14876. * }
  14877. * }
  14878. * @param {Object} opt
  14879. * @param {Array.<string>} subOpts
  14880. */
  14881. function defaultEmphasis(opt, subOpts) {
  14882. if (opt) {
  14883. var emphasisOpt = opt.emphasis = opt.emphasis || {};
  14884. var normalOpt = opt.normal = opt.normal || {};
  14885. // Default emphasis option from normal
  14886. for (var i = 0, len = subOpts.length; i < len; i++) {
  14887. var subOptName = subOpts[i];
  14888. if (!emphasisOpt.hasOwnProperty(subOptName)
  14889. && normalOpt.hasOwnProperty(subOptName)
  14890. ) {
  14891. emphasisOpt[subOptName] = normalOpt[subOptName];
  14892. }
  14893. }
  14894. }
  14895. }
  14896. var TEXT_STYLE_OPTIONS = [
  14897. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  14898. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  14899. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  14900. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  14901. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  14902. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  14903. ];
  14904. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  14905. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  14906. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  14907. // // FIXME: deprecated, check and remove it.
  14908. // 'textStyle'
  14909. // ]);
  14910. /**
  14911. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  14912. * This helper method retieves value from data.
  14913. * @param {string|number|Date|Array|Object} dataItem
  14914. * @return {number|string|Date|Array.<number|string|Date>}
  14915. */
  14916. function getDataItemValue(dataItem) {
  14917. // Performance sensitive.
  14918. return dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  14919. }
  14920. /**
  14921. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  14922. * This helper method determine if dataItem has extra option besides value
  14923. * @param {string|number|Date|Array|Object} dataItem
  14924. */
  14925. function isDataItemOption(dataItem) {
  14926. return isObject$2(dataItem)
  14927. && !(dataItem instanceof Array);
  14928. // // markLine data can be array
  14929. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  14930. }
  14931. /**
  14932. * This helper method convert value in data.
  14933. * @param {string|number|Date} value
  14934. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  14935. */
  14936. function converDataValue(value, dimInfo) {
  14937. // Performance sensitive.
  14938. var dimType = dimInfo && dimInfo.type;
  14939. if (dimType === 'ordinal') {
  14940. return value;
  14941. }
  14942. if (dimType === 'time'
  14943. // spead up when using timestamp
  14944. && typeof value !== 'number'
  14945. && value != null
  14946. && value !== '-'
  14947. ) {
  14948. value = +parseDate(value);
  14949. }
  14950. // dimType defaults 'number'.
  14951. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  14952. // parse to NaN.
  14953. return (value == null || value === '')
  14954. ? NaN : +value; // If string (like '-'), using '+' parse to NaN
  14955. }
  14956. /**
  14957. * Create a model proxy to be used in tooltip for edge data, markLine data, markPoint data.
  14958. * @param {module:echarts/data/List} data
  14959. * @param {Object} opt
  14960. * @param {string} [opt.seriesIndex]
  14961. * @param {Object} [opt.name]
  14962. * @param {Object} [opt.mainType]
  14963. * @param {Object} [opt.subType]
  14964. */
  14965. // PENDING A little ugly
  14966. var dataFormatMixin = {
  14967. /**
  14968. * Get params for formatter
  14969. * @param {number} dataIndex
  14970. * @param {string} [dataType]
  14971. * @return {Object}
  14972. */
  14973. getDataParams: function (dataIndex, dataType) {
  14974. var data = this.getData(dataType);
  14975. var rawValue = this.getRawValue(dataIndex, dataType);
  14976. var rawDataIndex = data.getRawIndex(dataIndex);
  14977. var name = data.getName(dataIndex, true);
  14978. var itemOpt = data.getRawDataItem(dataIndex);
  14979. var color = data.getItemVisual(dataIndex, 'color');
  14980. return {
  14981. componentType: this.mainType,
  14982. componentSubType: this.subType,
  14983. seriesType: this.mainType === 'series' ? this.subType : null,
  14984. seriesIndex: this.seriesIndex,
  14985. seriesId: this.id,
  14986. seriesName: this.name,
  14987. name: name,
  14988. dataIndex: rawDataIndex,
  14989. data: itemOpt,
  14990. dataType: dataType,
  14991. value: rawValue,
  14992. color: color,
  14993. marker: getTooltipMarker(color),
  14994. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  14995. $vars: ['seriesName', 'name', 'value']
  14996. };
  14997. },
  14998. /**
  14999. * Format label
  15000. * @param {number} dataIndex
  15001. * @param {string} [status='normal'] 'normal' or 'emphasis'
  15002. * @param {string} [dataType]
  15003. * @param {number} [dimIndex]
  15004. * @param {string} [labelProp='label']
  15005. * @return {string}
  15006. */
  15007. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  15008. status = status || 'normal';
  15009. var data = this.getData(dataType);
  15010. var itemModel = data.getItemModel(dataIndex);
  15011. var params = this.getDataParams(dataIndex, dataType);
  15012. if (dimIndex != null && (params.value instanceof Array)) {
  15013. params.value = params.value[dimIndex];
  15014. }
  15015. var formatter = itemModel.get([labelProp || 'label', status, 'formatter']);
  15016. if (typeof formatter === 'function') {
  15017. params.status = status;
  15018. return formatter(params);
  15019. }
  15020. else if (typeof formatter === 'string') {
  15021. return formatTpl(formatter, params);
  15022. }
  15023. },
  15024. /**
  15025. * Get raw value in option
  15026. * @param {number} idx
  15027. * @param {string} [dataType]
  15028. * @return {Object}
  15029. */
  15030. getRawValue: function (idx, dataType) {
  15031. var data = this.getData(dataType);
  15032. var dataItem = data.getRawDataItem(idx);
  15033. if (dataItem != null) {
  15034. return (isObject$2(dataItem) && !(dataItem instanceof Array))
  15035. ? dataItem.value : dataItem;
  15036. }
  15037. },
  15038. /**
  15039. * Should be implemented.
  15040. * @param {number} dataIndex
  15041. * @param {boolean} [multipleSeries=false]
  15042. * @param {number} [dataType]
  15043. * @return {string} tooltip string
  15044. */
  15045. formatTooltip: noop
  15046. };
  15047. /**
  15048. * Mapping to exists for merge.
  15049. *
  15050. * @public
  15051. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  15052. * @param {Object|Array.<Object>} newCptOptions
  15053. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  15054. * index of which is the same as exists.
  15055. */
  15056. function mappingToExists(exists, newCptOptions) {
  15057. // Mapping by the order by original option (but not order of
  15058. // new option) in merge mode. Because we should ensure
  15059. // some specified index (like xAxisIndex) is consistent with
  15060. // original option, which is easy to understand, espatially in
  15061. // media query. And in most case, merge option is used to
  15062. // update partial option but not be expected to change order.
  15063. newCptOptions = (newCptOptions || []).slice();
  15064. var result = map(exists || [], function (obj, index) {
  15065. return {exist: obj};
  15066. });
  15067. // Mapping by id or name if specified.
  15068. each$3(newCptOptions, function (cptOption, index) {
  15069. if (!isObject$2(cptOption)) {
  15070. return;
  15071. }
  15072. // id has highest priority.
  15073. for (var i = 0; i < result.length; i++) {
  15074. if (!result[i].option // Consider name: two map to one.
  15075. && cptOption.id != null
  15076. && result[i].exist.id === cptOption.id + ''
  15077. ) {
  15078. result[i].option = cptOption;
  15079. newCptOptions[index] = null;
  15080. return;
  15081. }
  15082. }
  15083. for (var i = 0; i < result.length; i++) {
  15084. var exist = result[i].exist;
  15085. if (!result[i].option // Consider name: two map to one.
  15086. // Can not match when both ids exist but different.
  15087. && (exist.id == null || cptOption.id == null)
  15088. && cptOption.name != null
  15089. && !isIdInner(cptOption)
  15090. && !isIdInner(exist)
  15091. && exist.name === cptOption.name + ''
  15092. ) {
  15093. result[i].option = cptOption;
  15094. newCptOptions[index] = null;
  15095. return;
  15096. }
  15097. }
  15098. });
  15099. // Otherwise mapping by index.
  15100. each$3(newCptOptions, function (cptOption, index) {
  15101. if (!isObject$2(cptOption)) {
  15102. return;
  15103. }
  15104. var i = 0;
  15105. for (; i < result.length; i++) {
  15106. var exist = result[i].exist;
  15107. if (!result[i].option
  15108. // Existing model that already has id should be able to
  15109. // mapped to (because after mapping performed model may
  15110. // be assigned with a id, whish should not affect next
  15111. // mapping), except those has inner id.
  15112. && !isIdInner(exist)
  15113. // Caution:
  15114. // Do not overwrite id. But name can be overwritten,
  15115. // because axis use name as 'show label text'.
  15116. // 'exist' always has id and name and we dont
  15117. // need to check it.
  15118. && cptOption.id == null
  15119. ) {
  15120. result[i].option = cptOption;
  15121. break;
  15122. }
  15123. }
  15124. if (i >= result.length) {
  15125. result.push({option: cptOption});
  15126. }
  15127. });
  15128. return result;
  15129. }
  15130. /**
  15131. * Make id and name for mapping result (result of mappingToExists)
  15132. * into `keyInfo` field.
  15133. *
  15134. * @public
  15135. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  15136. * which order is the same as exists.
  15137. * @return {Array.<Object>} The input.
  15138. */
  15139. function makeIdAndName(mapResult) {
  15140. // We use this id to hash component models and view instances
  15141. // in echarts. id can be specified by user, or auto generated.
  15142. // The id generation rule ensures new view instance are able
  15143. // to mapped to old instance when setOption are called in
  15144. // no-merge mode. So we generate model id by name and plus
  15145. // type in view id.
  15146. // name can be duplicated among components, which is convenient
  15147. // to specify multi components (like series) by one name.
  15148. // Ensure that each id is distinct.
  15149. var idMap = createHashMap();
  15150. each$3(mapResult, function (item, index) {
  15151. var existCpt = item.exist;
  15152. existCpt && idMap.set(existCpt.id, item);
  15153. });
  15154. each$3(mapResult, function (item, index) {
  15155. var opt = item.option;
  15156. assert(
  15157. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  15158. 'id duplicates: ' + (opt && opt.id)
  15159. );
  15160. opt && opt.id != null && idMap.set(opt.id, item);
  15161. !item.keyInfo && (item.keyInfo = {});
  15162. });
  15163. // Make name and id.
  15164. each$3(mapResult, function (item, index) {
  15165. var existCpt = item.exist;
  15166. var opt = item.option;
  15167. var keyInfo = item.keyInfo;
  15168. if (!isObject$2(opt)) {
  15169. return;
  15170. }
  15171. // name can be overwitten. Consider case: axis.name = '20km'.
  15172. // But id generated by name will not be changed, which affect
  15173. // only in that case: setOption with 'not merge mode' and view
  15174. // instance will be recreated, which can be accepted.
  15175. keyInfo.name = opt.name != null
  15176. ? opt.name + ''
  15177. : existCpt
  15178. ? existCpt.name
  15179. : '\0-'; // name may be displayed on screen, so use '-'.
  15180. if (existCpt) {
  15181. keyInfo.id = existCpt.id;
  15182. }
  15183. else if (opt.id != null) {
  15184. keyInfo.id = opt.id + '';
  15185. }
  15186. else {
  15187. // Consider this situatoin:
  15188. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  15189. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  15190. // Series with the same name between optionA and optionB
  15191. // should be mapped.
  15192. var idNum = 0;
  15193. do {
  15194. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  15195. }
  15196. while (idMap.get(keyInfo.id));
  15197. }
  15198. idMap.set(keyInfo.id, item);
  15199. });
  15200. }
  15201. /**
  15202. * @public
  15203. * @param {Object} cptOption
  15204. * @return {boolean}
  15205. */
  15206. function isIdInner(cptOption) {
  15207. return isObject$2(cptOption)
  15208. && cptOption.id
  15209. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  15210. }
  15211. /**
  15212. * A helper for removing duplicate items between batchA and batchB,
  15213. * and in themselves, and categorize by series.
  15214. *
  15215. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  15216. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  15217. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  15218. */
  15219. function compressBatches(batchA, batchB) {
  15220. var mapA = {};
  15221. var mapB = {};
  15222. makeMap(batchA || [], mapA);
  15223. makeMap(batchB || [], mapB, mapA);
  15224. return [mapToArray(mapA), mapToArray(mapB)];
  15225. function makeMap(sourceBatch, map$$1, otherMap) {
  15226. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  15227. var seriesId = sourceBatch[i].seriesId;
  15228. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  15229. var otherDataIndices = otherMap && otherMap[seriesId];
  15230. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  15231. var dataIndex = dataIndices[j];
  15232. if (otherDataIndices && otherDataIndices[dataIndex]) {
  15233. otherDataIndices[dataIndex] = null;
  15234. }
  15235. else {
  15236. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  15237. }
  15238. }
  15239. }
  15240. }
  15241. function mapToArray(map$$1, isData) {
  15242. var result = [];
  15243. for (var i in map$$1) {
  15244. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  15245. if (isData) {
  15246. result.push(+i);
  15247. }
  15248. else {
  15249. var dataIndices = mapToArray(map$$1[i], true);
  15250. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  15251. }
  15252. }
  15253. }
  15254. return result;
  15255. }
  15256. }
  15257. /**
  15258. * @param {module:echarts/data/List} data
  15259. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  15260. * each of which can be Array or primary type.
  15261. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  15262. */
  15263. function queryDataIndex(data, payload) {
  15264. if (payload.dataIndexInside != null) {
  15265. return payload.dataIndexInside;
  15266. }
  15267. else if (payload.dataIndex != null) {
  15268. return isArray(payload.dataIndex)
  15269. ? map(payload.dataIndex, function (value) {
  15270. return data.indexOfRawIndex(value);
  15271. })
  15272. : data.indexOfRawIndex(payload.dataIndex);
  15273. }
  15274. else if (payload.name != null) {
  15275. return isArray(payload.name)
  15276. ? map(payload.name, function (value) {
  15277. return data.indexOfName(value);
  15278. })
  15279. : data.indexOfName(payload.name);
  15280. }
  15281. }
  15282. /**
  15283. * Enable property storage to any host object.
  15284. * Notice: Serialization is not supported.
  15285. *
  15286. * For example:
  15287. * var get = modelUitl.makeGetter();
  15288. *
  15289. * function some(hostObj) {
  15290. * get(hostObj)._someProperty = 1212;
  15291. * ...
  15292. * }
  15293. *
  15294. * @return {Function}
  15295. */
  15296. var makeGetter = (function () {
  15297. var index = 0;
  15298. return function () {
  15299. var key = '\0__ec_prop_getter_' + index++;
  15300. return function (hostObj) {
  15301. return hostObj[key] || (hostObj[key] = {});
  15302. };
  15303. };
  15304. })();
  15305. /**
  15306. * @param {module:echarts/model/Global} ecModel
  15307. * @param {string|Object} finder
  15308. * If string, e.g., 'geo', means {geoIndex: 0}.
  15309. * If Object, could contain some of these properties below:
  15310. * {
  15311. * seriesIndex, seriesId, seriesName,
  15312. * geoIndex, geoId, geoName,
  15313. * bmapIndex, bmapId, bmapName,
  15314. * xAxisIndex, xAxisId, xAxisName,
  15315. * yAxisIndex, yAxisId, yAxisName,
  15316. * gridIndex, gridId, gridName,
  15317. * ... (can be extended)
  15318. * }
  15319. * Each properties can be number|string|Array.<number>|Array.<string>
  15320. * For example, a finder could be
  15321. * {
  15322. * seriesIndex: 3,
  15323. * geoId: ['aa', 'cc'],
  15324. * gridName: ['xx', 'rr']
  15325. * }
  15326. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  15327. * If nothing or null/undefined specified, return nothing.
  15328. * @param {Object} [opt]
  15329. * @param {string} [opt.defaultMainType]
  15330. * @param {Array.<string>} [opt.includeMainTypes]
  15331. * @return {Object} result like:
  15332. * {
  15333. * seriesModels: [seriesModel1, seriesModel2],
  15334. * seriesModel: seriesModel1, // The first model
  15335. * geoModels: [geoModel1, geoModel2],
  15336. * geoModel: geoModel1, // The first model
  15337. * ...
  15338. * }
  15339. */
  15340. function parseFinder(ecModel, finder, opt) {
  15341. if (isString(finder)) {
  15342. var obj = {};
  15343. obj[finder + 'Index'] = 0;
  15344. finder = obj;
  15345. }
  15346. var defaultMainType = opt && opt.defaultMainType;
  15347. if (defaultMainType
  15348. && !has(finder, defaultMainType + 'Index')
  15349. && !has(finder, defaultMainType + 'Id')
  15350. && !has(finder, defaultMainType + 'Name')
  15351. ) {
  15352. finder[defaultMainType + 'Index'] = 0;
  15353. }
  15354. var result = {};
  15355. each$3(finder, function (value, key) {
  15356. var value = finder[key];
  15357. // Exclude 'dataIndex' and other illgal keys.
  15358. if (key === 'dataIndex' || key === 'dataIndexInside') {
  15359. result[key] = value;
  15360. return;
  15361. }
  15362. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  15363. var mainType = parsedKey[1];
  15364. var queryType = (parsedKey[2] || '').toLowerCase();
  15365. if (!mainType
  15366. || !queryType
  15367. || value == null
  15368. || (queryType === 'index' && value === 'none')
  15369. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  15370. ) {
  15371. return;
  15372. }
  15373. var queryParam = {mainType: mainType};
  15374. if (queryType !== 'index' || value !== 'all') {
  15375. queryParam[queryType] = value;
  15376. }
  15377. var models = ecModel.queryComponents(queryParam);
  15378. result[mainType + 'Models'] = models;
  15379. result[mainType + 'Model'] = models[0];
  15380. });
  15381. return result;
  15382. }
  15383. /**
  15384. * @see {module:echarts/data/helper/completeDimensions}
  15385. * @param {module:echarts/data/List} data
  15386. * @param {string|number} dataDim
  15387. * @return {string}
  15388. */
  15389. function dataDimToCoordDim(data, dataDim) {
  15390. var dimensions = data.dimensions;
  15391. dataDim = data.getDimension(dataDim);
  15392. for (var i = 0; i < dimensions.length; i++) {
  15393. var dimItem = data.getDimensionInfo(dimensions[i]);
  15394. if (dimItem.name === dataDim) {
  15395. return dimItem.coordDim;
  15396. }
  15397. }
  15398. }
  15399. /**
  15400. * @see {module:echarts/data/helper/completeDimensions}
  15401. * @param {module:echarts/data/List} data
  15402. * @param {string} coordDim
  15403. * @return {Array.<string>} data dimensions on the coordDim.
  15404. */
  15405. function coordDimToDataDim(data, coordDim) {
  15406. var dataDim = [];
  15407. each$3(data.dimensions, function (dimName) {
  15408. var dimItem = data.getDimensionInfo(dimName);
  15409. if (dimItem.coordDim === coordDim) {
  15410. dataDim[dimItem.coordDimIndex] = dimItem.name;
  15411. }
  15412. });
  15413. return dataDim;
  15414. }
  15415. /**
  15416. * @see {module:echarts/data/helper/completeDimensions}
  15417. * @param {module:echarts/data/List} data
  15418. * @param {string} otherDim Can be `otherDims`
  15419. * like 'label' or 'tooltip'.
  15420. * @return {Array.<string>} data dimensions on the otherDim.
  15421. */
  15422. function otherDimToDataDim(data, otherDim) {
  15423. var dataDim = [];
  15424. each$3(data.dimensions, function (dimName) {
  15425. var dimItem = data.getDimensionInfo(dimName);
  15426. var otherDims = dimItem.otherDims;
  15427. var dimIndex = otherDims[otherDim];
  15428. if (dimIndex != null && dimIndex !== false) {
  15429. dataDim[dimIndex] = dimItem.name;
  15430. }
  15431. });
  15432. return dataDim;
  15433. }
  15434. function has(obj, prop) {
  15435. return obj && obj.hasOwnProperty(prop);
  15436. }
  15437. var base = 0;
  15438. var DELIMITER = '_';
  15439. /**
  15440. * @public
  15441. * @param {string} type
  15442. * @return {string}
  15443. */
  15444. function getUID(type) {
  15445. // Considering the case of crossing js context,
  15446. // use Math.random to make id as unique as possible.
  15447. return [(type || ''), base++, Math.random()].join(DELIMITER);
  15448. }
  15449. /**
  15450. * @inner
  15451. */
  15452. function enableSubTypeDefaulter(entity) {
  15453. var subTypeDefaulters = {};
  15454. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15455. componentType = parseClassType$1(componentType);
  15456. subTypeDefaulters[componentType.main] = defaulter;
  15457. };
  15458. entity.determineSubType = function (componentType, option) {
  15459. var type = option.type;
  15460. if (!type) {
  15461. var componentTypeMain = parseClassType$1(componentType).main;
  15462. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15463. type = subTypeDefaulters[componentTypeMain](option);
  15464. }
  15465. }
  15466. return type;
  15467. };
  15468. return entity;
  15469. }
  15470. /**
  15471. * Topological travel on Activity Network (Activity On Vertices).
  15472. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15473. *
  15474. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15475. *
  15476. * If there is circle dependencey, Error will be thrown.
  15477. *
  15478. */
  15479. function enableTopologicalTravel(entity, dependencyGetter) {
  15480. /**
  15481. * @public
  15482. * @param {Array.<string>} targetNameList Target Component type list.
  15483. * Can be ['aa', 'bb', 'aa.xx']
  15484. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15485. * @param {Function} callback Params: componentType, dependencies.
  15486. * @param {Object} context Scope of callback.
  15487. */
  15488. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15489. if (!targetNameList.length) {
  15490. return;
  15491. }
  15492. var result = makeDepndencyGraph(fullNameList);
  15493. var graph = result.graph;
  15494. var stack = result.noEntryList;
  15495. var targetNameSet = {};
  15496. each$1(targetNameList, function (name) {
  15497. targetNameSet[name] = true;
  15498. });
  15499. while (stack.length) {
  15500. var currComponentType = stack.pop();
  15501. var currVertex = graph[currComponentType];
  15502. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15503. if (isInTargetNameSet) {
  15504. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15505. delete targetNameSet[currComponentType];
  15506. }
  15507. each$1(
  15508. currVertex.successor,
  15509. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15510. );
  15511. }
  15512. each$1(targetNameSet, function () {
  15513. throw new Error('Circle dependency may exists');
  15514. });
  15515. function removeEdge(succComponentType) {
  15516. graph[succComponentType].entryCount--;
  15517. if (graph[succComponentType].entryCount === 0) {
  15518. stack.push(succComponentType);
  15519. }
  15520. }
  15521. // Consider this case: legend depends on series, and we call
  15522. // chart.setOption({series: [...]}), where only series is in option.
  15523. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15524. // not be called, but only sereis.mergeOption is called. Thus legend
  15525. // have no chance to update its local record about series (like which
  15526. // name of series is available in legend).
  15527. function removeEdgeAndAdd(succComponentType) {
  15528. targetNameSet[succComponentType] = true;
  15529. removeEdge(succComponentType);
  15530. }
  15531. };
  15532. /**
  15533. * DepndencyGraph: {Object}
  15534. * key: conponentType,
  15535. * value: {
  15536. * successor: [conponentTypes...],
  15537. * originalDeps: [conponentTypes...],
  15538. * entryCount: {number}
  15539. * }
  15540. */
  15541. function makeDepndencyGraph(fullNameList) {
  15542. var graph = {};
  15543. var noEntryList = [];
  15544. each$1(fullNameList, function (name) {
  15545. var thisItem = createDependencyGraphItem(graph, name);
  15546. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15547. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15548. thisItem.entryCount = availableDeps.length;
  15549. if (thisItem.entryCount === 0) {
  15550. noEntryList.push(name);
  15551. }
  15552. each$1(availableDeps, function (dependentName) {
  15553. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15554. thisItem.predecessor.push(dependentName);
  15555. }
  15556. var thatItem = createDependencyGraphItem(graph, dependentName);
  15557. if (indexOf(thatItem.successor, dependentName) < 0) {
  15558. thatItem.successor.push(name);
  15559. }
  15560. });
  15561. });
  15562. return {graph: graph, noEntryList: noEntryList};
  15563. }
  15564. function createDependencyGraphItem(graph, name) {
  15565. if (!graph[name]) {
  15566. graph[name] = {predecessor: [], successor: []};
  15567. }
  15568. return graph[name];
  15569. }
  15570. function getAvailableDependencies(originalDeps, fullNameList) {
  15571. var availableDeps = [];
  15572. each$1(originalDeps, function (dep) {
  15573. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15574. });
  15575. return availableDeps;
  15576. }
  15577. }
  15578. // Layout helpers for each component positioning
  15579. var each$4 = each$1;
  15580. /**
  15581. * @public
  15582. */
  15583. var LOCATION_PARAMS = [
  15584. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15585. ];
  15586. /**
  15587. * @public
  15588. */
  15589. var HV_NAMES = [
  15590. ['width', 'left', 'right'],
  15591. ['height', 'top', 'bottom']
  15592. ];
  15593. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15594. var x = 0;
  15595. var y = 0;
  15596. if (maxWidth == null) {
  15597. maxWidth = Infinity;
  15598. }
  15599. if (maxHeight == null) {
  15600. maxHeight = Infinity;
  15601. }
  15602. var currentLineMaxSize = 0;
  15603. group.eachChild(function (child, idx) {
  15604. var position = child.position;
  15605. var rect = child.getBoundingRect();
  15606. var nextChild = group.childAt(idx + 1);
  15607. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15608. var nextX;
  15609. var nextY;
  15610. if (orient === 'horizontal') {
  15611. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15612. nextX = x + moveX;
  15613. // Wrap when width exceeds maxWidth or meet a `newline` group
  15614. // FIXME compare before adding gap?
  15615. if (nextX > maxWidth || child.newline) {
  15616. x = 0;
  15617. nextX = moveX;
  15618. y += currentLineMaxSize + gap;
  15619. currentLineMaxSize = rect.height;
  15620. }
  15621. else {
  15622. // FIXME: consider rect.y is not `0`?
  15623. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15624. }
  15625. }
  15626. else {
  15627. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15628. nextY = y + moveY;
  15629. // Wrap when width exceeds maxHeight or meet a `newline` group
  15630. if (nextY > maxHeight || child.newline) {
  15631. x += currentLineMaxSize + gap;
  15632. y = 0;
  15633. nextY = moveY;
  15634. currentLineMaxSize = rect.width;
  15635. }
  15636. else {
  15637. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15638. }
  15639. }
  15640. if (child.newline) {
  15641. return;
  15642. }
  15643. position[0] = x;
  15644. position[1] = y;
  15645. orient === 'horizontal'
  15646. ? (x = nextX + gap)
  15647. : (y = nextY + gap);
  15648. });
  15649. }
  15650. /**
  15651. * VBox or HBox layouting
  15652. * @param {string} orient
  15653. * @param {module:zrender/container/Group} group
  15654. * @param {number} gap
  15655. * @param {number} [width=Infinity]
  15656. * @param {number} [height=Infinity]
  15657. */
  15658. var box = boxLayout;
  15659. /**
  15660. * VBox layouting
  15661. * @param {module:zrender/container/Group} group
  15662. * @param {number} gap
  15663. * @param {number} [width=Infinity]
  15664. * @param {number} [height=Infinity]
  15665. */
  15666. var vbox = curry(boxLayout, 'vertical');
  15667. /**
  15668. * HBox layouting
  15669. * @param {module:zrender/container/Group} group
  15670. * @param {number} gap
  15671. * @param {number} [width=Infinity]
  15672. * @param {number} [height=Infinity]
  15673. */
  15674. var hbox = curry(boxLayout, 'horizontal');
  15675. /**
  15676. * If x or x2 is not specified or 'center' 'left' 'right',
  15677. * the width would be as long as possible.
  15678. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15679. * the height would be as long as possible.
  15680. *
  15681. * @param {Object} positionInfo
  15682. * @param {number|string} [positionInfo.x]
  15683. * @param {number|string} [positionInfo.y]
  15684. * @param {number|string} [positionInfo.x2]
  15685. * @param {number|string} [positionInfo.y2]
  15686. * @param {Object} containerRect {width, height}
  15687. * @param {string|number} margin
  15688. * @return {Object} {width, height}
  15689. */
  15690. function getAvailableSize(positionInfo, containerRect, margin) {
  15691. var containerWidth = containerRect.width;
  15692. var containerHeight = containerRect.height;
  15693. var x = parsePercent$1(positionInfo.x, containerWidth);
  15694. var y = parsePercent$1(positionInfo.y, containerHeight);
  15695. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  15696. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  15697. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  15698. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  15699. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  15700. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  15701. margin = normalizeCssArray$1(margin || 0);
  15702. return {
  15703. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15704. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15705. };
  15706. }
  15707. /**
  15708. * Parse position info.
  15709. *
  15710. * @param {Object} positionInfo
  15711. * @param {number|string} [positionInfo.left]
  15712. * @param {number|string} [positionInfo.top]
  15713. * @param {number|string} [positionInfo.right]
  15714. * @param {number|string} [positionInfo.bottom]
  15715. * @param {number|string} [positionInfo.width]
  15716. * @param {number|string} [positionInfo.height]
  15717. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15718. * @param {Object} containerRect
  15719. * @param {string|number} [margin]
  15720. *
  15721. * @return {module:zrender/core/BoundingRect}
  15722. */
  15723. function getLayoutRect(
  15724. positionInfo, containerRect, margin
  15725. ) {
  15726. margin = normalizeCssArray$1(margin || 0);
  15727. var containerWidth = containerRect.width;
  15728. var containerHeight = containerRect.height;
  15729. var left = parsePercent$1(positionInfo.left, containerWidth);
  15730. var top = parsePercent$1(positionInfo.top, containerHeight);
  15731. var right = parsePercent$1(positionInfo.right, containerWidth);
  15732. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15733. var width = parsePercent$1(positionInfo.width, containerWidth);
  15734. var height = parsePercent$1(positionInfo.height, containerHeight);
  15735. var verticalMargin = margin[2] + margin[0];
  15736. var horizontalMargin = margin[1] + margin[3];
  15737. var aspect = positionInfo.aspect;
  15738. // If width is not specified, calculate width from left and right
  15739. if (isNaN(width)) {
  15740. width = containerWidth - right - horizontalMargin - left;
  15741. }
  15742. if (isNaN(height)) {
  15743. height = containerHeight - bottom - verticalMargin - top;
  15744. }
  15745. if (aspect != null) {
  15746. // If width and height are not given
  15747. // 1. Graph should not exceeds the container
  15748. // 2. Aspect must be keeped
  15749. // 3. Graph should take the space as more as possible
  15750. // FIXME
  15751. // Margin is not considered, because there is no case that both
  15752. // using margin and aspect so far.
  15753. if (isNaN(width) && isNaN(height)) {
  15754. if (aspect > containerWidth / containerHeight) {
  15755. width = containerWidth * 0.8;
  15756. }
  15757. else {
  15758. height = containerHeight * 0.8;
  15759. }
  15760. }
  15761. // Calculate width or height with given aspect
  15762. if (isNaN(width)) {
  15763. width = aspect * height;
  15764. }
  15765. if (isNaN(height)) {
  15766. height = width / aspect;
  15767. }
  15768. }
  15769. // If left is not specified, calculate left from right and width
  15770. if (isNaN(left)) {
  15771. left = containerWidth - right - width - horizontalMargin;
  15772. }
  15773. if (isNaN(top)) {
  15774. top = containerHeight - bottom - height - verticalMargin;
  15775. }
  15776. // Align left and top
  15777. switch (positionInfo.left || positionInfo.right) {
  15778. case 'center':
  15779. left = containerWidth / 2 - width / 2 - margin[3];
  15780. break;
  15781. case 'right':
  15782. left = containerWidth - width - horizontalMargin;
  15783. break;
  15784. }
  15785. switch (positionInfo.top || positionInfo.bottom) {
  15786. case 'middle':
  15787. case 'center':
  15788. top = containerHeight / 2 - height / 2 - margin[0];
  15789. break;
  15790. case 'bottom':
  15791. top = containerHeight - height - verticalMargin;
  15792. break;
  15793. }
  15794. // If something is wrong and left, top, width, height are calculated as NaN
  15795. left = left || 0;
  15796. top = top || 0;
  15797. if (isNaN(width)) {
  15798. // Width may be NaN if only one value is given except width
  15799. width = containerWidth - horizontalMargin - left - (right || 0);
  15800. }
  15801. if (isNaN(height)) {
  15802. // Height may be NaN if only one value is given except height
  15803. height = containerHeight - verticalMargin - top - (bottom || 0);
  15804. }
  15805. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15806. rect.margin = margin;
  15807. return rect;
  15808. }
  15809. /**
  15810. * Position a zr element in viewport
  15811. * Group position is specified by either
  15812. * {left, top}, {right, bottom}
  15813. * If all properties exists, right and bottom will be igonred.
  15814. *
  15815. * Logic:
  15816. * 1. Scale (against origin point in parent coord)
  15817. * 2. Rotate (against origin point in parent coord)
  15818. * 3. Traslate (with el.position by this method)
  15819. * So this method only fixes the last step 'Traslate', which does not affect
  15820. * scaling and rotating.
  15821. *
  15822. * If be called repeatly with the same input el, the same result will be gotten.
  15823. *
  15824. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15825. * @param {Object} positionInfo
  15826. * @param {number|string} [positionInfo.left]
  15827. * @param {number|string} [positionInfo.top]
  15828. * @param {number|string} [positionInfo.right]
  15829. * @param {number|string} [positionInfo.bottom]
  15830. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15831. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15832. * @param {Object} containerRect
  15833. * @param {string|number} margin
  15834. * @param {Object} [opt]
  15835. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15836. * @param {Array.<number>} [opt.boundingMode='all']
  15837. * Specify how to calculate boundingRect when locating.
  15838. * 'all': Position the boundingRect that is transformed and uioned
  15839. * both itself and its descendants.
  15840. * This mode simplies confine the elements in the bounding
  15841. * of their container (e.g., using 'right: 0').
  15842. * 'raw': Position the boundingRect that is not transformed and only itself.
  15843. * This mode is useful when you want a element can overflow its
  15844. * container. (Consider a rotated circle needs to be located in a corner.)
  15845. * In this mode positionInfo.width/height can only be number.
  15846. */
  15847. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15848. var h = !opt || !opt.hv || opt.hv[0];
  15849. var v = !opt || !opt.hv || opt.hv[1];
  15850. var boundingMode = opt && opt.boundingMode || 'all';
  15851. if (!h && !v) {
  15852. return;
  15853. }
  15854. var rect;
  15855. if (boundingMode === 'raw') {
  15856. rect = el.type === 'group'
  15857. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15858. : el.getBoundingRect();
  15859. }
  15860. else {
  15861. rect = el.getBoundingRect();
  15862. if (el.needLocalTransform()) {
  15863. var transform = el.getLocalTransform();
  15864. // Notice: raw rect may be inner object of el,
  15865. // which should not be modified.
  15866. rect = rect.clone();
  15867. rect.applyTransform(transform);
  15868. }
  15869. }
  15870. // The real width and height can not be specified but calculated by the given el.
  15871. positionInfo = getLayoutRect(
  15872. defaults(
  15873. {width: rect.width, height: rect.height},
  15874. positionInfo
  15875. ),
  15876. containerRect,
  15877. margin
  15878. );
  15879. // Because 'tranlate' is the last step in transform
  15880. // (see zrender/core/Transformable#getLocalTransfrom),
  15881. // we can just only modify el.position to get final result.
  15882. var elPos = el.position;
  15883. var dx = h ? positionInfo.x - rect.x : 0;
  15884. var dy = v ? positionInfo.y - rect.y : 0;
  15885. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15886. }
  15887. /**
  15888. * @param {Object} option Contains some of the properties in HV_NAMES.
  15889. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15890. */
  15891. function sizeCalculable(option, hvIdx) {
  15892. return option[HV_NAMES[hvIdx][0]] != null
  15893. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  15894. }
  15895. /**
  15896. * Consider Case:
  15897. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15898. * through setOption or media query, using normal zrUtil.merge will cause
  15899. * {right: 0} does not take effect.
  15900. *
  15901. * @example
  15902. * ComponentModel.extend({
  15903. * init: function () {
  15904. * ...
  15905. * var inputPositionParams = layout.getLayoutParams(option);
  15906. * this.mergeOption(inputPositionParams);
  15907. * },
  15908. * mergeOption: function (newOption) {
  15909. * newOption && zrUtil.merge(thisOption, newOption, true);
  15910. * layout.mergeLayoutParam(thisOption, newOption);
  15911. * }
  15912. * });
  15913. *
  15914. * @param {Object} targetOption
  15915. * @param {Object} newOption
  15916. * @param {Object|string} [opt]
  15917. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15918. * that width (or height) should not be calculated by left and right (or top and bottom).
  15919. */
  15920. function mergeLayoutParam(targetOption, newOption, opt) {
  15921. !isObject(opt) && (opt = {});
  15922. var ignoreSize = opt.ignoreSize;
  15923. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15924. var hResult = merge$$1(HV_NAMES[0], 0);
  15925. var vResult = merge$$1(HV_NAMES[1], 1);
  15926. copy(HV_NAMES[0], targetOption, hResult);
  15927. copy(HV_NAMES[1], targetOption, vResult);
  15928. function merge$$1(names, hvIdx) {
  15929. var newParams = {};
  15930. var newValueCount = 0;
  15931. var merged = {};
  15932. var mergedValueCount = 0;
  15933. var enoughParamNumber = 2;
  15934. each$4(names, function (name) {
  15935. merged[name] = targetOption[name];
  15936. });
  15937. each$4(names, function (name) {
  15938. // Consider case: newOption.width is null, which is
  15939. // set by user for removing width setting.
  15940. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15941. hasValue(newParams, name) && newValueCount++;
  15942. hasValue(merged, name) && mergedValueCount++;
  15943. });
  15944. if (ignoreSize[hvIdx]) {
  15945. // Only one of left/right is premitted to exist.
  15946. if (hasValue(newOption, names[1])) {
  15947. merged[names[2]] = null;
  15948. }
  15949. else if (hasValue(newOption, names[2])) {
  15950. merged[names[1]] = null;
  15951. }
  15952. return merged;
  15953. }
  15954. // Case: newOption: {width: ..., right: ...},
  15955. // or targetOption: {right: ...} and newOption: {width: ...},
  15956. // There is no conflict when merged only has params count
  15957. // little than enoughParamNumber.
  15958. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15959. return merged;
  15960. }
  15961. // Case: newOption: {width: ..., right: ...},
  15962. // Than we can make sure user only want those two, and ignore
  15963. // all origin params in targetOption.
  15964. else if (newValueCount >= enoughParamNumber) {
  15965. return newParams;
  15966. }
  15967. else {
  15968. // Chose another param from targetOption by priority.
  15969. for (var i = 0; i < names.length; i++) {
  15970. var name = names[i];
  15971. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  15972. newParams[name] = targetOption[name];
  15973. break;
  15974. }
  15975. }
  15976. return newParams;
  15977. }
  15978. }
  15979. function hasProp(obj, name) {
  15980. return obj.hasOwnProperty(name);
  15981. }
  15982. function hasValue(obj, name) {
  15983. return obj[name] != null && obj[name] !== 'auto';
  15984. }
  15985. function copy(names, target, source) {
  15986. each$4(names, function (name) {
  15987. target[name] = source[name];
  15988. });
  15989. }
  15990. }
  15991. /**
  15992. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15993. * @param {Object} source
  15994. * @return {Object} Result contains those props.
  15995. */
  15996. function getLayoutParams(source) {
  15997. return copyLayoutParams({}, source);
  15998. }
  15999. /**
  16000. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16001. * @param {Object} source
  16002. * @return {Object} Result contains those props.
  16003. */
  16004. function copyLayoutParams(target, source) {
  16005. source && target && each$4(LOCATION_PARAMS, function (name) {
  16006. source.hasOwnProperty(name) && (target[name] = source[name]);
  16007. });
  16008. return target;
  16009. }
  16010. var boxLayoutMixin = {
  16011. getBoxLayoutParams: function () {
  16012. return {
  16013. left: this.get('left'),
  16014. top: this.get('top'),
  16015. right: this.get('right'),
  16016. bottom: this.get('bottom'),
  16017. width: this.get('width'),
  16018. height: this.get('height')
  16019. };
  16020. }
  16021. };
  16022. /**
  16023. * Component model
  16024. *
  16025. * @module echarts/model/Component
  16026. */
  16027. var arrayPush = Array.prototype.push;
  16028. /**
  16029. * @alias module:echarts/model/Component
  16030. * @constructor
  16031. * @param {Object} option
  16032. * @param {module:echarts/model/Model} parentModel
  16033. * @param {module:echarts/model/Model} ecModel
  16034. */
  16035. var ComponentModel = Model.extend({
  16036. type: 'component',
  16037. /**
  16038. * @readOnly
  16039. * @type {string}
  16040. */
  16041. id: '',
  16042. /**
  16043. * @readOnly
  16044. */
  16045. name: '',
  16046. /**
  16047. * @readOnly
  16048. * @type {string}
  16049. */
  16050. mainType: '',
  16051. /**
  16052. * @readOnly
  16053. * @type {string}
  16054. */
  16055. subType: '',
  16056. /**
  16057. * @readOnly
  16058. * @type {number}
  16059. */
  16060. componentIndex: 0,
  16061. /**
  16062. * @type {Object}
  16063. * @protected
  16064. */
  16065. defaultOption: null,
  16066. /**
  16067. * @type {module:echarts/model/Global}
  16068. * @readOnly
  16069. */
  16070. ecModel: null,
  16071. /**
  16072. * key: componentType
  16073. * value: Component model list, can not be null.
  16074. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16075. * @readOnly
  16076. */
  16077. dependentModels: [],
  16078. /**
  16079. * @type {string}
  16080. * @readOnly
  16081. */
  16082. uid: null,
  16083. /**
  16084. * Support merge layout params.
  16085. * Only support 'box' now (left/right/top/bottom/width/height).
  16086. * @type {string|Object} Object can be {ignoreSize: true}
  16087. * @readOnly
  16088. */
  16089. layoutMode: null,
  16090. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16091. Model.call(this, option, parentModel, ecModel, extraOpt);
  16092. this.uid = getUID('componentModel');
  16093. },
  16094. init: function (option, parentModel, ecModel, extraOpt) {
  16095. this.mergeDefaultAndTheme(option, ecModel);
  16096. },
  16097. mergeDefaultAndTheme: function (option, ecModel) {
  16098. var layoutMode = this.layoutMode;
  16099. var inputPositionParams = layoutMode
  16100. ? getLayoutParams(option) : {};
  16101. var themeModel = ecModel.getTheme();
  16102. merge(option, themeModel.get(this.mainType));
  16103. merge(option, this.getDefaultOption());
  16104. if (layoutMode) {
  16105. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16106. }
  16107. },
  16108. mergeOption: function (option, extraOpt) {
  16109. merge(this.option, option, true);
  16110. var layoutMode = this.layoutMode;
  16111. if (layoutMode) {
  16112. mergeLayoutParam(this.option, option, layoutMode);
  16113. }
  16114. },
  16115. // Hooker after init or mergeOption
  16116. optionUpdated: function (newCptOption, isInit) {},
  16117. getDefaultOption: function () {
  16118. if (!hasOwn(this, '__defaultOption')) {
  16119. var optList = [];
  16120. var Class = this.constructor;
  16121. while (Class) {
  16122. var opt = Class.prototype.defaultOption;
  16123. opt && optList.push(opt);
  16124. Class = Class.superClass;
  16125. }
  16126. var defaultOption = {};
  16127. for (var i = optList.length - 1; i >= 0; i--) {
  16128. defaultOption = merge(defaultOption, optList[i], true);
  16129. }
  16130. set$1(this, '__defaultOption', defaultOption);
  16131. }
  16132. return get(this, '__defaultOption');
  16133. },
  16134. getReferringComponents: function (mainType) {
  16135. return this.ecModel.queryComponents({
  16136. mainType: mainType,
  16137. index: this.get(mainType + 'Index', true),
  16138. id: this.get(mainType + 'Id', true)
  16139. });
  16140. }
  16141. });
  16142. // Reset ComponentModel.extend, add preConstruct.
  16143. // clazzUtil.enableClassExtend(
  16144. // ComponentModel,
  16145. // function (option, parentModel, ecModel, extraOpt) {
  16146. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16147. // zrUtil.extend(this, extraOpt);
  16148. // this.uid = componentUtil.getUID('componentModel');
  16149. // // this.setReadOnly([
  16150. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16151. // // 'dependentModels', 'componentIndex'
  16152. // // ]);
  16153. // }
  16154. // );
  16155. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16156. enableClassManagement(
  16157. ComponentModel, {registerWhenExtend: true}
  16158. );
  16159. enableSubTypeDefaulter(ComponentModel);
  16160. // Add capability of ComponentModel.topologicalTravel.
  16161. enableTopologicalTravel(ComponentModel, getDependencies);
  16162. function getDependencies(componentType) {
  16163. var deps = [];
  16164. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16165. arrayPush.apply(deps, Clazz.prototype.dependencies || []);
  16166. });
  16167. // Ensure main type
  16168. return map(deps, function (type) {
  16169. return parseClassType$1(type).main;
  16170. });
  16171. }
  16172. mixin(ComponentModel, boxLayoutMixin);
  16173. var platform = '';
  16174. // Navigator not exists in node
  16175. if (typeof navigator !== 'undefined') {
  16176. platform = navigator.platform || '';
  16177. }
  16178. var globalDefault = {
  16179. // 全图默认背景
  16180. // backgroundColor: 'rgba(0,0,0,0)',
  16181. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16182. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16183. // 浅色
  16184. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16185. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16186. // 深色
  16187. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16188. // 默认需要 Grid 配置项
  16189. // grid: {},
  16190. // 主题,主题
  16191. textStyle: {
  16192. // color: '#000',
  16193. // decoration: 'none',
  16194. // PENDING
  16195. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16196. // fontFamily: 'Arial, Verdana, sans-serif',
  16197. fontSize: 12,
  16198. fontStyle: 'normal',
  16199. fontWeight: 'normal'
  16200. },
  16201. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16202. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16203. // Default is source-over
  16204. blendMode: null,
  16205. animation: 'auto',
  16206. animationDuration: 1000,
  16207. animationDurationUpdate: 300,
  16208. animationEasing: 'exponentialOut',
  16209. animationEasingUpdate: 'cubicOut',
  16210. animationThreshold: 2000,
  16211. // Configuration for progressive/incremental rendering
  16212. progressiveThreshold: 3000,
  16213. progressive: 400,
  16214. // Threshold of if use single hover layer to optimize.
  16215. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16216. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16217. // which is unexpected.
  16218. // see example <echarts/test/heatmap-large.html>.
  16219. hoverLayerThreshold: 3000,
  16220. // See: module:echarts/scale/Time
  16221. useUTC: false
  16222. };
  16223. var colorPaletteMixin = {
  16224. clearColorPalette: function () {
  16225. set$1(this, 'colorIdx', 0);
  16226. set$1(this, 'colorNameMap', {});
  16227. },
  16228. getColorFromPalette: function (name, scope) {
  16229. scope = scope || this;
  16230. var colorIdx = get(scope, 'colorIdx') || 0;
  16231. var colorNameMap = get(scope, 'colorNameMap') || set$1(scope, 'colorNameMap', {});
  16232. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16233. if (colorNameMap.hasOwnProperty(name)) {
  16234. return colorNameMap[name];
  16235. }
  16236. var colorPalette = this.get('color', true) || [];
  16237. if (!colorPalette.length) {
  16238. return;
  16239. }
  16240. var color = colorPalette[colorIdx];
  16241. if (name) {
  16242. colorNameMap[name] = color;
  16243. }
  16244. set$1(scope, 'colorIdx', (colorIdx + 1) % colorPalette.length);
  16245. return color;
  16246. }
  16247. };
  16248. /**
  16249. * ECharts global model
  16250. *
  16251. * @module {echarts/model/Global}
  16252. */
  16253. /**
  16254. * Caution: If the mechanism should be changed some day, these cases
  16255. * should be considered:
  16256. *
  16257. * (1) In `merge option` mode, if using the same option to call `setOption`
  16258. * many times, the result should be the same (try our best to ensure that).
  16259. * (2) In `merge option` mode, if a component has no id/name specified, it
  16260. * will be merged by index, and the result sequence of the components is
  16261. * consistent to the original sequence.
  16262. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  16263. * `mergeOption` in module:echarts/model/OptionManager.
  16264. */
  16265. var each$2 = each$1;
  16266. var filter$1 = filter;
  16267. var map$1 = map;
  16268. var isArray$1 = isArray;
  16269. var indexOf$1 = indexOf;
  16270. var isObject$1 = isObject;
  16271. var OPTION_INNER_KEY = '\0_ec_inner';
  16272. /**
  16273. * @alias module:echarts/model/Global
  16274. *
  16275. * @param {Object} option
  16276. * @param {module:echarts/model/Model} parentModel
  16277. * @param {Object} theme
  16278. */
  16279. var GlobalModel = Model.extend({
  16280. constructor: GlobalModel,
  16281. init: function (option, parentModel, theme, optionManager) {
  16282. theme = theme || {};
  16283. this.option = null; // Mark as not initialized.
  16284. /**
  16285. * @type {module:echarts/model/Model}
  16286. * @private
  16287. */
  16288. this._theme = new Model(theme);
  16289. /**
  16290. * @type {module:echarts/model/OptionManager}
  16291. */
  16292. this._optionManager = optionManager;
  16293. },
  16294. setOption: function (option, optionPreprocessorFuncs) {
  16295. assert(
  16296. !(OPTION_INNER_KEY in option),
  16297. 'please use chart.getOption()'
  16298. );
  16299. this._optionManager.setOption(option, optionPreprocessorFuncs);
  16300. this.resetOption(null);
  16301. },
  16302. /**
  16303. * @param {string} type null/undefined: reset all.
  16304. * 'recreate': force recreate all.
  16305. * 'timeline': only reset timeline option
  16306. * 'media': only reset media query option
  16307. * @return {boolean} Whether option changed.
  16308. */
  16309. resetOption: function (type) {
  16310. var optionChanged = false;
  16311. var optionManager = this._optionManager;
  16312. if (!type || type === 'recreate') {
  16313. var baseOption = optionManager.mountOption(type === 'recreate');
  16314. if (!this.option || type === 'recreate') {
  16315. initBase.call(this, baseOption);
  16316. }
  16317. else {
  16318. this.restoreData();
  16319. this.mergeOption(baseOption);
  16320. }
  16321. optionChanged = true;
  16322. }
  16323. if (type === 'timeline' || type === 'media') {
  16324. this.restoreData();
  16325. }
  16326. if (!type || type === 'recreate' || type === 'timeline') {
  16327. var timelineOption = optionManager.getTimelineOption(this);
  16328. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  16329. }
  16330. if (!type || type === 'recreate' || type === 'media') {
  16331. var mediaOptions = optionManager.getMediaOption(this, this._api);
  16332. if (mediaOptions.length) {
  16333. each$2(mediaOptions, function (mediaOption) {
  16334. this.mergeOption(mediaOption, optionChanged = true);
  16335. }, this);
  16336. }
  16337. }
  16338. return optionChanged;
  16339. },
  16340. /**
  16341. * @protected
  16342. */
  16343. mergeOption: function (newOption) {
  16344. var option = this.option;
  16345. var componentsMap = this._componentsMap;
  16346. var newCptTypes = [];
  16347. // 如果不存在对应的 component model 则直接 merge
  16348. each$2(newOption, function (componentOption, mainType) {
  16349. if (componentOption == null) {
  16350. return;
  16351. }
  16352. if (!ComponentModel.hasClass(mainType)) {
  16353. option[mainType] = option[mainType] == null
  16354. ? clone(componentOption)
  16355. : merge(option[mainType], componentOption, true);
  16356. }
  16357. else {
  16358. newCptTypes.push(mainType);
  16359. }
  16360. });
  16361. // FIXME OPTION 同步是否要改回原来的
  16362. ComponentModel.topologicalTravel(
  16363. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  16364. );
  16365. this._seriesIndices = this._seriesIndices || [];
  16366. function visitComponent(mainType, dependencies) {
  16367. var newCptOptionList = normalizeToArray(newOption[mainType]);
  16368. var mapResult = mappingToExists(
  16369. componentsMap.get(mainType), newCptOptionList
  16370. );
  16371. makeIdAndName(mapResult);
  16372. // Set mainType and complete subType.
  16373. each$2(mapResult, function (item, index) {
  16374. var opt = item.option;
  16375. if (isObject$1(opt)) {
  16376. item.keyInfo.mainType = mainType;
  16377. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  16378. }
  16379. });
  16380. var dependentModels = getComponentsByTypes(
  16381. componentsMap, dependencies
  16382. );
  16383. option[mainType] = [];
  16384. componentsMap.set(mainType, []);
  16385. each$2(mapResult, function (resultItem, index) {
  16386. var componentModel = resultItem.exist;
  16387. var newCptOption = resultItem.option;
  16388. assert(
  16389. isObject$1(newCptOption) || componentModel,
  16390. 'Empty component definition'
  16391. );
  16392. // Consider where is no new option and should be merged using {},
  16393. // see removeEdgeAndAdd in topologicalTravel and
  16394. // ComponentModel.getAllClassMainTypes.
  16395. if (!newCptOption) {
  16396. componentModel.mergeOption({}, this);
  16397. componentModel.optionUpdated({}, false);
  16398. }
  16399. else {
  16400. var ComponentModelClass = ComponentModel.getClass(
  16401. mainType, resultItem.keyInfo.subType, true
  16402. );
  16403. if (componentModel && componentModel instanceof ComponentModelClass) {
  16404. componentModel.name = resultItem.keyInfo.name;
  16405. componentModel.mergeOption(newCptOption, this);
  16406. componentModel.optionUpdated(newCptOption, false);
  16407. }
  16408. else {
  16409. // PENDING Global as parent ?
  16410. var extraOpt = extend(
  16411. {
  16412. dependentModels: dependentModels,
  16413. componentIndex: index
  16414. },
  16415. resultItem.keyInfo
  16416. );
  16417. componentModel = new ComponentModelClass(
  16418. newCptOption, this, this, extraOpt
  16419. );
  16420. extend(componentModel, extraOpt);
  16421. componentModel.init(newCptOption, this, this, extraOpt);
  16422. // Call optionUpdated after init.
  16423. // newCptOption has been used as componentModel.option
  16424. // and may be merged with theme and default, so pass null
  16425. // to avoid confusion.
  16426. componentModel.optionUpdated(null, true);
  16427. }
  16428. }
  16429. componentsMap.get(mainType)[index] = componentModel;
  16430. option[mainType][index] = componentModel.option;
  16431. }, this);
  16432. // Backup series for filtering.
  16433. if (mainType === 'series') {
  16434. this._seriesIndices = createSeriesIndices(componentsMap.get('series'));
  16435. }
  16436. }
  16437. },
  16438. /**
  16439. * Get option for output (cloned option and inner info removed)
  16440. * @public
  16441. * @return {Object}
  16442. */
  16443. getOption: function () {
  16444. var option = clone(this.option);
  16445. each$2(option, function (opts, mainType) {
  16446. if (ComponentModel.hasClass(mainType)) {
  16447. var opts = normalizeToArray(opts);
  16448. for (var i = opts.length - 1; i >= 0; i--) {
  16449. // Remove options with inner id.
  16450. if (isIdInner(opts[i])) {
  16451. opts.splice(i, 1);
  16452. }
  16453. }
  16454. option[mainType] = opts;
  16455. }
  16456. });
  16457. delete option[OPTION_INNER_KEY];
  16458. return option;
  16459. },
  16460. /**
  16461. * @return {module:echarts/model/Model}
  16462. */
  16463. getTheme: function () {
  16464. return this._theme;
  16465. },
  16466. /**
  16467. * @param {string} mainType
  16468. * @param {number} [idx=0]
  16469. * @return {module:echarts/model/Component}
  16470. */
  16471. getComponent: function (mainType, idx) {
  16472. var list = this._componentsMap.get(mainType);
  16473. if (list) {
  16474. return list[idx || 0];
  16475. }
  16476. },
  16477. /**
  16478. * If none of index and id and name used, return all components with mainType.
  16479. * @param {Object} condition
  16480. * @param {string} condition.mainType
  16481. * @param {string} [condition.subType] If ignore, only query by mainType
  16482. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  16483. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  16484. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  16485. * @return {Array.<module:echarts/model/Component>}
  16486. */
  16487. queryComponents: function (condition) {
  16488. var mainType = condition.mainType;
  16489. if (!mainType) {
  16490. return [];
  16491. }
  16492. var index = condition.index;
  16493. var id = condition.id;
  16494. var name = condition.name;
  16495. var cpts = this._componentsMap.get(mainType);
  16496. if (!cpts || !cpts.length) {
  16497. return [];
  16498. }
  16499. var result;
  16500. if (index != null) {
  16501. if (!isArray$1(index)) {
  16502. index = [index];
  16503. }
  16504. result = filter$1(map$1(index, function (idx) {
  16505. return cpts[idx];
  16506. }), function (val) {
  16507. return !!val;
  16508. });
  16509. }
  16510. else if (id != null) {
  16511. var isIdArray = isArray$1(id);
  16512. result = filter$1(cpts, function (cpt) {
  16513. return (isIdArray && indexOf$1(id, cpt.id) >= 0)
  16514. || (!isIdArray && cpt.id === id);
  16515. });
  16516. }
  16517. else if (name != null) {
  16518. var isNameArray = isArray$1(name);
  16519. result = filter$1(cpts, function (cpt) {
  16520. return (isNameArray && indexOf$1(name, cpt.name) >= 0)
  16521. || (!isNameArray && cpt.name === name);
  16522. });
  16523. }
  16524. else {
  16525. // Return all components with mainType
  16526. result = cpts.slice();
  16527. }
  16528. return filterBySubType(result, condition);
  16529. },
  16530. /**
  16531. * The interface is different from queryComponents,
  16532. * which is convenient for inner usage.
  16533. *
  16534. * @usage
  16535. * var result = findComponents(
  16536. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16537. * );
  16538. * var result = findComponents(
  16539. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16540. * );
  16541. * var result = findComponents(
  16542. * {mainType: 'series'},
  16543. * function (model, index) {...}
  16544. * );
  16545. * // result like [component0, componnet1, ...]
  16546. *
  16547. * @param {Object} condition
  16548. * @param {string} condition.mainType Mandatory.
  16549. * @param {string} [condition.subType] Optional.
  16550. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  16551. * where xxx is mainType.
  16552. * If query attribute is null/undefined or has no index/id/name,
  16553. * do not filtering by query conditions, which is convenient for
  16554. * no-payload situations or when target of action is global.
  16555. * @param {Function} [condition.filter] parameter: component, return boolean.
  16556. * @return {Array.<module:echarts/model/Component>}
  16557. */
  16558. findComponents: function (condition) {
  16559. var query = condition.query;
  16560. var mainType = condition.mainType;
  16561. var queryCond = getQueryCond(query);
  16562. var result = queryCond
  16563. ? this.queryComponents(queryCond)
  16564. : this._componentsMap.get(mainType);
  16565. return doFilter(filterBySubType(result, condition));
  16566. function getQueryCond(q) {
  16567. var indexAttr = mainType + 'Index';
  16568. var idAttr = mainType + 'Id';
  16569. var nameAttr = mainType + 'Name';
  16570. return q && (
  16571. q[indexAttr] != null
  16572. || q[idAttr] != null
  16573. || q[nameAttr] != null
  16574. )
  16575. ? {
  16576. mainType: mainType,
  16577. // subType will be filtered finally.
  16578. index: q[indexAttr],
  16579. id: q[idAttr],
  16580. name: q[nameAttr]
  16581. }
  16582. : null;
  16583. }
  16584. function doFilter(res) {
  16585. return condition.filter
  16586. ? filter$1(res, condition.filter)
  16587. : res;
  16588. }
  16589. },
  16590. /**
  16591. * @usage
  16592. * eachComponent('legend', function (legendModel, index) {
  16593. * ...
  16594. * });
  16595. * eachComponent(function (componentType, model, index) {
  16596. * // componentType does not include subType
  16597. * // (componentType is 'xxx' but not 'xxx.aa')
  16598. * });
  16599. * eachComponent(
  16600. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  16601. * function (model, index) {...}
  16602. * );
  16603. * eachComponent(
  16604. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  16605. * function (model, index) {...}
  16606. * );
  16607. *
  16608. * @param {string|Object=} mainType When mainType is object, the definition
  16609. * is the same as the method 'findComponents'.
  16610. * @param {Function} cb
  16611. * @param {*} context
  16612. */
  16613. eachComponent: function (mainType, cb, context) {
  16614. var componentsMap = this._componentsMap;
  16615. if (typeof mainType === 'function') {
  16616. context = cb;
  16617. cb = mainType;
  16618. componentsMap.each(function (components, componentType) {
  16619. each$2(components, function (component, index) {
  16620. cb.call(context, componentType, component, index);
  16621. });
  16622. });
  16623. }
  16624. else if (isString(mainType)) {
  16625. each$2(componentsMap.get(mainType), cb, context);
  16626. }
  16627. else if (isObject$1(mainType)) {
  16628. var queryResult = this.findComponents(mainType);
  16629. each$2(queryResult, cb, context);
  16630. }
  16631. },
  16632. /**
  16633. * @param {string} name
  16634. * @return {Array.<module:echarts/model/Series>}
  16635. */
  16636. getSeriesByName: function (name) {
  16637. var series = this._componentsMap.get('series');
  16638. return filter$1(series, function (oneSeries) {
  16639. return oneSeries.name === name;
  16640. });
  16641. },
  16642. /**
  16643. * @param {number} seriesIndex
  16644. * @return {module:echarts/model/Series}
  16645. */
  16646. getSeriesByIndex: function (seriesIndex) {
  16647. return this._componentsMap.get('series')[seriesIndex];
  16648. },
  16649. /**
  16650. * @param {string} subType
  16651. * @return {Array.<module:echarts/model/Series>}
  16652. */
  16653. getSeriesByType: function (subType) {
  16654. var series = this._componentsMap.get('series');
  16655. return filter$1(series, function (oneSeries) {
  16656. return oneSeries.subType === subType;
  16657. });
  16658. },
  16659. /**
  16660. * @return {Array.<module:echarts/model/Series>}
  16661. */
  16662. getSeries: function () {
  16663. return this._componentsMap.get('series').slice();
  16664. },
  16665. /**
  16666. * After filtering, series may be different
  16667. * frome raw series.
  16668. *
  16669. * @param {Function} cb
  16670. * @param {*} context
  16671. */
  16672. eachSeries: function (cb, context) {
  16673. assertSeriesInitialized(this);
  16674. each$2(this._seriesIndices, function (rawSeriesIndex) {
  16675. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16676. cb.call(context, series, rawSeriesIndex);
  16677. }, this);
  16678. },
  16679. /**
  16680. * Iterate raw series before filtered.
  16681. *
  16682. * @param {Function} cb
  16683. * @param {*} context
  16684. */
  16685. eachRawSeries: function (cb, context) {
  16686. each$2(this._componentsMap.get('series'), cb, context);
  16687. },
  16688. /**
  16689. * After filtering, series may be different.
  16690. * frome raw series.
  16691. *
  16692. * @parma {string} subType
  16693. * @param {Function} cb
  16694. * @param {*} context
  16695. */
  16696. eachSeriesByType: function (subType, cb, context) {
  16697. assertSeriesInitialized(this);
  16698. each$2(this._seriesIndices, function (rawSeriesIndex) {
  16699. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16700. if (series.subType === subType) {
  16701. cb.call(context, series, rawSeriesIndex);
  16702. }
  16703. }, this);
  16704. },
  16705. /**
  16706. * Iterate raw series before filtered of given type.
  16707. *
  16708. * @parma {string} subType
  16709. * @param {Function} cb
  16710. * @param {*} context
  16711. */
  16712. eachRawSeriesByType: function (subType, cb, context) {
  16713. return each$2(this.getSeriesByType(subType), cb, context);
  16714. },
  16715. /**
  16716. * @param {module:echarts/model/Series} seriesModel
  16717. */
  16718. isSeriesFiltered: function (seriesModel) {
  16719. assertSeriesInitialized(this);
  16720. return indexOf(this._seriesIndices, seriesModel.componentIndex) < 0;
  16721. },
  16722. /**
  16723. * @return {Array.<number>}
  16724. */
  16725. getCurrentSeriesIndices: function () {
  16726. return (this._seriesIndices || []).slice();
  16727. },
  16728. /**
  16729. * @param {Function} cb
  16730. * @param {*} context
  16731. */
  16732. filterSeries: function (cb, context) {
  16733. assertSeriesInitialized(this);
  16734. var filteredSeries = filter$1(
  16735. this._componentsMap.get('series'), cb, context
  16736. );
  16737. this._seriesIndices = createSeriesIndices(filteredSeries);
  16738. },
  16739. restoreData: function () {
  16740. var componentsMap = this._componentsMap;
  16741. this._seriesIndices = createSeriesIndices(componentsMap.get('series'));
  16742. var componentTypes = [];
  16743. componentsMap.each(function (components, componentType) {
  16744. componentTypes.push(componentType);
  16745. });
  16746. ComponentModel.topologicalTravel(
  16747. componentTypes,
  16748. ComponentModel.getAllClassMainTypes(),
  16749. function (componentType, dependencies) {
  16750. each$2(componentsMap.get(componentType), function (component) {
  16751. component.restoreData();
  16752. });
  16753. }
  16754. );
  16755. }
  16756. });
  16757. /**
  16758. * @inner
  16759. */
  16760. function mergeTheme(option, theme) {
  16761. each$1(theme, function (themeItem, name) {
  16762. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  16763. if (!ComponentModel.hasClass(name)) {
  16764. if (typeof themeItem === 'object') {
  16765. option[name] = !option[name]
  16766. ? clone(themeItem)
  16767. : merge(option[name], themeItem, false);
  16768. }
  16769. else {
  16770. if (option[name] == null) {
  16771. option[name] = themeItem;
  16772. }
  16773. }
  16774. }
  16775. });
  16776. }
  16777. function initBase(baseOption) {
  16778. baseOption = baseOption;
  16779. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  16780. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  16781. this.option = {};
  16782. this.option[OPTION_INNER_KEY] = 1;
  16783. /**
  16784. * Init with series: [], in case of calling findSeries method
  16785. * before series initialized.
  16786. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16787. * @private
  16788. */
  16789. this._componentsMap = createHashMap({series: []});
  16790. /**
  16791. * Mapping between filtered series list and raw series list.
  16792. * key: filtered series indices, value: raw series indices.
  16793. * @type {Array.<nubmer>}
  16794. * @private
  16795. */
  16796. this._seriesIndices = null;
  16797. mergeTheme(baseOption, this._theme.option);
  16798. // TODO Needs clone when merging to the unexisted property
  16799. merge(baseOption, globalDefault, false);
  16800. this.mergeOption(baseOption);
  16801. }
  16802. /**
  16803. * @inner
  16804. * @param {Array.<string>|string} types model types
  16805. * @return {Object} key: {string} type, value: {Array.<Object>} models
  16806. */
  16807. function getComponentsByTypes(componentsMap, types) {
  16808. if (!isArray(types)) {
  16809. types = types ? [types] : [];
  16810. }
  16811. var ret = {};
  16812. each$2(types, function (type) {
  16813. ret[type] = (componentsMap.get(type) || []).slice();
  16814. });
  16815. return ret;
  16816. }
  16817. /**
  16818. * @inner
  16819. */
  16820. function determineSubType(mainType, newCptOption, existComponent) {
  16821. var subType = newCptOption.type
  16822. ? newCptOption.type
  16823. : existComponent
  16824. ? existComponent.subType
  16825. // Use determineSubType only when there is no existComponent.
  16826. : ComponentModel.determineSubType(mainType, newCptOption);
  16827. // tooltip, markline, markpoint may always has no subType
  16828. return subType;
  16829. }
  16830. /**
  16831. * @inner
  16832. */
  16833. function createSeriesIndices(seriesModels) {
  16834. return map$1(seriesModels, function (series) {
  16835. return series.componentIndex;
  16836. }) || [];
  16837. }
  16838. /**
  16839. * @inner
  16840. */
  16841. function filterBySubType(components, condition) {
  16842. // Using hasOwnProperty for restrict. Consider
  16843. // subType is undefined in user payload.
  16844. return condition.hasOwnProperty('subType')
  16845. ? filter$1(components, function (cpt) {
  16846. return cpt.subType === condition.subType;
  16847. })
  16848. : components;
  16849. }
  16850. /**
  16851. * @inner
  16852. */
  16853. function assertSeriesInitialized(ecModel) {
  16854. // Components that use _seriesIndices should depends on series component,
  16855. // which make sure that their initialization is after series.
  16856. if (__DEV__) {
  16857. if (!ecModel._seriesIndices) {
  16858. throw new Error('Option should contains series.');
  16859. }
  16860. }
  16861. }
  16862. mixin(GlobalModel, colorPaletteMixin);
  16863. var echartsAPIList = [
  16864. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  16865. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  16866. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  16867. ];
  16868. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  16869. function ExtensionAPI(chartInstance) {
  16870. each$1(echartsAPIList, function (name) {
  16871. this[name] = bind(chartInstance[name], chartInstance);
  16872. }, this);
  16873. }
  16874. var coordinateSystemCreators = {};
  16875. function CoordinateSystemManager() {
  16876. this._coordinateSystems = [];
  16877. }
  16878. CoordinateSystemManager.prototype = {
  16879. constructor: CoordinateSystemManager,
  16880. create: function (ecModel, api) {
  16881. var coordinateSystems = [];
  16882. each$1(coordinateSystemCreators, function (creater, type) {
  16883. var list = creater.create(ecModel, api);
  16884. coordinateSystems = coordinateSystems.concat(list || []);
  16885. });
  16886. this._coordinateSystems = coordinateSystems;
  16887. },
  16888. update: function (ecModel, api) {
  16889. each$1(this._coordinateSystems, function (coordSys) {
  16890. // FIXME MUST have
  16891. coordSys.update && coordSys.update(ecModel, api);
  16892. });
  16893. },
  16894. getCoordinateSystems: function () {
  16895. return this._coordinateSystems.slice();
  16896. }
  16897. };
  16898. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  16899. coordinateSystemCreators[type] = coordinateSystemCreator;
  16900. };
  16901. CoordinateSystemManager.get = function (type) {
  16902. return coordinateSystemCreators[type];
  16903. };
  16904. /**
  16905. * ECharts option manager
  16906. *
  16907. * @module {echarts/model/OptionManager}
  16908. */
  16909. var each$5 = each$1;
  16910. var clone$2 = clone;
  16911. var map$2 = map;
  16912. var merge$1 = merge;
  16913. var QUERY_REG = /^(min|max)?(.+)$/;
  16914. /**
  16915. * TERM EXPLANATIONS:
  16916. *
  16917. * [option]:
  16918. *
  16919. * An object that contains definitions of components. For example:
  16920. * var option = {
  16921. * title: {...},
  16922. * legend: {...},
  16923. * visualMap: {...},
  16924. * series: [
  16925. * {data: [...]},
  16926. * {data: [...]},
  16927. * ...
  16928. * ]
  16929. * };
  16930. *
  16931. * [rawOption]:
  16932. *
  16933. * An object input to echarts.setOption. 'rawOption' may be an
  16934. * 'option', or may be an object contains multi-options. For example:
  16935. * var option = {
  16936. * baseOption: {
  16937. * title: {...},
  16938. * legend: {...},
  16939. * series: [
  16940. * {data: [...]},
  16941. * {data: [...]},
  16942. * ...
  16943. * ]
  16944. * },
  16945. * timeline: {...},
  16946. * options: [
  16947. * {title: {...}, series: {data: [...]}},
  16948. * {title: {...}, series: {data: [...]}},
  16949. * ...
  16950. * ],
  16951. * media: [
  16952. * {
  16953. * query: {maxWidth: 320},
  16954. * option: {series: {x: 20}, visualMap: {show: false}}
  16955. * },
  16956. * {
  16957. * query: {minWidth: 320, maxWidth: 720},
  16958. * option: {series: {x: 500}, visualMap: {show: true}}
  16959. * },
  16960. * {
  16961. * option: {series: {x: 1200}, visualMap: {show: true}}
  16962. * }
  16963. * ]
  16964. * };
  16965. *
  16966. * @alias module:echarts/model/OptionManager
  16967. * @param {module:echarts/ExtensionAPI} api
  16968. */
  16969. function OptionManager(api) {
  16970. /**
  16971. * @private
  16972. * @type {module:echarts/ExtensionAPI}
  16973. */
  16974. this._api = api;
  16975. /**
  16976. * @private
  16977. * @type {Array.<number>}
  16978. */
  16979. this._timelineOptions = [];
  16980. /**
  16981. * @private
  16982. * @type {Array.<Object>}
  16983. */
  16984. this._mediaList = [];
  16985. /**
  16986. * @private
  16987. * @type {Object}
  16988. */
  16989. this._mediaDefault;
  16990. /**
  16991. * -1, means default.
  16992. * empty means no media.
  16993. * @private
  16994. * @type {Array.<number>}
  16995. */
  16996. this._currentMediaIndices = [];
  16997. /**
  16998. * @private
  16999. * @type {Object}
  17000. */
  17001. this._optionBackup;
  17002. /**
  17003. * @private
  17004. * @type {Object}
  17005. */
  17006. this._newBaseOption;
  17007. }
  17008. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17009. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17010. // rawOption cloned and backuped when timeline changed, which does no
  17011. // good to performance. What's more, that both timeline and setOption
  17012. // method supply 'notMerge' brings complex and some problems.
  17013. // Consider this case:
  17014. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17015. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17016. OptionManager.prototype = {
  17017. constructor: OptionManager,
  17018. /**
  17019. * @public
  17020. * @param {Object} rawOption Raw option.
  17021. * @param {module:echarts/model/Global} ecModel
  17022. * @param {Array.<Function>} optionPreprocessorFuncs
  17023. * @return {Object} Init option
  17024. */
  17025. setOption: function (rawOption, optionPreprocessorFuncs) {
  17026. rawOption = clone$2(rawOption, true);
  17027. // FIXME
  17028. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17029. var oldOptionBackup = this._optionBackup;
  17030. var newParsedOption = parseRawOption.call(
  17031. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17032. );
  17033. this._newBaseOption = newParsedOption.baseOption;
  17034. // For setOption at second time (using merge mode);
  17035. if (oldOptionBackup) {
  17036. // Only baseOption can be merged.
  17037. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17038. // For simplicity, timeline options and media options do not support merge,
  17039. // that is, if you `setOption` twice and both has timeline options, the latter
  17040. // timeline opitons will not be merged to the formers, but just substitude them.
  17041. if (newParsedOption.timelineOptions.length) {
  17042. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17043. }
  17044. if (newParsedOption.mediaList.length) {
  17045. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17046. }
  17047. if (newParsedOption.mediaDefault) {
  17048. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17049. }
  17050. }
  17051. else {
  17052. this._optionBackup = newParsedOption;
  17053. }
  17054. },
  17055. /**
  17056. * @param {boolean} isRecreate
  17057. * @return {Object}
  17058. */
  17059. mountOption: function (isRecreate) {
  17060. var optionBackup = this._optionBackup;
  17061. // TODO
  17062. // 如果没有reset功能则不clone。
  17063. this._timelineOptions = map$2(optionBackup.timelineOptions, clone$2);
  17064. this._mediaList = map$2(optionBackup.mediaList, clone$2);
  17065. this._mediaDefault = clone$2(optionBackup.mediaDefault);
  17066. this._currentMediaIndices = [];
  17067. return clone$2(isRecreate
  17068. // this._optionBackup.baseOption, which is created at the first `setOption`
  17069. // called, and is merged into every new option by inner method `mergeOption`
  17070. // each time `setOption` called, can be only used in `isRecreate`, because
  17071. // its reliability is under suspicion. In other cases option merge is
  17072. // performed by `model.mergeOption`.
  17073. ? optionBackup.baseOption : this._newBaseOption
  17074. );
  17075. },
  17076. /**
  17077. * @param {module:echarts/model/Global} ecModel
  17078. * @return {Object}
  17079. */
  17080. getTimelineOption: function (ecModel) {
  17081. var option;
  17082. var timelineOptions = this._timelineOptions;
  17083. if (timelineOptions.length) {
  17084. // getTimelineOption can only be called after ecModel inited,
  17085. // so we can get currentIndex from timelineModel.
  17086. var timelineModel = ecModel.getComponent('timeline');
  17087. if (timelineModel) {
  17088. option = clone$2(
  17089. timelineOptions[timelineModel.getCurrentIndex()],
  17090. true
  17091. );
  17092. }
  17093. }
  17094. return option;
  17095. },
  17096. /**
  17097. * @param {module:echarts/model/Global} ecModel
  17098. * @return {Array.<Object>}
  17099. */
  17100. getMediaOption: function (ecModel) {
  17101. var ecWidth = this._api.getWidth();
  17102. var ecHeight = this._api.getHeight();
  17103. var mediaList = this._mediaList;
  17104. var mediaDefault = this._mediaDefault;
  17105. var indices = [];
  17106. var result = [];
  17107. // No media defined.
  17108. if (!mediaList.length && !mediaDefault) {
  17109. return result;
  17110. }
  17111. // Multi media may be applied, the latter defined media has higher priority.
  17112. for (var i = 0, len = mediaList.length; i < len; i++) {
  17113. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17114. indices.push(i);
  17115. }
  17116. }
  17117. // FIXME
  17118. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17119. if (!indices.length && mediaDefault) {
  17120. indices = [-1];
  17121. }
  17122. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17123. result = map$2(indices, function (index) {
  17124. return clone$2(
  17125. index === -1 ? mediaDefault.option : mediaList[index].option
  17126. );
  17127. });
  17128. }
  17129. // Otherwise return nothing.
  17130. this._currentMediaIndices = indices;
  17131. return result;
  17132. }
  17133. };
  17134. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17135. var timelineOptions = [];
  17136. var mediaList = [];
  17137. var mediaDefault;
  17138. var baseOption;
  17139. // Compatible with ec2.
  17140. var timelineOpt = rawOption.timeline;
  17141. if (rawOption.baseOption) {
  17142. baseOption = rawOption.baseOption;
  17143. }
  17144. // For timeline
  17145. if (timelineOpt || rawOption.options) {
  17146. baseOption = baseOption || {};
  17147. timelineOptions = (rawOption.options || []).slice();
  17148. }
  17149. // For media query
  17150. if (rawOption.media) {
  17151. baseOption = baseOption || {};
  17152. var media = rawOption.media;
  17153. each$5(media, function (singleMedia) {
  17154. if (singleMedia && singleMedia.option) {
  17155. if (singleMedia.query) {
  17156. mediaList.push(singleMedia);
  17157. }
  17158. else if (!mediaDefault) {
  17159. // Use the first media default.
  17160. mediaDefault = singleMedia;
  17161. }
  17162. }
  17163. });
  17164. }
  17165. // For normal option
  17166. if (!baseOption) {
  17167. baseOption = rawOption;
  17168. }
  17169. // Set timelineOpt to baseOption in ec3,
  17170. // which is convenient for merge option.
  17171. if (!baseOption.timeline) {
  17172. baseOption.timeline = timelineOpt;
  17173. }
  17174. // Preprocess.
  17175. each$5([baseOption].concat(timelineOptions)
  17176. .concat(map(mediaList, function (media) {
  17177. return media.option;
  17178. })),
  17179. function (option) {
  17180. each$5(optionPreprocessorFuncs, function (preProcess) {
  17181. preProcess(option, isNew);
  17182. });
  17183. }
  17184. );
  17185. return {
  17186. baseOption: baseOption,
  17187. timelineOptions: timelineOptions,
  17188. mediaDefault: mediaDefault,
  17189. mediaList: mediaList
  17190. };
  17191. }
  17192. /**
  17193. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17194. * Support: width, height, aspectRatio
  17195. * Can use max or min as prefix.
  17196. */
  17197. function applyMediaQuery(query, ecWidth, ecHeight) {
  17198. var realMap = {
  17199. width: ecWidth,
  17200. height: ecHeight,
  17201. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17202. };
  17203. var applicatable = true;
  17204. each$1(query, function (value, attr) {
  17205. var matched = attr.match(QUERY_REG);
  17206. if (!matched || !matched[1] || !matched[2]) {
  17207. return;
  17208. }
  17209. var operator = matched[1];
  17210. var realAttr = matched[2].toLowerCase();
  17211. if (!compare(realMap[realAttr], value, operator)) {
  17212. applicatable = false;
  17213. }
  17214. });
  17215. return applicatable;
  17216. }
  17217. function compare(real, expect, operator) {
  17218. if (operator === 'min') {
  17219. return real >= expect;
  17220. }
  17221. else if (operator === 'max') {
  17222. return real <= expect;
  17223. }
  17224. else { // Equals
  17225. return real === expect;
  17226. }
  17227. }
  17228. function indicesEquals(indices1, indices2) {
  17229. // indices is always order by asc and has only finite number.
  17230. return indices1.join(',') === indices2.join(',');
  17231. }
  17232. /**
  17233. * Consider case:
  17234. * `chart.setOption(opt1);`
  17235. * Then user do some interaction like dataZoom, dataView changing.
  17236. * `chart.setOption(opt2);`
  17237. * Then user press 'reset button' in toolbox.
  17238. *
  17239. * After doing that all of the interaction effects should be reset, the
  17240. * chart should be the same as the result of invoke
  17241. * `chart.setOption(opt1); chart.setOption(opt2);`.
  17242. *
  17243. * Although it is not able ensure that
  17244. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  17245. * `chart.setOption(merge(opt1, opt2));` exactly,
  17246. * this might be the only simple way to implement that feature.
  17247. *
  17248. * MEMO: We've considered some other approaches:
  17249. * 1. Each model handle its self restoration but not uniform treatment.
  17250. * (Too complex in logic and error-prone)
  17251. * 2. Use a shadow ecModel. (Performace expensive)
  17252. */
  17253. function mergeOption(oldOption, newOption) {
  17254. newOption = newOption || {};
  17255. each$5(newOption, function (newCptOpt, mainType) {
  17256. if (newCptOpt == null) {
  17257. return;
  17258. }
  17259. var oldCptOpt = oldOption[mainType];
  17260. if (!ComponentModel.hasClass(mainType)) {
  17261. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  17262. }
  17263. else {
  17264. newCptOpt = normalizeToArray(newCptOpt);
  17265. oldCptOpt = normalizeToArray(oldCptOpt);
  17266. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  17267. oldOption[mainType] = map$2(mapResult, function (item) {
  17268. return (item.option && item.exist)
  17269. ? merge$1(item.exist, item.option, true)
  17270. : (item.exist || item.option);
  17271. });
  17272. }
  17273. });
  17274. }
  17275. var each$6 = each$1;
  17276. var isObject$3 = isObject;
  17277. var POSSIBLE_STYLES = [
  17278. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  17279. 'chordStyle', 'label', 'labelLine'
  17280. ];
  17281. function compatItemStyle(opt) {
  17282. var itemStyleOpt = opt && opt.itemStyle;
  17283. if (!itemStyleOpt) {
  17284. return;
  17285. }
  17286. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17287. var styleName = POSSIBLE_STYLES[i];
  17288. var normalItemStyleOpt = itemStyleOpt.normal;
  17289. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17290. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17291. opt[styleName] = opt[styleName] || {};
  17292. if (!opt[styleName].normal) {
  17293. opt[styleName].normal = normalItemStyleOpt[styleName];
  17294. }
  17295. else {
  17296. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17297. }
  17298. normalItemStyleOpt[styleName] = null;
  17299. }
  17300. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17301. opt[styleName] = opt[styleName] || {};
  17302. if (!opt[styleName].emphasis) {
  17303. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17304. }
  17305. else {
  17306. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17307. }
  17308. emphasisItemStyleOpt[styleName] = null;
  17309. }
  17310. }
  17311. }
  17312. function compatTextStyle(opt, propName) {
  17313. var labelOptSingle = isObject$3(opt) && opt[propName];
  17314. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  17315. if (textStyle) {
  17316. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17317. var propName = TEXT_STYLE_OPTIONS[i];
  17318. if (textStyle.hasOwnProperty(propName)) {
  17319. labelOptSingle[propName] = textStyle[propName];
  17320. }
  17321. }
  17322. }
  17323. }
  17324. function compatLabelTextStyle(labelOpt) {
  17325. if (isObject$3(labelOpt)) {
  17326. compatTextStyle(labelOpt, 'normal');
  17327. compatTextStyle(labelOpt, 'emphasis');
  17328. }
  17329. }
  17330. function processSeries(seriesOpt) {
  17331. if (!isObject$3(seriesOpt)) {
  17332. return;
  17333. }
  17334. compatItemStyle(seriesOpt);
  17335. compatLabelTextStyle(seriesOpt.label);
  17336. // treemap
  17337. compatLabelTextStyle(seriesOpt.upperLabel);
  17338. // graph
  17339. compatLabelTextStyle(seriesOpt.edgeLabel);
  17340. var markPoint = seriesOpt.markPoint;
  17341. compatItemStyle(markPoint);
  17342. compatLabelTextStyle(markPoint && markPoint.label);
  17343. var markLine = seriesOpt.markLine;
  17344. compatItemStyle(seriesOpt.markLine);
  17345. compatLabelTextStyle(markLine && markLine.label);
  17346. var markArea = seriesOpt.markArea;
  17347. compatLabelTextStyle(markArea && markArea.label);
  17348. // For gauge
  17349. compatTextStyle(seriesOpt, 'axisLabel');
  17350. compatTextStyle(seriesOpt, 'title');
  17351. compatTextStyle(seriesOpt, 'detail');
  17352. var data = seriesOpt.data;
  17353. if (data) {
  17354. for (var i = 0; i < data.length; i++) {
  17355. compatItemStyle(data[i]);
  17356. compatLabelTextStyle(data[i] && data[i].label);
  17357. }
  17358. }
  17359. // mark point data
  17360. var markPoint = seriesOpt.markPoint;
  17361. if (markPoint && markPoint.data) {
  17362. var mpData = markPoint.data;
  17363. for (var i = 0; i < mpData.length; i++) {
  17364. compatItemStyle(mpData[i]);
  17365. compatLabelTextStyle(mpData[i] && mpData[i].label);
  17366. }
  17367. }
  17368. // mark line data
  17369. var markLine = seriesOpt.markLine;
  17370. if (markLine && markLine.data) {
  17371. var mlData = markLine.data;
  17372. for (var i = 0; i < mlData.length; i++) {
  17373. if (isArray(mlData[i])) {
  17374. compatItemStyle(mlData[i][0]);
  17375. compatLabelTextStyle(mlData[i][0] && mlData[i][0].label);
  17376. compatItemStyle(mlData[i][1]);
  17377. compatLabelTextStyle(mlData[i][1] && mlData[i][1].label);
  17378. }
  17379. else {
  17380. compatItemStyle(mlData[i]);
  17381. compatLabelTextStyle(mlData[i] && mlData[i].label);
  17382. }
  17383. }
  17384. }
  17385. }
  17386. function toArr(o) {
  17387. return isArray(o) ? o : o ? [o] : [];
  17388. }
  17389. function toObj(o) {
  17390. return (isArray(o) ? o[0] : o) || {};
  17391. }
  17392. var compatStyle = function (option, isTheme) {
  17393. each$6(toArr(option.series), function (seriesOpt) {
  17394. isObject$3(seriesOpt) && processSeries(seriesOpt);
  17395. });
  17396. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17397. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17398. each$6(
  17399. axes,
  17400. function (axisName) {
  17401. each$6(toArr(option[axisName]), function (axisOpt) {
  17402. if (axisOpt) {
  17403. compatTextStyle(axisOpt, 'axisLabel');
  17404. compatTextStyle(axisOpt.axisPointer, 'label');
  17405. }
  17406. });
  17407. }
  17408. );
  17409. each$6(toArr(option.parallel), function (parallelOpt) {
  17410. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17411. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17412. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17413. });
  17414. each$6(toArr(option.calendar), function (calendarOpt) {
  17415. compatTextStyle(calendarOpt, 'dayLabel');
  17416. compatTextStyle(calendarOpt, 'monthLabel');
  17417. compatTextStyle(calendarOpt, 'yearLabel');
  17418. });
  17419. // radar.name.textStyle
  17420. each$6(toArr(option.radar), function (radarOpt) {
  17421. compatTextStyle(radarOpt, 'name');
  17422. });
  17423. each$6(toArr(option.geo), function (geoOpt) {
  17424. if (isObject$3(geoOpt)) {
  17425. compatLabelTextStyle(geoOpt.label);
  17426. each$6(toArr(geoOpt.regions), function (regionObj) {
  17427. compatLabelTextStyle(regionObj.label);
  17428. });
  17429. }
  17430. });
  17431. compatLabelTextStyle(toObj(option.timeline).label);
  17432. compatTextStyle(toObj(option.axisPointer), 'label');
  17433. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  17434. };
  17435. // Compatitable with 2.0
  17436. function get$1(opt, path) {
  17437. path = path.split(',');
  17438. var obj = opt;
  17439. for (var i = 0; i < path.length; i++) {
  17440. obj = obj && obj[path[i]];
  17441. if (obj == null) {
  17442. break;
  17443. }
  17444. }
  17445. return obj;
  17446. }
  17447. function set$2(opt, path, val, overwrite) {
  17448. path = path.split(',');
  17449. var obj = opt;
  17450. var key;
  17451. for (var i = 0; i < path.length - 1; i++) {
  17452. key = path[i];
  17453. if (obj[key] == null) {
  17454. obj[key] = {};
  17455. }
  17456. obj = obj[key];
  17457. }
  17458. if (overwrite || obj[path[i]] == null) {
  17459. obj[path[i]] = val;
  17460. }
  17461. }
  17462. function compatLayoutProperties(option) {
  17463. each$1(LAYOUT_PROPERTIES, function (prop) {
  17464. if (prop[0] in option && !(prop[1] in option)) {
  17465. option[prop[1]] = option[prop[0]];
  17466. }
  17467. });
  17468. }
  17469. var LAYOUT_PROPERTIES = [
  17470. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  17471. ];
  17472. var COMPATITABLE_COMPONENTS = [
  17473. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  17474. ];
  17475. var COMPATITABLE_SERIES = [
  17476. 'bar', 'boxplot', 'candlestick', 'chord', 'effectScatter',
  17477. 'funnel', 'gauge', 'lines', 'graph', 'heatmap', 'line', 'map', 'parallel',
  17478. 'pie', 'radar', 'sankey', 'scatter', 'treemap'
  17479. ];
  17480. var backwardCompat = function (option, isTheme) {
  17481. compatStyle(option, isTheme);
  17482. // Make sure series array for model initialization.
  17483. option.series = normalizeToArray(option.series);
  17484. each$1(option.series, function (seriesOpt) {
  17485. if (!isObject(seriesOpt)) {
  17486. return;
  17487. }
  17488. var seriesType = seriesOpt.type;
  17489. if (seriesType === 'pie' || seriesType === 'gauge') {
  17490. if (seriesOpt.clockWise != null) {
  17491. seriesOpt.clockwise = seriesOpt.clockWise;
  17492. }
  17493. }
  17494. if (seriesType === 'gauge') {
  17495. var pointerColor = get$1(seriesOpt, 'pointer.color');
  17496. pointerColor != null
  17497. && set$2(seriesOpt, 'itemStyle.normal.color', pointerColor);
  17498. }
  17499. for (var i = 0; i < COMPATITABLE_SERIES.length; i++) {
  17500. if (COMPATITABLE_SERIES[i] === seriesOpt.type) {
  17501. compatLayoutProperties(seriesOpt);
  17502. break;
  17503. }
  17504. }
  17505. });
  17506. // dataRange has changed to visualMap
  17507. if (option.dataRange) {
  17508. option.visualMap = option.dataRange;
  17509. }
  17510. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  17511. var options = option[componentName];
  17512. if (options) {
  17513. if (!isArray(options)) {
  17514. options = [options];
  17515. }
  17516. each$1(options, function (option) {
  17517. compatLayoutProperties(option);
  17518. });
  17519. }
  17520. });
  17521. };
  17522. var SeriesModel = ComponentModel.extend({
  17523. type: 'series.__base__',
  17524. /**
  17525. * @readOnly
  17526. */
  17527. seriesIndex: 0,
  17528. // coodinateSystem will be injected in the echarts/CoordinateSystem
  17529. coordinateSystem: null,
  17530. /**
  17531. * @type {Object}
  17532. * @protected
  17533. */
  17534. defaultOption: null,
  17535. /**
  17536. * Data provided for legend
  17537. * @type {Function}
  17538. */
  17539. // PENDING
  17540. legendDataProvider: null,
  17541. /**
  17542. * Access path of color for visual
  17543. */
  17544. visualColorAccessPath: 'itemStyle.normal.color',
  17545. /**
  17546. * Support merge layout params.
  17547. * Only support 'box' now (left/right/top/bottom/width/height).
  17548. * @type {string|Object} Object can be {ignoreSize: true}
  17549. * @readOnly
  17550. */
  17551. layoutMode: null,
  17552. init: function (option, parentModel, ecModel, extraOpt) {
  17553. /**
  17554. * @type {number}
  17555. * @readOnly
  17556. */
  17557. this.seriesIndex = this.componentIndex;
  17558. this.mergeDefaultAndTheme(option, ecModel);
  17559. var data = this.getInitialData(option, ecModel);
  17560. if (__DEV__) {
  17561. assert(data, 'getInitialData returned invalid data.');
  17562. }
  17563. /**
  17564. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  17565. * @private
  17566. */
  17567. set$1(this, 'dataBeforeProcessed', data);
  17568. // If we reverse the order (make data firstly, and then make
  17569. // dataBeforeProcessed by cloneShallow), cloneShallow will
  17570. // cause data.graph.data !== data when using
  17571. // module:echarts/data/Graph or module:echarts/data/Tree.
  17572. // See module:echarts/data/helper/linkList
  17573. this.restoreData();
  17574. },
  17575. /**
  17576. * Util for merge default and theme to option
  17577. * @param {Object} option
  17578. * @param {module:echarts/model/Global} ecModel
  17579. */
  17580. mergeDefaultAndTheme: function (option, ecModel) {
  17581. var layoutMode = this.layoutMode;
  17582. var inputPositionParams = layoutMode
  17583. ? getLayoutParams(option) : {};
  17584. // Backward compat: using subType on theme.
  17585. // But if name duplicate between series subType
  17586. // (for example: parallel) add component mainType,
  17587. // add suffix 'Series'.
  17588. var themeSubType = this.subType;
  17589. if (ComponentModel.hasClass(themeSubType)) {
  17590. themeSubType += 'Series';
  17591. }
  17592. merge(
  17593. option,
  17594. ecModel.getTheme().get(this.subType)
  17595. );
  17596. merge(option, this.getDefaultOption());
  17597. // Default label emphasis `show`
  17598. defaultEmphasis(option.label, ['show']);
  17599. this.fillDataTextStyle(option.data);
  17600. if (layoutMode) {
  17601. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17602. }
  17603. },
  17604. mergeOption: function (newSeriesOption, ecModel) {
  17605. newSeriesOption = merge(this.option, newSeriesOption, true);
  17606. this.fillDataTextStyle(newSeriesOption.data);
  17607. var layoutMode = this.layoutMode;
  17608. if (layoutMode) {
  17609. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  17610. }
  17611. var data = this.getInitialData(newSeriesOption, ecModel);
  17612. // TODO Merge data?
  17613. if (data) {
  17614. set$1(this, 'data', data);
  17615. set$1(this, 'dataBeforeProcessed', data.cloneShallow());
  17616. }
  17617. },
  17618. fillDataTextStyle: function (data) {
  17619. // Default data label emphasis `show`
  17620. // FIXME Tree structure data ?
  17621. // FIXME Performance ?
  17622. if (data) {
  17623. var props = ['show'];
  17624. for (var i = 0; i < data.length; i++) {
  17625. if (data[i] && data[i].label) {
  17626. defaultEmphasis(data[i].label, props);
  17627. }
  17628. }
  17629. }
  17630. },
  17631. /**
  17632. * Init a data structure from data related option in series
  17633. * Must be overwritten
  17634. */
  17635. getInitialData: function () {},
  17636. /**
  17637. * @param {string} [dataType]
  17638. * @return {module:echarts/data/List}
  17639. */
  17640. getData: function (dataType) {
  17641. var data = get(this, 'data');
  17642. return dataType == null ? data : data.getLinkedData(dataType);
  17643. },
  17644. /**
  17645. * @param {module:echarts/data/List} data
  17646. */
  17647. setData: function (data) {
  17648. set$1(this, 'data', data);
  17649. },
  17650. /**
  17651. * Get data before processed
  17652. * @return {module:echarts/data/List}
  17653. */
  17654. getRawData: function () {
  17655. return get(this, 'dataBeforeProcessed');
  17656. },
  17657. /**
  17658. * Coord dimension to data dimension.
  17659. *
  17660. * By default the result is the same as dimensions of series data.
  17661. * But in some series data dimensions are different from coord dimensions (i.e.
  17662. * candlestick and boxplot). Override this method to handle those cases.
  17663. *
  17664. * Coord dimension to data dimension can be one-to-many
  17665. *
  17666. * @param {string} coordDim
  17667. * @return {Array.<string>} dimensions on the axis.
  17668. */
  17669. coordDimToDataDim: function (coordDim) {
  17670. return coordDimToDataDim(this.getData(), coordDim);
  17671. },
  17672. /**
  17673. * Convert data dimension to coord dimension.
  17674. *
  17675. * @param {string|number} dataDim
  17676. * @return {string}
  17677. */
  17678. dataDimToCoordDim: function (dataDim) {
  17679. return dataDimToCoordDim(this.getData(), dataDim);
  17680. },
  17681. /**
  17682. * Get base axis if has coordinate system and has axis.
  17683. * By default use coordSys.getBaseAxis();
  17684. * Can be overrided for some chart.
  17685. * @return {type} description
  17686. */
  17687. getBaseAxis: function () {
  17688. var coordSys = this.coordinateSystem;
  17689. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  17690. },
  17691. // FIXME
  17692. /**
  17693. * Default tooltip formatter
  17694. *
  17695. * @param {number} dataIndex
  17696. * @param {boolean} [multipleSeries=false]
  17697. * @param {number} [dataType]
  17698. */
  17699. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  17700. function formatArrayValue(value) {
  17701. var vertially = reduce(value, function (vertially, val, idx) {
  17702. var dimItem = data.getDimensionInfo(idx);
  17703. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.tooltipName != null;
  17704. }, 0);
  17705. var result = [];
  17706. var tooltipDims = otherDimToDataDim(data, 'tooltip');
  17707. tooltipDims.length
  17708. ? each$1(tooltipDims, function (dimIdx) {
  17709. setEachItem(data.get(dimIdx, dataIndex), dimIdx);
  17710. })
  17711. // By default, all dims is used on tooltip.
  17712. : each$1(value, setEachItem);
  17713. function setEachItem(val, dimIdx) {
  17714. var dimInfo = data.getDimensionInfo(dimIdx);
  17715. // If `dimInfo.tooltip` is not set, show tooltip.
  17716. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  17717. return;
  17718. }
  17719. var dimType = dimInfo.type;
  17720. var valStr = (vertially ? '- ' + (dimInfo.tooltipName || dimInfo.name) + ': ' : '')
  17721. + (dimType === 'ordinal'
  17722. ? val + ''
  17723. : dimType === 'time'
  17724. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  17725. : addCommas(val)
  17726. );
  17727. valStr && result.push(encodeHTML(valStr));
  17728. }
  17729. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  17730. }
  17731. var data = get(this, 'data');
  17732. var value = this.getRawValue(dataIndex);
  17733. var formattedValue = isArray(value)
  17734. ? formatArrayValue(value) : encodeHTML(addCommas(value));
  17735. var name = data.getName(dataIndex);
  17736. var color = data.getItemVisual(dataIndex, 'color');
  17737. if (isObject(color) && color.colorStops) {
  17738. color = (color.colorStops[0] || {}).color;
  17739. }
  17740. color = color || 'transparent';
  17741. var colorEl = getTooltipMarker(color);
  17742. var seriesName = this.name;
  17743. // FIXME
  17744. if (seriesName === '\0-') {
  17745. // Not show '-'
  17746. seriesName = '';
  17747. }
  17748. seriesName = seriesName
  17749. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  17750. : '';
  17751. return !multipleSeries
  17752. ? seriesName + colorEl
  17753. + (name
  17754. ? encodeHTML(name) + ': ' + formattedValue
  17755. : formattedValue
  17756. )
  17757. : colorEl + seriesName + formattedValue;
  17758. },
  17759. /**
  17760. * @return {boolean}
  17761. */
  17762. isAnimationEnabled: function () {
  17763. if (env$1.node) {
  17764. return false;
  17765. }
  17766. var animationEnabled = this.getShallow('animation');
  17767. if (animationEnabled) {
  17768. if (this.getData().count() > this.getShallow('animationThreshold')) {
  17769. animationEnabled = false;
  17770. }
  17771. }
  17772. return animationEnabled;
  17773. },
  17774. restoreData: function () {
  17775. set$1(this, 'data', get(this, 'dataBeforeProcessed').cloneShallow());
  17776. },
  17777. getColorFromPalette: function (name, scope) {
  17778. var ecModel = this.ecModel;
  17779. // PENDING
  17780. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope);
  17781. if (!color) {
  17782. color = ecModel.getColorFromPalette(name, scope);
  17783. }
  17784. return color;
  17785. },
  17786. /**
  17787. * Get data indices for show tooltip content. See tooltip.
  17788. * @abstract
  17789. * @param {Array.<string>|string} dim
  17790. * @param {Array.<number>} value
  17791. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  17792. * @return {Object} {dataIndices, nestestValue}.
  17793. */
  17794. getAxisTooltipData: null,
  17795. /**
  17796. * See tooltip.
  17797. * @abstract
  17798. * @param {number} dataIndex
  17799. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  17800. */
  17801. getTooltipPosition: null
  17802. });
  17803. mixin(SeriesModel, dataFormatMixin);
  17804. mixin(SeriesModel, colorPaletteMixin);
  17805. var Component = function () {
  17806. /**
  17807. * @type {module:zrender/container/Group}
  17808. * @readOnly
  17809. */
  17810. this.group = new Group();
  17811. /**
  17812. * @type {string}
  17813. * @readOnly
  17814. */
  17815. this.uid = getUID('viewComponent');
  17816. };
  17817. Component.prototype = {
  17818. constructor: Component,
  17819. init: function (ecModel, api) {},
  17820. render: function (componentModel, ecModel, api, payload) {},
  17821. dispose: function () {}
  17822. };
  17823. var componentProto = Component.prototype;
  17824. componentProto.updateView
  17825. = componentProto.updateLayout
  17826. = componentProto.updateVisual
  17827. = function (seriesModel, ecModel, api, payload) {
  17828. // Do nothing;
  17829. };
  17830. // Enable Component.extend.
  17831. enableClassExtend(Component);
  17832. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17833. enableClassManagement(Component, {registerWhenExtend: true});
  17834. function Chart() {
  17835. /**
  17836. * @type {module:zrender/container/Group}
  17837. * @readOnly
  17838. */
  17839. this.group = new Group();
  17840. /**
  17841. * @type {string}
  17842. * @readOnly
  17843. */
  17844. this.uid = getUID('viewChart');
  17845. }
  17846. Chart.prototype = {
  17847. type: 'chart',
  17848. /**
  17849. * Init the chart
  17850. * @param {module:echarts/model/Global} ecModel
  17851. * @param {module:echarts/ExtensionAPI} api
  17852. */
  17853. init: function (ecModel, api) {},
  17854. /**
  17855. * Render the chart
  17856. * @param {module:echarts/model/Series} seriesModel
  17857. * @param {module:echarts/model/Global} ecModel
  17858. * @param {module:echarts/ExtensionAPI} api
  17859. * @param {Object} payload
  17860. */
  17861. render: function (seriesModel, ecModel, api, payload) {},
  17862. /**
  17863. * Highlight series or specified data item
  17864. * @param {module:echarts/model/Series} seriesModel
  17865. * @param {module:echarts/model/Global} ecModel
  17866. * @param {module:echarts/ExtensionAPI} api
  17867. * @param {Object} payload
  17868. */
  17869. highlight: function (seriesModel, ecModel, api, payload) {
  17870. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  17871. },
  17872. /**
  17873. * Downplay series or specified data item
  17874. * @param {module:echarts/model/Series} seriesModel
  17875. * @param {module:echarts/model/Global} ecModel
  17876. * @param {module:echarts/ExtensionAPI} api
  17877. * @param {Object} payload
  17878. */
  17879. downplay: function (seriesModel, ecModel, api, payload) {
  17880. toggleHighlight(seriesModel.getData(), payload, 'normal');
  17881. },
  17882. /**
  17883. * Remove self
  17884. * @param {module:echarts/model/Global} ecModel
  17885. * @param {module:echarts/ExtensionAPI} api
  17886. */
  17887. remove: function (ecModel, api) {
  17888. this.group.removeAll();
  17889. },
  17890. /**
  17891. * Dispose self
  17892. * @param {module:echarts/model/Global} ecModel
  17893. * @param {module:echarts/ExtensionAPI} api
  17894. */
  17895. dispose: function () {}
  17896. /**
  17897. * The view contains the given point.
  17898. * @interface
  17899. * @param {Array.<number>} point
  17900. * @return {boolean}
  17901. */
  17902. // containPoint: function () {}
  17903. };
  17904. var chartProto = Chart.prototype;
  17905. chartProto.updateView
  17906. = chartProto.updateLayout
  17907. = chartProto.updateVisual
  17908. = function (seriesModel, ecModel, api, payload) {
  17909. this.render(seriesModel, ecModel, api, payload);
  17910. };
  17911. /**
  17912. * Set state of single element
  17913. * @param {module:zrender/Element} el
  17914. * @param {string} state
  17915. */
  17916. function elSetState(el, state) {
  17917. if (el) {
  17918. el.trigger(state);
  17919. if (el.type === 'group') {
  17920. for (var i = 0; i < el.childCount(); i++) {
  17921. elSetState(el.childAt(i), state);
  17922. }
  17923. }
  17924. }
  17925. }
  17926. /**
  17927. * @param {module:echarts/data/List} data
  17928. * @param {Object} payload
  17929. * @param {string} state 'normal'|'emphasis'
  17930. * @inner
  17931. */
  17932. function toggleHighlight(data, payload, state) {
  17933. var dataIndex = queryDataIndex(data, payload);
  17934. if (dataIndex != null) {
  17935. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  17936. elSetState(data.getItemGraphicEl(dataIdx), state);
  17937. });
  17938. }
  17939. else {
  17940. data.eachItemGraphicEl(function (el) {
  17941. elSetState(el, state);
  17942. });
  17943. }
  17944. }
  17945. // Enable Chart.extend.
  17946. enableClassExtend(Chart, ['dispose']);
  17947. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17948. enableClassManagement(Chart, {registerWhenExtend: true});
  17949. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  17950. var RATE = '\0__throttleRate';
  17951. var THROTTLE_TYPE = '\0__throttleType';
  17952. /**
  17953. * @public
  17954. * @param {(Function)} fn
  17955. * @param {number} [delay=0] Unit: ms.
  17956. * @param {boolean} [debounce=false]
  17957. * true: If call interval less than `delay`, only the last call works.
  17958. * false: If call interval less than `delay, call works on fixed rate.
  17959. * @return {(Function)} throttled fn.
  17960. */
  17961. function throttle(fn, delay, debounce) {
  17962. var currCall;
  17963. var lastCall = 0;
  17964. var lastExec = 0;
  17965. var timer = null;
  17966. var diff;
  17967. var scope;
  17968. var args;
  17969. var debounceNextCall;
  17970. delay = delay || 0;
  17971. function exec() {
  17972. lastExec = (new Date()).getTime();
  17973. timer = null;
  17974. fn.apply(scope, args || []);
  17975. }
  17976. var cb = function () {
  17977. currCall = (new Date()).getTime();
  17978. scope = this;
  17979. args = arguments;
  17980. var thisDelay = debounceNextCall || delay;
  17981. var thisDebounce = debounceNextCall || debounce;
  17982. debounceNextCall = null;
  17983. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  17984. clearTimeout(timer);
  17985. if (thisDebounce) {
  17986. timer = setTimeout(exec, thisDelay);
  17987. }
  17988. else {
  17989. if (diff >= 0) {
  17990. exec();
  17991. }
  17992. else {
  17993. timer = setTimeout(exec, -diff);
  17994. }
  17995. }
  17996. lastCall = currCall;
  17997. };
  17998. /**
  17999. * Clear throttle.
  18000. * @public
  18001. */
  18002. cb.clear = function () {
  18003. if (timer) {
  18004. clearTimeout(timer);
  18005. timer = null;
  18006. }
  18007. };
  18008. /**
  18009. * Enable debounce once.
  18010. */
  18011. cb.debounceNextCall = function (debounceDelay) {
  18012. debounceNextCall = debounceDelay;
  18013. };
  18014. return cb;
  18015. }
  18016. /**
  18017. * Create throttle method or update throttle rate.
  18018. *
  18019. * @example
  18020. * ComponentView.prototype.render = function () {
  18021. * ...
  18022. * throttle.createOrUpdate(
  18023. * this,
  18024. * '_dispatchAction',
  18025. * this.model.get('throttle'),
  18026. * 'fixRate'
  18027. * );
  18028. * };
  18029. * ComponentView.prototype.remove = function () {
  18030. * throttle.clear(this, '_dispatchAction');
  18031. * };
  18032. * ComponentView.prototype.dispose = function () {
  18033. * throttle.clear(this, '_dispatchAction');
  18034. * };
  18035. *
  18036. * @public
  18037. * @param {Object} obj
  18038. * @param {string} fnAttr
  18039. * @param {number} [rate]
  18040. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  18041. * @return {Function} throttled function.
  18042. */
  18043. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  18044. var fn = obj[fnAttr];
  18045. if (!fn) {
  18046. return;
  18047. }
  18048. var originFn = fn[ORIGIN_METHOD] || fn;
  18049. var lastThrottleType = fn[THROTTLE_TYPE];
  18050. var lastRate = fn[RATE];
  18051. if (lastRate !== rate || lastThrottleType !== throttleType) {
  18052. if (rate == null || !throttleType) {
  18053. return (obj[fnAttr] = originFn);
  18054. }
  18055. fn = obj[fnAttr] = throttle(
  18056. originFn, rate, throttleType === 'debounce'
  18057. );
  18058. fn[ORIGIN_METHOD] = originFn;
  18059. fn[THROTTLE_TYPE] = throttleType;
  18060. fn[RATE] = rate;
  18061. }
  18062. return fn;
  18063. }
  18064. /**
  18065. * Clear throttle. Example see throttle.createOrUpdate.
  18066. *
  18067. * @public
  18068. * @param {Object} obj
  18069. * @param {string} fnAttr
  18070. */
  18071. function clear(obj, fnAttr) {
  18072. var fn = obj[fnAttr];
  18073. if (fn && fn[ORIGIN_METHOD]) {
  18074. obj[fnAttr] = fn[ORIGIN_METHOD];
  18075. }
  18076. }
  18077. var seriesColor = function (ecModel) {
  18078. function encodeColor(seriesModel) {
  18079. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.normal.color').split('.');
  18080. var data = seriesModel.getData();
  18081. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  18082. || seriesModel.getColorFromPalette(seriesModel.get('name')); // Default color
  18083. // FIXME Set color function or use the platte color
  18084. data.setVisual('color', color);
  18085. // Only visible series has each data be visual encoded
  18086. if (!ecModel.isSeriesFiltered(seriesModel)) {
  18087. if (typeof color === 'function' && !(color instanceof Gradient)) {
  18088. data.each(function (idx) {
  18089. data.setItemVisual(
  18090. idx, 'color', color(seriesModel.getDataParams(idx))
  18091. );
  18092. });
  18093. }
  18094. // itemStyle in each data item
  18095. data.each(function (idx) {
  18096. var itemModel = data.getItemModel(idx);
  18097. var color = itemModel.get(colorAccessPath, true);
  18098. if (color != null) {
  18099. data.setItemVisual(idx, 'color', color);
  18100. }
  18101. });
  18102. }
  18103. }
  18104. ecModel.eachRawSeries(encodeColor);
  18105. };
  18106. var PI$1 = Math.PI;
  18107. /**
  18108. * @param {module:echarts/ExtensionAPI} api
  18109. * @param {Object} [opts]
  18110. * @param {string} [opts.text]
  18111. * @param {string} [opts.color]
  18112. * @param {string} [opts.textColor]
  18113. * @return {module:zrender/Element}
  18114. */
  18115. var loadingDefault = function (api, opts) {
  18116. opts = opts || {};
  18117. defaults(opts, {
  18118. text: 'loading',
  18119. color: '#c23531',
  18120. textColor: '#000',
  18121. maskColor: 'rgba(255, 255, 255, 0.8)',
  18122. zlevel: 0
  18123. });
  18124. var mask = new Rect({
  18125. style: {
  18126. fill: opts.maskColor
  18127. },
  18128. zlevel: opts.zlevel,
  18129. z: 10000
  18130. });
  18131. var arc = new Arc({
  18132. shape: {
  18133. startAngle: -PI$1 / 2,
  18134. endAngle: -PI$1 / 2 + 0.1,
  18135. r: 10
  18136. },
  18137. style: {
  18138. stroke: opts.color,
  18139. lineCap: 'round',
  18140. lineWidth: 5
  18141. },
  18142. zlevel: opts.zlevel,
  18143. z: 10001
  18144. });
  18145. var labelRect = new Rect({
  18146. style: {
  18147. fill: 'none',
  18148. text: opts.text,
  18149. textPosition: 'right',
  18150. textDistance: 10,
  18151. textFill: opts.textColor
  18152. },
  18153. zlevel: opts.zlevel,
  18154. z: 10001
  18155. });
  18156. arc.animateShape(true)
  18157. .when(1000, {
  18158. endAngle: PI$1 * 3 / 2
  18159. })
  18160. .start('circularInOut');
  18161. arc.animateShape(true)
  18162. .when(1000, {
  18163. startAngle: PI$1 * 3 / 2
  18164. })
  18165. .delay(300)
  18166. .start('circularInOut');
  18167. var group = new Group();
  18168. group.add(arc);
  18169. group.add(labelRect);
  18170. group.add(mask);
  18171. // Inject resize
  18172. group.resize = function () {
  18173. var cx = api.getWidth() / 2;
  18174. var cy = api.getHeight() / 2;
  18175. arc.setShape({
  18176. cx: cx,
  18177. cy: cy
  18178. });
  18179. var r = arc.shape.r;
  18180. labelRect.setShape({
  18181. x: cx - r,
  18182. y: cy - r,
  18183. width: r * 2,
  18184. height: r * 2
  18185. });
  18186. mask.setShape({
  18187. x: 0,
  18188. y: 0,
  18189. width: api.getWidth(),
  18190. height: api.getHeight()
  18191. });
  18192. };
  18193. group.resize();
  18194. return group;
  18195. };
  18196. /*!
  18197. * ECharts, a javascript interactive chart library.
  18198. *
  18199. * Copyright (c) 2015, Baidu Inc.
  18200. * All rights reserved.
  18201. *
  18202. * LICENSE
  18203. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  18204. */
  18205. var each = each$1;
  18206. var parseClassType = ComponentModel.parseClassType;
  18207. var version = '3.8.5';
  18208. var dependencies = {
  18209. zrender: '3.7.4'
  18210. };
  18211. var PRIORITY_PROCESSOR_FILTER = 1000;
  18212. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  18213. var PRIORITY_VISUAL_LAYOUT = 1000;
  18214. var PRIORITY_VISUAL_GLOBAL = 2000;
  18215. var PRIORITY_VISUAL_CHART = 3000;
  18216. var PRIORITY_VISUAL_COMPONENT = 4000;
  18217. // FIXME
  18218. // necessary?
  18219. var PRIORITY_VISUAL_BRUSH = 5000;
  18220. var PRIORITY = {
  18221. PROCESSOR: {
  18222. FILTER: PRIORITY_PROCESSOR_FILTER,
  18223. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  18224. },
  18225. VISUAL: {
  18226. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  18227. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  18228. CHART: PRIORITY_VISUAL_CHART,
  18229. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  18230. BRUSH: PRIORITY_VISUAL_BRUSH
  18231. }
  18232. };
  18233. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  18234. // where they must not be invoked nestedly, except the only case: invoke
  18235. // dispatchAction with updateMethod "none" in main process.
  18236. // This flag is used to carry out this rule.
  18237. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  18238. var IN_MAIN_PROCESS = '__flagInMainProcess';
  18239. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  18240. var OPTION_UPDATED = '__optionUpdated';
  18241. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  18242. function createRegisterEventWithLowercaseName(method) {
  18243. return function (eventName, handler, context) {
  18244. // Event name is all lowercase
  18245. eventName = eventName && eventName.toLowerCase();
  18246. Eventful.prototype[method].call(this, eventName, handler, context);
  18247. };
  18248. }
  18249. /**
  18250. * @module echarts~MessageCenter
  18251. */
  18252. function MessageCenter() {
  18253. Eventful.call(this);
  18254. }
  18255. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  18256. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  18257. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  18258. mixin(MessageCenter, Eventful);
  18259. /**
  18260. * @module echarts~ECharts
  18261. */
  18262. function ECharts(dom, theme, opts) {
  18263. opts = opts || {};
  18264. // Get theme by name
  18265. if (typeof theme === 'string') {
  18266. theme = themeStorage[theme];
  18267. }
  18268. /**
  18269. * @type {string}
  18270. */
  18271. this.id;
  18272. /**
  18273. * Group id
  18274. * @type {string}
  18275. */
  18276. this.group;
  18277. /**
  18278. * @type {HTMLElement}
  18279. * @private
  18280. */
  18281. this._dom = dom;
  18282. var defaultRenderer = 'canvas';
  18283. if (__DEV__) {
  18284. defaultRenderer = (
  18285. typeof window === 'undefined' ? global : window
  18286. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  18287. }
  18288. /**
  18289. * @type {module:zrender/ZRender}
  18290. * @private
  18291. */
  18292. var zr = this._zr = init$1(dom, {
  18293. renderer: opts.renderer || defaultRenderer,
  18294. devicePixelRatio: opts.devicePixelRatio,
  18295. width: opts.width,
  18296. height: opts.height
  18297. });
  18298. /**
  18299. * Expect 60 pfs.
  18300. * @type {Function}
  18301. * @private
  18302. */
  18303. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  18304. var theme = clone(theme);
  18305. theme && backwardCompat(theme, true);
  18306. /**
  18307. * @type {Object}
  18308. * @private
  18309. */
  18310. this._theme = theme;
  18311. /**
  18312. * @type {Array.<module:echarts/view/Chart>}
  18313. * @private
  18314. */
  18315. this._chartsViews = [];
  18316. /**
  18317. * @type {Object.<string, module:echarts/view/Chart>}
  18318. * @private
  18319. */
  18320. this._chartsMap = {};
  18321. /**
  18322. * @type {Array.<module:echarts/view/Component>}
  18323. * @private
  18324. */
  18325. this._componentsViews = [];
  18326. /**
  18327. * @type {Object.<string, module:echarts/view/Component>}
  18328. * @private
  18329. */
  18330. this._componentsMap = {};
  18331. /**
  18332. * @type {module:echarts/CoordinateSystem}
  18333. * @private
  18334. */
  18335. this._coordSysMgr = new CoordinateSystemManager();
  18336. /**
  18337. * @type {module:echarts/ExtensionAPI}
  18338. * @private
  18339. */
  18340. this._api = createExtensionAPI(this);
  18341. Eventful.call(this);
  18342. /**
  18343. * @type {module:echarts~MessageCenter}
  18344. * @private
  18345. */
  18346. this._messageCenter = new MessageCenter();
  18347. // Init mouse events
  18348. this._initEvents();
  18349. // In case some people write `window.onresize = chart.resize`
  18350. this.resize = bind(this.resize, this);
  18351. // Can't dispatch action during rendering procedure
  18352. this._pendingActions = [];
  18353. // Sort on demand
  18354. function prioritySortFunc(a, b) {
  18355. return a.prio - b.prio;
  18356. }
  18357. sort(visualFuncs, prioritySortFunc);
  18358. sort(dataProcessorFuncs, prioritySortFunc);
  18359. zr.animation.on('frame', this._onframe, this);
  18360. // ECharts instance can be used as value.
  18361. setAsPrimitive(this);
  18362. }
  18363. var echartsProto = ECharts.prototype;
  18364. echartsProto._onframe = function () {
  18365. // Lazy update
  18366. if (this[OPTION_UPDATED]) {
  18367. var silent = this[OPTION_UPDATED].silent;
  18368. this[IN_MAIN_PROCESS] = true;
  18369. updateMethods.prepareAndUpdate.call(this);
  18370. this[IN_MAIN_PROCESS] = false;
  18371. this[OPTION_UPDATED] = false;
  18372. flushPendingActions.call(this, silent);
  18373. triggerUpdatedEvent.call(this, silent);
  18374. }
  18375. };
  18376. /**
  18377. * @return {HTMLElement}
  18378. */
  18379. echartsProto.getDom = function () {
  18380. return this._dom;
  18381. };
  18382. /**
  18383. * @return {module:zrender~ZRender}
  18384. */
  18385. echartsProto.getZr = function () {
  18386. return this._zr;
  18387. };
  18388. /**
  18389. * Usage:
  18390. * chart.setOption(option, notMerge, lazyUpdate);
  18391. * chart.setOption(option, {
  18392. * notMerge: ...,
  18393. * lazyUpdate: ...,
  18394. * silent: ...
  18395. * });
  18396. *
  18397. * @param {Object} option
  18398. * @param {Object|boolean} [opts] opts or notMerge.
  18399. * @param {boolean} [opts.notMerge=false]
  18400. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  18401. */
  18402. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  18403. if (__DEV__) {
  18404. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  18405. }
  18406. var silent;
  18407. if (isObject(notMerge)) {
  18408. lazyUpdate = notMerge.lazyUpdate;
  18409. silent = notMerge.silent;
  18410. notMerge = notMerge.notMerge;
  18411. }
  18412. this[IN_MAIN_PROCESS] = true;
  18413. if (!this._model || notMerge) {
  18414. var optionManager = new OptionManager(this._api);
  18415. var theme = this._theme;
  18416. var ecModel = this._model = new GlobalModel(null, null, theme, optionManager);
  18417. ecModel.init(null, null, theme, optionManager);
  18418. }
  18419. this._model.setOption(option, optionPreprocessorFuncs);
  18420. if (lazyUpdate) {
  18421. this[OPTION_UPDATED] = {silent: silent};
  18422. this[IN_MAIN_PROCESS] = false;
  18423. }
  18424. else {
  18425. updateMethods.prepareAndUpdate.call(this);
  18426. // Ensure zr refresh sychronously, and then pixel in canvas can be
  18427. // fetched after `setOption`.
  18428. this._zr.flush();
  18429. this[OPTION_UPDATED] = false;
  18430. this[IN_MAIN_PROCESS] = false;
  18431. flushPendingActions.call(this, silent);
  18432. triggerUpdatedEvent.call(this, silent);
  18433. }
  18434. };
  18435. /**
  18436. * @DEPRECATED
  18437. */
  18438. echartsProto.setTheme = function () {
  18439. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  18440. };
  18441. /**
  18442. * @return {module:echarts/model/Global}
  18443. */
  18444. echartsProto.getModel = function () {
  18445. return this._model;
  18446. };
  18447. /**
  18448. * @return {Object}
  18449. */
  18450. echartsProto.getOption = function () {
  18451. return this._model && this._model.getOption();
  18452. };
  18453. /**
  18454. * @return {number}
  18455. */
  18456. echartsProto.getWidth = function () {
  18457. return this._zr.getWidth();
  18458. };
  18459. /**
  18460. * @return {number}
  18461. */
  18462. echartsProto.getHeight = function () {
  18463. return this._zr.getHeight();
  18464. };
  18465. /**
  18466. * @return {number}
  18467. */
  18468. echartsProto.getDevicePixelRatio = function () {
  18469. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  18470. };
  18471. /**
  18472. * Get canvas which has all thing rendered
  18473. * @param {Object} opts
  18474. * @param {string} [opts.backgroundColor]
  18475. * @return {string}
  18476. */
  18477. echartsProto.getRenderedCanvas = function (opts) {
  18478. if (!env$1.canvasSupported) {
  18479. return;
  18480. }
  18481. opts = opts || {};
  18482. opts.pixelRatio = opts.pixelRatio || 1;
  18483. opts.backgroundColor = opts.backgroundColor
  18484. || this._model.get('backgroundColor');
  18485. var zr = this._zr;
  18486. var list = zr.storage.getDisplayList();
  18487. // Stop animations
  18488. each$1(list, function (el) {
  18489. el.stopAnimation(true);
  18490. });
  18491. return zr.painter.getRenderedCanvas(opts);
  18492. };
  18493. /**
  18494. * Get svg data url
  18495. * @return {string}
  18496. */
  18497. echartsProto.getSvgDataUrl = function () {
  18498. if (!env$1.svgSupported) {
  18499. return;
  18500. }
  18501. var zr = this._zr;
  18502. var list = zr.storage.getDisplayList();
  18503. // Stop animations
  18504. each$1(list, function (el) {
  18505. el.stopAnimation(true);
  18506. });
  18507. return zr.painter.pathToSvg();
  18508. };
  18509. /**
  18510. * @return {string}
  18511. * @param {Object} opts
  18512. * @param {string} [opts.type='png']
  18513. * @param {string} [opts.pixelRatio=1]
  18514. * @param {string} [opts.backgroundColor]
  18515. * @param {string} [opts.excludeComponents]
  18516. */
  18517. echartsProto.getDataURL = function (opts) {
  18518. opts = opts || {};
  18519. var excludeComponents = opts.excludeComponents;
  18520. var ecModel = this._model;
  18521. var excludesComponentViews = [];
  18522. var self = this;
  18523. each(excludeComponents, function (componentType) {
  18524. ecModel.eachComponent({
  18525. mainType: componentType
  18526. }, function (component) {
  18527. var view = self._componentsMap[component.__viewId];
  18528. if (!view.group.ignore) {
  18529. excludesComponentViews.push(view);
  18530. view.group.ignore = true;
  18531. }
  18532. });
  18533. });
  18534. var url = this._zr.painter.getType() === 'svg'
  18535. ? this.getSvgDataUrl()
  18536. : this.getRenderedCanvas(opts).toDataURL(
  18537. 'image/' + (opts && opts.type || 'png')
  18538. );
  18539. each(excludesComponentViews, function (view) {
  18540. view.group.ignore = false;
  18541. });
  18542. return url;
  18543. };
  18544. /**
  18545. * @return {string}
  18546. * @param {Object} opts
  18547. * @param {string} [opts.type='png']
  18548. * @param {string} [opts.pixelRatio=1]
  18549. * @param {string} [opts.backgroundColor]
  18550. */
  18551. echartsProto.getConnectedDataURL = function (opts) {
  18552. if (!env$1.canvasSupported) {
  18553. return;
  18554. }
  18555. var groupId = this.group;
  18556. var mathMin = Math.min;
  18557. var mathMax = Math.max;
  18558. var MAX_NUMBER = Infinity;
  18559. if (connectedGroups[groupId]) {
  18560. var left = MAX_NUMBER;
  18561. var top = MAX_NUMBER;
  18562. var right = -MAX_NUMBER;
  18563. var bottom = -MAX_NUMBER;
  18564. var canvasList = [];
  18565. var dpr = (opts && opts.pixelRatio) || 1;
  18566. each$1(instances, function (chart, id) {
  18567. if (chart.group === groupId) {
  18568. var canvas = chart.getRenderedCanvas(
  18569. clone(opts)
  18570. );
  18571. var boundingRect = chart.getDom().getBoundingClientRect();
  18572. left = mathMin(boundingRect.left, left);
  18573. top = mathMin(boundingRect.top, top);
  18574. right = mathMax(boundingRect.right, right);
  18575. bottom = mathMax(boundingRect.bottom, bottom);
  18576. canvasList.push({
  18577. dom: canvas,
  18578. left: boundingRect.left,
  18579. top: boundingRect.top
  18580. });
  18581. }
  18582. });
  18583. left *= dpr;
  18584. top *= dpr;
  18585. right *= dpr;
  18586. bottom *= dpr;
  18587. var width = right - left;
  18588. var height = bottom - top;
  18589. var targetCanvas = createCanvas();
  18590. targetCanvas.width = width;
  18591. targetCanvas.height = height;
  18592. var zr = init$1(targetCanvas);
  18593. each(canvasList, function (item) {
  18594. var img = new ZImage({
  18595. style: {
  18596. x: item.left * dpr - left,
  18597. y: item.top * dpr - top,
  18598. image: item.dom
  18599. }
  18600. });
  18601. zr.add(img);
  18602. });
  18603. zr.refreshImmediately();
  18604. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  18605. }
  18606. else {
  18607. return this.getDataURL(opts);
  18608. }
  18609. };
  18610. /**
  18611. * Convert from logical coordinate system to pixel coordinate system.
  18612. * See CoordinateSystem#convertToPixel.
  18613. * @param {string|Object} finder
  18614. * If string, e.g., 'geo', means {geoIndex: 0}.
  18615. * If Object, could contain some of these properties below:
  18616. * {
  18617. * seriesIndex / seriesId / seriesName,
  18618. * geoIndex / geoId, geoName,
  18619. * bmapIndex / bmapId / bmapName,
  18620. * xAxisIndex / xAxisId / xAxisName,
  18621. * yAxisIndex / yAxisId / yAxisName,
  18622. * gridIndex / gridId / gridName,
  18623. * ... (can be extended)
  18624. * }
  18625. * @param {Array|number} value
  18626. * @return {Array|number} result
  18627. */
  18628. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  18629. /**
  18630. * Convert from pixel coordinate system to logical coordinate system.
  18631. * See CoordinateSystem#convertFromPixel.
  18632. * @param {string|Object} finder
  18633. * If string, e.g., 'geo', means {geoIndex: 0}.
  18634. * If Object, could contain some of these properties below:
  18635. * {
  18636. * seriesIndex / seriesId / seriesName,
  18637. * geoIndex / geoId / geoName,
  18638. * bmapIndex / bmapId / bmapName,
  18639. * xAxisIndex / xAxisId / xAxisName,
  18640. * yAxisIndex / yAxisId / yAxisName
  18641. * gridIndex / gridId / gridName,
  18642. * ... (can be extended)
  18643. * }
  18644. * @param {Array|number} value
  18645. * @return {Array|number} result
  18646. */
  18647. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  18648. function doConvertPixel(methodName, finder, value) {
  18649. var ecModel = this._model;
  18650. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  18651. var result;
  18652. finder = parseFinder(ecModel, finder);
  18653. for (var i = 0; i < coordSysList.length; i++) {
  18654. var coordSys = coordSysList[i];
  18655. if (coordSys[methodName]
  18656. && (result = coordSys[methodName](ecModel, finder, value)) != null
  18657. ) {
  18658. return result;
  18659. }
  18660. }
  18661. if (__DEV__) {
  18662. console.warn(
  18663. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  18664. );
  18665. }
  18666. }
  18667. /**
  18668. * Is the specified coordinate systems or components contain the given pixel point.
  18669. * @param {string|Object} finder
  18670. * If string, e.g., 'geo', means {geoIndex: 0}.
  18671. * If Object, could contain some of these properties below:
  18672. * {
  18673. * seriesIndex / seriesId / seriesName,
  18674. * geoIndex / geoId / geoName,
  18675. * bmapIndex / bmapId / bmapName,
  18676. * xAxisIndex / xAxisId / xAxisName,
  18677. * yAxisIndex / yAxisId / yAxisName,
  18678. * gridIndex / gridId / gridName,
  18679. * ... (can be extended)
  18680. * }
  18681. * @param {Array|number} value
  18682. * @return {boolean} result
  18683. */
  18684. echartsProto.containPixel = function (finder, value) {
  18685. var ecModel = this._model;
  18686. var result;
  18687. finder = parseFinder(ecModel, finder);
  18688. each$1(finder, function (models, key) {
  18689. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  18690. var coordSys = model.coordinateSystem;
  18691. if (coordSys && coordSys.containPoint) {
  18692. result |= !!coordSys.containPoint(value);
  18693. }
  18694. else if (key === 'seriesModels') {
  18695. var view = this._chartsMap[model.__viewId];
  18696. if (view && view.containPoint) {
  18697. result |= view.containPoint(value, model);
  18698. }
  18699. else {
  18700. if (__DEV__) {
  18701. console.warn(key + ': ' + (view
  18702. ? 'The found component do not support containPoint.'
  18703. : 'No view mapping to the found component.'
  18704. ));
  18705. }
  18706. }
  18707. }
  18708. else {
  18709. if (__DEV__) {
  18710. console.warn(key + ': containPoint is not supported');
  18711. }
  18712. }
  18713. }, this);
  18714. }, this);
  18715. return !!result;
  18716. };
  18717. /**
  18718. * Get visual from series or data.
  18719. * @param {string|Object} finder
  18720. * If string, e.g., 'series', means {seriesIndex: 0}.
  18721. * If Object, could contain some of these properties below:
  18722. * {
  18723. * seriesIndex / seriesId / seriesName,
  18724. * dataIndex / dataIndexInside
  18725. * }
  18726. * If dataIndex is not specified, series visual will be fetched,
  18727. * but not data item visual.
  18728. * If all of seriesIndex, seriesId, seriesName are not specified,
  18729. * visual will be fetched from first series.
  18730. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  18731. */
  18732. echartsProto.getVisual = function (finder, visualType) {
  18733. var ecModel = this._model;
  18734. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  18735. var seriesModel = finder.seriesModel;
  18736. if (__DEV__) {
  18737. if (!seriesModel) {
  18738. console.warn('There is no specified seires model');
  18739. }
  18740. }
  18741. var data = seriesModel.getData();
  18742. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  18743. ? finder.dataIndexInside
  18744. : finder.hasOwnProperty('dataIndex')
  18745. ? data.indexOfRawIndex(finder.dataIndex)
  18746. : null;
  18747. return dataIndexInside != null
  18748. ? data.getItemVisual(dataIndexInside, visualType)
  18749. : data.getVisual(visualType);
  18750. };
  18751. /**
  18752. * Get view of corresponding component model
  18753. * @param {module:echarts/model/Component} componentModel
  18754. * @return {module:echarts/view/Component}
  18755. */
  18756. echartsProto.getViewOfComponentModel = function (componentModel) {
  18757. return this._componentsMap[componentModel.__viewId];
  18758. };
  18759. /**
  18760. * Get view of corresponding series model
  18761. * @param {module:echarts/model/Series} seriesModel
  18762. * @return {module:echarts/view/Chart}
  18763. */
  18764. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  18765. return this._chartsMap[seriesModel.__viewId];
  18766. };
  18767. var updateMethods = {
  18768. /**
  18769. * @param {Object} payload
  18770. * @private
  18771. */
  18772. update: function (payload) {
  18773. // console.profile && console.profile('update');
  18774. var ecModel = this._model;
  18775. var api = this._api;
  18776. var coordSysMgr = this._coordSysMgr;
  18777. var zr = this._zr;
  18778. // update before setOption
  18779. if (!ecModel) {
  18780. return;
  18781. }
  18782. // Fixme First time update ?
  18783. ecModel.restoreData();
  18784. // TODO
  18785. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  18786. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  18787. // Create new coordinate system each update
  18788. // In LineView may save the old coordinate system and use it to get the orignal point
  18789. coordSysMgr.create(this._model, this._api);
  18790. processData.call(this, ecModel, api);
  18791. stackSeriesData.call(this, ecModel);
  18792. coordSysMgr.update(ecModel, api);
  18793. doVisualEncoding.call(this, ecModel, payload);
  18794. doRender.call(this, ecModel, payload);
  18795. // Set background
  18796. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  18797. var painter = zr.painter;
  18798. // TODO all use clearColor ?
  18799. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  18800. zr.configLayer(0, {
  18801. clearColor: backgroundColor
  18802. });
  18803. }
  18804. else {
  18805. // In IE8
  18806. if (!env$1.canvasSupported) {
  18807. var colorArr = parse(backgroundColor);
  18808. backgroundColor = stringify(colorArr, 'rgb');
  18809. if (colorArr[3] === 0) {
  18810. backgroundColor = 'transparent';
  18811. }
  18812. }
  18813. if (backgroundColor.colorStops || backgroundColor.image) {
  18814. // Gradient background
  18815. // FIXME Fixed layer?
  18816. zr.configLayer(0, {
  18817. clearColor: backgroundColor
  18818. });
  18819. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  18820. this._dom.style.background = 'transparent';
  18821. }
  18822. else {
  18823. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  18824. zr.configLayer(0, {
  18825. clearColor: null
  18826. });
  18827. }
  18828. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  18829. this._dom.style.background = backgroundColor;
  18830. }
  18831. }
  18832. each(postUpdateFuncs, function (func) {
  18833. func(ecModel, api);
  18834. });
  18835. // console.profile && console.profileEnd('update');
  18836. },
  18837. /**
  18838. * @param {Object} payload
  18839. * @private
  18840. */
  18841. updateView: function (payload) {
  18842. var ecModel = this._model;
  18843. // update before setOption
  18844. if (!ecModel) {
  18845. return;
  18846. }
  18847. ecModel.eachSeries(function (seriesModel) {
  18848. seriesModel.getData().clearAllVisual();
  18849. });
  18850. doVisualEncoding.call(this, ecModel, payload);
  18851. invokeUpdateMethod.call(this, 'updateView', ecModel, payload);
  18852. },
  18853. /**
  18854. * @param {Object} payload
  18855. * @private
  18856. */
  18857. updateVisual: function (payload) {
  18858. var ecModel = this._model;
  18859. // update before setOption
  18860. if (!ecModel) {
  18861. return;
  18862. }
  18863. ecModel.eachSeries(function (seriesModel) {
  18864. seriesModel.getData().clearAllVisual();
  18865. });
  18866. doVisualEncoding.call(this, ecModel, payload, true);
  18867. invokeUpdateMethod.call(this, 'updateVisual', ecModel, payload);
  18868. },
  18869. /**
  18870. * @param {Object} payload
  18871. * @private
  18872. */
  18873. updateLayout: function (payload) {
  18874. var ecModel = this._model;
  18875. // update before setOption
  18876. if (!ecModel) {
  18877. return;
  18878. }
  18879. doLayout.call(this, ecModel, payload);
  18880. invokeUpdateMethod.call(this, 'updateLayout', ecModel, payload);
  18881. },
  18882. /**
  18883. * @param {Object} payload
  18884. * @private
  18885. */
  18886. prepareAndUpdate: function (payload) {
  18887. var ecModel = this._model;
  18888. prepareView.call(this, 'component', ecModel);
  18889. prepareView.call(this, 'chart', ecModel);
  18890. updateMethods.update.call(this, payload);
  18891. }
  18892. };
  18893. /**
  18894. * @private
  18895. */
  18896. function updateDirectly(ecIns, method, payload, mainType, subType) {
  18897. var ecModel = ecIns._model;
  18898. // broadcast
  18899. if (!mainType) {
  18900. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  18901. return;
  18902. }
  18903. var query = {};
  18904. query[mainType + 'Id'] = payload[mainType + 'Id'];
  18905. query[mainType + 'Index'] = payload[mainType + 'Index'];
  18906. query[mainType + 'Name'] = payload[mainType + 'Name'];
  18907. var condition = {mainType: mainType, query: query};
  18908. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  18909. // If dispatchAction before setOption, do nothing.
  18910. ecModel && ecModel.eachComponent(condition, function (model, index) {
  18911. callView(ecIns[
  18912. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  18913. ][model.__viewId]);
  18914. }, ecIns);
  18915. function callView(view) {
  18916. view && view.__alive && view[method] && view[method](
  18917. view.__model, ecModel, ecIns._api, payload
  18918. );
  18919. }
  18920. }
  18921. /**
  18922. * Resize the chart
  18923. * @param {Object} opts
  18924. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  18925. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  18926. * @param {boolean} [opts.silent=false]
  18927. */
  18928. echartsProto.resize = function (opts) {
  18929. if (__DEV__) {
  18930. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  18931. }
  18932. this[IN_MAIN_PROCESS] = true;
  18933. this._zr.resize(opts);
  18934. var optionChanged = this._model && this._model.resetOption('media');
  18935. var updateMethod = optionChanged ? 'prepareAndUpdate' : 'update';
  18936. updateMethods[updateMethod].call(this);
  18937. // Resize loading effect
  18938. this._loadingFX && this._loadingFX.resize();
  18939. this[IN_MAIN_PROCESS] = false;
  18940. var silent = opts && opts.silent;
  18941. flushPendingActions.call(this, silent);
  18942. triggerUpdatedEvent.call(this, silent);
  18943. };
  18944. /**
  18945. * Show loading effect
  18946. * @param {string} [name='default']
  18947. * @param {Object} [cfg]
  18948. */
  18949. echartsProto.showLoading = function (name, cfg) {
  18950. if (isObject(name)) {
  18951. cfg = name;
  18952. name = '';
  18953. }
  18954. name = name || 'default';
  18955. this.hideLoading();
  18956. if (!loadingEffects[name]) {
  18957. if (__DEV__) {
  18958. console.warn('Loading effects ' + name + ' not exists.');
  18959. }
  18960. return;
  18961. }
  18962. var el = loadingEffects[name](this._api, cfg);
  18963. var zr = this._zr;
  18964. this._loadingFX = el;
  18965. zr.add(el);
  18966. };
  18967. /**
  18968. * Hide loading effect
  18969. */
  18970. echartsProto.hideLoading = function () {
  18971. this._loadingFX && this._zr.remove(this._loadingFX);
  18972. this._loadingFX = null;
  18973. };
  18974. /**
  18975. * @param {Object} eventObj
  18976. * @return {Object}
  18977. */
  18978. echartsProto.makeActionFromEvent = function (eventObj) {
  18979. var payload = extend({}, eventObj);
  18980. payload.type = eventActionMap[eventObj.type];
  18981. return payload;
  18982. };
  18983. /**
  18984. * @pubilc
  18985. * @param {Object} payload
  18986. * @param {string} [payload.type] Action type
  18987. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  18988. * @param {boolean} [opt.silent=false] Whether trigger events.
  18989. * @param {boolean} [opt.flush=undefined]
  18990. * true: Flush immediately, and then pixel in canvas can be fetched
  18991. * immediately. Caution: it might affect performance.
  18992. * false: Not not flush.
  18993. * undefined: Auto decide whether perform flush.
  18994. */
  18995. echartsProto.dispatchAction = function (payload, opt) {
  18996. if (!isObject(opt)) {
  18997. opt = {silent: !!opt};
  18998. }
  18999. if (!actions[payload.type]) {
  19000. return;
  19001. }
  19002. // Avoid dispatch action before setOption. Especially in `connect`.
  19003. if (!this._model) {
  19004. return;
  19005. }
  19006. // May dispatchAction in rendering procedure
  19007. if (this[IN_MAIN_PROCESS]) {
  19008. this._pendingActions.push(payload);
  19009. return;
  19010. }
  19011. doDispatchAction.call(this, payload, opt.silent);
  19012. if (opt.flush) {
  19013. this._zr.flush(true);
  19014. }
  19015. else if (opt.flush !== false && env$1.browser.weChat) {
  19016. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  19017. // hang when sliding page (on touch event), which cause that zr does not
  19018. // refresh util user interaction finished, which is not expected.
  19019. // But `dispatchAction` may be called too frequently when pan on touch
  19020. // screen, which impacts performance if do not throttle them.
  19021. this._throttledZrFlush();
  19022. }
  19023. flushPendingActions.call(this, opt.silent);
  19024. triggerUpdatedEvent.call(this, opt.silent);
  19025. };
  19026. function doDispatchAction(payload, silent) {
  19027. var payloadType = payload.type;
  19028. var escapeConnect = payload.escapeConnect;
  19029. var actionWrap = actions[payloadType];
  19030. var actionInfo = actionWrap.actionInfo;
  19031. var cptType = (actionInfo.update || 'update').split(':');
  19032. var updateMethod = cptType.pop();
  19033. cptType = cptType[0] != null && parseClassType(cptType[0]);
  19034. this[IN_MAIN_PROCESS] = true;
  19035. var payloads = [payload];
  19036. var batched = false;
  19037. // Batch action
  19038. if (payload.batch) {
  19039. batched = true;
  19040. payloads = map(payload.batch, function (item) {
  19041. item = defaults(extend({}, item), payload);
  19042. item.batch = null;
  19043. return item;
  19044. });
  19045. }
  19046. var eventObjBatch = [];
  19047. var eventObj;
  19048. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  19049. each(payloads, function (batchItem) {
  19050. // Action can specify the event by return it.
  19051. eventObj = actionWrap.action(batchItem, this._model, this._api);
  19052. // Emit event outside
  19053. eventObj = eventObj || extend({}, batchItem);
  19054. // Convert type to eventType
  19055. eventObj.type = actionInfo.event || eventObj.type;
  19056. eventObjBatch.push(eventObj);
  19057. // light update does not perform data process, layout and visual.
  19058. if (isHighDown) {
  19059. // method, payload, mainType, subType
  19060. updateDirectly(this, updateMethod, batchItem, 'series');
  19061. }
  19062. else if (cptType) {
  19063. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  19064. }
  19065. }, this);
  19066. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  19067. // Still dirty
  19068. if (this[OPTION_UPDATED]) {
  19069. // FIXME Pass payload ?
  19070. updateMethods.prepareAndUpdate.call(this, payload);
  19071. this[OPTION_UPDATED] = false;
  19072. }
  19073. else {
  19074. updateMethods[updateMethod].call(this, payload);
  19075. }
  19076. }
  19077. // Follow the rule of action batch
  19078. if (batched) {
  19079. eventObj = {
  19080. type: actionInfo.event || payloadType,
  19081. escapeConnect: escapeConnect,
  19082. batch: eventObjBatch
  19083. };
  19084. }
  19085. else {
  19086. eventObj = eventObjBatch[0];
  19087. }
  19088. this[IN_MAIN_PROCESS] = false;
  19089. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  19090. }
  19091. function flushPendingActions(silent) {
  19092. var pendingActions = this._pendingActions;
  19093. while (pendingActions.length) {
  19094. var payload = pendingActions.shift();
  19095. doDispatchAction.call(this, payload, silent);
  19096. }
  19097. }
  19098. function triggerUpdatedEvent(silent) {
  19099. !silent && this.trigger('updated');
  19100. }
  19101. /**
  19102. * Register event
  19103. * @method
  19104. */
  19105. echartsProto.on = createRegisterEventWithLowercaseName('on');
  19106. echartsProto.off = createRegisterEventWithLowercaseName('off');
  19107. echartsProto.one = createRegisterEventWithLowercaseName('one');
  19108. /**
  19109. * @param {string} methodName
  19110. * @private
  19111. */
  19112. function invokeUpdateMethod(methodName, ecModel, payload) {
  19113. var api = this._api;
  19114. // Update all components
  19115. each(this._componentsViews, function (component) {
  19116. var componentModel = component.__model;
  19117. component[methodName](componentModel, ecModel, api, payload);
  19118. updateZ(componentModel, component);
  19119. }, this);
  19120. // Upate all charts
  19121. ecModel.eachSeries(function (seriesModel, idx) {
  19122. var chart = this._chartsMap[seriesModel.__viewId];
  19123. chart[methodName](seriesModel, ecModel, api, payload);
  19124. updateZ(seriesModel, chart);
  19125. updateProgressiveAndBlend(seriesModel, chart);
  19126. }, this);
  19127. // If use hover layer
  19128. updateHoverLayerStatus(this._zr, ecModel);
  19129. // Post render
  19130. each(postUpdateFuncs, function (func) {
  19131. func(ecModel, api);
  19132. });
  19133. }
  19134. /**
  19135. * Prepare view instances of charts and components
  19136. * @param {module:echarts/model/Global} ecModel
  19137. * @private
  19138. */
  19139. function prepareView(type, ecModel) {
  19140. var isComponent = type === 'component';
  19141. var viewList = isComponent ? this._componentsViews : this._chartsViews;
  19142. var viewMap = isComponent ? this._componentsMap : this._chartsMap;
  19143. var zr = this._zr;
  19144. for (var i = 0; i < viewList.length; i++) {
  19145. viewList[i].__alive = false;
  19146. }
  19147. ecModel[isComponent ? 'eachComponent' : 'eachSeries'](function (componentType, model) {
  19148. if (isComponent) {
  19149. if (componentType === 'series') {
  19150. return;
  19151. }
  19152. }
  19153. else {
  19154. model = componentType;
  19155. }
  19156. // Consider: id same and type changed.
  19157. var viewId = '_ec_' + model.id + '_' + model.type;
  19158. var view = viewMap[viewId];
  19159. if (!view) {
  19160. var classType = parseClassType(model.type);
  19161. var Clazz = isComponent
  19162. ? Component.getClass(classType.main, classType.sub)
  19163. : Chart.getClass(classType.sub);
  19164. if (Clazz) {
  19165. view = new Clazz();
  19166. view.init(ecModel, this._api);
  19167. viewMap[viewId] = view;
  19168. viewList.push(view);
  19169. zr.add(view.group);
  19170. }
  19171. else {
  19172. // Error
  19173. return;
  19174. }
  19175. }
  19176. model.__viewId = view.__id = viewId;
  19177. view.__alive = true;
  19178. view.__model = model;
  19179. view.group.__ecComponentInfo = {
  19180. mainType: model.mainType,
  19181. index: model.componentIndex
  19182. };
  19183. }, this);
  19184. for (var i = 0; i < viewList.length;) {
  19185. var view = viewList[i];
  19186. if (!view.__alive) {
  19187. zr.remove(view.group);
  19188. view.dispose(ecModel, this._api);
  19189. viewList.splice(i, 1);
  19190. delete viewMap[view.__id];
  19191. view.__id = view.group.__ecComponentInfo = null;
  19192. }
  19193. else {
  19194. i++;
  19195. }
  19196. }
  19197. }
  19198. /**
  19199. * Processor data in each series
  19200. *
  19201. * @param {module:echarts/model/Global} ecModel
  19202. * @private
  19203. */
  19204. function processData(ecModel, api) {
  19205. each(dataProcessorFuncs, function (process) {
  19206. process.func(ecModel, api);
  19207. });
  19208. }
  19209. /**
  19210. * @private
  19211. */
  19212. function stackSeriesData(ecModel) {
  19213. var stackedDataMap = {};
  19214. ecModel.eachSeries(function (series) {
  19215. var stack = series.get('stack');
  19216. var data = series.getData();
  19217. if (stack && data.type === 'list') {
  19218. var previousStack = stackedDataMap[stack];
  19219. // Avoid conflict with Object.prototype
  19220. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  19221. data.stackedOn = previousStack;
  19222. }
  19223. stackedDataMap[stack] = data;
  19224. }
  19225. });
  19226. }
  19227. /**
  19228. * Layout before each chart render there series, special visual encoding stage
  19229. *
  19230. * @param {module:echarts/model/Global} ecModel
  19231. * @private
  19232. */
  19233. function doLayout(ecModel, payload) {
  19234. var api = this._api;
  19235. each(visualFuncs, function (visual) {
  19236. if (visual.isLayout) {
  19237. visual.func(ecModel, api, payload);
  19238. }
  19239. });
  19240. }
  19241. /**
  19242. * Encode visual infomation from data after data processing
  19243. *
  19244. * @param {module:echarts/model/Global} ecModel
  19245. * @param {object} layout
  19246. * @param {boolean} [excludesLayout]
  19247. * @private
  19248. */
  19249. function doVisualEncoding(ecModel, payload, excludesLayout) {
  19250. var api = this._api;
  19251. ecModel.clearColorPalette();
  19252. ecModel.eachSeries(function (seriesModel) {
  19253. seriesModel.clearColorPalette();
  19254. });
  19255. each(visualFuncs, function (visual) {
  19256. (!excludesLayout || !visual.isLayout)
  19257. && visual.func(ecModel, api, payload);
  19258. });
  19259. }
  19260. /**
  19261. * Render each chart and component
  19262. * @private
  19263. */
  19264. function doRender(ecModel, payload) {
  19265. var api = this._api;
  19266. // Render all components
  19267. each(this._componentsViews, function (componentView) {
  19268. var componentModel = componentView.__model;
  19269. componentView.render(componentModel, ecModel, api, payload);
  19270. updateZ(componentModel, componentView);
  19271. }, this);
  19272. each(this._chartsViews, function (chart) {
  19273. chart.__alive = false;
  19274. }, this);
  19275. // Render all charts
  19276. ecModel.eachSeries(function (seriesModel, idx) {
  19277. var chartView = this._chartsMap[seriesModel.__viewId];
  19278. chartView.__alive = true;
  19279. chartView.render(seriesModel, ecModel, api, payload);
  19280. chartView.group.silent = !!seriesModel.get('silent');
  19281. updateZ(seriesModel, chartView);
  19282. updateProgressiveAndBlend(seriesModel, chartView);
  19283. }, this);
  19284. // If use hover layer
  19285. updateHoverLayerStatus(this._zr, ecModel);
  19286. // Remove groups of unrendered charts
  19287. each(this._chartsViews, function (chart) {
  19288. if (!chart.__alive) {
  19289. chart.remove(ecModel, api);
  19290. }
  19291. }, this);
  19292. }
  19293. var MOUSE_EVENT_NAMES = [
  19294. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  19295. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  19296. ];
  19297. /**
  19298. * @private
  19299. */
  19300. echartsProto._initEvents = function () {
  19301. each(MOUSE_EVENT_NAMES, function (eveName) {
  19302. this._zr.on(eveName, function (e) {
  19303. var ecModel = this.getModel();
  19304. var el = e.target;
  19305. var params;
  19306. // no e.target when 'globalout'.
  19307. if (eveName === 'globalout') {
  19308. params = {};
  19309. }
  19310. else if (el && el.dataIndex != null) {
  19311. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  19312. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  19313. }
  19314. // If element has custom eventData of components
  19315. else if (el && el.eventData) {
  19316. params = extend({}, el.eventData);
  19317. }
  19318. if (params) {
  19319. params.event = e;
  19320. params.type = eveName;
  19321. this.trigger(eveName, params);
  19322. }
  19323. }, this);
  19324. }, this);
  19325. each(eventActionMap, function (actionType, eventType) {
  19326. this._messageCenter.on(eventType, function (event) {
  19327. this.trigger(eventType, event);
  19328. }, this);
  19329. }, this);
  19330. };
  19331. /**
  19332. * @return {boolean}
  19333. */
  19334. echartsProto.isDisposed = function () {
  19335. return this._disposed;
  19336. };
  19337. /**
  19338. * Clear
  19339. */
  19340. echartsProto.clear = function () {
  19341. this.setOption({ series: [] }, true);
  19342. };
  19343. /**
  19344. * Dispose instance
  19345. */
  19346. echartsProto.dispose = function () {
  19347. if (this._disposed) {
  19348. if (__DEV__) {
  19349. console.warn('Instance ' + this.id + ' has been disposed');
  19350. }
  19351. return;
  19352. }
  19353. this._disposed = true;
  19354. var api = this._api;
  19355. var ecModel = this._model;
  19356. each(this._componentsViews, function (component) {
  19357. component.dispose(ecModel, api);
  19358. });
  19359. each(this._chartsViews, function (chart) {
  19360. chart.dispose(ecModel, api);
  19361. });
  19362. // Dispose after all views disposed
  19363. this._zr.dispose();
  19364. delete instances[this.id];
  19365. };
  19366. mixin(ECharts, Eventful);
  19367. function updateHoverLayerStatus(zr, ecModel) {
  19368. var storage = zr.storage;
  19369. var elCount = 0;
  19370. storage.traverse(function (el) {
  19371. if (!el.isGroup) {
  19372. elCount++;
  19373. }
  19374. });
  19375. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  19376. storage.traverse(function (el) {
  19377. if (!el.isGroup) {
  19378. el.useHoverLayer = true;
  19379. }
  19380. });
  19381. }
  19382. }
  19383. /**
  19384. * Update chart progressive and blend.
  19385. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  19386. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  19387. */
  19388. function updateProgressiveAndBlend(seriesModel, chartView) {
  19389. // Progressive configuration
  19390. var elCount = 0;
  19391. chartView.group.traverse(function (el) {
  19392. if (el.type !== 'group' && !el.ignore) {
  19393. elCount++;
  19394. }
  19395. });
  19396. var frameDrawNum = +seriesModel.get('progressive');
  19397. var needProgressive = elCount > seriesModel.get('progressiveThreshold') && frameDrawNum && !env$1.node;
  19398. if (needProgressive) {
  19399. chartView.group.traverse(function (el) {
  19400. // FIXME marker and other components
  19401. if (!el.isGroup) {
  19402. el.progressive = needProgressive ?
  19403. Math.floor(elCount++ / frameDrawNum) : -1;
  19404. if (needProgressive) {
  19405. el.stopAnimation(true);
  19406. }
  19407. }
  19408. });
  19409. }
  19410. // Blend configration
  19411. var blendMode = seriesModel.get('blendMode') || null;
  19412. if (__DEV__) {
  19413. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  19414. console.warn('Only canvas support blendMode');
  19415. }
  19416. }
  19417. chartView.group.traverse(function (el) {
  19418. // FIXME marker and other components
  19419. if (!el.isGroup) {
  19420. el.setStyle('blend', blendMode);
  19421. }
  19422. });
  19423. }
  19424. /**
  19425. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  19426. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  19427. */
  19428. function updateZ(model, view) {
  19429. var z = model.get('z');
  19430. var zlevel = model.get('zlevel');
  19431. // Set z and zlevel
  19432. view.group.traverse(function (el) {
  19433. if (el.type !== 'group') {
  19434. z != null && (el.z = z);
  19435. zlevel != null && (el.zlevel = zlevel);
  19436. }
  19437. });
  19438. }
  19439. function createExtensionAPI(ecInstance) {
  19440. var coordSysMgr = ecInstance._coordSysMgr;
  19441. return extend(new ExtensionAPI(ecInstance), {
  19442. // Inject methods
  19443. getCoordinateSystems: bind(
  19444. coordSysMgr.getCoordinateSystems, coordSysMgr
  19445. ),
  19446. getComponentByElement: function (el) {
  19447. while (el) {
  19448. var modelInfo = el.__ecComponentInfo;
  19449. if (modelInfo != null) {
  19450. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  19451. }
  19452. el = el.parent;
  19453. }
  19454. }
  19455. });
  19456. }
  19457. /**
  19458. * @type {Object} key: actionType.
  19459. * @inner
  19460. */
  19461. var actions = {};
  19462. /**
  19463. * Map eventType to actionType
  19464. * @type {Object}
  19465. */
  19466. var eventActionMap = {};
  19467. /**
  19468. * Data processor functions of each stage
  19469. * @type {Array.<Object.<string, Function>>}
  19470. * @inner
  19471. */
  19472. var dataProcessorFuncs = [];
  19473. /**
  19474. * @type {Array.<Function>}
  19475. * @inner
  19476. */
  19477. var optionPreprocessorFuncs = [];
  19478. /**
  19479. * @type {Array.<Function>}
  19480. * @inner
  19481. */
  19482. var postUpdateFuncs = [];
  19483. /**
  19484. * Visual encoding functions of each stage
  19485. * @type {Array.<Object.<string, Function>>}
  19486. * @inner
  19487. */
  19488. var visualFuncs = [];
  19489. /**
  19490. * Theme storage
  19491. * @type {Object.<key, Object>}
  19492. */
  19493. var themeStorage = {};
  19494. /**
  19495. * Loading effects
  19496. */
  19497. var loadingEffects = {};
  19498. var instances = {};
  19499. var connectedGroups = {};
  19500. var idBase = new Date() - 0;
  19501. var groupIdBase = new Date() - 0;
  19502. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  19503. var mapDataStores = {};
  19504. function enableConnect(chart) {
  19505. var STATUS_PENDING = 0;
  19506. var STATUS_UPDATING = 1;
  19507. var STATUS_UPDATED = 2;
  19508. var STATUS_KEY = '__connectUpdateStatus';
  19509. function updateConnectedChartsStatus(charts, status) {
  19510. for (var i = 0; i < charts.length; i++) {
  19511. var otherChart = charts[i];
  19512. otherChart[STATUS_KEY] = status;
  19513. }
  19514. }
  19515. each$1(eventActionMap, function (actionType, eventType) {
  19516. chart._messageCenter.on(eventType, function (event) {
  19517. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  19518. if (event && event.escapeConnect) {
  19519. return;
  19520. }
  19521. var action = chart.makeActionFromEvent(event);
  19522. var otherCharts = [];
  19523. each$1(instances, function (otherChart) {
  19524. if (otherChart !== chart && otherChart.group === chart.group) {
  19525. otherCharts.push(otherChart);
  19526. }
  19527. });
  19528. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  19529. each(otherCharts, function (otherChart) {
  19530. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  19531. otherChart.dispatchAction(action);
  19532. }
  19533. });
  19534. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  19535. }
  19536. });
  19537. });
  19538. }
  19539. /**
  19540. * @param {HTMLElement} dom
  19541. * @param {Object} [theme]
  19542. * @param {Object} opts
  19543. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  19544. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  19545. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  19546. * Can be 'auto' (the same as null/undefined)
  19547. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  19548. * Can be 'auto' (the same as null/undefined)
  19549. */
  19550. function init(dom, theme, opts) {
  19551. if (__DEV__) {
  19552. // Check version
  19553. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  19554. throw new Error(
  19555. 'zrender/src ' + version$1
  19556. + ' is too old for ECharts ' + version
  19557. + '. Current version need ZRender '
  19558. + dependencies.zrender + '+'
  19559. );
  19560. }
  19561. if (!dom) {
  19562. throw new Error('Initialize failed: invalid dom.');
  19563. }
  19564. }
  19565. var existInstance = getInstanceByDom(dom);
  19566. if (existInstance) {
  19567. if (__DEV__) {
  19568. console.warn('There is a chart instance already initialized on the dom.');
  19569. }
  19570. return existInstance;
  19571. }
  19572. if (__DEV__) {
  19573. if (isDom(dom)
  19574. && dom.nodeName.toUpperCase() !== 'CANVAS'
  19575. && (
  19576. (!dom.clientWidth && (!opts || opts.width == null))
  19577. || (!dom.clientHeight && (!opts || opts.height == null))
  19578. )
  19579. ) {
  19580. console.warn('Can\'t get dom width or height');
  19581. }
  19582. }
  19583. var chart = new ECharts(dom, theme, opts);
  19584. chart.id = 'ec_' + idBase++;
  19585. instances[chart.id] = chart;
  19586. if (dom.setAttribute) {
  19587. dom.setAttribute(DOM_ATTRIBUTE_KEY, chart.id);
  19588. }
  19589. else {
  19590. dom[DOM_ATTRIBUTE_KEY] = chart.id;
  19591. }
  19592. enableConnect(chart);
  19593. return chart;
  19594. }
  19595. /**
  19596. * @return {string|Array.<module:echarts~ECharts>} groupId
  19597. */
  19598. function connect(groupId) {
  19599. // Is array of charts
  19600. if (isArray(groupId)) {
  19601. var charts = groupId;
  19602. groupId = null;
  19603. // If any chart has group
  19604. each$1(charts, function (chart) {
  19605. if (chart.group != null) {
  19606. groupId = chart.group;
  19607. }
  19608. });
  19609. groupId = groupId || ('g_' + groupIdBase++);
  19610. each$1(charts, function (chart) {
  19611. chart.group = groupId;
  19612. });
  19613. }
  19614. connectedGroups[groupId] = true;
  19615. return groupId;
  19616. }
  19617. /**
  19618. * @DEPRECATED
  19619. * @return {string} groupId
  19620. */
  19621. function disConnect(groupId) {
  19622. connectedGroups[groupId] = false;
  19623. }
  19624. /**
  19625. * @return {string} groupId
  19626. */
  19627. var disconnect = disConnect;
  19628. /**
  19629. * Dispose a chart instance
  19630. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  19631. */
  19632. function dispose(chart) {
  19633. if (typeof chart === 'string') {
  19634. chart = instances[chart];
  19635. }
  19636. else if (!(chart instanceof ECharts)){
  19637. // Try to treat as dom
  19638. chart = getInstanceByDom(chart);
  19639. }
  19640. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  19641. chart.dispose();
  19642. }
  19643. }
  19644. /**
  19645. * @param {HTMLElement} dom
  19646. * @return {echarts~ECharts}
  19647. */
  19648. function getInstanceByDom(dom) {
  19649. var key;
  19650. if (dom.getAttribute) {
  19651. key = dom.getAttribute(DOM_ATTRIBUTE_KEY);
  19652. }
  19653. else {
  19654. key = dom[DOM_ATTRIBUTE_KEY];
  19655. }
  19656. return instances[key];
  19657. }
  19658. /**
  19659. * @param {string} key
  19660. * @return {echarts~ECharts}
  19661. */
  19662. function getInstanceById(key) {
  19663. return instances[key];
  19664. }
  19665. /**
  19666. * Register theme
  19667. */
  19668. function registerTheme(name, theme) {
  19669. themeStorage[name] = theme;
  19670. }
  19671. /**
  19672. * Register option preprocessor
  19673. * @param {Function} preprocessorFunc
  19674. */
  19675. function registerPreprocessor(preprocessorFunc) {
  19676. optionPreprocessorFuncs.push(preprocessorFunc);
  19677. }
  19678. /**
  19679. * @param {number} [priority=1000]
  19680. * @param {Function} processorFunc
  19681. */
  19682. function registerProcessor(priority, processorFunc) {
  19683. if (typeof priority === 'function') {
  19684. processorFunc = priority;
  19685. priority = PRIORITY_PROCESSOR_FILTER;
  19686. }
  19687. if (__DEV__) {
  19688. if (isNaN(priority)) {
  19689. throw new Error('Unkown processor priority');
  19690. }
  19691. }
  19692. dataProcessorFuncs.push({
  19693. prio: priority,
  19694. func: processorFunc
  19695. });
  19696. }
  19697. /**
  19698. * Register postUpdater
  19699. * @param {Function} postUpdateFunc
  19700. */
  19701. function registerPostUpdate(postUpdateFunc) {
  19702. postUpdateFuncs.push(postUpdateFunc);
  19703. }
  19704. /**
  19705. * Usage:
  19706. * registerAction('someAction', 'someEvent', function () { ... });
  19707. * registerAction('someAction', function () { ... });
  19708. * registerAction(
  19709. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  19710. * function () { ... }
  19711. * );
  19712. *
  19713. * @param {(string|Object)} actionInfo
  19714. * @param {string} actionInfo.type
  19715. * @param {string} [actionInfo.event]
  19716. * @param {string} [actionInfo.update]
  19717. * @param {string} [eventName]
  19718. * @param {Function} action
  19719. */
  19720. function registerAction(actionInfo, eventName, action) {
  19721. if (typeof eventName === 'function') {
  19722. action = eventName;
  19723. eventName = '';
  19724. }
  19725. var actionType = isObject(actionInfo)
  19726. ? actionInfo.type
  19727. : ([actionInfo, actionInfo = {
  19728. event: eventName
  19729. }][0]);
  19730. // Event name is all lowercase
  19731. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  19732. eventName = actionInfo.event;
  19733. // Validate action type and event name.
  19734. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  19735. if (!actions[actionType]) {
  19736. actions[actionType] = {action: action, actionInfo: actionInfo};
  19737. }
  19738. eventActionMap[eventName] = actionType;
  19739. }
  19740. /**
  19741. * @param {string} type
  19742. * @param {*} CoordinateSystem
  19743. */
  19744. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  19745. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  19746. }
  19747. /**
  19748. * Get dimensions of specified coordinate system.
  19749. * @param {string} type
  19750. * @return {Array.<string|Object>}
  19751. */
  19752. function getCoordinateSystemDimensions(type) {
  19753. var coordSysCreator = CoordinateSystemManager.get(type);
  19754. if (coordSysCreator) {
  19755. return coordSysCreator.getDimensionsInfo
  19756. ? coordSysCreator.getDimensionsInfo()
  19757. : coordSysCreator.dimensions.slice();
  19758. }
  19759. }
  19760. /**
  19761. * Layout is a special stage of visual encoding
  19762. * Most visual encoding like color are common for different chart
  19763. * But each chart has it's own layout algorithm
  19764. *
  19765. * @param {number} [priority=1000]
  19766. * @param {Function} layoutFunc
  19767. */
  19768. function registerLayout(priority, layoutFunc) {
  19769. if (typeof priority === 'function') {
  19770. layoutFunc = priority;
  19771. priority = PRIORITY_VISUAL_LAYOUT;
  19772. }
  19773. if (__DEV__) {
  19774. if (isNaN(priority)) {
  19775. throw new Error('Unkown layout priority');
  19776. }
  19777. }
  19778. visualFuncs.push({
  19779. prio: priority,
  19780. func: layoutFunc,
  19781. isLayout: true
  19782. });
  19783. }
  19784. /**
  19785. * @param {number} [priority=3000]
  19786. * @param {Function} visualFunc
  19787. */
  19788. function registerVisual(priority, visualFunc) {
  19789. if (typeof priority === 'function') {
  19790. visualFunc = priority;
  19791. priority = PRIORITY_VISUAL_CHART;
  19792. }
  19793. if (__DEV__) {
  19794. if (isNaN(priority)) {
  19795. throw new Error('Unkown visual priority');
  19796. }
  19797. }
  19798. visualFuncs.push({
  19799. prio: priority,
  19800. func: visualFunc
  19801. });
  19802. }
  19803. /**
  19804. * @param {string} name
  19805. */
  19806. function registerLoading(name, loadingFx) {
  19807. loadingEffects[name] = loadingFx;
  19808. }
  19809. /**
  19810. * @param {Object} opts
  19811. * @param {string} [superClass]
  19812. */
  19813. function extendComponentModel(opts/*, superClass*/) {
  19814. // var Clazz = ComponentModel;
  19815. // if (superClass) {
  19816. // var classType = parseClassType(superClass);
  19817. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  19818. // }
  19819. return ComponentModel.extend(opts);
  19820. }
  19821. /**
  19822. * @param {Object} opts
  19823. * @param {string} [superClass]
  19824. */
  19825. function extendComponentView(opts/*, superClass*/) {
  19826. // var Clazz = ComponentView;
  19827. // if (superClass) {
  19828. // var classType = parseClassType(superClass);
  19829. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  19830. // }
  19831. return Component.extend(opts);
  19832. }
  19833. /**
  19834. * @param {Object} opts
  19835. * @param {string} [superClass]
  19836. */
  19837. function extendSeriesModel(opts/*, superClass*/) {
  19838. // var Clazz = SeriesModel;
  19839. // if (superClass) {
  19840. // superClass = 'series.' + superClass.replace('series.', '');
  19841. // var classType = parseClassType(superClass);
  19842. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  19843. // }
  19844. return SeriesModel.extend(opts);
  19845. }
  19846. /**
  19847. * @param {Object} opts
  19848. * @param {string} [superClass]
  19849. */
  19850. function extendChartView(opts/*, superClass*/) {
  19851. // var Clazz = ChartView;
  19852. // if (superClass) {
  19853. // superClass = superClass.replace('series.', '');
  19854. // var classType = parseClassType(superClass);
  19855. // Clazz = ChartView.getClass(classType.main, true);
  19856. // }
  19857. return Chart.extend(opts);
  19858. }
  19859. /**
  19860. * ZRender need a canvas context to do measureText.
  19861. * But in node environment canvas may be created by node-canvas.
  19862. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  19863. *
  19864. * Be careful of using it in the browser.
  19865. *
  19866. * @param {Function} creator
  19867. * @example
  19868. * var Canvas = require('canvas');
  19869. * var echarts = require('echarts');
  19870. * echarts.setCanvasCreator(function () {
  19871. * // Small size is enough.
  19872. * return new Canvas(32, 32);
  19873. * });
  19874. */
  19875. function setCanvasCreator(creator) {
  19876. $override('createCanvas', creator);
  19877. }
  19878. /**
  19879. * @param {string} mapName
  19880. * @param {Object|string} geoJson
  19881. * @param {Object} [specialAreas]
  19882. *
  19883. * @example
  19884. * $.get('USA.json', function (geoJson) {
  19885. * echarts.registerMap('USA', geoJson);
  19886. * // Or
  19887. * echarts.registerMap('USA', {
  19888. * geoJson: geoJson,
  19889. * specialAreas: {}
  19890. * })
  19891. * });
  19892. */
  19893. function registerMap(mapName, geoJson, specialAreas) {
  19894. if (geoJson.geoJson && !geoJson.features) {
  19895. specialAreas = geoJson.specialAreas;
  19896. geoJson = geoJson.geoJson;
  19897. }
  19898. if (typeof geoJson === 'string') {
  19899. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  19900. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  19901. }
  19902. mapDataStores[mapName] = {
  19903. geoJson: geoJson,
  19904. specialAreas: specialAreas
  19905. };
  19906. }
  19907. /**
  19908. * @param {string} mapName
  19909. * @return {Object}
  19910. */
  19911. function getMap(mapName) {
  19912. return mapDataStores[mapName];
  19913. }
  19914. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  19915. registerPreprocessor(backwardCompat);
  19916. registerLoading('default', loadingDefault);
  19917. // Default actions
  19918. registerAction({
  19919. type: 'highlight',
  19920. event: 'highlight',
  19921. update: 'highlight'
  19922. }, noop);
  19923. registerAction({
  19924. type: 'downplay',
  19925. event: 'downplay',
  19926. update: 'downplay'
  19927. }, noop);
  19928. // For backward compatibility, where the namespace `dataTool` will
  19929. // be mounted on `echarts` is the extension `dataTool` is imported.
  19930. var dataTool = {};
  19931. function defaultKeyGetter(item) {
  19932. return item;
  19933. }
  19934. /**
  19935. * @param {Array} oldArr
  19936. * @param {Array} newArr
  19937. * @param {Function} oldKeyGetter
  19938. * @param {Function} newKeyGetter
  19939. * @param {Object} [context] Can be visited by this.context in callback.
  19940. */
  19941. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  19942. this._old = oldArr;
  19943. this._new = newArr;
  19944. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  19945. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  19946. this.context = context;
  19947. }
  19948. DataDiffer.prototype = {
  19949. constructor: DataDiffer,
  19950. /**
  19951. * Callback function when add a data
  19952. */
  19953. add: function (func) {
  19954. this._add = func;
  19955. return this;
  19956. },
  19957. /**
  19958. * Callback function when update a data
  19959. */
  19960. update: function (func) {
  19961. this._update = func;
  19962. return this;
  19963. },
  19964. /**
  19965. * Callback function when remove a data
  19966. */
  19967. remove: function (func) {
  19968. this._remove = func;
  19969. return this;
  19970. },
  19971. execute: function () {
  19972. var oldArr = this._old;
  19973. var newArr = this._new;
  19974. var oldDataIndexMap = {};
  19975. var newDataIndexMap = {};
  19976. var oldDataKeyArr = [];
  19977. var newDataKeyArr = [];
  19978. var i;
  19979. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  19980. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  19981. // Travel by inverted order to make sure order consistency
  19982. // when duplicate keys exists (consider newDataIndex.pop() below).
  19983. // For performance consideration, these code below do not look neat.
  19984. for (i = 0; i < oldArr.length; i++) {
  19985. var key = oldDataKeyArr[i];
  19986. var idx = newDataIndexMap[key];
  19987. // idx can never be empty array here. see 'set null' logic below.
  19988. if (idx != null) {
  19989. // Consider there is duplicate key (for example, use dataItem.name as key).
  19990. // We should make sure every item in newArr and oldArr can be visited.
  19991. var len = idx.length;
  19992. if (len) {
  19993. len === 1 && (newDataIndexMap[key] = null);
  19994. idx = idx.unshift();
  19995. }
  19996. else {
  19997. newDataIndexMap[key] = null;
  19998. }
  19999. this._update && this._update(idx, i);
  20000. }
  20001. else {
  20002. this._remove && this._remove(i);
  20003. }
  20004. }
  20005. for (var i = 0; i < newDataKeyArr.length; i++) {
  20006. var key = newDataKeyArr[i];
  20007. if (newDataIndexMap.hasOwnProperty(key)) {
  20008. var idx = newDataIndexMap[key];
  20009. if (idx == null) {
  20010. continue;
  20011. }
  20012. // idx can never be empty array here. see 'set null' logic above.
  20013. if (!idx.length) {
  20014. this._add && this._add(idx);
  20015. }
  20016. else {
  20017. for (var j = 0, len = idx.length; j < len; j++) {
  20018. this._add && this._add(idx[j]);
  20019. }
  20020. }
  20021. }
  20022. }
  20023. }
  20024. };
  20025. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  20026. for (var i = 0; i < arr.length; i++) {
  20027. // Add prefix to avoid conflict with Object.prototype.
  20028. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  20029. var existence = map[key];
  20030. if (existence == null) {
  20031. keyArr.push(key);
  20032. map[key] = i;
  20033. }
  20034. else {
  20035. if (!existence.length) {
  20036. map[key] = existence = [existence];
  20037. }
  20038. existence.push(i);
  20039. }
  20040. }
  20041. }
  20042. /**
  20043. * List for data storage
  20044. * @module echarts/data/List
  20045. */
  20046. var isObject$4 = isObject;
  20047. var UNDEFINED = 'undefined';
  20048. var globalObj = typeof window === UNDEFINED ? global : window;
  20049. var dataCtors = {
  20050. 'float': typeof globalObj.Float64Array === UNDEFINED
  20051. ? Array : globalObj.Float64Array,
  20052. 'int': typeof globalObj.Int32Array === UNDEFINED
  20053. ? Array : globalObj.Int32Array,
  20054. // Ordinal data type can be string or int
  20055. 'ordinal': Array,
  20056. 'number': Array,
  20057. 'time': Array
  20058. };
  20059. var TRANSFERABLE_PROPERTIES = [
  20060. 'stackedOn', 'hasItemOption', '_nameList', '_idList', '_rawData'
  20061. ];
  20062. function transferProperties(a, b) {
  20063. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  20064. if (b.hasOwnProperty(propName)) {
  20065. a[propName] = b[propName];
  20066. }
  20067. });
  20068. a.__wrappedMethods = b.__wrappedMethods;
  20069. }
  20070. function DefaultDataProvider(dataArray) {
  20071. this._array = dataArray || [];
  20072. }
  20073. DefaultDataProvider.prototype.pure = false;
  20074. DefaultDataProvider.prototype.count = function () {
  20075. return this._array.length;
  20076. };
  20077. DefaultDataProvider.prototype.getItem = function (idx) {
  20078. return this._array[idx];
  20079. };
  20080. /**
  20081. * @constructor
  20082. * @alias module:echarts/data/List
  20083. *
  20084. * @param {Array.<string|Object>} dimensions
  20085. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  20086. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  20087. * @param {module:echarts/model/Model} hostModel
  20088. */
  20089. var List = function (dimensions, hostModel) {
  20090. dimensions = dimensions || ['x', 'y'];
  20091. var dimensionInfos = {};
  20092. var dimensionNames = [];
  20093. for (var i = 0; i < dimensions.length; i++) {
  20094. var dimensionName;
  20095. var dimensionInfo = {};
  20096. if (typeof dimensions[i] === 'string') {
  20097. dimensionName = dimensions[i];
  20098. dimensionInfo = {
  20099. name: dimensionName,
  20100. coordDim: dimensionName,
  20101. coordDimIndex: 0,
  20102. stackable: false,
  20103. // Type can be 'float', 'int', 'number'
  20104. // Default is number, Precision of float may not enough
  20105. type: 'number'
  20106. };
  20107. }
  20108. else {
  20109. dimensionInfo = dimensions[i];
  20110. dimensionName = dimensionInfo.name;
  20111. dimensionInfo.type = dimensionInfo.type || 'number';
  20112. if (!dimensionInfo.coordDim) {
  20113. dimensionInfo.coordDim = dimensionName;
  20114. dimensionInfo.coordDimIndex = 0;
  20115. }
  20116. }
  20117. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  20118. dimensionNames.push(dimensionName);
  20119. dimensionInfos[dimensionName] = dimensionInfo;
  20120. }
  20121. /**
  20122. * @readOnly
  20123. * @type {Array.<string>}
  20124. */
  20125. this.dimensions = dimensionNames;
  20126. /**
  20127. * Infomation of each data dimension, like data type.
  20128. * @type {Object}
  20129. */
  20130. this._dimensionInfos = dimensionInfos;
  20131. /**
  20132. * @type {module:echarts/model/Model}
  20133. */
  20134. this.hostModel = hostModel;
  20135. /**
  20136. * @type {module:echarts/model/Model}
  20137. */
  20138. this.dataType;
  20139. /**
  20140. * Indices stores the indices of data subset after filtered.
  20141. * This data subset will be used in chart.
  20142. * @type {Array.<number>}
  20143. * @readOnly
  20144. */
  20145. this.indices = [];
  20146. /**
  20147. * Data storage
  20148. * @type {Object.<key, TypedArray|Array>}
  20149. * @private
  20150. */
  20151. this._storage = {};
  20152. /**
  20153. * @type {Array.<string>}
  20154. */
  20155. this._nameList = [];
  20156. /**
  20157. * @type {Array.<string>}
  20158. */
  20159. this._idList = [];
  20160. /**
  20161. * Models of data option is stored sparse for optimizing memory cost
  20162. * @type {Array.<module:echarts/model/Model>}
  20163. * @private
  20164. */
  20165. this._optionModels = [];
  20166. /**
  20167. * @param {module:echarts/data/List}
  20168. */
  20169. this.stackedOn = null;
  20170. /**
  20171. * Global visual properties after visual coding
  20172. * @type {Object}
  20173. * @private
  20174. */
  20175. this._visual = {};
  20176. /**
  20177. * Globel layout properties.
  20178. * @type {Object}
  20179. * @private
  20180. */
  20181. this._layout = {};
  20182. /**
  20183. * Item visual properties after visual coding
  20184. * @type {Array.<Object>}
  20185. * @private
  20186. */
  20187. this._itemVisuals = [];
  20188. /**
  20189. * Item layout properties after layout
  20190. * @type {Array.<Object>}
  20191. * @private
  20192. */
  20193. this._itemLayouts = [];
  20194. /**
  20195. * Graphic elemnents
  20196. * @type {Array.<module:zrender/Element>}
  20197. * @private
  20198. */
  20199. this._graphicEls = [];
  20200. /**
  20201. * @type {Array.<Array|Object>}
  20202. * @private
  20203. */
  20204. this._rawData;
  20205. /**
  20206. * @type {Object}
  20207. * @private
  20208. */
  20209. this._extent;
  20210. };
  20211. var listProto = List.prototype;
  20212. listProto.type = 'list';
  20213. /**
  20214. * If each data item has it's own option
  20215. * @type {boolean}
  20216. */
  20217. listProto.hasItemOption = true;
  20218. /**
  20219. * Get dimension name
  20220. * @param {string|number} dim
  20221. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  20222. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  20223. * @return {string} Concrete dim name.
  20224. */
  20225. listProto.getDimension = function (dim) {
  20226. if (!isNaN(dim)) {
  20227. dim = this.dimensions[dim] || dim;
  20228. }
  20229. return dim;
  20230. };
  20231. /**
  20232. * Get type and stackable info of particular dimension
  20233. * @param {string|number} dim
  20234. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  20235. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  20236. */
  20237. listProto.getDimensionInfo = function (dim) {
  20238. return clone(this._dimensionInfos[this.getDimension(dim)]);
  20239. };
  20240. /**
  20241. * Initialize from data
  20242. * @param {Array.<Object|number|Array>} data
  20243. * @param {Array.<string>} [nameList]
  20244. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  20245. */
  20246. listProto.initData = function (data, nameList, dimValueGetter) {
  20247. data = data || [];
  20248. var isDataArray = isArray(data);
  20249. if (isDataArray) {
  20250. data = new DefaultDataProvider(data);
  20251. }
  20252. if (__DEV__) {
  20253. if (!isDataArray && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  20254. throw new Error('Inavlid data provider.');
  20255. }
  20256. }
  20257. this._rawData = data;
  20258. // Clear
  20259. var storage = this._storage = {};
  20260. var indices = this.indices = [];
  20261. var dimensions = this.dimensions;
  20262. var dimensionInfoMap = this._dimensionInfos;
  20263. var size = data.count();
  20264. var idList = [];
  20265. var nameRepeatCount = {};
  20266. var nameDimIdx;
  20267. nameList = nameList || [];
  20268. // Init storage
  20269. for (var i = 0; i < dimensions.length; i++) {
  20270. var dimInfo = dimensionInfoMap[dimensions[i]];
  20271. dimInfo.otherDims.itemName === 0 && (nameDimIdx = i);
  20272. var DataCtor = dataCtors[dimInfo.type];
  20273. storage[dimensions[i]] = new DataCtor(size);
  20274. }
  20275. var self = this;
  20276. if (!dimValueGetter) {
  20277. self.hasItemOption = false;
  20278. }
  20279. // Default dim value getter
  20280. dimValueGetter = dimValueGetter || function (dataItem, dimName, dataIndex, dimIndex) {
  20281. var value = getDataItemValue(dataItem);
  20282. // If any dataItem is like { value: 10 }
  20283. if (isDataItemOption(dataItem)) {
  20284. self.hasItemOption = true;
  20285. }
  20286. return converDataValue(
  20287. (value instanceof Array)
  20288. ? value[dimIndex]
  20289. // If value is a single number or something else not array.
  20290. : value,
  20291. dimensionInfoMap[dimName]
  20292. );
  20293. };
  20294. for (var i = 0; i < size; i++) {
  20295. // NOTICE: Try not to write things into dataItem
  20296. var dataItem = data.getItem(i);
  20297. // Each data item is value
  20298. // [1, 2]
  20299. // 2
  20300. // Bar chart, line chart which uses category axis
  20301. // only gives the 'y' value. 'x' value is the indices of cateogry
  20302. // Use a tempValue to normalize the value to be a (x, y) value
  20303. // Store the data by dimensions
  20304. for (var k = 0; k < dimensions.length; k++) {
  20305. var dim = dimensions[k];
  20306. var dimStorage = storage[dim];
  20307. // PENDING NULL is empty or zero
  20308. dimStorage[i] = dimValueGetter(dataItem, dim, i, k);
  20309. }
  20310. indices.push(i);
  20311. }
  20312. // Use the name in option and create id
  20313. for (var i = 0; i < size; i++) {
  20314. var dataItem = data.getItem(i);
  20315. if (!nameList[i] && dataItem) {
  20316. if (dataItem.name != null) {
  20317. nameList[i] = dataItem.name;
  20318. }
  20319. else if (nameDimIdx != null) {
  20320. nameList[i] = storage[dimensions[nameDimIdx]][i];
  20321. }
  20322. }
  20323. var name = nameList[i] || '';
  20324. // Try using the id in option
  20325. var id = dataItem && dataItem.id;
  20326. if (!id && name) {
  20327. // Use name as id and add counter to avoid same name
  20328. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  20329. id = name;
  20330. if (nameRepeatCount[name] > 0) {
  20331. id += '__ec__' + nameRepeatCount[name];
  20332. }
  20333. nameRepeatCount[name]++;
  20334. }
  20335. id && (idList[i] = id);
  20336. }
  20337. this._nameList = nameList;
  20338. this._idList = idList;
  20339. };
  20340. /**
  20341. * @return {number}
  20342. */
  20343. listProto.count = function () {
  20344. return this.indices.length;
  20345. };
  20346. /**
  20347. * Get value. Return NaN if idx is out of range.
  20348. * @param {string} dim Dim must be concrete name.
  20349. * @param {number} idx
  20350. * @param {boolean} stack
  20351. * @return {number}
  20352. */
  20353. listProto.get = function (dim, idx, stack) {
  20354. var storage = this._storage;
  20355. var dataIndex = this.indices[idx];
  20356. // If value not exists
  20357. if (dataIndex == null || !storage[dim]) {
  20358. return NaN;
  20359. }
  20360. var value = storage[dim][dataIndex];
  20361. // FIXME ordinal data type is not stackable
  20362. if (stack) {
  20363. var dimensionInfo = this._dimensionInfos[dim];
  20364. if (dimensionInfo && dimensionInfo.stackable) {
  20365. var stackedOn = this.stackedOn;
  20366. while (stackedOn) {
  20367. // Get no stacked data of stacked on
  20368. var stackedValue = stackedOn.get(dim, idx);
  20369. // Considering positive stack, negative stack and empty data
  20370. if ((value >= 0 && stackedValue > 0) // Positive stack
  20371. || (value <= 0 && stackedValue < 0) // Negative stack
  20372. ) {
  20373. value += stackedValue;
  20374. }
  20375. stackedOn = stackedOn.stackedOn;
  20376. }
  20377. }
  20378. }
  20379. return value;
  20380. };
  20381. /**
  20382. * Get value for multi dimensions.
  20383. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  20384. * @param {number} idx
  20385. * @param {boolean} stack
  20386. * @return {number}
  20387. */
  20388. listProto.getValues = function (dimensions, idx, stack) {
  20389. var values = [];
  20390. if (!isArray(dimensions)) {
  20391. stack = idx;
  20392. idx = dimensions;
  20393. dimensions = this.dimensions;
  20394. }
  20395. for (var i = 0, len = dimensions.length; i < len; i++) {
  20396. values.push(this.get(dimensions[i], idx, stack));
  20397. }
  20398. return values;
  20399. };
  20400. /**
  20401. * If value is NaN. Inlcuding '-'
  20402. * @param {string} dim
  20403. * @param {number} idx
  20404. * @return {number}
  20405. */
  20406. listProto.hasValue = function (idx) {
  20407. var dimensions = this.dimensions;
  20408. var dimensionInfos = this._dimensionInfos;
  20409. for (var i = 0, len = dimensions.length; i < len; i++) {
  20410. if (
  20411. // Ordinal type can be string or number
  20412. dimensionInfos[dimensions[i]].type !== 'ordinal'
  20413. && isNaN(this.get(dimensions[i], idx))
  20414. ) {
  20415. return false;
  20416. }
  20417. }
  20418. return true;
  20419. };
  20420. /**
  20421. * Get extent of data in one dimension
  20422. * @param {string} dim
  20423. * @param {boolean} stack
  20424. * @param {Function} filter
  20425. */
  20426. listProto.getDataExtent = function (dim, stack, filter$$1) {
  20427. dim = this.getDimension(dim);
  20428. var dimData = this._storage[dim];
  20429. var dimInfo = this.getDimensionInfo(dim);
  20430. stack = (dimInfo && dimInfo.stackable) && stack;
  20431. var dimExtent = (this._extent || (this._extent = {}))[dim + (!!stack)];
  20432. var value;
  20433. if (dimExtent) {
  20434. return dimExtent;
  20435. }
  20436. // var dimInfo = this._dimensionInfos[dim];
  20437. if (dimData) {
  20438. var min = Infinity;
  20439. var max = -Infinity;
  20440. // var isOrdinal = dimInfo.type === 'ordinal';
  20441. for (var i = 0, len = this.count(); i < len; i++) {
  20442. value = this.get(dim, i, stack);
  20443. // FIXME
  20444. // if (isOrdinal && typeof value === 'string') {
  20445. // value = zrUtil.indexOf(dimData, value);
  20446. // }
  20447. if (!filter$$1 || filter$$1(value, dim, i)) {
  20448. value < min && (min = value);
  20449. value > max && (max = value);
  20450. }
  20451. }
  20452. return (this._extent[dim + !!stack] = [min, max]);
  20453. }
  20454. else {
  20455. return [Infinity, -Infinity];
  20456. }
  20457. };
  20458. /**
  20459. * Get sum of data in one dimension
  20460. * @param {string} dim
  20461. * @param {boolean} stack
  20462. */
  20463. listProto.getSum = function (dim, stack) {
  20464. var dimData = this._storage[dim];
  20465. var sum = 0;
  20466. if (dimData) {
  20467. for (var i = 0, len = this.count(); i < len; i++) {
  20468. var value = this.get(dim, i, stack);
  20469. if (!isNaN(value)) {
  20470. sum += value;
  20471. }
  20472. }
  20473. }
  20474. return sum;
  20475. };
  20476. /**
  20477. * Retreive the index with given value
  20478. * @param {number} idx
  20479. * @param {number} value
  20480. * @return {number}
  20481. */
  20482. // FIXME Precision of float value
  20483. listProto.indexOf = function (dim, value) {
  20484. var storage = this._storage;
  20485. var dimData = storage[dim];
  20486. var indices = this.indices;
  20487. if (dimData) {
  20488. for (var i = 0, len = indices.length; i < len; i++) {
  20489. var rawIndex = indices[i];
  20490. if (dimData[rawIndex] === value) {
  20491. return i;
  20492. }
  20493. }
  20494. }
  20495. return -1;
  20496. };
  20497. /**
  20498. * Retreive the index with given name
  20499. * @param {number} idx
  20500. * @param {number} name
  20501. * @return {number}
  20502. */
  20503. listProto.indexOfName = function (name) {
  20504. var indices = this.indices;
  20505. var nameList = this._nameList;
  20506. for (var i = 0, len = indices.length; i < len; i++) {
  20507. var rawIndex = indices[i];
  20508. if (nameList[rawIndex] === name) {
  20509. return i;
  20510. }
  20511. }
  20512. return -1;
  20513. };
  20514. /**
  20515. * Retreive the index with given raw data index
  20516. * @param {number} idx
  20517. * @param {number} name
  20518. * @return {number}
  20519. */
  20520. listProto.indexOfRawIndex = function (rawIndex) {
  20521. // Indices are ascending
  20522. var indices = this.indices;
  20523. // If rawIndex === dataIndex
  20524. var rawDataIndex = indices[rawIndex];
  20525. if (rawDataIndex != null && rawDataIndex === rawIndex) {
  20526. return rawIndex;
  20527. }
  20528. var left = 0;
  20529. var right = indices.length - 1;
  20530. while (left <= right) {
  20531. var mid = (left + right) / 2 | 0;
  20532. if (indices[mid] < rawIndex) {
  20533. left = mid + 1;
  20534. }
  20535. else if (indices[mid] > rawIndex) {
  20536. right = mid - 1;
  20537. }
  20538. else {
  20539. return mid;
  20540. }
  20541. }
  20542. return -1;
  20543. };
  20544. /**
  20545. * Retreive the index of nearest value
  20546. * @param {string} dim
  20547. * @param {number} value
  20548. * @param {boolean} stack If given value is after stacked
  20549. * @param {number} [maxDistance=Infinity]
  20550. * @return {Array.<number>} Considere multiple points has the same value.
  20551. */
  20552. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  20553. var storage = this._storage;
  20554. var dimData = storage[dim];
  20555. var nearestIndices = [];
  20556. if (!dimData) {
  20557. return nearestIndices;
  20558. }
  20559. if (maxDistance == null) {
  20560. maxDistance = Infinity;
  20561. }
  20562. var minDist = Number.MAX_VALUE;
  20563. var minDiff = -1;
  20564. for (var i = 0, len = this.count(); i < len; i++) {
  20565. var diff = value - this.get(dim, i, stack);
  20566. var dist = Math.abs(diff);
  20567. if (diff <= maxDistance && dist <= minDist) {
  20568. // For the case of two data are same on xAxis, which has sequence data.
  20569. // Show the nearest index
  20570. // https://github.com/ecomfe/echarts/issues/2869
  20571. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  20572. minDist = dist;
  20573. minDiff = diff;
  20574. nearestIndices.length = 0;
  20575. }
  20576. nearestIndices.push(i);
  20577. }
  20578. }
  20579. return nearestIndices;
  20580. };
  20581. /**
  20582. * Get raw data index
  20583. * @param {number} idx
  20584. * @return {number}
  20585. */
  20586. listProto.getRawIndex = function (idx) {
  20587. var rawIdx = this.indices[idx];
  20588. return rawIdx == null ? -1 : rawIdx;
  20589. };
  20590. /**
  20591. * Get raw data item
  20592. * @param {number} idx
  20593. * @return {number}
  20594. */
  20595. listProto.getRawDataItem = function (idx) {
  20596. return this._rawData.getItem(this.getRawIndex(idx));
  20597. };
  20598. /**
  20599. * @param {number} idx
  20600. * @param {boolean} [notDefaultIdx=false]
  20601. * @return {string}
  20602. */
  20603. listProto.getName = function (idx) {
  20604. return this._nameList[this.indices[idx]] || '';
  20605. };
  20606. /**
  20607. * @param {number} idx
  20608. * @param {boolean} [notDefaultIdx=false]
  20609. * @return {string}
  20610. */
  20611. listProto.getId = function (idx) {
  20612. return this._idList[this.indices[idx]] || (this.getRawIndex(idx) + '');
  20613. };
  20614. function normalizeDimensions(dimensions) {
  20615. if (!isArray(dimensions)) {
  20616. dimensions = [dimensions];
  20617. }
  20618. return dimensions;
  20619. }
  20620. /**
  20621. * Data iteration
  20622. * @param {string|Array.<string>}
  20623. * @param {Function} cb
  20624. * @param {boolean} [stack=false]
  20625. * @param {*} [context=this]
  20626. *
  20627. * @example
  20628. * list.each('x', function (x, idx) {});
  20629. * list.each(['x', 'y'], function (x, y, idx) {});
  20630. * list.each(function (idx) {})
  20631. */
  20632. listProto.each = function (dims, cb, stack, context) {
  20633. if (typeof dims === 'function') {
  20634. context = stack;
  20635. stack = cb;
  20636. cb = dims;
  20637. dims = [];
  20638. }
  20639. dims = map(normalizeDimensions(dims), this.getDimension, this);
  20640. var value = [];
  20641. var dimSize = dims.length;
  20642. var indices = this.indices;
  20643. context = context || this;
  20644. for (var i = 0; i < indices.length; i++) {
  20645. // Simple optimization
  20646. switch (dimSize) {
  20647. case 0:
  20648. cb.call(context, i);
  20649. break;
  20650. case 1:
  20651. cb.call(context, this.get(dims[0], i, stack), i);
  20652. break;
  20653. case 2:
  20654. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  20655. break;
  20656. default:
  20657. for (var k = 0; k < dimSize; k++) {
  20658. value[k] = this.get(dims[k], i, stack);
  20659. }
  20660. // Index
  20661. value[k] = i;
  20662. cb.apply(context, value);
  20663. }
  20664. }
  20665. };
  20666. /**
  20667. * Data filter
  20668. * @param {string|Array.<string>}
  20669. * @param {Function} cb
  20670. * @param {boolean} [stack=false]
  20671. * @param {*} [context=this]
  20672. */
  20673. listProto.filterSelf = function (dimensions, cb, stack, context) {
  20674. if (typeof dimensions === 'function') {
  20675. context = stack;
  20676. stack = cb;
  20677. cb = dimensions;
  20678. dimensions = [];
  20679. }
  20680. dimensions = map(
  20681. normalizeDimensions(dimensions), this.getDimension, this
  20682. );
  20683. var newIndices = [];
  20684. var value = [];
  20685. var dimSize = dimensions.length;
  20686. var indices = this.indices;
  20687. context = context || this;
  20688. for (var i = 0; i < indices.length; i++) {
  20689. var keep;
  20690. // Simple optimization
  20691. if (!dimSize) {
  20692. keep = cb.call(context, i);
  20693. }
  20694. else if (dimSize === 1) {
  20695. keep = cb.call(
  20696. context, this.get(dimensions[0], i, stack), i
  20697. );
  20698. }
  20699. else {
  20700. for (var k = 0; k < dimSize; k++) {
  20701. value[k] = this.get(dimensions[k], i, stack);
  20702. }
  20703. value[k] = i;
  20704. keep = cb.apply(context, value);
  20705. }
  20706. if (keep) {
  20707. newIndices.push(indices[i]);
  20708. }
  20709. }
  20710. this.indices = newIndices;
  20711. // Reset data extent
  20712. this._extent = {};
  20713. return this;
  20714. };
  20715. /**
  20716. * Data mapping to a plain array
  20717. * @param {string|Array.<string>} [dimensions]
  20718. * @param {Function} cb
  20719. * @param {boolean} [stack=false]
  20720. * @param {*} [context=this]
  20721. * @return {Array}
  20722. */
  20723. listProto.mapArray = function (dimensions, cb, stack, context) {
  20724. if (typeof dimensions === 'function') {
  20725. context = stack;
  20726. stack = cb;
  20727. cb = dimensions;
  20728. dimensions = [];
  20729. }
  20730. var result = [];
  20731. this.each(dimensions, function () {
  20732. result.push(cb && cb.apply(this, arguments));
  20733. }, stack, context);
  20734. return result;
  20735. };
  20736. function cloneListForMapAndSample(original, excludeDimensions) {
  20737. var allDimensions = original.dimensions;
  20738. var list = new List(
  20739. map(allDimensions, original.getDimensionInfo, original),
  20740. original.hostModel
  20741. );
  20742. // FIXME If needs stackedOn, value may already been stacked
  20743. transferProperties(list, original);
  20744. var storage = list._storage = {};
  20745. var originalStorage = original._storage;
  20746. // Init storage
  20747. for (var i = 0; i < allDimensions.length; i++) {
  20748. var dim = allDimensions[i];
  20749. var dimStore = originalStorage[dim];
  20750. if (indexOf(excludeDimensions, dim) >= 0) {
  20751. storage[dim] = new dimStore.constructor(
  20752. originalStorage[dim].length
  20753. );
  20754. }
  20755. else {
  20756. // Direct reference for other dimensions
  20757. storage[dim] = originalStorage[dim];
  20758. }
  20759. }
  20760. return list;
  20761. }
  20762. /**
  20763. * Data mapping to a new List with given dimensions
  20764. * @param {string|Array.<string>} dimensions
  20765. * @param {Function} cb
  20766. * @param {boolean} [stack=false]
  20767. * @param {*} [context=this]
  20768. * @return {Array}
  20769. */
  20770. listProto.map = function (dimensions, cb, stack, context) {
  20771. dimensions = map(
  20772. normalizeDimensions(dimensions), this.getDimension, this
  20773. );
  20774. var list = cloneListForMapAndSample(this, dimensions);
  20775. // Following properties are all immutable.
  20776. // So we can reference to the same value
  20777. var indices = list.indices = this.indices;
  20778. var storage = list._storage;
  20779. var tmpRetValue = [];
  20780. this.each(dimensions, function () {
  20781. var idx = arguments[arguments.length - 1];
  20782. var retValue = cb && cb.apply(this, arguments);
  20783. if (retValue != null) {
  20784. // a number
  20785. if (typeof retValue === 'number') {
  20786. tmpRetValue[0] = retValue;
  20787. retValue = tmpRetValue;
  20788. }
  20789. for (var i = 0; i < retValue.length; i++) {
  20790. var dim = dimensions[i];
  20791. var dimStore = storage[dim];
  20792. var rawIdx = indices[idx];
  20793. if (dimStore) {
  20794. dimStore[rawIdx] = retValue[i];
  20795. }
  20796. }
  20797. }
  20798. }, stack, context);
  20799. return list;
  20800. };
  20801. /**
  20802. * Large data down sampling on given dimension
  20803. * @param {string} dimension
  20804. * @param {number} rate
  20805. * @param {Function} sampleValue
  20806. * @param {Function} sampleIndex Sample index for name and id
  20807. */
  20808. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20809. var list = cloneListForMapAndSample(this, [dimension]);
  20810. var storage = this._storage;
  20811. var targetStorage = list._storage;
  20812. var originalIndices = this.indices;
  20813. var indices = list.indices = [];
  20814. var frameValues = [];
  20815. var frameIndices = [];
  20816. var frameSize = Math.floor(1 / rate);
  20817. var dimStore = targetStorage[dimension];
  20818. var len = this.count();
  20819. // Copy data from original data
  20820. for (var i = 0; i < storage[dimension].length; i++) {
  20821. targetStorage[dimension][i] = storage[dimension][i];
  20822. }
  20823. for (var i = 0; i < len; i += frameSize) {
  20824. // Last frame
  20825. if (frameSize > len - i) {
  20826. frameSize = len - i;
  20827. frameValues.length = frameSize;
  20828. }
  20829. for (var k = 0; k < frameSize; k++) {
  20830. var idx = originalIndices[i + k];
  20831. frameValues[k] = dimStore[idx];
  20832. frameIndices[k] = idx;
  20833. }
  20834. var value = sampleValue(frameValues);
  20835. var idx = frameIndices[sampleIndex(frameValues, value) || 0];
  20836. // Only write value on the filtered data
  20837. dimStore[idx] = value;
  20838. indices.push(idx);
  20839. }
  20840. return list;
  20841. };
  20842. /**
  20843. * Get model of one data item.
  20844. *
  20845. * @param {number} idx
  20846. */
  20847. // FIXME Model proxy ?
  20848. listProto.getItemModel = function (idx) {
  20849. var hostModel = this.hostModel;
  20850. idx = this.indices[idx];
  20851. return new Model(this._rawData.getItem(idx), hostModel, hostModel && hostModel.ecModel);
  20852. };
  20853. /**
  20854. * Create a data differ
  20855. * @param {module:echarts/data/List} otherList
  20856. * @return {module:echarts/data/DataDiffer}
  20857. */
  20858. listProto.diff = function (otherList) {
  20859. var idList = this._idList;
  20860. var otherIdList = otherList && otherList._idList;
  20861. var val;
  20862. // Use prefix to avoid index to be the same as otherIdList[idx],
  20863. // which will cause weird udpate animation.
  20864. var prefix = 'e\0\0';
  20865. return new DataDiffer(
  20866. otherList ? otherList.indices : [],
  20867. this.indices,
  20868. function (idx) {
  20869. return (val = otherIdList[idx]) != null ? val : prefix + idx;
  20870. },
  20871. function (idx) {
  20872. return (val = idList[idx]) != null ? val : prefix + idx;
  20873. }
  20874. );
  20875. };
  20876. /**
  20877. * Get visual property.
  20878. * @param {string} key
  20879. */
  20880. listProto.getVisual = function (key) {
  20881. var visual = this._visual;
  20882. return visual && visual[key];
  20883. };
  20884. /**
  20885. * Set visual property
  20886. * @param {string|Object} key
  20887. * @param {*} [value]
  20888. *
  20889. * @example
  20890. * setVisual('color', color);
  20891. * setVisual({
  20892. * 'color': color
  20893. * });
  20894. */
  20895. listProto.setVisual = function (key, val) {
  20896. if (isObject$4(key)) {
  20897. for (var name in key) {
  20898. if (key.hasOwnProperty(name)) {
  20899. this.setVisual(name, key[name]);
  20900. }
  20901. }
  20902. return;
  20903. }
  20904. this._visual = this._visual || {};
  20905. this._visual[key] = val;
  20906. };
  20907. /**
  20908. * Set layout property.
  20909. * @param {string|Object} key
  20910. * @param {*} [val]
  20911. */
  20912. listProto.setLayout = function (key, val) {
  20913. if (isObject$4(key)) {
  20914. for (var name in key) {
  20915. if (key.hasOwnProperty(name)) {
  20916. this.setLayout(name, key[name]);
  20917. }
  20918. }
  20919. return;
  20920. }
  20921. this._layout[key] = val;
  20922. };
  20923. /**
  20924. * Get layout property.
  20925. * @param {string} key.
  20926. * @return {*}
  20927. */
  20928. listProto.getLayout = function (key) {
  20929. return this._layout[key];
  20930. };
  20931. /**
  20932. * Get layout of single data item
  20933. * @param {number} idx
  20934. */
  20935. listProto.getItemLayout = function (idx) {
  20936. return this._itemLayouts[idx];
  20937. };
  20938. /**
  20939. * Set layout of single data item
  20940. * @param {number} idx
  20941. * @param {Object} layout
  20942. * @param {boolean=} [merge=false]
  20943. */
  20944. listProto.setItemLayout = function (idx, layout, merge$$1) {
  20945. this._itemLayouts[idx] = merge$$1
  20946. ? extend(this._itemLayouts[idx] || {}, layout)
  20947. : layout;
  20948. };
  20949. /**
  20950. * Clear all layout of single data item
  20951. */
  20952. listProto.clearItemLayouts = function () {
  20953. this._itemLayouts.length = 0;
  20954. };
  20955. /**
  20956. * Get visual property of single data item
  20957. * @param {number} idx
  20958. * @param {string} key
  20959. * @param {boolean} [ignoreParent=false]
  20960. */
  20961. listProto.getItemVisual = function (idx, key, ignoreParent) {
  20962. var itemVisual = this._itemVisuals[idx];
  20963. var val = itemVisual && itemVisual[key];
  20964. if (val == null && !ignoreParent) {
  20965. // Use global visual property
  20966. return this.getVisual(key);
  20967. }
  20968. return val;
  20969. };
  20970. /**
  20971. * Set visual property of single data item
  20972. *
  20973. * @param {number} idx
  20974. * @param {string|Object} key
  20975. * @param {*} [value]
  20976. *
  20977. * @example
  20978. * setItemVisual(0, 'color', color);
  20979. * setItemVisual(0, {
  20980. * 'color': color
  20981. * });
  20982. */
  20983. listProto.setItemVisual = function (idx, key, value) {
  20984. var itemVisual = this._itemVisuals[idx] || {};
  20985. this._itemVisuals[idx] = itemVisual;
  20986. if (isObject$4(key)) {
  20987. for (var name in key) {
  20988. if (key.hasOwnProperty(name)) {
  20989. itemVisual[name] = key[name];
  20990. }
  20991. }
  20992. return;
  20993. }
  20994. itemVisual[key] = value;
  20995. };
  20996. /**
  20997. * Clear itemVisuals and list visual.
  20998. */
  20999. listProto.clearAllVisual = function () {
  21000. this._visual = {};
  21001. this._itemVisuals = [];
  21002. };
  21003. var setItemDataAndSeriesIndex = function (child) {
  21004. child.seriesIndex = this.seriesIndex;
  21005. child.dataIndex = this.dataIndex;
  21006. child.dataType = this.dataType;
  21007. };
  21008. /**
  21009. * Set graphic element relative to data. It can be set as null
  21010. * @param {number} idx
  21011. * @param {module:zrender/Element} [el]
  21012. */
  21013. listProto.setItemGraphicEl = function (idx, el) {
  21014. var hostModel = this.hostModel;
  21015. if (el) {
  21016. // Add data index and series index for indexing the data by element
  21017. // Useful in tooltip
  21018. el.dataIndex = idx;
  21019. el.dataType = this.dataType;
  21020. el.seriesIndex = hostModel && hostModel.seriesIndex;
  21021. if (el.type === 'group') {
  21022. el.traverse(setItemDataAndSeriesIndex, el);
  21023. }
  21024. }
  21025. this._graphicEls[idx] = el;
  21026. };
  21027. /**
  21028. * @param {number} idx
  21029. * @return {module:zrender/Element}
  21030. */
  21031. listProto.getItemGraphicEl = function (idx) {
  21032. return this._graphicEls[idx];
  21033. };
  21034. /**
  21035. * @param {Function} cb
  21036. * @param {*} context
  21037. */
  21038. listProto.eachItemGraphicEl = function (cb, context) {
  21039. each$1(this._graphicEls, function (el, idx) {
  21040. if (el) {
  21041. cb && cb.call(context, el, idx);
  21042. }
  21043. });
  21044. };
  21045. /**
  21046. * Shallow clone a new list except visual and layout properties, and graph elements.
  21047. * New list only change the indices.
  21048. */
  21049. listProto.cloneShallow = function () {
  21050. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  21051. var list = new List(dimensionInfoList, this.hostModel);
  21052. // FIXME
  21053. list._storage = this._storage;
  21054. transferProperties(list, this);
  21055. // Clone will not change the data extent and indices
  21056. list.indices = this.indices.slice();
  21057. if (this._extent) {
  21058. list._extent = extend({}, this._extent);
  21059. }
  21060. return list;
  21061. };
  21062. /**
  21063. * Wrap some method to add more feature
  21064. * @param {string} methodName
  21065. * @param {Function} injectFunction
  21066. */
  21067. listProto.wrapMethod = function (methodName, injectFunction) {
  21068. var originalMethod = this[methodName];
  21069. if (typeof originalMethod !== 'function') {
  21070. return;
  21071. }
  21072. this.__wrappedMethods = this.__wrappedMethods || [];
  21073. this.__wrappedMethods.push(methodName);
  21074. this[methodName] = function () {
  21075. var res = originalMethod.apply(this, arguments);
  21076. return injectFunction.apply(this, [res].concat(slice(arguments)));
  21077. };
  21078. };
  21079. // Methods that create a new list based on this list should be listed here.
  21080. // Notice that those method should `RETURN` the new list.
  21081. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  21082. // Methods that change indices of this list should be listed here.
  21083. listProto.CHANGABLE_METHODS = ['filterSelf'];
  21084. /**
  21085. * Complete dimensions by data (guess dimension).
  21086. */
  21087. var each$7 = each$1;
  21088. var isString$1 = isString;
  21089. var defaults$1 = defaults;
  21090. var OTHER_DIMS = {tooltip: 1, label: 1, itemName: 1};
  21091. /**
  21092. * Complete the dimensions array, by user defined `dimension` and `encode`,
  21093. * and guessing from the data structure.
  21094. * If no 'value' dimension specified, the first no-named dimension will be
  21095. * named as 'value'.
  21096. *
  21097. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  21098. * provides not only dim template, but also default order.
  21099. * `name` of each item provides default coord name.
  21100. * [{dimsDef: []}, ...] can be specified to give names.
  21101. * @param {Array} data Data list. [[1, 2, 3], [2, 3, 4]].
  21102. * @param {Object} [opt]
  21103. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  21104. * For example: ['asdf', {name, type}, ...].
  21105. * @param {Object} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  21106. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  21107. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  21108. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  21109. * If not specified, extra dim names will be:
  21110. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  21111. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  21112. * @return {Array.<Object>} [{
  21113. * name: string mandatory,
  21114. * coordDim: string mandatory,
  21115. * coordDimIndex: number mandatory,
  21116. * type: string optional,
  21117. * tooltipName: string optional,
  21118. * otherDims: {
  21119. * tooltip: number optional,
  21120. * label: number optional
  21121. * },
  21122. * isExtraCoord: boolean true or undefined.
  21123. * other props ...
  21124. * }]
  21125. */
  21126. function completeDimensions(sysDims, data, opt) {
  21127. data = data || [];
  21128. opt = opt || {};
  21129. sysDims = (sysDims || []).slice();
  21130. var dimsDef = (opt.dimsDef || []).slice();
  21131. var encodeDef = createHashMap(opt.encodeDef);
  21132. var dataDimNameMap = createHashMap();
  21133. var coordDimNameMap = createHashMap();
  21134. // var valueCandidate;
  21135. var result = [];
  21136. var dimCount = opt.dimCount;
  21137. if (dimCount == null) {
  21138. var value0 = retrieveValue(data[0]);
  21139. dimCount = Math.max(
  21140. isArray(value0) && value0.length || 1,
  21141. sysDims.length,
  21142. dimsDef.length
  21143. );
  21144. each$7(sysDims, function (sysDimItem) {
  21145. var sysDimItemDimsDef = sysDimItem.dimsDef;
  21146. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  21147. });
  21148. }
  21149. // Apply user defined dims (`name` and `type`) and init result.
  21150. for (var i = 0; i < dimCount; i++) {
  21151. var dimDefItem = isString$1(dimsDef[i]) ? {name: dimsDef[i]} : (dimsDef[i] || {});
  21152. var userDimName = dimDefItem.name;
  21153. var resultItem = result[i] = {otherDims: {}};
  21154. // Name will be applied later for avoiding duplication.
  21155. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  21156. // Only if `series.dimensions` is defined in option, tooltipName
  21157. // will be set, and dimension will be diplayed vertically in
  21158. // tooltip by default.
  21159. resultItem.name = resultItem.tooltipName = userDimName;
  21160. dataDimNameMap.set(userDimName, i);
  21161. }
  21162. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  21163. }
  21164. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  21165. encodeDef.each(function (dataDims, coordDim) {
  21166. dataDims = encodeDef.set(coordDim, normalizeToArray(dataDims).slice());
  21167. each$7(dataDims, function (resultDimIdx, coordDimIndex) {
  21168. // The input resultDimIdx can be dim name or index.
  21169. isString$1(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  21170. if (resultDimIdx != null && resultDimIdx < dimCount) {
  21171. dataDims[coordDimIndex] = resultDimIdx;
  21172. applyDim(result[resultDimIdx], coordDim, coordDimIndex);
  21173. }
  21174. });
  21175. });
  21176. // Apply templetes and default order from `sysDims`.
  21177. var availDimIdx = 0;
  21178. each$7(sysDims, function (sysDimItem, sysDimIndex) {
  21179. var coordDim;
  21180. var sysDimItem;
  21181. var sysDimItemDimsDef;
  21182. var sysDimItemOtherDims;
  21183. if (isString$1(sysDimItem)) {
  21184. coordDim = sysDimItem;
  21185. sysDimItem = {};
  21186. }
  21187. else {
  21188. coordDim = sysDimItem.name;
  21189. sysDimItem = clone(sysDimItem);
  21190. // `coordDimIndex` should not be set directly.
  21191. sysDimItemDimsDef = sysDimItem.dimsDef;
  21192. sysDimItemOtherDims = sysDimItem.otherDims;
  21193. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  21194. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  21195. }
  21196. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  21197. // dimensions provides default dim sequences.
  21198. if (!dataDims.length) {
  21199. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  21200. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  21201. availDimIdx++;
  21202. }
  21203. availDimIdx < result.length && dataDims.push(availDimIdx++);
  21204. }
  21205. }
  21206. // Apply templates.
  21207. each$7(dataDims, function (resultDimIdx, coordDimIndex) {
  21208. var resultItem = result[resultDimIdx];
  21209. applyDim(defaults$1(resultItem, sysDimItem), coordDim, coordDimIndex);
  21210. if (resultItem.name == null && sysDimItemDimsDef) {
  21211. resultItem.name = resultItem.tooltipName = sysDimItemDimsDef[coordDimIndex];
  21212. }
  21213. sysDimItemOtherDims && defaults$1(resultItem.otherDims, sysDimItemOtherDims);
  21214. });
  21215. });
  21216. // Make sure the first extra dim is 'value'.
  21217. var extra = opt.extraPrefix || 'value';
  21218. // Set dim `name` and other `coordDim` and other props.
  21219. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  21220. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  21221. var coordDim = resultItem.coordDim;
  21222. coordDim == null && (
  21223. resultItem.coordDim = genName(extra, coordDimNameMap, opt.extraFromZero),
  21224. resultItem.coordDimIndex = 0,
  21225. resultItem.isExtraCoord = true
  21226. );
  21227. resultItem.name == null && (resultItem.name = genName(
  21228. resultItem.coordDim,
  21229. dataDimNameMap
  21230. ));
  21231. resultItem.type == null && guessOrdinal(data, resultDimIdx)
  21232. && (resultItem.type = 'ordinal');
  21233. }
  21234. return result;
  21235. function applyDim(resultItem, coordDim, coordDimIndex) {
  21236. if (OTHER_DIMS[coordDim]) {
  21237. resultItem.otherDims[coordDim] = coordDimIndex;
  21238. }
  21239. else {
  21240. resultItem.coordDim = coordDim;
  21241. resultItem.coordDimIndex = coordDimIndex;
  21242. coordDimNameMap.set(coordDim, true);
  21243. }
  21244. }
  21245. function genName(name, map$$1, fromZero) {
  21246. if (fromZero || map$$1.get(name) != null) {
  21247. var i = 0;
  21248. while (map$$1.get(name + i) != null) {
  21249. i++;
  21250. }
  21251. name += i;
  21252. }
  21253. map$$1.set(name, true);
  21254. return name;
  21255. }
  21256. }
  21257. // The rule should not be complex, otherwise user might not
  21258. // be able to known where the data is wrong.
  21259. var guessOrdinal = completeDimensions.guessOrdinal = function (data, dimIndex) {
  21260. for (var i = 0, len = data.length; i < len; i++) {
  21261. var value = retrieveValue(data[i]);
  21262. if (!isArray(value)) {
  21263. return false;
  21264. }
  21265. var value = value[dimIndex];
  21266. // Consider usage convenience, '1', '2' will be treated as "number".
  21267. // `isFinit('')` get `true`.
  21268. if (value != null && isFinite(value) && value !== '') {
  21269. return false;
  21270. }
  21271. else if (isString$1(value) && value !== '-') {
  21272. return true;
  21273. }
  21274. }
  21275. return false;
  21276. };
  21277. function retrieveValue(o) {
  21278. return isArray(o) ? o : isObject(o) ? o.value: o;
  21279. }
  21280. function firstDataNotNull(data) {
  21281. var i = 0;
  21282. while (i < data.length && data[i] == null) {
  21283. i++;
  21284. }
  21285. return data[i];
  21286. }
  21287. function ifNeedCompleteOrdinalData(data) {
  21288. var sampleItem = firstDataNotNull(data);
  21289. return sampleItem != null
  21290. && !isArray(getDataItemValue(sampleItem));
  21291. }
  21292. /**
  21293. * Helper function to create a list from option data
  21294. */
  21295. function createListFromArray(data, seriesModel, ecModel) {
  21296. // If data is undefined
  21297. data = data || [];
  21298. if (__DEV__) {
  21299. if (!isArray(data)) {
  21300. throw new Error('Invalid data.');
  21301. }
  21302. }
  21303. var coordSysName = seriesModel.get('coordinateSystem');
  21304. var creator = creators[coordSysName];
  21305. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  21306. var completeDimOpt = {
  21307. encodeDef: seriesModel.get('encode'),
  21308. dimsDef: seriesModel.get('dimensions')
  21309. };
  21310. // FIXME
  21311. var axesInfo = creator && creator(data, seriesModel, ecModel, completeDimOpt);
  21312. var dimensions = axesInfo && axesInfo.dimensions;
  21313. if (!dimensions) {
  21314. // Get dimensions from registered coordinate system
  21315. dimensions = (registeredCoordSys && (
  21316. registeredCoordSys.getDimensionsInfo
  21317. ? registeredCoordSys.getDimensionsInfo()
  21318. : registeredCoordSys.dimensions.slice()
  21319. )) || ['x', 'y'];
  21320. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21321. }
  21322. var categoryIndex = axesInfo ? axesInfo.categoryIndex : -1;
  21323. var list = new List(dimensions, seriesModel);
  21324. var nameList = createNameList(axesInfo, data);
  21325. var categories = {};
  21326. var dimValueGetter = (categoryIndex >= 0 && ifNeedCompleteOrdinalData(data))
  21327. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  21328. // If any dataItem is like { value: 10 }
  21329. if (isDataItemOption(itemOpt)) {
  21330. list.hasItemOption = true;
  21331. }
  21332. // Use dataIndex as ordinal value in categoryAxis
  21333. return dimIndex === categoryIndex
  21334. ? dataIndex
  21335. : converDataValue(getDataItemValue(itemOpt), dimensions[dimIndex]);
  21336. }
  21337. : function (itemOpt, dimName, dataIndex, dimIndex) {
  21338. var value = getDataItemValue(itemOpt);
  21339. var val = converDataValue(value && value[dimIndex], dimensions[dimIndex]);
  21340. // If any dataItem is like { value: 10 }
  21341. if (isDataItemOption(itemOpt)) {
  21342. list.hasItemOption = true;
  21343. }
  21344. var categoryAxesModels = axesInfo && axesInfo.categoryAxesModels;
  21345. if (categoryAxesModels && categoryAxesModels[dimName]) {
  21346. // If given value is a category string
  21347. if (typeof val === 'string') {
  21348. // Lazy get categories
  21349. categories[dimName] = categories[dimName]
  21350. || categoryAxesModels[dimName].getCategories();
  21351. val = indexOf(categories[dimName], val);
  21352. if (val < 0 && !isNaN(val)) {
  21353. // In case some one write '1', '2' istead of 1, 2
  21354. val = +val;
  21355. }
  21356. }
  21357. }
  21358. return val;
  21359. };
  21360. list.hasItemOption = false;
  21361. list.initData(data, nameList, dimValueGetter);
  21362. return list;
  21363. }
  21364. function isStackable(axisType) {
  21365. return axisType !== 'category' && axisType !== 'time';
  21366. }
  21367. function getDimTypeByAxis(axisType) {
  21368. return axisType === 'category'
  21369. ? 'ordinal'
  21370. : axisType === 'time'
  21371. ? 'time'
  21372. : 'float';
  21373. }
  21374. /**
  21375. * Creaters for each coord system.
  21376. */
  21377. var creators = {
  21378. cartesian2d: function (data, seriesModel, ecModel, completeDimOpt) {
  21379. var axesModels = map(['xAxis', 'yAxis'], function (name) {
  21380. return ecModel.queryComponents({
  21381. mainType: name,
  21382. index: seriesModel.get(name + 'Index'),
  21383. id: seriesModel.get(name + 'Id')
  21384. })[0];
  21385. });
  21386. var xAxisModel = axesModels[0];
  21387. var yAxisModel = axesModels[1];
  21388. if (__DEV__) {
  21389. if (!xAxisModel) {
  21390. throw new Error('xAxis "' + retrieve(
  21391. seriesModel.get('xAxisIndex'),
  21392. seriesModel.get('xAxisId'),
  21393. 0
  21394. ) + '" not found');
  21395. }
  21396. if (!yAxisModel) {
  21397. throw new Error('yAxis "' + retrieve(
  21398. seriesModel.get('xAxisIndex'),
  21399. seriesModel.get('yAxisId'),
  21400. 0
  21401. ) + '" not found');
  21402. }
  21403. }
  21404. var xAxisType = xAxisModel.get('type');
  21405. var yAxisType = yAxisModel.get('type');
  21406. var dimensions = [
  21407. {
  21408. name: 'x',
  21409. type: getDimTypeByAxis(xAxisType),
  21410. stackable: isStackable(xAxisType)
  21411. },
  21412. {
  21413. name: 'y',
  21414. // If two category axes
  21415. type: getDimTypeByAxis(yAxisType),
  21416. stackable: isStackable(yAxisType)
  21417. }
  21418. ];
  21419. var isXAxisCateogry = xAxisType === 'category';
  21420. var isYAxisCategory = yAxisType === 'category';
  21421. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21422. var categoryAxesModels = {};
  21423. if (isXAxisCateogry) {
  21424. categoryAxesModels.x = xAxisModel;
  21425. }
  21426. if (isYAxisCategory) {
  21427. categoryAxesModels.y = yAxisModel;
  21428. }
  21429. return {
  21430. dimensions: dimensions,
  21431. categoryIndex: isXAxisCateogry ? 0 : (isYAxisCategory ? 1 : -1),
  21432. categoryAxesModels: categoryAxesModels
  21433. };
  21434. },
  21435. singleAxis: function (data, seriesModel, ecModel, completeDimOpt) {
  21436. var singleAxisModel = ecModel.queryComponents({
  21437. mainType: 'singleAxis',
  21438. index: seriesModel.get('singleAxisIndex'),
  21439. id: seriesModel.get('singleAxisId')
  21440. })[0];
  21441. if (__DEV__) {
  21442. if (!singleAxisModel) {
  21443. throw new Error('singleAxis should be specified.');
  21444. }
  21445. }
  21446. var singleAxisType = singleAxisModel.get('type');
  21447. var isCategory = singleAxisType === 'category';
  21448. var dimensions = [{
  21449. name: 'single',
  21450. type: getDimTypeByAxis(singleAxisType),
  21451. stackable: isStackable(singleAxisType)
  21452. }];
  21453. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21454. var categoryAxesModels = {};
  21455. if (isCategory) {
  21456. categoryAxesModels.single = singleAxisModel;
  21457. }
  21458. return {
  21459. dimensions: dimensions,
  21460. categoryIndex: isCategory ? 0 : -1,
  21461. categoryAxesModels: categoryAxesModels
  21462. };
  21463. },
  21464. polar: function (data, seriesModel, ecModel, completeDimOpt) {
  21465. var polarModel = ecModel.queryComponents({
  21466. mainType: 'polar',
  21467. index: seriesModel.get('polarIndex'),
  21468. id: seriesModel.get('polarId')
  21469. })[0];
  21470. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  21471. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  21472. if (__DEV__) {
  21473. if (!angleAxisModel) {
  21474. throw new Error('angleAxis option not found');
  21475. }
  21476. if (!radiusAxisModel) {
  21477. throw new Error('radiusAxis option not found');
  21478. }
  21479. }
  21480. var radiusAxisType = radiusAxisModel.get('type');
  21481. var angleAxisType = angleAxisModel.get('type');
  21482. var dimensions = [
  21483. {
  21484. name: 'radius',
  21485. type: getDimTypeByAxis(radiusAxisType),
  21486. stackable: isStackable(radiusAxisType)
  21487. },
  21488. {
  21489. name: 'angle',
  21490. type: getDimTypeByAxis(angleAxisType),
  21491. stackable: isStackable(angleAxisType)
  21492. }
  21493. ];
  21494. var isAngleAxisCateogry = angleAxisType === 'category';
  21495. var isRadiusAxisCateogry = radiusAxisType === 'category';
  21496. dimensions = completeDimensions(dimensions, data, completeDimOpt);
  21497. var categoryAxesModels = {};
  21498. if (isRadiusAxisCateogry) {
  21499. categoryAxesModels.radius = radiusAxisModel;
  21500. }
  21501. if (isAngleAxisCateogry) {
  21502. categoryAxesModels.angle = angleAxisModel;
  21503. }
  21504. return {
  21505. dimensions: dimensions,
  21506. categoryIndex: isAngleAxisCateogry ? 1 : (isRadiusAxisCateogry ? 0 : -1),
  21507. categoryAxesModels: categoryAxesModels
  21508. };
  21509. },
  21510. geo: function (data, seriesModel, ecModel, completeDimOpt) {
  21511. // TODO Region
  21512. // 多个散点图系列在同一个地区的时候
  21513. return {
  21514. dimensions: completeDimensions([
  21515. {name: 'lng'},
  21516. {name: 'lat'}
  21517. ], data, completeDimOpt)
  21518. };
  21519. }
  21520. };
  21521. function createNameList(result, data) {
  21522. var nameList = [];
  21523. var categoryDim = result && result.dimensions[result.categoryIndex];
  21524. var categoryAxisModel;
  21525. if (categoryDim) {
  21526. categoryAxisModel = result.categoryAxesModels[categoryDim.name];
  21527. }
  21528. if (categoryAxisModel) {
  21529. // FIXME Two category axis
  21530. var categories = categoryAxisModel.getCategories();
  21531. if (categories) {
  21532. var dataLen = data.length;
  21533. // Ordered data is given explicitly like
  21534. // [[3, 0.2], [1, 0.3], [2, 0.15]]
  21535. // or given scatter data,
  21536. // pick the category
  21537. if (isArray(data[0]) && data[0].length > 1) {
  21538. nameList = [];
  21539. for (var i = 0; i < dataLen; i++) {
  21540. nameList[i] = categories[data[i][result.categoryIndex || 0]];
  21541. }
  21542. }
  21543. else {
  21544. nameList = categories.slice(0);
  21545. }
  21546. }
  21547. }
  21548. return nameList;
  21549. }
  21550. /**
  21551. * // Scale class management
  21552. * @module echarts/scale/Scale
  21553. */
  21554. /**
  21555. * @param {Object} [setting]
  21556. */
  21557. function Scale(setting) {
  21558. this._setting = setting || {};
  21559. /**
  21560. * Extent
  21561. * @type {Array.<number>}
  21562. * @protected
  21563. */
  21564. this._extent = [Infinity, -Infinity];
  21565. /**
  21566. * Step is calculated in adjustExtent
  21567. * @type {Array.<number>}
  21568. * @protected
  21569. */
  21570. this._interval = 0;
  21571. this.init && this.init.apply(this, arguments);
  21572. }
  21573. /**
  21574. * Parse input val to valid inner number.
  21575. * @param {*} val
  21576. * @return {number}
  21577. */
  21578. Scale.prototype.parse = function (val) {
  21579. // Notice: This would be a trap here, If the implementation
  21580. // of this method depends on extent, and this method is used
  21581. // before extent set (like in dataZoom), it would be wrong.
  21582. // Nevertheless, parse does not depend on extent generally.
  21583. return val;
  21584. };
  21585. Scale.prototype.getSetting = function (name) {
  21586. return this._setting[name];
  21587. };
  21588. Scale.prototype.contain = function (val) {
  21589. var extent = this._extent;
  21590. return val >= extent[0] && val <= extent[1];
  21591. };
  21592. /**
  21593. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  21594. * @param {number} val
  21595. * @return {number}
  21596. */
  21597. Scale.prototype.normalize = function (val) {
  21598. var extent = this._extent;
  21599. if (extent[1] === extent[0]) {
  21600. return 0.5;
  21601. }
  21602. return (val - extent[0]) / (extent[1] - extent[0]);
  21603. };
  21604. /**
  21605. * Scale normalized value
  21606. * @param {number} val
  21607. * @return {number}
  21608. */
  21609. Scale.prototype.scale = function (val) {
  21610. var extent = this._extent;
  21611. return val * (extent[1] - extent[0]) + extent[0];
  21612. };
  21613. /**
  21614. * Set extent from data
  21615. * @param {Array.<number>} other
  21616. */
  21617. Scale.prototype.unionExtent = function (other) {
  21618. var extent = this._extent;
  21619. other[0] < extent[0] && (extent[0] = other[0]);
  21620. other[1] > extent[1] && (extent[1] = other[1]);
  21621. // not setExtent because in log axis it may transformed to power
  21622. // this.setExtent(extent[0], extent[1]);
  21623. };
  21624. /**
  21625. * Set extent from data
  21626. * @param {module:echarts/data/List} data
  21627. * @param {string} dim
  21628. */
  21629. Scale.prototype.unionExtentFromData = function (data, dim) {
  21630. this.unionExtent(data.getDataExtent(dim, true));
  21631. };
  21632. /**
  21633. * Get extent
  21634. * @return {Array.<number>}
  21635. */
  21636. Scale.prototype.getExtent = function () {
  21637. return this._extent.slice();
  21638. };
  21639. /**
  21640. * Set extent
  21641. * @param {number} start
  21642. * @param {number} end
  21643. */
  21644. Scale.prototype.setExtent = function (start, end) {
  21645. var thisExtent = this._extent;
  21646. if (!isNaN(start)) {
  21647. thisExtent[0] = start;
  21648. }
  21649. if (!isNaN(end)) {
  21650. thisExtent[1] = end;
  21651. }
  21652. };
  21653. /**
  21654. * @return {Array.<string>}
  21655. */
  21656. Scale.prototype.getTicksLabels = function () {
  21657. var labels = [];
  21658. var ticks = this.getTicks();
  21659. for (var i = 0; i < ticks.length; i++) {
  21660. labels.push(this.getLabel(ticks[i]));
  21661. }
  21662. return labels;
  21663. };
  21664. /**
  21665. * When axis extent depends on data and no data exists,
  21666. * axis ticks should not be drawn, which is named 'blank'.
  21667. */
  21668. Scale.prototype.isBlank = function () {
  21669. return this._isBlank;
  21670. },
  21671. /**
  21672. * When axis extent depends on data and no data exists,
  21673. * axis ticks should not be drawn, which is named 'blank'.
  21674. */
  21675. Scale.prototype.setBlank = function (isBlank) {
  21676. this._isBlank = isBlank;
  21677. };
  21678. enableClassExtend(Scale);
  21679. enableClassManagement(Scale, {
  21680. registerWhenExtend: true
  21681. });
  21682. /**
  21683. * Linear continuous scale
  21684. * @module echarts/coord/scale/Ordinal
  21685. *
  21686. * http://en.wikipedia.org/wiki/Level_of_measurement
  21687. */
  21688. // FIXME only one data
  21689. var scaleProto = Scale.prototype;
  21690. var OrdinalScale = Scale.extend({
  21691. type: 'ordinal',
  21692. init: function (data, extent) {
  21693. this._data = data;
  21694. this._extent = extent || [0, data.length - 1];
  21695. },
  21696. parse: function (val) {
  21697. return typeof val === 'string'
  21698. ? indexOf(this._data, val)
  21699. // val might be float.
  21700. : Math.round(val);
  21701. },
  21702. contain: function (rank) {
  21703. rank = this.parse(rank);
  21704. return scaleProto.contain.call(this, rank)
  21705. && this._data[rank] != null;
  21706. },
  21707. /**
  21708. * Normalize given rank or name to linear [0, 1]
  21709. * @param {number|string} [val]
  21710. * @return {number}
  21711. */
  21712. normalize: function (val) {
  21713. return scaleProto.normalize.call(this, this.parse(val));
  21714. },
  21715. scale: function (val) {
  21716. return Math.round(scaleProto.scale.call(this, val));
  21717. },
  21718. /**
  21719. * @return {Array}
  21720. */
  21721. getTicks: function () {
  21722. var ticks = [];
  21723. var extent = this._extent;
  21724. var rank = extent[0];
  21725. while (rank <= extent[1]) {
  21726. ticks.push(rank);
  21727. rank++;
  21728. }
  21729. return ticks;
  21730. },
  21731. /**
  21732. * Get item on rank n
  21733. * @param {number} n
  21734. * @return {string}
  21735. */
  21736. getLabel: function (n) {
  21737. return this._data[n];
  21738. },
  21739. /**
  21740. * @return {number}
  21741. */
  21742. count: function () {
  21743. return this._extent[1] - this._extent[0] + 1;
  21744. },
  21745. /**
  21746. * @override
  21747. */
  21748. unionExtentFromData: function (data, dim) {
  21749. this.unionExtent(data.getDataExtent(dim, false));
  21750. },
  21751. niceTicks: noop,
  21752. niceExtent: noop
  21753. });
  21754. /**
  21755. * @return {module:echarts/scale/Time}
  21756. */
  21757. OrdinalScale.create = function () {
  21758. return new OrdinalScale();
  21759. };
  21760. /**
  21761. * For testable.
  21762. */
  21763. var roundNumber$1 = round;
  21764. /**
  21765. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  21766. * Should be extent[0] < extent[1].
  21767. * @param {number} splitNumber splitNumber should be >= 1.
  21768. * @param {number} [minInterval]
  21769. * @param {number} [maxInterval]
  21770. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  21771. */
  21772. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  21773. var result = {};
  21774. var span = extent[1] - extent[0];
  21775. var interval = result.interval = nice(span / splitNumber, true);
  21776. if (minInterval != null && interval < minInterval) {
  21777. interval = result.interval = minInterval;
  21778. }
  21779. if (maxInterval != null && interval > maxInterval) {
  21780. interval = result.interval = maxInterval;
  21781. }
  21782. // Tow more digital for tick.
  21783. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  21784. // Niced extent inside original extent
  21785. var niceTickExtent = result.niceTickExtent = [
  21786. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  21787. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  21788. ];
  21789. fixExtent(niceTickExtent, extent);
  21790. return result;
  21791. }
  21792. /**
  21793. * @param {number} interval
  21794. * @return {number} interval precision
  21795. */
  21796. function getIntervalPrecision(interval) {
  21797. // Tow more digital for tick.
  21798. return getPrecisionSafe(interval) + 2;
  21799. }
  21800. function clamp(niceTickExtent, idx, extent) {
  21801. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  21802. }
  21803. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  21804. function fixExtent(niceTickExtent, extent) {
  21805. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  21806. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  21807. clamp(niceTickExtent, 0, extent);
  21808. clamp(niceTickExtent, 1, extent);
  21809. if (niceTickExtent[0] > niceTickExtent[1]) {
  21810. niceTickExtent[0] = niceTickExtent[1];
  21811. }
  21812. }
  21813. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  21814. var ticks = [];
  21815. // If interval is 0, return [];
  21816. if (!interval) {
  21817. return ticks;
  21818. }
  21819. // Consider this case: using dataZoom toolbox, zoom and zoom.
  21820. var safeLimit = 10000;
  21821. if (extent[0] < niceTickExtent[0]) {
  21822. ticks.push(extent[0]);
  21823. }
  21824. var tick = niceTickExtent[0];
  21825. while (tick <= niceTickExtent[1]) {
  21826. ticks.push(tick);
  21827. // Avoid rounding error
  21828. tick = roundNumber$1(tick + interval, intervalPrecision);
  21829. if (tick === ticks[ticks.length - 1]) {
  21830. // Consider out of safe float point, e.g.,
  21831. // -3711126.9907707 + 2e-10 === -3711126.9907707
  21832. break;
  21833. }
  21834. if (ticks.length > safeLimit) {
  21835. return [];
  21836. }
  21837. }
  21838. // Consider this case: the last item of ticks is smaller
  21839. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  21840. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  21841. ticks.push(extent[1]);
  21842. }
  21843. return ticks;
  21844. }
  21845. /**
  21846. * Interval scale
  21847. * @module echarts/scale/Interval
  21848. */
  21849. var roundNumber = round;
  21850. /**
  21851. * @alias module:echarts/coord/scale/Interval
  21852. * @constructor
  21853. */
  21854. var IntervalScale = Scale.extend({
  21855. type: 'interval',
  21856. _interval: 0,
  21857. _intervalPrecision: 2,
  21858. setExtent: function (start, end) {
  21859. var thisExtent = this._extent;
  21860. //start,end may be a Number like '25',so...
  21861. if (!isNaN(start)) {
  21862. thisExtent[0] = parseFloat(start);
  21863. }
  21864. if (!isNaN(end)) {
  21865. thisExtent[1] = parseFloat(end);
  21866. }
  21867. },
  21868. unionExtent: function (other) {
  21869. var extent = this._extent;
  21870. other[0] < extent[0] && (extent[0] = other[0]);
  21871. other[1] > extent[1] && (extent[1] = other[1]);
  21872. // unionExtent may called by it's sub classes
  21873. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  21874. },
  21875. /**
  21876. * Get interval
  21877. */
  21878. getInterval: function () {
  21879. return this._interval;
  21880. },
  21881. /**
  21882. * Set interval
  21883. */
  21884. setInterval: function (interval) {
  21885. this._interval = interval;
  21886. // Dropped auto calculated niceExtent and use user setted extent
  21887. // We assume user wan't to set both interval, min, max to get a better result
  21888. this._niceExtent = this._extent.slice();
  21889. this._intervalPrecision = getIntervalPrecision(interval);
  21890. },
  21891. /**
  21892. * @return {Array.<number>}
  21893. */
  21894. getTicks: function () {
  21895. return intervalScaleGetTicks(
  21896. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  21897. );
  21898. },
  21899. /**
  21900. * @return {Array.<string>}
  21901. */
  21902. getTicksLabels: function () {
  21903. var labels = [];
  21904. var ticks = this.getTicks();
  21905. for (var i = 0; i < ticks.length; i++) {
  21906. labels.push(this.getLabel(ticks[i]));
  21907. }
  21908. return labels;
  21909. },
  21910. /**
  21911. * @param {number} data
  21912. * @param {Object} [opt]
  21913. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  21914. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  21915. * @return {string}
  21916. */
  21917. getLabel: function (data, opt) {
  21918. if (data == null) {
  21919. return '';
  21920. }
  21921. var precision = opt && opt.precision;
  21922. if (precision == null) {
  21923. precision = getPrecisionSafe(data) || 0;
  21924. }
  21925. else if (precision === 'auto') {
  21926. // Should be more precise then tick.
  21927. precision = this._intervalPrecision;
  21928. }
  21929. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  21930. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  21931. data = roundNumber(data, precision, true);
  21932. return addCommas(data);
  21933. },
  21934. /**
  21935. * Update interval and extent of intervals for nice ticks
  21936. *
  21937. * @param {number} [splitNumber = 5] Desired number of ticks
  21938. * @param {number} [minInterval]
  21939. * @param {number} [maxInterval]
  21940. */
  21941. niceTicks: function (splitNumber, minInterval, maxInterval) {
  21942. splitNumber = splitNumber || 5;
  21943. var extent = this._extent;
  21944. var span = extent[1] - extent[0];
  21945. if (!isFinite(span)) {
  21946. return;
  21947. }
  21948. // User may set axis min 0 and data are all negative
  21949. // FIXME If it needs to reverse ?
  21950. if (span < 0) {
  21951. span = -span;
  21952. extent.reverse();
  21953. }
  21954. var result = intervalScaleNiceTicks(
  21955. extent, splitNumber, minInterval, maxInterval
  21956. );
  21957. this._intervalPrecision = result.intervalPrecision;
  21958. this._interval = result.interval;
  21959. this._niceExtent = result.niceTickExtent;
  21960. },
  21961. /**
  21962. * Nice extent.
  21963. * @param {Object} opt
  21964. * @param {number} [opt.splitNumber = 5] Given approx tick number
  21965. * @param {boolean} [opt.fixMin=false]
  21966. * @param {boolean} [opt.fixMax=false]
  21967. * @param {boolean} [opt.minInterval]
  21968. * @param {boolean} [opt.maxInterval]
  21969. */
  21970. niceExtent: function (opt) {
  21971. var extent = this._extent;
  21972. // If extent start and end are same, expand them
  21973. if (extent[0] === extent[1]) {
  21974. if (extent[0] !== 0) {
  21975. // Expand extent
  21976. var expandSize = extent[0];
  21977. // In the fowllowing case
  21978. // Axis has been fixed max 100
  21979. // Plus data are all 100 and axis extent are [100, 100].
  21980. // Extend to the both side will cause expanded max is larger than fixed max.
  21981. // So only expand to the smaller side.
  21982. if (!opt.fixMax) {
  21983. extent[1] += expandSize / 2;
  21984. extent[0] -= expandSize / 2;
  21985. }
  21986. else {
  21987. extent[0] -= expandSize / 2;
  21988. }
  21989. }
  21990. else {
  21991. extent[1] = 1;
  21992. }
  21993. }
  21994. var span = extent[1] - extent[0];
  21995. // If there are no data and extent are [Infinity, -Infinity]
  21996. if (!isFinite(span)) {
  21997. extent[0] = 0;
  21998. extent[1] = 1;
  21999. }
  22000. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  22001. // var extent = this._extent;
  22002. var interval = this._interval;
  22003. if (!opt.fixMin) {
  22004. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  22005. }
  22006. if (!opt.fixMax) {
  22007. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  22008. }
  22009. }
  22010. });
  22011. /**
  22012. * @return {module:echarts/scale/Time}
  22013. */
  22014. IntervalScale.create = function () {
  22015. return new IntervalScale();
  22016. };
  22017. // [About UTC and local time zone]:
  22018. // In most cases, `number.parseDate` will treat input data string as local time
  22019. // (except time zone is specified in time string). And `format.formateTime` returns
  22020. // local time by default. option.useUTC is false by default. This design have
  22021. // concidered these common case:
  22022. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  22023. // in local time by default.
  22024. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  22025. // as its original time, without any time difference.
  22026. var intervalScaleProto = IntervalScale.prototype;
  22027. var mathCeil = Math.ceil;
  22028. var mathFloor = Math.floor;
  22029. var ONE_SECOND = 1000;
  22030. var ONE_MINUTE = ONE_SECOND * 60;
  22031. var ONE_HOUR = ONE_MINUTE * 60;
  22032. var ONE_DAY = ONE_HOUR * 24;
  22033. // FIXME 公用?
  22034. var bisect = function (a, x, lo, hi) {
  22035. while (lo < hi) {
  22036. var mid = lo + hi >>> 1;
  22037. if (a[mid][1] < x) {
  22038. lo = mid + 1;
  22039. }
  22040. else {
  22041. hi = mid;
  22042. }
  22043. }
  22044. return lo;
  22045. };
  22046. /**
  22047. * @alias module:echarts/coord/scale/Time
  22048. * @constructor
  22049. */
  22050. var TimeScale = IntervalScale.extend({
  22051. type: 'time',
  22052. /**
  22053. * @override
  22054. */
  22055. getLabel: function (val) {
  22056. var stepLvl = this._stepLvl;
  22057. var date = new Date(val);
  22058. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  22059. },
  22060. /**
  22061. * @override
  22062. */
  22063. niceExtent: function (opt) {
  22064. var extent = this._extent;
  22065. // If extent start and end are same, expand them
  22066. if (extent[0] === extent[1]) {
  22067. // Expand extent
  22068. extent[0] -= ONE_DAY;
  22069. extent[1] += ONE_DAY;
  22070. }
  22071. // If there are no data and extent are [Infinity, -Infinity]
  22072. if (extent[1] === -Infinity && extent[0] === Infinity) {
  22073. var d = new Date();
  22074. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  22075. extent[0] = extent[1] - ONE_DAY;
  22076. }
  22077. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  22078. // var extent = this._extent;
  22079. var interval = this._interval;
  22080. if (!opt.fixMin) {
  22081. extent[0] = round(mathFloor(extent[0] / interval) * interval);
  22082. }
  22083. if (!opt.fixMax) {
  22084. extent[1] = round(mathCeil(extent[1] / interval) * interval);
  22085. }
  22086. },
  22087. /**
  22088. * @override
  22089. */
  22090. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  22091. approxTickNum = approxTickNum || 10;
  22092. var extent = this._extent;
  22093. var span = extent[1] - extent[0];
  22094. var approxInterval = span / approxTickNum;
  22095. if (minInterval != null && approxInterval < minInterval) {
  22096. approxInterval = minInterval;
  22097. }
  22098. if (maxInterval != null && approxInterval > maxInterval) {
  22099. approxInterval = maxInterval;
  22100. }
  22101. var scaleLevelsLen = scaleLevels.length;
  22102. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  22103. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  22104. var interval = level[1];
  22105. // Same with interval scale if span is much larger than 1 year
  22106. if (level[0] === 'year') {
  22107. var yearSpan = span / interval;
  22108. // From "Nice Numbers for Graph Labels" of Graphic Gems
  22109. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  22110. var yearStep = nice(yearSpan / approxTickNum, true);
  22111. interval *= yearStep;
  22112. }
  22113. var timezoneOffset = this.getSetting('useUTC')
  22114. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  22115. var niceExtent = [
  22116. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  22117. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  22118. ];
  22119. fixExtent(niceExtent, extent);
  22120. this._stepLvl = level;
  22121. // Interval will be used in getTicks
  22122. this._interval = interval;
  22123. this._niceExtent = niceExtent;
  22124. },
  22125. parse: function (val) {
  22126. // val might be float.
  22127. return +parseDate(val);
  22128. }
  22129. });
  22130. each$1(['contain', 'normalize'], function (methodName) {
  22131. TimeScale.prototype[methodName] = function (val) {
  22132. return intervalScaleProto[methodName].call(this, this.parse(val));
  22133. };
  22134. });
  22135. // Steps from d3
  22136. var scaleLevels = [
  22137. // Format interval
  22138. ['hh:mm:ss', ONE_SECOND], // 1s
  22139. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  22140. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  22141. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  22142. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  22143. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  22144. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  22145. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  22146. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  22147. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  22148. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  22149. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  22150. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  22151. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  22152. ['MM-dd\nyyyy', ONE_DAY], // 1d
  22153. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  22154. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  22155. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  22156. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  22157. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  22158. ['week', ONE_DAY * 7], // 7d
  22159. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  22160. ['week', ONE_DAY * 14], // 2w
  22161. ['week', ONE_DAY * 21], // 3w
  22162. ['month', ONE_DAY * 31], // 1M
  22163. ['week', ONE_DAY * 42], // 6w
  22164. ['month', ONE_DAY * 62], // 2M
  22165. ['week', ONE_DAY * 42], // 10w
  22166. ['quarter', ONE_DAY * 380 / 4], // 3M
  22167. ['month', ONE_DAY * 31 * 4], // 4M
  22168. ['month', ONE_DAY * 31 * 5], // 5M
  22169. ['half-year', ONE_DAY * 380 / 2], // 6M
  22170. ['month', ONE_DAY * 31 * 8], // 8M
  22171. ['month', ONE_DAY * 31 * 10], // 10M
  22172. ['year', ONE_DAY * 380] // 1Y
  22173. ];
  22174. /**
  22175. * @param {module:echarts/model/Model}
  22176. * @return {module:echarts/scale/Time}
  22177. */
  22178. TimeScale.create = function (model) {
  22179. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  22180. };
  22181. /**
  22182. * Log scale
  22183. * @module echarts/scale/Log
  22184. */
  22185. // Use some method of IntervalScale
  22186. var scaleProto$1 = Scale.prototype;
  22187. var intervalScaleProto$1 = IntervalScale.prototype;
  22188. var getPrecisionSafe$1 = getPrecisionSafe;
  22189. var roundingErrorFix = round;
  22190. var mathFloor$1 = Math.floor;
  22191. var mathCeil$1 = Math.ceil;
  22192. var mathPow$1 = Math.pow;
  22193. var mathLog = Math.log;
  22194. var LogScale = Scale.extend({
  22195. type: 'log',
  22196. base: 10,
  22197. $constructor: function () {
  22198. Scale.apply(this, arguments);
  22199. this._originalScale = new IntervalScale();
  22200. },
  22201. /**
  22202. * @return {Array.<number>}
  22203. */
  22204. getTicks: function () {
  22205. var originalScale = this._originalScale;
  22206. var extent = this._extent;
  22207. var originalExtent = originalScale.getExtent();
  22208. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  22209. var powVal = round(mathPow$1(this.base, val));
  22210. // Fix #4158
  22211. powVal = (val === extent[0] && originalScale.__fixMin)
  22212. ? fixRoundingError(powVal, originalExtent[0])
  22213. : powVal;
  22214. powVal = (val === extent[1] && originalScale.__fixMax)
  22215. ? fixRoundingError(powVal, originalExtent[1])
  22216. : powVal;
  22217. return powVal;
  22218. }, this);
  22219. },
  22220. /**
  22221. * @param {number} val
  22222. * @return {string}
  22223. */
  22224. getLabel: intervalScaleProto$1.getLabel,
  22225. /**
  22226. * @param {number} val
  22227. * @return {number}
  22228. */
  22229. scale: function (val) {
  22230. val = scaleProto$1.scale.call(this, val);
  22231. return mathPow$1(this.base, val);
  22232. },
  22233. /**
  22234. * @param {number} start
  22235. * @param {number} end
  22236. */
  22237. setExtent: function (start, end) {
  22238. var base = this.base;
  22239. start = mathLog(start) / mathLog(base);
  22240. end = mathLog(end) / mathLog(base);
  22241. intervalScaleProto$1.setExtent.call(this, start, end);
  22242. },
  22243. /**
  22244. * @return {number} end
  22245. */
  22246. getExtent: function () {
  22247. var base = this.base;
  22248. var extent = scaleProto$1.getExtent.call(this);
  22249. extent[0] = mathPow$1(base, extent[0]);
  22250. extent[1] = mathPow$1(base, extent[1]);
  22251. // Fix #4158
  22252. var originalScale = this._originalScale;
  22253. var originalExtent = originalScale.getExtent();
  22254. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  22255. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  22256. return extent;
  22257. },
  22258. /**
  22259. * @param {Array.<number>} extent
  22260. */
  22261. unionExtent: function (extent) {
  22262. this._originalScale.unionExtent(extent);
  22263. var base = this.base;
  22264. extent[0] = mathLog(extent[0]) / mathLog(base);
  22265. extent[1] = mathLog(extent[1]) / mathLog(base);
  22266. scaleProto$1.unionExtent.call(this, extent);
  22267. },
  22268. /**
  22269. * @override
  22270. */
  22271. unionExtentFromData: function (data, dim) {
  22272. this.unionExtent(data.getDataExtent(dim, true, function (val) {
  22273. return val > 0;
  22274. }));
  22275. },
  22276. /**
  22277. * Update interval and extent of intervals for nice ticks
  22278. * @param {number} [approxTickNum = 10] Given approx tick number
  22279. */
  22280. niceTicks: function (approxTickNum) {
  22281. approxTickNum = approxTickNum || 10;
  22282. var extent = this._extent;
  22283. var span = extent[1] - extent[0];
  22284. if (span === Infinity || span <= 0) {
  22285. return;
  22286. }
  22287. var interval = quantity(span);
  22288. var err = approxTickNum / span * interval;
  22289. // Filter ticks to get closer to the desired count.
  22290. if (err <= 0.5) {
  22291. interval *= 10;
  22292. }
  22293. // Interval should be integer
  22294. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  22295. interval *= 10;
  22296. }
  22297. var niceExtent = [
  22298. round(mathCeil$1(extent[0] / interval) * interval),
  22299. round(mathFloor$1(extent[1] / interval) * interval)
  22300. ];
  22301. this._interval = interval;
  22302. this._niceExtent = niceExtent;
  22303. },
  22304. /**
  22305. * Nice extent.
  22306. * @override
  22307. */
  22308. niceExtent: function (opt) {
  22309. intervalScaleProto$1.niceExtent.call(this, opt);
  22310. var originalScale = this._originalScale;
  22311. originalScale.__fixMin = opt.fixMin;
  22312. originalScale.__fixMax = opt.fixMax;
  22313. }
  22314. });
  22315. each$1(['contain', 'normalize'], function (methodName) {
  22316. LogScale.prototype[methodName] = function (val) {
  22317. val = mathLog(val) / mathLog(this.base);
  22318. return scaleProto$1[methodName].call(this, val);
  22319. };
  22320. });
  22321. LogScale.create = function () {
  22322. return new LogScale();
  22323. };
  22324. function fixRoundingError(val, originalVal) {
  22325. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  22326. }
  22327. /**
  22328. * Get axis scale extent before niced.
  22329. * Item of returned array can only be number (including Infinity and NaN).
  22330. */
  22331. function getScaleExtent(scale, model) {
  22332. var scaleType = scale.type;
  22333. var min = model.getMin();
  22334. var max = model.getMax();
  22335. var fixMin = min != null;
  22336. var fixMax = max != null;
  22337. var originalExtent = scale.getExtent();
  22338. var axisDataLen;
  22339. var boundaryGap;
  22340. var span;
  22341. if (scaleType === 'ordinal') {
  22342. axisDataLen = (model.get('data') || []).length;
  22343. }
  22344. else {
  22345. boundaryGap = model.get('boundaryGap');
  22346. if (!isArray(boundaryGap)) {
  22347. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  22348. }
  22349. if (typeof boundaryGap[0] === 'boolean') {
  22350. if (__DEV__) {
  22351. console.warn('Boolean type for boundaryGap is only '
  22352. + 'allowed for ordinal axis. Please use string in '
  22353. + 'percentage instead, e.g., "20%". Currently, '
  22354. + 'boundaryGap is set to be 0.');
  22355. }
  22356. boundaryGap = [0, 0];
  22357. }
  22358. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  22359. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  22360. span = (originalExtent[1] - originalExtent[0])
  22361. || Math.abs(originalExtent[0]);
  22362. }
  22363. // Notice: When min/max is not set (that is, when there are null/undefined,
  22364. // which is the most common case), these cases should be ensured:
  22365. // (1) For 'ordinal', show all axis.data.
  22366. // (2) For others:
  22367. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  22368. // disabled).
  22369. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  22370. // be the result that originalExtent enlarged by boundaryGap.
  22371. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  22372. // FIXME
  22373. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  22374. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  22375. // that the results processed by boundaryGap are positive/negative?
  22376. if (min == null) {
  22377. min = scaleType === 'ordinal'
  22378. ? (axisDataLen ? 0 : NaN)
  22379. : originalExtent[0] - boundaryGap[0] * span;
  22380. }
  22381. if (max == null) {
  22382. max = scaleType === 'ordinal'
  22383. ? (axisDataLen ? axisDataLen - 1 : NaN)
  22384. : originalExtent[1] + boundaryGap[1] * span;
  22385. }
  22386. if (min === 'dataMin') {
  22387. min = originalExtent[0];
  22388. }
  22389. else if (typeof min === 'function') {
  22390. min = min({
  22391. min: originalExtent[0],
  22392. max: originalExtent[1]
  22393. });
  22394. }
  22395. if (max === 'dataMax') {
  22396. max = originalExtent[1];
  22397. }
  22398. else if (typeof max === 'function') {
  22399. max = max({
  22400. min: originalExtent[0],
  22401. max: originalExtent[1]
  22402. });
  22403. }
  22404. (min == null || !isFinite(min)) && (min = NaN);
  22405. (max == null || !isFinite(max)) && (max = NaN);
  22406. scale.setBlank(eqNaN(min) || eqNaN(max));
  22407. // Evaluate if axis needs cross zero
  22408. if (model.getNeedCrossZero()) {
  22409. // Axis is over zero and min is not set
  22410. if (min > 0 && max > 0 && !fixMin) {
  22411. min = 0;
  22412. }
  22413. // Axis is under zero and max is not set
  22414. if (min < 0 && max < 0 && !fixMax) {
  22415. max = 0;
  22416. }
  22417. }
  22418. return [min, max];
  22419. }
  22420. function niceScaleExtent(scale, model) {
  22421. var extent = getScaleExtent(scale, model);
  22422. var fixMin = model.getMin() != null;
  22423. var fixMax = model.getMax() != null;
  22424. var splitNumber = model.get('splitNumber');
  22425. if (scale.type === 'log') {
  22426. scale.base = model.get('logBase');
  22427. }
  22428. var scaleType = scale.type;
  22429. scale.setExtent(extent[0], extent[1]);
  22430. scale.niceExtent({
  22431. splitNumber: splitNumber,
  22432. fixMin: fixMin,
  22433. fixMax: fixMax,
  22434. minInterval: (scaleType === 'interval' || scaleType === 'time')
  22435. ? model.get('minInterval') : null,
  22436. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  22437. ? model.get('maxInterval') : null
  22438. });
  22439. // If some one specified the min, max. And the default calculated interval
  22440. // is not good enough. He can specify the interval. It is often appeared
  22441. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  22442. // to be 60.
  22443. // FIXME
  22444. var interval = model.get('interval');
  22445. if (interval != null) {
  22446. scale.setInterval && scale.setInterval(interval);
  22447. }
  22448. }
  22449. /**
  22450. * @param {module:echarts/model/Model} model
  22451. * @param {string} [axisType] Default retrieve from model.type
  22452. * @return {module:echarts/scale/*}
  22453. */
  22454. function createScaleByModel(model, axisType) {
  22455. axisType = axisType || model.get('type');
  22456. if (axisType) {
  22457. switch (axisType) {
  22458. // Buildin scale
  22459. case 'category':
  22460. return new OrdinalScale(
  22461. model.getCategories(), [Infinity, -Infinity]
  22462. );
  22463. case 'value':
  22464. return new IntervalScale();
  22465. // Extended scale, like time and log
  22466. default:
  22467. return (Scale.getClass(axisType) || IntervalScale).create(model);
  22468. }
  22469. }
  22470. }
  22471. /**
  22472. * Check if the axis corss 0
  22473. */
  22474. function ifAxisCrossZero(axis) {
  22475. var dataExtent = axis.scale.getExtent();
  22476. var min = dataExtent[0];
  22477. var max = dataExtent[1];
  22478. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  22479. }
  22480. /**
  22481. * @param {Array.<number>} tickCoords In axis self coordinate.
  22482. * @param {Array.<string>} labels
  22483. * @param {string} font
  22484. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  22485. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  22486. * @return {number}
  22487. */
  22488. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  22489. var textSpaceTakenRect;
  22490. var autoLabelInterval = 0;
  22491. var accumulatedLabelInterval = 0;
  22492. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  22493. var step = 1;
  22494. if (labels.length > 40) {
  22495. // Simple optimization for large amount of labels
  22496. step = Math.floor(labels.length / 40);
  22497. }
  22498. for (var i = 0; i < tickCoords.length; i += step) {
  22499. var tickCoord = tickCoords[i];
  22500. // Not precise, do not consider align and vertical align
  22501. // and each distance from axis line yet.
  22502. var rect = getBoundingRect(
  22503. labels[i], font, 'center', 'top'
  22504. );
  22505. rect.x += tickCoord * Math.cos(rotation);
  22506. rect.y += tickCoord * Math.sin(rotation);
  22507. // Magic number
  22508. rect.width *= 1.3;
  22509. rect.height *= 1.3;
  22510. if (!textSpaceTakenRect) {
  22511. textSpaceTakenRect = rect.clone();
  22512. }
  22513. // There is no space for current label;
  22514. else if (textSpaceTakenRect.intersect(rect)) {
  22515. accumulatedLabelInterval++;
  22516. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  22517. }
  22518. else {
  22519. textSpaceTakenRect.union(rect);
  22520. // Reset
  22521. accumulatedLabelInterval = 0;
  22522. }
  22523. }
  22524. if (autoLabelInterval === 0 && step > 1) {
  22525. return step;
  22526. }
  22527. return (autoLabelInterval + 1) * step - 1;
  22528. }
  22529. /**
  22530. * @param {Object} axis
  22531. * @param {Function} labelFormatter
  22532. * @return {Array.<string>}
  22533. */
  22534. function getFormattedLabels(axis, labelFormatter) {
  22535. var scale = axis.scale;
  22536. var labels = scale.getTicksLabels();
  22537. var ticks = scale.getTicks();
  22538. if (typeof labelFormatter === 'string') {
  22539. labelFormatter = (function (tpl) {
  22540. return function (val) {
  22541. return tpl.replace('{value}', val != null ? val : '');
  22542. };
  22543. })(labelFormatter);
  22544. // Consider empty array
  22545. return map(labels, labelFormatter);
  22546. }
  22547. else if (typeof labelFormatter === 'function') {
  22548. return map(ticks, function (tick, idx) {
  22549. return labelFormatter(
  22550. getAxisRawValue(axis, tick),
  22551. idx
  22552. );
  22553. }, this);
  22554. }
  22555. else {
  22556. return labels;
  22557. }
  22558. }
  22559. function getAxisRawValue(axis, value) {
  22560. // In category axis with data zoom, tick is not the original
  22561. // index of axis.data. So tick should not be exposed to user
  22562. // in category axis.
  22563. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  22564. }
  22565. function getName(obj) {
  22566. if (isObject(obj) && obj.value != null) {
  22567. return obj.value;
  22568. }
  22569. else {
  22570. return obj + '';
  22571. }
  22572. }
  22573. var axisModelCommonMixin = {
  22574. /**
  22575. * Format labels
  22576. * @return {Array.<string>}
  22577. */
  22578. getFormattedLabels: function () {
  22579. return getFormattedLabels(
  22580. this.axis,
  22581. this.get('axisLabel.formatter')
  22582. );
  22583. },
  22584. /**
  22585. * Get categories
  22586. */
  22587. getCategories: function () {
  22588. return this.get('type') === 'category'
  22589. && map(this.get('data'), getName);
  22590. },
  22591. /**
  22592. * @param {boolean} origin
  22593. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  22594. */
  22595. getMin: function (origin) {
  22596. var option = this.option;
  22597. var min = (!origin && option.rangeStart != null)
  22598. ? option.rangeStart : option.min;
  22599. if (this.axis
  22600. && min != null
  22601. && min !== 'dataMin'
  22602. && typeof min !== 'function'
  22603. && !eqNaN(min)
  22604. ) {
  22605. min = this.axis.scale.parse(min);
  22606. }
  22607. return min;
  22608. },
  22609. /**
  22610. * @param {boolean} origin
  22611. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  22612. */
  22613. getMax: function (origin) {
  22614. var option = this.option;
  22615. var max = (!origin && option.rangeEnd != null)
  22616. ? option.rangeEnd : option.max;
  22617. if (this.axis
  22618. && max != null
  22619. && max !== 'dataMax'
  22620. && typeof max !== 'function'
  22621. && !eqNaN(max)
  22622. ) {
  22623. max = this.axis.scale.parse(max);
  22624. }
  22625. return max;
  22626. },
  22627. /**
  22628. * @return {boolean}
  22629. */
  22630. getNeedCrossZero: function () {
  22631. var option = this.option;
  22632. return (option.rangeStart != null || option.rangeEnd != null)
  22633. ? false : !option.scale;
  22634. },
  22635. /**
  22636. * Should be implemented by each axis model if necessary.
  22637. * @return {module:echarts/model/Component} coordinate system model
  22638. */
  22639. getCoordSysModel: noop,
  22640. /**
  22641. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  22642. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  22643. */
  22644. setRange: function (rangeStart, rangeEnd) {
  22645. this.option.rangeStart = rangeStart;
  22646. this.option.rangeEnd = rangeEnd;
  22647. },
  22648. /**
  22649. * Reset range
  22650. */
  22651. resetRange: function () {
  22652. // rangeStart and rangeEnd is readonly.
  22653. this.option.rangeStart = this.option.rangeEnd = null;
  22654. }
  22655. };
  22656. // Symbol factory
  22657. /**
  22658. * Triangle shape
  22659. * @inner
  22660. */
  22661. var Triangle = extendShape({
  22662. type: 'triangle',
  22663. shape: {
  22664. cx: 0,
  22665. cy: 0,
  22666. width: 0,
  22667. height: 0
  22668. },
  22669. buildPath: function (path, shape) {
  22670. var cx = shape.cx;
  22671. var cy = shape.cy;
  22672. var width = shape.width / 2;
  22673. var height = shape.height / 2;
  22674. path.moveTo(cx, cy - height);
  22675. path.lineTo(cx + width, cy + height);
  22676. path.lineTo(cx - width, cy + height);
  22677. path.closePath();
  22678. }
  22679. });
  22680. /**
  22681. * Diamond shape
  22682. * @inner
  22683. */
  22684. var Diamond = extendShape({
  22685. type: 'diamond',
  22686. shape: {
  22687. cx: 0,
  22688. cy: 0,
  22689. width: 0,
  22690. height: 0
  22691. },
  22692. buildPath: function (path, shape) {
  22693. var cx = shape.cx;
  22694. var cy = shape.cy;
  22695. var width = shape.width / 2;
  22696. var height = shape.height / 2;
  22697. path.moveTo(cx, cy - height);
  22698. path.lineTo(cx + width, cy);
  22699. path.lineTo(cx, cy + height);
  22700. path.lineTo(cx - width, cy);
  22701. path.closePath();
  22702. }
  22703. });
  22704. /**
  22705. * Pin shape
  22706. * @inner
  22707. */
  22708. var Pin = extendShape({
  22709. type: 'pin',
  22710. shape: {
  22711. // x, y on the cusp
  22712. x: 0,
  22713. y: 0,
  22714. width: 0,
  22715. height: 0
  22716. },
  22717. buildPath: function (path, shape) {
  22718. var x = shape.x;
  22719. var y = shape.y;
  22720. var w = shape.width / 5 * 3;
  22721. // Height must be larger than width
  22722. var h = Math.max(w, shape.height);
  22723. var r = w / 2;
  22724. // Dist on y with tangent point and circle center
  22725. var dy = r * r / (h - r);
  22726. var cy = y - h + r + dy;
  22727. var angle = Math.asin(dy / r);
  22728. // Dist on x with tangent point and circle center
  22729. var dx = Math.cos(angle) * r;
  22730. var tanX = Math.sin(angle);
  22731. var tanY = Math.cos(angle);
  22732. var cpLen = r * 0.6;
  22733. var cpLen2 = r * 0.7;
  22734. path.moveTo(x - dx, cy + dy);
  22735. path.arc(
  22736. x, cy, r,
  22737. Math.PI - angle,
  22738. Math.PI * 2 + angle
  22739. );
  22740. path.bezierCurveTo(
  22741. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  22742. x, y - cpLen2,
  22743. x, y
  22744. );
  22745. path.bezierCurveTo(
  22746. x, y - cpLen2,
  22747. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  22748. x - dx, cy + dy
  22749. );
  22750. path.closePath();
  22751. }
  22752. });
  22753. /**
  22754. * Arrow shape
  22755. * @inner
  22756. */
  22757. var Arrow = extendShape({
  22758. type: 'arrow',
  22759. shape: {
  22760. x: 0,
  22761. y: 0,
  22762. width: 0,
  22763. height: 0
  22764. },
  22765. buildPath: function (ctx, shape) {
  22766. var height = shape.height;
  22767. var width = shape.width;
  22768. var x = shape.x;
  22769. var y = shape.y;
  22770. var dx = width / 3 * 2;
  22771. ctx.moveTo(x, y);
  22772. ctx.lineTo(x + dx, y + height);
  22773. ctx.lineTo(x, y + height / 4 * 3);
  22774. ctx.lineTo(x - dx, y + height);
  22775. ctx.lineTo(x, y);
  22776. ctx.closePath();
  22777. }
  22778. });
  22779. /**
  22780. * Map of path contructors
  22781. * @type {Object.<string, module:zrender/graphic/Path>}
  22782. */
  22783. var symbolCtors = {
  22784. line: Line,
  22785. rect: Rect,
  22786. roundRect: Rect,
  22787. square: Rect,
  22788. circle: Circle,
  22789. diamond: Diamond,
  22790. pin: Pin,
  22791. arrow: Arrow,
  22792. triangle: Triangle
  22793. };
  22794. var symbolShapeMakers = {
  22795. line: function (x, y, w, h, shape) {
  22796. // FIXME
  22797. shape.x1 = x;
  22798. shape.y1 = y + h / 2;
  22799. shape.x2 = x + w;
  22800. shape.y2 = y + h / 2;
  22801. },
  22802. rect: function (x, y, w, h, shape) {
  22803. shape.x = x;
  22804. shape.y = y;
  22805. shape.width = w;
  22806. shape.height = h;
  22807. },
  22808. roundRect: function (x, y, w, h, shape) {
  22809. shape.x = x;
  22810. shape.y = y;
  22811. shape.width = w;
  22812. shape.height = h;
  22813. shape.r = Math.min(w, h) / 4;
  22814. },
  22815. square: function (x, y, w, h, shape) {
  22816. var size = Math.min(w, h);
  22817. shape.x = x;
  22818. shape.y = y;
  22819. shape.width = size;
  22820. shape.height = size;
  22821. },
  22822. circle: function (x, y, w, h, shape) {
  22823. // Put circle in the center of square
  22824. shape.cx = x + w / 2;
  22825. shape.cy = y + h / 2;
  22826. shape.r = Math.min(w, h) / 2;
  22827. },
  22828. diamond: function (x, y, w, h, shape) {
  22829. shape.cx = x + w / 2;
  22830. shape.cy = y + h / 2;
  22831. shape.width = w;
  22832. shape.height = h;
  22833. },
  22834. pin: 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. arrow: function (x, y, w, h, shape) {
  22841. shape.x = x + w / 2;
  22842. shape.y = y + h / 2;
  22843. shape.width = w;
  22844. shape.height = h;
  22845. },
  22846. triangle: function (x, y, w, h, shape) {
  22847. shape.cx = x + w / 2;
  22848. shape.cy = y + h / 2;
  22849. shape.width = w;
  22850. shape.height = h;
  22851. }
  22852. };
  22853. var symbolBuildProxies = {};
  22854. each$1(symbolCtors, function (Ctor, name) {
  22855. symbolBuildProxies[name] = new Ctor();
  22856. });
  22857. var SymbolClz = extendShape({
  22858. type: 'symbol',
  22859. shape: {
  22860. symbolType: '',
  22861. x: 0,
  22862. y: 0,
  22863. width: 0,
  22864. height: 0
  22865. },
  22866. beforeBrush: function () {
  22867. var style = this.style;
  22868. var shape = this.shape;
  22869. // FIXME
  22870. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  22871. style.textPosition = ['50%', '40%'];
  22872. style.textAlign = 'center';
  22873. style.textVerticalAlign = 'middle';
  22874. }
  22875. },
  22876. buildPath: function (ctx, shape, inBundle) {
  22877. var symbolType = shape.symbolType;
  22878. var proxySymbol = symbolBuildProxies[symbolType];
  22879. if (shape.symbolType !== 'none') {
  22880. if (!proxySymbol) {
  22881. // Default rect
  22882. symbolType = 'rect';
  22883. proxySymbol = symbolBuildProxies[symbolType];
  22884. }
  22885. symbolShapeMakers[symbolType](
  22886. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  22887. );
  22888. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  22889. }
  22890. }
  22891. });
  22892. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  22893. function symbolPathSetColor(color, innerColor) {
  22894. if (this.type !== 'image') {
  22895. var symbolStyle = this.style;
  22896. var symbolShape = this.shape;
  22897. if (symbolShape && symbolShape.symbolType === 'line') {
  22898. symbolStyle.stroke = color;
  22899. }
  22900. else if (this.__isEmptyBrush) {
  22901. symbolStyle.stroke = color;
  22902. symbolStyle.fill = innerColor || '#fff';
  22903. }
  22904. else {
  22905. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  22906. symbolStyle.fill && (symbolStyle.fill = color);
  22907. symbolStyle.stroke && (symbolStyle.stroke = color);
  22908. }
  22909. this.dirty(false);
  22910. }
  22911. }
  22912. /**
  22913. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  22914. * @param {string} symbolType
  22915. * @param {number} x
  22916. * @param {number} y
  22917. * @param {number} w
  22918. * @param {number} h
  22919. * @param {string} color
  22920. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  22921. * for path and image only.
  22922. */
  22923. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  22924. // TODO Support image object, DynamicImage.
  22925. var isEmpty = symbolType.indexOf('empty') === 0;
  22926. if (isEmpty) {
  22927. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  22928. }
  22929. var symbolPath;
  22930. if (symbolType.indexOf('image://') === 0) {
  22931. symbolPath = makeImage(
  22932. symbolType.slice(8),
  22933. new BoundingRect(x, y, w, h),
  22934. keepAspect ? 'center' : 'cover'
  22935. );
  22936. }
  22937. else if (symbolType.indexOf('path://') === 0) {
  22938. symbolPath = makePath(
  22939. symbolType.slice(7),
  22940. {},
  22941. new BoundingRect(x, y, w, h),
  22942. keepAspect ? 'center' : 'cover'
  22943. );
  22944. }
  22945. else {
  22946. symbolPath = new SymbolClz({
  22947. shape: {
  22948. symbolType: symbolType,
  22949. x: x,
  22950. y: y,
  22951. width: w,
  22952. height: h
  22953. }
  22954. });
  22955. }
  22956. symbolPath.__isEmptyBrush = isEmpty;
  22957. symbolPath.setColor = symbolPathSetColor;
  22958. symbolPath.setColor(color);
  22959. return symbolPath;
  22960. }
  22961. /**
  22962. * Create a muti dimension List structure from seriesModel.
  22963. * @param {module:echarts/model/Model} seriesModel
  22964. * @return {module:echarts/data/List} list
  22965. */
  22966. function createList(seriesModel) {
  22967. var data = seriesModel.get('data');
  22968. return createListFromArray(data, seriesModel, seriesModel.ecModel);
  22969. }
  22970. /**
  22971. * Create scale
  22972. * @param {Array.<number>} dataExtent
  22973. * @param {Object|module:echarts/Model} option
  22974. */
  22975. function createScale(dataExtent, option) {
  22976. var axisModel = option;
  22977. if (!(option instanceof Model)) {
  22978. axisModel = new Model(option);
  22979. mixin(axisModel, axisModelCommonMixin);
  22980. }
  22981. var scale = createScaleByModel(axisModel);
  22982. scale.setExtent(dataExtent[0], dataExtent[1]);
  22983. niceScaleExtent(scale, axisModel);
  22984. return scale;
  22985. }
  22986. /**
  22987. * Mixin common methods to axis model,
  22988. *
  22989. * Inlcude methods
  22990. * `getFormattedLabels() => Array.<string>`
  22991. * `getCategories() => Array.<string>`
  22992. * `getMin(origin: boolean) => number`
  22993. * `getMax(origin: boolean) => number`
  22994. * `getNeedCrossZero() => boolean`
  22995. * `setRange(start: number, end: number)`
  22996. * `resetRange()`
  22997. */
  22998. function mixinAxisModelCommonMethods(Model$$1) {
  22999. mixin(Model$$1, axisModelCommonMixin);
  23000. }
  23001. var helper = (Object.freeze || Object)({
  23002. createList: createList,
  23003. createScale: createScale,
  23004. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  23005. completeDimensions: completeDimensions,
  23006. createSymbol: createSymbol
  23007. });
  23008. var linearMap$1 = linearMap;
  23009. function fixExtentWithBands(extent, nTick) {
  23010. var size = extent[1] - extent[0];
  23011. var len = nTick;
  23012. var margin = size / len / 2;
  23013. extent[0] += margin;
  23014. extent[1] -= margin;
  23015. }
  23016. var normalizedExtent = [0, 1];
  23017. /**
  23018. * @name module:echarts/coord/CartesianAxis
  23019. * @constructor
  23020. */
  23021. var Axis = function (dim, scale, extent) {
  23022. /**
  23023. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  23024. * @type {string}
  23025. */
  23026. this.dim = dim;
  23027. /**
  23028. * Axis scale
  23029. * @type {module:echarts/coord/scale/*}
  23030. */
  23031. this.scale = scale;
  23032. /**
  23033. * @type {Array.<number>}
  23034. * @private
  23035. */
  23036. this._extent = extent || [0, 0];
  23037. /**
  23038. * @type {boolean}
  23039. */
  23040. this.inverse = false;
  23041. /**
  23042. * Usually true when axis has a ordinal scale
  23043. * @type {boolean}
  23044. */
  23045. this.onBand = false;
  23046. /**
  23047. * @private
  23048. * @type {number}
  23049. */
  23050. this._labelInterval;
  23051. };
  23052. Axis.prototype = {
  23053. constructor: Axis,
  23054. /**
  23055. * If axis extent contain given coord
  23056. * @param {number} coord
  23057. * @return {boolean}
  23058. */
  23059. contain: function (coord) {
  23060. var extent = this._extent;
  23061. var min = Math.min(extent[0], extent[1]);
  23062. var max = Math.max(extent[0], extent[1]);
  23063. return coord >= min && coord <= max;
  23064. },
  23065. /**
  23066. * If axis extent contain given data
  23067. * @param {number} data
  23068. * @return {boolean}
  23069. */
  23070. containData: function (data) {
  23071. return this.contain(this.dataToCoord(data));
  23072. },
  23073. /**
  23074. * Get coord extent.
  23075. * @return {Array.<number>}
  23076. */
  23077. getExtent: function () {
  23078. return this._extent.slice();
  23079. },
  23080. /**
  23081. * Get precision used for formatting
  23082. * @param {Array.<number>} [dataExtent]
  23083. * @return {number}
  23084. */
  23085. getPixelPrecision: function (dataExtent) {
  23086. return getPixelPrecision(
  23087. dataExtent || this.scale.getExtent(),
  23088. this._extent
  23089. );
  23090. },
  23091. /**
  23092. * Set coord extent
  23093. * @param {number} start
  23094. * @param {number} end
  23095. */
  23096. setExtent: function (start, end) {
  23097. var extent = this._extent;
  23098. extent[0] = start;
  23099. extent[1] = end;
  23100. },
  23101. /**
  23102. * Convert data to coord. Data is the rank if it has a ordinal scale
  23103. * @param {number} data
  23104. * @param {boolean} clamp
  23105. * @return {number}
  23106. */
  23107. dataToCoord: function (data, clamp) {
  23108. var extent = this._extent;
  23109. var scale = this.scale;
  23110. data = scale.normalize(data);
  23111. if (this.onBand && scale.type === 'ordinal') {
  23112. extent = extent.slice();
  23113. fixExtentWithBands(extent, scale.count());
  23114. }
  23115. return linearMap$1(data, normalizedExtent, extent, clamp);
  23116. },
  23117. /**
  23118. * Convert coord to data. Data is the rank if it has a ordinal scale
  23119. * @param {number} coord
  23120. * @param {boolean} clamp
  23121. * @return {number}
  23122. */
  23123. coordToData: function (coord, clamp) {
  23124. var extent = this._extent;
  23125. var scale = this.scale;
  23126. if (this.onBand && scale.type === 'ordinal') {
  23127. extent = extent.slice();
  23128. fixExtentWithBands(extent, scale.count());
  23129. }
  23130. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  23131. return this.scale.scale(t);
  23132. },
  23133. /**
  23134. * Convert pixel point to data in axis
  23135. * @param {Array.<number>} point
  23136. * @param {boolean} clamp
  23137. * @return {number} data
  23138. */
  23139. pointToData: function (point, clamp) {
  23140. // Should be implemented in derived class if necessary.
  23141. },
  23142. /**
  23143. * @return {Array.<number>}
  23144. */
  23145. getTicksCoords: function (alignWithLabel) {
  23146. if (this.onBand && !alignWithLabel) {
  23147. var bands = this.getBands();
  23148. var coords = [];
  23149. for (var i = 0; i < bands.length; i++) {
  23150. coords.push(bands[i][0]);
  23151. }
  23152. if (bands[i - 1]) {
  23153. coords.push(bands[i - 1][1]);
  23154. }
  23155. return coords;
  23156. }
  23157. else {
  23158. return map(this.scale.getTicks(), this.dataToCoord, this);
  23159. }
  23160. },
  23161. /**
  23162. * Coords of labels are on the ticks or on the middle of bands
  23163. * @return {Array.<number>}
  23164. */
  23165. getLabelsCoords: function () {
  23166. return map(this.scale.getTicks(), this.dataToCoord, this);
  23167. },
  23168. /**
  23169. * Get bands.
  23170. *
  23171. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  23172. * |---1---|---2---|---3---|---4---|.
  23173. *
  23174. * @return {Array}
  23175. */
  23176. // FIXME Situation when labels is on ticks
  23177. getBands: function () {
  23178. var extent = this.getExtent();
  23179. var bands = [];
  23180. var len = this.scale.count();
  23181. var start = extent[0];
  23182. var end = extent[1];
  23183. var span = end - start;
  23184. for (var i = 0; i < len; i++) {
  23185. bands.push([
  23186. span * i / len + start,
  23187. span * (i + 1) / len + start
  23188. ]);
  23189. }
  23190. return bands;
  23191. },
  23192. /**
  23193. * Get width of band
  23194. * @return {number}
  23195. */
  23196. getBandWidth: function () {
  23197. var axisExtent = this._extent;
  23198. var dataExtent = this.scale.getExtent();
  23199. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  23200. // Fix #2728, avoid NaN when only one data.
  23201. len === 0 && (len = 1);
  23202. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  23203. return Math.abs(size) / len;
  23204. },
  23205. /**
  23206. * @abstract
  23207. * @return {boolean} Is horizontal
  23208. */
  23209. isHorizontal: null,
  23210. /**
  23211. * @abstract
  23212. * @return {number} Get axis rotate, by degree.
  23213. */
  23214. getRotate: null,
  23215. /**
  23216. * Get interval of the axis label.
  23217. * To get precise result, at least one of `getRotate` and `isHorizontal`
  23218. * should be implemented.
  23219. * @return {number}
  23220. */
  23221. getLabelInterval: function () {
  23222. var labelInterval = this._labelInterval;
  23223. if (!labelInterval) {
  23224. var axisModel = this.model;
  23225. var labelModel = axisModel.getModel('axisLabel');
  23226. labelInterval = labelModel.get('interval');
  23227. if (this.type === 'category'
  23228. && (labelInterval == null || labelInterval === 'auto')
  23229. ) {
  23230. labelInterval = getAxisLabelInterval(
  23231. map(this.scale.getTicks(), this.dataToCoord, this),
  23232. axisModel.getFormattedLabels(),
  23233. labelModel.getFont(),
  23234. this.getRotate
  23235. ? this.getRotate()
  23236. : (this.isHorizontal && !this.isHorizontal())
  23237. ? 90
  23238. : 0,
  23239. labelModel.get('rotate')
  23240. );
  23241. }
  23242. this._labelInterval = labelInterval;
  23243. }
  23244. return labelInterval;
  23245. }
  23246. };
  23247. var EPSILON$3 = 1e-8;
  23248. function isAroundEqual$1(a, b) {
  23249. return Math.abs(a - b) < EPSILON$3;
  23250. }
  23251. function contain$1(points, x, y) {
  23252. var w = 0;
  23253. var p = points[0];
  23254. if (!p) {
  23255. return false;
  23256. }
  23257. for (var i = 1; i < points.length; i++) {
  23258. var p2 = points[i];
  23259. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  23260. p = p2;
  23261. }
  23262. // Close polygon
  23263. var p0 = points[0];
  23264. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  23265. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  23266. }
  23267. return w !== 0;
  23268. }
  23269. /**
  23270. * @module echarts/coord/geo/Region
  23271. */
  23272. /**
  23273. * @param {string} name
  23274. * @param {Array} geometries
  23275. * @param {Array.<number>} cp
  23276. */
  23277. function Region(name, geometries, cp) {
  23278. /**
  23279. * @type {string}
  23280. * @readOnly
  23281. */
  23282. this.name = name;
  23283. /**
  23284. * @type {Array.<Array>}
  23285. * @readOnly
  23286. */
  23287. this.geometries = geometries;
  23288. if (!cp) {
  23289. var rect = this.getBoundingRect();
  23290. cp = [
  23291. rect.x + rect.width / 2,
  23292. rect.y + rect.height / 2
  23293. ];
  23294. }
  23295. else {
  23296. cp = [cp[0], cp[1]];
  23297. }
  23298. /**
  23299. * @type {Array.<number>}
  23300. */
  23301. this.center = cp;
  23302. }
  23303. Region.prototype = {
  23304. constructor: Region,
  23305. properties: null,
  23306. /**
  23307. * @return {module:zrender/core/BoundingRect}
  23308. */
  23309. getBoundingRect: function () {
  23310. var rect = this._rect;
  23311. if (rect) {
  23312. return rect;
  23313. }
  23314. var MAX_NUMBER = Number.MAX_VALUE;
  23315. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  23316. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  23317. var min2 = [];
  23318. var max2 = [];
  23319. var geometries = this.geometries;
  23320. for (var i = 0; i < geometries.length; i++) {
  23321. // Only support polygon
  23322. if (geometries[i].type !== 'polygon') {
  23323. continue;
  23324. }
  23325. // Doesn't consider hole
  23326. var exterior = geometries[i].exterior;
  23327. fromPoints(exterior, min2, max2);
  23328. min(min$$1, min$$1, min2);
  23329. max(max$$1, max$$1, max2);
  23330. }
  23331. // No data
  23332. if (i === 0) {
  23333. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  23334. }
  23335. return (this._rect = new BoundingRect(
  23336. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  23337. ));
  23338. },
  23339. /**
  23340. * @param {<Array.<number>} coord
  23341. * @return {boolean}
  23342. */
  23343. contain: function (coord) {
  23344. var rect = this.getBoundingRect();
  23345. var geometries = this.geometries;
  23346. if (!rect.contain(coord[0], coord[1])) {
  23347. return false;
  23348. }
  23349. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  23350. // Only support polygon.
  23351. if (geometries[i].type !== 'polygon') {
  23352. continue;
  23353. }
  23354. var exterior = geometries[i].exterior;
  23355. var interiors = geometries[i].interiors;
  23356. if (contain$1(exterior, coord[0], coord[1])) {
  23357. // Not in the region if point is in the hole.
  23358. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  23359. if (contain$1(interiors[k])) {
  23360. continue loopGeo;
  23361. }
  23362. }
  23363. return true;
  23364. }
  23365. }
  23366. return false;
  23367. },
  23368. transformTo: function (x, y, width, height) {
  23369. var rect = this.getBoundingRect();
  23370. var aspect = rect.width / rect.height;
  23371. if (!width) {
  23372. width = aspect * height;
  23373. }
  23374. else if (!height) {
  23375. height = width / aspect ;
  23376. }
  23377. var target = new BoundingRect(x, y, width, height);
  23378. var transform = rect.calculateTransform(target);
  23379. var geometries = this.geometries;
  23380. for (var i = 0; i < geometries.length; i++) {
  23381. // Only support polygon.
  23382. if (geometries[i].type !== 'polygon') {
  23383. continue;
  23384. }
  23385. var exterior = geometries[i].exterior;
  23386. var interiors = geometries[i].interiors;
  23387. for (var p = 0; p < exterior.length; p++) {
  23388. applyTransform(exterior[p], exterior[p], transform);
  23389. }
  23390. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  23391. for (var p = 0; p < interiors[h].length; p++) {
  23392. applyTransform(interiors[h][p], interiors[h][p], transform);
  23393. }
  23394. }
  23395. }
  23396. rect = this._rect;
  23397. rect.copy(target);
  23398. // Update center
  23399. this.center = [
  23400. rect.x + rect.width / 2,
  23401. rect.y + rect.height / 2
  23402. ];
  23403. }
  23404. };
  23405. /**
  23406. * Parse and decode geo json
  23407. * @module echarts/coord/geo/parseGeoJson
  23408. */
  23409. function decode(json) {
  23410. if (!json.UTF8Encoding) {
  23411. return json;
  23412. }
  23413. var encodeScale = json.UTF8Scale;
  23414. if (encodeScale == null) {
  23415. encodeScale = 1024;
  23416. }
  23417. var features = json.features;
  23418. for (var f = 0; f < features.length; f++) {
  23419. var feature = features[f];
  23420. var geometry = feature.geometry;
  23421. var coordinates = geometry.coordinates;
  23422. var encodeOffsets = geometry.encodeOffsets;
  23423. for (var c = 0; c < coordinates.length; c++) {
  23424. var coordinate = coordinates[c];
  23425. if (geometry.type === 'Polygon') {
  23426. coordinates[c] = decodePolygon(
  23427. coordinate,
  23428. encodeOffsets[c],
  23429. encodeScale
  23430. );
  23431. }
  23432. else if (geometry.type === 'MultiPolygon') {
  23433. for (var c2 = 0; c2 < coordinate.length; c2++) {
  23434. var polygon = coordinate[c2];
  23435. coordinate[c2] = decodePolygon(
  23436. polygon,
  23437. encodeOffsets[c][c2],
  23438. encodeScale
  23439. );
  23440. }
  23441. }
  23442. }
  23443. }
  23444. // Has been decoded
  23445. json.UTF8Encoding = false;
  23446. return json;
  23447. }
  23448. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  23449. var result = [];
  23450. var prevX = encodeOffsets[0];
  23451. var prevY = encodeOffsets[1];
  23452. for (var i = 0; i < coordinate.length; i += 2) {
  23453. var x = coordinate.charCodeAt(i) - 64;
  23454. var y = coordinate.charCodeAt(i + 1) - 64;
  23455. // ZigZag decoding
  23456. x = (x >> 1) ^ (-(x & 1));
  23457. y = (y >> 1) ^ (-(y & 1));
  23458. // Delta deocding
  23459. x += prevX;
  23460. y += prevY;
  23461. prevX = x;
  23462. prevY = y;
  23463. // Dequantize
  23464. result.push([x / encodeScale, y / encodeScale]);
  23465. }
  23466. return result;
  23467. }
  23468. /**
  23469. * @alias module:echarts/coord/geo/parseGeoJson
  23470. * @param {Object} geoJson
  23471. * @return {module:zrender/container/Group}
  23472. */
  23473. var parseGeoJson = function (geoJson) {
  23474. decode(geoJson);
  23475. return map(filter(geoJson.features, function (featureObj) {
  23476. // Output of mapshaper may have geometry null
  23477. return featureObj.geometry
  23478. && featureObj.properties
  23479. && featureObj.geometry.coordinates.length > 0;
  23480. }), function (featureObj) {
  23481. var properties = featureObj.properties;
  23482. var geo = featureObj.geometry;
  23483. var coordinates = geo.coordinates;
  23484. var geometries = [];
  23485. if (geo.type === 'Polygon') {
  23486. geometries.push({
  23487. type: 'polygon',
  23488. // According to the GeoJSON specification.
  23489. // First must be exterior, and the rest are all interior(holes).
  23490. exterior: coordinates[0],
  23491. interiors: coordinates.slice(1)
  23492. });
  23493. }
  23494. if (geo.type === 'MultiPolygon') {
  23495. each$1(coordinates, function (item) {
  23496. if (item[0]) {
  23497. geometries.push({
  23498. type: 'polygon',
  23499. exterior: item[0],
  23500. interiors: item.slice(1)
  23501. });
  23502. }
  23503. });
  23504. }
  23505. var region = new Region(
  23506. properties.name,
  23507. geometries,
  23508. properties.cp
  23509. );
  23510. region.properties = properties;
  23511. return region;
  23512. });
  23513. };
  23514. /**
  23515. * Do not mount those modules on 'src/echarts' for better tree shaking.
  23516. */
  23517. var ecUtil = {};
  23518. each$1([
  23519. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  23520. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  23521. 'extend', 'defaults', 'clone', 'merge'
  23522. ],
  23523. function (name) {
  23524. ecUtil[name] = zrUtil[name];
  23525. }
  23526. );
  23527. SeriesModel.extend({
  23528. type: 'series.line',
  23529. dependencies: ['grid', 'polar'],
  23530. getInitialData: function (option, ecModel) {
  23531. if (__DEV__) {
  23532. var coordSys = option.coordinateSystem;
  23533. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  23534. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  23535. }
  23536. }
  23537. return createListFromArray(option.data, this, ecModel);
  23538. },
  23539. defaultOption: {
  23540. zlevel: 0, // 一级层叠
  23541. z: 2, // 二级层叠
  23542. coordinateSystem: 'cartesian2d',
  23543. legendHoverLink: true,
  23544. hoverAnimation: true,
  23545. // stack: null
  23546. // xAxisIndex: 0,
  23547. // yAxisIndex: 0,
  23548. // polarIndex: 0,
  23549. // If clip the overflow value
  23550. clipOverflow: true,
  23551. // cursor: null,
  23552. label: {
  23553. normal: {
  23554. position: 'top'
  23555. }
  23556. },
  23557. // itemStyle: {
  23558. // normal: {},
  23559. // emphasis: {}
  23560. // },
  23561. lineStyle: {
  23562. normal: {
  23563. width: 2,
  23564. type: 'solid'
  23565. }
  23566. },
  23567. // areaStyle: {},
  23568. // false, 'start', 'end', 'middle'
  23569. step: false,
  23570. // Disabled if step is true
  23571. smooth: false,
  23572. smoothMonotone: null,
  23573. // 拐点图形类型
  23574. symbol: 'emptyCircle',
  23575. // 拐点图形大小
  23576. symbolSize: 4,
  23577. // 拐点图形旋转控制
  23578. symbolRotate: null,
  23579. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  23580. showSymbol: true,
  23581. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  23582. showAllSymbol: false,
  23583. // 是否连接断点
  23584. connectNulls: false,
  23585. // 数据过滤,'average', 'max', 'min', 'sum'
  23586. sampling: 'none',
  23587. animationEasing: 'linear',
  23588. // Disable progressive
  23589. progressive: 0,
  23590. hoverLayerThreshold: Infinity
  23591. }
  23592. });
  23593. /**
  23594. * @module echarts/chart/helper/Symbol
  23595. */
  23596. function findLabelValueDim(data) {
  23597. var valueDim;
  23598. var labelDims = otherDimToDataDim(data, 'label');
  23599. if (labelDims.length) {
  23600. valueDim = labelDims[0];
  23601. }
  23602. else {
  23603. // Get last value dim
  23604. var dimensions = data.dimensions.slice();
  23605. var dataType;
  23606. while (dimensions.length && (
  23607. valueDim = dimensions.pop(),
  23608. dataType = data.getDimensionInfo(valueDim).type,
  23609. dataType === 'ordinal' || dataType === 'time'
  23610. )) {} // jshint ignore:line
  23611. }
  23612. return valueDim;
  23613. }
  23614. /**
  23615. * @module echarts/chart/helper/Symbol
  23616. */
  23617. function getSymbolSize(data, idx) {
  23618. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  23619. return symbolSize instanceof Array
  23620. ? symbolSize.slice()
  23621. : [+symbolSize, +symbolSize];
  23622. }
  23623. function getScale(symbolSize) {
  23624. return [symbolSize[0] / 2, symbolSize[1] / 2];
  23625. }
  23626. /**
  23627. * @constructor
  23628. * @alias {module:echarts/chart/helper/Symbol}
  23629. * @param {module:echarts/data/List} data
  23630. * @param {number} idx
  23631. * @extends {module:zrender/graphic/Group}
  23632. */
  23633. function SymbolClz$1(data, idx, seriesScope) {
  23634. Group.call(this);
  23635. this.updateData(data, idx, seriesScope);
  23636. }
  23637. var symbolProto = SymbolClz$1.prototype;
  23638. function driftSymbol(dx, dy) {
  23639. this.parent.drift(dx, dy);
  23640. }
  23641. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  23642. // Remove paths created before
  23643. this.removeAll();
  23644. var color = data.getItemVisual(idx, 'color');
  23645. // var symbolPath = createSymbol(
  23646. // symbolType, -0.5, -0.5, 1, 1, color
  23647. // );
  23648. // If width/height are set too small (e.g., set to 1) on ios10
  23649. // and macOS Sierra, a circle stroke become a rect, no matter what
  23650. // the scale is set. So we set width/height as 2. See #4150.
  23651. var symbolPath = createSymbol(
  23652. symbolType, -1, -1, 2, 2, color
  23653. );
  23654. symbolPath.attr({
  23655. z2: 100,
  23656. culling: true,
  23657. scale: getScale(symbolSize)
  23658. });
  23659. // Rewrite drift method
  23660. symbolPath.drift = driftSymbol;
  23661. this._symbolType = symbolType;
  23662. this.add(symbolPath);
  23663. };
  23664. /**
  23665. * Stop animation
  23666. * @param {boolean} toLastFrame
  23667. */
  23668. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  23669. this.childAt(0).stopAnimation(toLastFrame);
  23670. };
  23671. /**
  23672. * FIXME:
  23673. * Caution: This method breaks the encapsulation of this module,
  23674. * but it indeed brings convenience. So do not use the method
  23675. * unless you detailedly know all the implements of `Symbol`,
  23676. * especially animation.
  23677. *
  23678. * Get symbol path element.
  23679. */
  23680. symbolProto.getSymbolPath = function () {
  23681. return this.childAt(0);
  23682. };
  23683. /**
  23684. * Get scale(aka, current symbol size).
  23685. * Including the change caused by animation
  23686. */
  23687. symbolProto.getScale = function () {
  23688. return this.childAt(0).scale;
  23689. };
  23690. /**
  23691. * Highlight symbol
  23692. */
  23693. symbolProto.highlight = function () {
  23694. this.childAt(0).trigger('emphasis');
  23695. };
  23696. /**
  23697. * Downplay symbol
  23698. */
  23699. symbolProto.downplay = function () {
  23700. this.childAt(0).trigger('normal');
  23701. };
  23702. /**
  23703. * @param {number} zlevel
  23704. * @param {number} z
  23705. */
  23706. symbolProto.setZ = function (zlevel, z) {
  23707. var symbolPath = this.childAt(0);
  23708. symbolPath.zlevel = zlevel;
  23709. symbolPath.z = z;
  23710. };
  23711. symbolProto.setDraggable = function (draggable) {
  23712. var symbolPath = this.childAt(0);
  23713. symbolPath.draggable = draggable;
  23714. symbolPath.cursor = draggable ? 'move' : 'pointer';
  23715. };
  23716. /**
  23717. * Update symbol properties
  23718. * @param {module:echarts/data/List} data
  23719. * @param {number} idx
  23720. * @param {Object} [seriesScope]
  23721. * @param {Object} [seriesScope.itemStyle]
  23722. * @param {Object} [seriesScope.hoverItemStyle]
  23723. * @param {Object} [seriesScope.symbolRotate]
  23724. * @param {Object} [seriesScope.symbolOffset]
  23725. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  23726. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  23727. * @param {boolean} [seriesScope.hoverAnimation]
  23728. * @param {Object} [seriesScope.cursorStyle]
  23729. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  23730. * @param {string} [seriesScope.symbolInnerColor]
  23731. * @param {Object} [seriesScope.fadeIn=false]
  23732. */
  23733. symbolProto.updateData = function (data, idx, seriesScope) {
  23734. this.silent = false;
  23735. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  23736. var seriesModel = data.hostModel;
  23737. var symbolSize = getSymbolSize(data, idx);
  23738. var isInit = symbolType !== this._symbolType;
  23739. if (isInit) {
  23740. this._createSymbol(symbolType, data, idx, symbolSize);
  23741. }
  23742. else {
  23743. var symbolPath = this.childAt(0);
  23744. symbolPath.silent = false;
  23745. updateProps(symbolPath, {
  23746. scale: getScale(symbolSize)
  23747. }, seriesModel, idx);
  23748. }
  23749. this._updateCommon(data, idx, symbolSize, seriesScope);
  23750. if (isInit) {
  23751. var symbolPath = this.childAt(0);
  23752. var fadeIn = seriesScope && seriesScope.fadeIn;
  23753. var target = {scale: symbolPath.scale.slice()};
  23754. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  23755. symbolPath.scale = [0, 0];
  23756. fadeIn && (symbolPath.style.opacity = 0);
  23757. initProps(symbolPath, target, seriesModel, idx);
  23758. }
  23759. this._seriesModel = seriesModel;
  23760. };
  23761. // Update common properties
  23762. var normalStyleAccessPath = ['itemStyle', 'normal'];
  23763. var emphasisStyleAccessPath = ['itemStyle', 'emphasis'];
  23764. var normalLabelAccessPath = ['label', 'normal'];
  23765. var emphasisLabelAccessPath = ['label', 'emphasis'];
  23766. /**
  23767. * @param {module:echarts/data/List} data
  23768. * @param {number} idx
  23769. * @param {Array.<number>} symbolSize
  23770. * @param {Object} [seriesScope]
  23771. */
  23772. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  23773. var symbolPath = this.childAt(0);
  23774. var seriesModel = data.hostModel;
  23775. var color = data.getItemVisual(idx, 'color');
  23776. // Reset style
  23777. if (symbolPath.type !== 'image') {
  23778. symbolPath.useStyle({
  23779. strokeNoScale: true
  23780. });
  23781. }
  23782. var itemStyle = seriesScope && seriesScope.itemStyle;
  23783. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  23784. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  23785. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  23786. var labelModel = seriesScope && seriesScope.labelModel;
  23787. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  23788. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  23789. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  23790. if (!seriesScope || data.hasItemOption) {
  23791. var itemModel = (seriesScope && seriesScope.itemModel)
  23792. ? seriesScope.itemModel : data.getItemModel(idx);
  23793. // Color must be excluded.
  23794. // Because symbol provide setColor individually to set fill and stroke
  23795. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  23796. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  23797. symbolRotate = itemModel.getShallow('symbolRotate');
  23798. symbolOffset = itemModel.getShallow('symbolOffset');
  23799. labelModel = itemModel.getModel(normalLabelAccessPath);
  23800. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  23801. hoverAnimation = itemModel.getShallow('hoverAnimation');
  23802. cursorStyle = itemModel.getShallow('cursor');
  23803. }
  23804. else {
  23805. hoverItemStyle = extend({}, hoverItemStyle);
  23806. }
  23807. var elStyle = symbolPath.style;
  23808. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  23809. if (symbolOffset) {
  23810. symbolPath.attr('position', [
  23811. parsePercent$1(symbolOffset[0], symbolSize[0]),
  23812. parsePercent$1(symbolOffset[1], symbolSize[1])
  23813. ]);
  23814. }
  23815. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  23816. // PENDING setColor before setStyle!!!
  23817. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  23818. symbolPath.setStyle(itemStyle);
  23819. var opacity = data.getItemVisual(idx, 'opacity');
  23820. if (opacity != null) {
  23821. elStyle.opacity = opacity;
  23822. }
  23823. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  23824. var valueDim = !useNameLabel && findLabelValueDim(data);
  23825. if (useNameLabel || valueDim != null) {
  23826. setLabelStyle(
  23827. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  23828. {
  23829. labelFetcher: seriesModel,
  23830. labelDataIndex: idx,
  23831. defaultText: useNameLabel ? data.getName(idx) : data.get(valueDim, idx),
  23832. isRectText: true,
  23833. autoColor: color
  23834. }
  23835. );
  23836. }
  23837. symbolPath.off('mouseover')
  23838. .off('mouseout')
  23839. .off('emphasis')
  23840. .off('normal');
  23841. symbolPath.hoverStyle = hoverItemStyle;
  23842. // FIXME
  23843. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  23844. setHoverStyle(symbolPath);
  23845. var scale = getScale(symbolSize);
  23846. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  23847. var onEmphasis = function() {
  23848. var ratio = scale[1] / scale[0];
  23849. this.animateTo({
  23850. scale: [
  23851. Math.max(scale[0] * 1.1, scale[0] + 3),
  23852. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  23853. ]
  23854. }, 400, 'elasticOut');
  23855. };
  23856. var onNormal = function() {
  23857. this.animateTo({
  23858. scale: scale
  23859. }, 400, 'elasticOut');
  23860. };
  23861. symbolPath.on('mouseover', onEmphasis)
  23862. .on('mouseout', onNormal)
  23863. .on('emphasis', onEmphasis)
  23864. .on('normal', onNormal);
  23865. }
  23866. };
  23867. /**
  23868. * @param {Function} cb
  23869. * @param {Object} [opt]
  23870. * @param {Object} [opt.keepLabel=true]
  23871. */
  23872. symbolProto.fadeOut = function (cb, opt) {
  23873. var symbolPath = this.childAt(0);
  23874. // Avoid mistaken hover when fading out
  23875. this.silent = symbolPath.silent = true;
  23876. // Not show text when animating
  23877. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  23878. updateProps(
  23879. symbolPath,
  23880. {
  23881. style: {opacity: 0},
  23882. scale: [0, 0]
  23883. },
  23884. this._seriesModel,
  23885. this.dataIndex,
  23886. cb
  23887. );
  23888. };
  23889. inherits(SymbolClz$1, Group);
  23890. /**
  23891. * @module echarts/chart/helper/SymbolDraw
  23892. */
  23893. /**
  23894. * @constructor
  23895. * @alias module:echarts/chart/helper/SymbolDraw
  23896. * @param {module:zrender/graphic/Group} [symbolCtor]
  23897. */
  23898. function SymbolDraw(symbolCtor) {
  23899. this.group = new Group();
  23900. this._symbolCtor = symbolCtor || SymbolClz$1;
  23901. }
  23902. var symbolDrawProto = SymbolDraw.prototype;
  23903. function symbolNeedsDraw(data, idx, isIgnore) {
  23904. var point = data.getItemLayout(idx);
  23905. // Is an object
  23906. // if (point && point.hasOwnProperty('point')) {
  23907. // point = point.point;
  23908. // }
  23909. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(isIgnore && isIgnore(idx))
  23910. && data.getItemVisual(idx, 'symbol') !== 'none';
  23911. }
  23912. /**
  23913. * Update symbols draw by new data
  23914. * @param {module:echarts/data/List} data
  23915. * @param {Array.<boolean>} [isIgnore]
  23916. */
  23917. symbolDrawProto.updateData = function (data, isIgnore) {
  23918. var group = this.group;
  23919. var seriesModel = data.hostModel;
  23920. var oldData = this._data;
  23921. var SymbolCtor = this._symbolCtor;
  23922. var seriesScope = {
  23923. itemStyle: seriesModel.getModel('itemStyle.normal').getItemStyle(['color']),
  23924. hoverItemStyle: seriesModel.getModel('itemStyle.emphasis').getItemStyle(),
  23925. symbolRotate: seriesModel.get('symbolRotate'),
  23926. symbolOffset: seriesModel.get('symbolOffset'),
  23927. hoverAnimation: seriesModel.get('hoverAnimation'),
  23928. labelModel: seriesModel.getModel('label.normal'),
  23929. hoverLabelModel: seriesModel.getModel('label.emphasis'),
  23930. cursorStyle: seriesModel.get('cursor')
  23931. };
  23932. data.diff(oldData)
  23933. .add(function (newIdx) {
  23934. var point = data.getItemLayout(newIdx);
  23935. if (symbolNeedsDraw(data, newIdx, isIgnore)) {
  23936. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  23937. symbolEl.attr('position', point);
  23938. data.setItemGraphicEl(newIdx, symbolEl);
  23939. group.add(symbolEl);
  23940. }
  23941. })
  23942. .update(function (newIdx, oldIdx) {
  23943. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  23944. var point = data.getItemLayout(newIdx);
  23945. if (!symbolNeedsDraw(data, newIdx, isIgnore)) {
  23946. group.remove(symbolEl);
  23947. return;
  23948. }
  23949. if (!symbolEl) {
  23950. symbolEl = new SymbolCtor(data, newIdx);
  23951. symbolEl.attr('position', point);
  23952. }
  23953. else {
  23954. symbolEl.updateData(data, newIdx, seriesScope);
  23955. updateProps(symbolEl, {
  23956. position: point
  23957. }, seriesModel);
  23958. }
  23959. // Add back
  23960. group.add(symbolEl);
  23961. data.setItemGraphicEl(newIdx, symbolEl);
  23962. })
  23963. .remove(function (oldIdx) {
  23964. var el = oldData.getItemGraphicEl(oldIdx);
  23965. el && el.fadeOut(function () {
  23966. group.remove(el);
  23967. });
  23968. })
  23969. .execute();
  23970. this._data = data;
  23971. };
  23972. symbolDrawProto.updateLayout = function () {
  23973. var data = this._data;
  23974. if (data) {
  23975. // Not use animation
  23976. data.eachItemGraphicEl(function (el, idx) {
  23977. var point = data.getItemLayout(idx);
  23978. el.attr('position', point);
  23979. });
  23980. }
  23981. };
  23982. symbolDrawProto.remove = function (enableAnimation) {
  23983. var group = this.group;
  23984. var data = this._data;
  23985. if (data) {
  23986. if (enableAnimation) {
  23987. data.eachItemGraphicEl(function (el) {
  23988. el.fadeOut(function () {
  23989. group.remove(el);
  23990. });
  23991. });
  23992. }
  23993. else {
  23994. group.removeAll();
  23995. }
  23996. }
  23997. };
  23998. // var arrayDiff = require('zrender/src/core/arrayDiff');
  23999. // 'zrender/src/core/arrayDiff' has been used before, but it did
  24000. // not do well in performance when roam with fixed dataZoom window.
  24001. function sign$1(val) {
  24002. return val >= 0 ? 1 : -1;
  24003. }
  24004. function getStackedOnPoint(coordSys, data, idx) {
  24005. var baseAxis = coordSys.getBaseAxis();
  24006. var valueAxis = coordSys.getOtherAxis(baseAxis);
  24007. var valueStart = baseAxis.onZero
  24008. ? 0 : valueAxis.scale.getExtent()[0];
  24009. var valueDim = valueAxis.dim;
  24010. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  24011. var stackedOnSameSign;
  24012. var stackedOn = data.stackedOn;
  24013. var val = data.get(valueDim, idx);
  24014. // Find first stacked value with same sign
  24015. while (stackedOn &&
  24016. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  24017. ) {
  24018. stackedOnSameSign = stackedOn;
  24019. break;
  24020. }
  24021. var stackedData = [];
  24022. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  24023. stackedData[1 - baseDataOffset] = stackedOnSameSign
  24024. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  24025. return coordSys.dataToPoint(stackedData);
  24026. }
  24027. // function convertToIntId(newIdList, oldIdList) {
  24028. // // Generate int id instead of string id.
  24029. // // Compare string maybe slow in score function of arrDiff
  24030. // // Assume id in idList are all unique
  24031. // var idIndicesMap = {};
  24032. // var idx = 0;
  24033. // for (var i = 0; i < newIdList.length; i++) {
  24034. // idIndicesMap[newIdList[i]] = idx;
  24035. // newIdList[i] = idx++;
  24036. // }
  24037. // for (var i = 0; i < oldIdList.length; i++) {
  24038. // var oldId = oldIdList[i];
  24039. // // Same with newIdList
  24040. // if (idIndicesMap[oldId]) {
  24041. // oldIdList[i] = idIndicesMap[oldId];
  24042. // }
  24043. // else {
  24044. // oldIdList[i] = idx++;
  24045. // }
  24046. // }
  24047. // }
  24048. function diffData(oldData, newData) {
  24049. var diffResult = [];
  24050. newData.diff(oldData)
  24051. .add(function (idx) {
  24052. diffResult.push({cmd: '+', idx: idx});
  24053. })
  24054. .update(function (newIdx, oldIdx) {
  24055. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  24056. })
  24057. .remove(function (idx) {
  24058. diffResult.push({cmd: '-', idx: idx});
  24059. })
  24060. .execute();
  24061. return diffResult;
  24062. }
  24063. var lineAnimationDiff = function (
  24064. oldData, newData,
  24065. oldStackedOnPoints, newStackedOnPoints,
  24066. oldCoordSys, newCoordSys
  24067. ) {
  24068. var diff = diffData(oldData, newData);
  24069. // var newIdList = newData.mapArray(newData.getId);
  24070. // var oldIdList = oldData.mapArray(oldData.getId);
  24071. // convertToIntId(newIdList, oldIdList);
  24072. // // FIXME One data ?
  24073. // diff = arrayDiff(oldIdList, newIdList);
  24074. var currPoints = [];
  24075. var nextPoints = [];
  24076. // Points for stacking base line
  24077. var currStackedPoints = [];
  24078. var nextStackedPoints = [];
  24079. var status = [];
  24080. var sortedIndices = [];
  24081. var rawIndices = [];
  24082. var dims = newCoordSys.dimensions;
  24083. for (var i = 0; i < diff.length; i++) {
  24084. var diffItem = diff[i];
  24085. var pointAdded = true;
  24086. // FIXME, animation is not so perfect when dataZoom window moves fast
  24087. // Which is in case remvoing or add more than one data in the tail or head
  24088. switch (diffItem.cmd) {
  24089. case '=':
  24090. var currentPt = oldData.getItemLayout(diffItem.idx);
  24091. var nextPt = newData.getItemLayout(diffItem.idx1);
  24092. // If previous data is NaN, use next point directly
  24093. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  24094. currentPt = nextPt.slice();
  24095. }
  24096. currPoints.push(currentPt);
  24097. nextPoints.push(nextPt);
  24098. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  24099. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  24100. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  24101. break;
  24102. case '+':
  24103. var idx = diffItem.idx;
  24104. currPoints.push(
  24105. oldCoordSys.dataToPoint([
  24106. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  24107. ])
  24108. );
  24109. nextPoints.push(newData.getItemLayout(idx).slice());
  24110. currStackedPoints.push(
  24111. getStackedOnPoint(oldCoordSys, newData, idx)
  24112. );
  24113. nextStackedPoints.push(newStackedOnPoints[idx]);
  24114. rawIndices.push(newData.getRawIndex(idx));
  24115. break;
  24116. case '-':
  24117. var idx = diffItem.idx;
  24118. var rawIndex = oldData.getRawIndex(idx);
  24119. // Data is replaced. In the case of dynamic data queue
  24120. // FIXME FIXME FIXME
  24121. if (rawIndex !== idx) {
  24122. currPoints.push(oldData.getItemLayout(idx));
  24123. nextPoints.push(newCoordSys.dataToPoint([
  24124. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  24125. ]));
  24126. currStackedPoints.push(oldStackedOnPoints[idx]);
  24127. nextStackedPoints.push(
  24128. getStackedOnPoint(
  24129. newCoordSys, oldData, idx
  24130. )
  24131. );
  24132. rawIndices.push(rawIndex);
  24133. }
  24134. else {
  24135. pointAdded = false;
  24136. }
  24137. }
  24138. // Original indices
  24139. if (pointAdded) {
  24140. status.push(diffItem);
  24141. sortedIndices.push(sortedIndices.length);
  24142. }
  24143. }
  24144. // Diff result may be crossed if all items are changed
  24145. // Sort by data index
  24146. sortedIndices.sort(function (a, b) {
  24147. return rawIndices[a] - rawIndices[b];
  24148. });
  24149. var sortedCurrPoints = [];
  24150. var sortedNextPoints = [];
  24151. var sortedCurrStackedPoints = [];
  24152. var sortedNextStackedPoints = [];
  24153. var sortedStatus = [];
  24154. for (var i = 0; i < sortedIndices.length; i++) {
  24155. var idx = sortedIndices[i];
  24156. sortedCurrPoints[i] = currPoints[idx];
  24157. sortedNextPoints[i] = nextPoints[idx];
  24158. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  24159. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  24160. sortedStatus[i] = status[idx];
  24161. }
  24162. return {
  24163. current: sortedCurrPoints,
  24164. next: sortedNextPoints,
  24165. stackedOnCurrent: sortedCurrStackedPoints,
  24166. stackedOnNext: sortedNextStackedPoints,
  24167. status: sortedStatus
  24168. };
  24169. };
  24170. // Poly path support NaN point
  24171. var vec2Min = min;
  24172. var vec2Max = max;
  24173. var scaleAndAdd$1 = scaleAndAdd;
  24174. var v2Copy = copy;
  24175. // Temporary variable
  24176. var v = [];
  24177. var cp0 = [];
  24178. var cp1 = [];
  24179. function isPointNull(p) {
  24180. return isNaN(p[0]) || isNaN(p[1]);
  24181. }
  24182. function drawSegment(
  24183. ctx, points, start, segLen, allLen,
  24184. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  24185. ) {
  24186. var prevIdx = 0;
  24187. var idx = start;
  24188. for (var k = 0; k < segLen; k++) {
  24189. var p = points[idx];
  24190. if (idx >= allLen || idx < 0) {
  24191. break;
  24192. }
  24193. if (isPointNull(p)) {
  24194. if (connectNulls) {
  24195. idx += dir;
  24196. continue;
  24197. }
  24198. break;
  24199. }
  24200. if (idx === start) {
  24201. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  24202. v2Copy(cp0, p);
  24203. }
  24204. else {
  24205. if (smooth > 0) {
  24206. var nextIdx = idx + dir;
  24207. var nextP = points[nextIdx];
  24208. if (connectNulls) {
  24209. // Find next point not null
  24210. while (nextP && isPointNull(points[nextIdx])) {
  24211. nextIdx += dir;
  24212. nextP = points[nextIdx];
  24213. }
  24214. }
  24215. var ratioNextSeg = 0.5;
  24216. var prevP = points[prevIdx];
  24217. var nextP = points[nextIdx];
  24218. // Last point
  24219. if (!nextP || isPointNull(nextP)) {
  24220. v2Copy(cp1, p);
  24221. }
  24222. else {
  24223. // If next data is null in not connect case
  24224. if (isPointNull(nextP) && !connectNulls) {
  24225. nextP = p;
  24226. }
  24227. sub(v, nextP, prevP);
  24228. var lenPrevSeg;
  24229. var lenNextSeg;
  24230. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  24231. var dim = smoothMonotone === 'x' ? 0 : 1;
  24232. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  24233. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  24234. }
  24235. else {
  24236. lenPrevSeg = dist(p, prevP);
  24237. lenNextSeg = dist(p, nextP);
  24238. }
  24239. // Use ratio of seg length
  24240. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  24241. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  24242. }
  24243. // Smooth constraint
  24244. vec2Min(cp0, cp0, smoothMax);
  24245. vec2Max(cp0, cp0, smoothMin);
  24246. vec2Min(cp1, cp1, smoothMax);
  24247. vec2Max(cp1, cp1, smoothMin);
  24248. ctx.bezierCurveTo(
  24249. cp0[0], cp0[1],
  24250. cp1[0], cp1[1],
  24251. p[0], p[1]
  24252. );
  24253. // cp0 of next segment
  24254. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  24255. }
  24256. else {
  24257. ctx.lineTo(p[0], p[1]);
  24258. }
  24259. }
  24260. prevIdx = idx;
  24261. idx += dir;
  24262. }
  24263. return k;
  24264. }
  24265. function getBoundingBox(points, smoothConstraint) {
  24266. var ptMin = [Infinity, Infinity];
  24267. var ptMax = [-Infinity, -Infinity];
  24268. if (smoothConstraint) {
  24269. for (var i = 0; i < points.length; i++) {
  24270. var pt = points[i];
  24271. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  24272. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  24273. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  24274. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  24275. }
  24276. }
  24277. return {
  24278. min: smoothConstraint ? ptMin : ptMax,
  24279. max: smoothConstraint ? ptMax : ptMin
  24280. };
  24281. }
  24282. var Polyline$1 = Path.extend({
  24283. type: 'ec-polyline',
  24284. shape: {
  24285. points: [],
  24286. smooth: 0,
  24287. smoothConstraint: true,
  24288. smoothMonotone: null,
  24289. connectNulls: false
  24290. },
  24291. style: {
  24292. fill: null,
  24293. stroke: '#000'
  24294. },
  24295. brush: fixClipWithShadow(Path.prototype.brush),
  24296. buildPath: function (ctx, shape) {
  24297. var points = shape.points;
  24298. var i = 0;
  24299. var len$$1 = points.length;
  24300. var result = getBoundingBox(points, shape.smoothConstraint);
  24301. if (shape.connectNulls) {
  24302. // Must remove first and last null values avoid draw error in polygon
  24303. for (; len$$1 > 0; len$$1--) {
  24304. if (!isPointNull(points[len$$1 - 1])) {
  24305. break;
  24306. }
  24307. }
  24308. for (; i < len$$1; i++) {
  24309. if (!isPointNull(points[i])) {
  24310. break;
  24311. }
  24312. }
  24313. }
  24314. while (i < len$$1) {
  24315. i += drawSegment(
  24316. ctx, points, i, len$$1, len$$1,
  24317. 1, result.min, result.max, shape.smooth,
  24318. shape.smoothMonotone, shape.connectNulls
  24319. ) + 1;
  24320. }
  24321. }
  24322. });
  24323. var Polygon$1 = Path.extend({
  24324. type: 'ec-polygon',
  24325. shape: {
  24326. points: [],
  24327. // Offset between stacked base points and points
  24328. stackedOnPoints: [],
  24329. smooth: 0,
  24330. stackedOnSmooth: 0,
  24331. smoothConstraint: true,
  24332. smoothMonotone: null,
  24333. connectNulls: false
  24334. },
  24335. brush: fixClipWithShadow(Path.prototype.brush),
  24336. buildPath: function (ctx, shape) {
  24337. var points = shape.points;
  24338. var stackedOnPoints = shape.stackedOnPoints;
  24339. var i = 0;
  24340. var len$$1 = points.length;
  24341. var smoothMonotone = shape.smoothMonotone;
  24342. var bbox = getBoundingBox(points, shape.smoothConstraint);
  24343. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  24344. if (shape.connectNulls) {
  24345. // Must remove first and last null values avoid draw error in polygon
  24346. for (; len$$1 > 0; len$$1--) {
  24347. if (!isPointNull(points[len$$1 - 1])) {
  24348. break;
  24349. }
  24350. }
  24351. for (; i < len$$1; i++) {
  24352. if (!isPointNull(points[i])) {
  24353. break;
  24354. }
  24355. }
  24356. }
  24357. while (i < len$$1) {
  24358. var k = drawSegment(
  24359. ctx, points, i, len$$1, len$$1,
  24360. 1, bbox.min, bbox.max, shape.smooth,
  24361. smoothMonotone, shape.connectNulls
  24362. );
  24363. drawSegment(
  24364. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  24365. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  24366. smoothMonotone, shape.connectNulls
  24367. );
  24368. i += k + 1;
  24369. ctx.closePath();
  24370. }
  24371. }
  24372. });
  24373. // FIXME step not support polar
  24374. function isPointsSame(points1, points2) {
  24375. if (points1.length !== points2.length) {
  24376. return;
  24377. }
  24378. for (var i = 0; i < points1.length; i++) {
  24379. var p1 = points1[i];
  24380. var p2 = points2[i];
  24381. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  24382. return;
  24383. }
  24384. }
  24385. return true;
  24386. }
  24387. function getSmooth(smooth) {
  24388. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  24389. }
  24390. function getAxisExtentWithGap(axis) {
  24391. var extent = axis.getGlobalExtent();
  24392. if (axis.onBand) {
  24393. // Remove extra 1px to avoid line miter in clipped edge
  24394. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  24395. var dir = extent[1] > extent[0] ? 1 : -1;
  24396. extent[0] += dir * halfBandWidth;
  24397. extent[1] -= dir * halfBandWidth;
  24398. }
  24399. return extent;
  24400. }
  24401. function sign(val) {
  24402. return val >= 0 ? 1 : -1;
  24403. }
  24404. /**
  24405. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  24406. * @param {module:echarts/data/List} data
  24407. * @param {Array.<Array.<number>>} points
  24408. * @private
  24409. */
  24410. function getStackedOnPoints(coordSys, data) {
  24411. var baseAxis = coordSys.getBaseAxis();
  24412. var valueAxis = coordSys.getOtherAxis(baseAxis);
  24413. var valueStart = 0;
  24414. if (!baseAxis.onZero) {
  24415. var extent = valueAxis.scale.getExtent();
  24416. if (extent[0] > 0) {
  24417. // Both positive
  24418. valueStart = extent[0];
  24419. }
  24420. else if (extent[1] < 0) {
  24421. // Both negative
  24422. valueStart = extent[1];
  24423. }
  24424. // If is one positive, and one negative, onZero shall be true
  24425. }
  24426. var valueDim = valueAxis.dim;
  24427. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  24428. return data.mapArray([valueDim], function (val, idx) {
  24429. var stackedOnSameSign;
  24430. var stackedOn = data.stackedOn;
  24431. // Find first stacked value with same sign
  24432. while (stackedOn &&
  24433. sign(stackedOn.get(valueDim, idx)) === sign(val)
  24434. ) {
  24435. stackedOnSameSign = stackedOn;
  24436. break;
  24437. }
  24438. var stackedData = [];
  24439. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  24440. stackedData[1 - baseDataOffset] = stackedOnSameSign
  24441. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  24442. return coordSys.dataToPoint(stackedData);
  24443. }, true);
  24444. }
  24445. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  24446. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  24447. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  24448. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  24449. var x = Math.min(xExtent[0], xExtent[1]);
  24450. var y = Math.min(yExtent[0], yExtent[1]);
  24451. var width = Math.max(xExtent[0], xExtent[1]) - x;
  24452. var height = Math.max(yExtent[0], yExtent[1]) - y;
  24453. var lineWidth = seriesModel.get('lineStyle.normal.width') || 2;
  24454. // Expand clip shape to avoid clipping when line value exceeds axis
  24455. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  24456. if (isHorizontal) {
  24457. y -= expandSize;
  24458. height += expandSize * 2;
  24459. }
  24460. else {
  24461. x -= expandSize;
  24462. width += expandSize * 2;
  24463. }
  24464. var clipPath = new Rect({
  24465. shape: {
  24466. x: x,
  24467. y: y,
  24468. width: width,
  24469. height: height
  24470. }
  24471. });
  24472. if (hasAnimation) {
  24473. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  24474. initProps(clipPath, {
  24475. shape: {
  24476. width: width,
  24477. height: height
  24478. }
  24479. }, seriesModel);
  24480. }
  24481. return clipPath;
  24482. }
  24483. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  24484. var angleAxis = polar.getAngleAxis();
  24485. var radiusAxis = polar.getRadiusAxis();
  24486. var radiusExtent = radiusAxis.getExtent();
  24487. var angleExtent = angleAxis.getExtent();
  24488. var RADIAN = Math.PI / 180;
  24489. var clipPath = new Sector({
  24490. shape: {
  24491. cx: polar.cx,
  24492. cy: polar.cy,
  24493. r0: radiusExtent[0],
  24494. r: radiusExtent[1],
  24495. startAngle: -angleExtent[0] * RADIAN,
  24496. endAngle: -angleExtent[1] * RADIAN,
  24497. clockwise: angleAxis.inverse
  24498. }
  24499. });
  24500. if (hasAnimation) {
  24501. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  24502. initProps(clipPath, {
  24503. shape: {
  24504. endAngle: -angleExtent[1] * RADIAN
  24505. }
  24506. }, seriesModel);
  24507. }
  24508. return clipPath;
  24509. }
  24510. function createClipShape(coordSys, hasAnimation, seriesModel) {
  24511. return coordSys.type === 'polar'
  24512. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  24513. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  24514. }
  24515. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  24516. var baseAxis = coordSys.getBaseAxis();
  24517. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  24518. var stepPoints = [];
  24519. for (var i = 0; i < points.length - 1; i++) {
  24520. var nextPt = points[i + 1];
  24521. var pt = points[i];
  24522. stepPoints.push(pt);
  24523. var stepPt = [];
  24524. switch (stepTurnAt) {
  24525. case 'end':
  24526. stepPt[baseIndex] = nextPt[baseIndex];
  24527. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  24528. // default is start
  24529. stepPoints.push(stepPt);
  24530. break;
  24531. case 'middle':
  24532. // default is start
  24533. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  24534. var stepPt2 = [];
  24535. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  24536. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  24537. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  24538. stepPoints.push(stepPt);
  24539. stepPoints.push(stepPt2);
  24540. break;
  24541. default:
  24542. stepPt[baseIndex] = pt[baseIndex];
  24543. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  24544. // default is start
  24545. stepPoints.push(stepPt);
  24546. }
  24547. }
  24548. // Last points
  24549. points[i] && stepPoints.push(points[i]);
  24550. return stepPoints;
  24551. }
  24552. function getVisualGradient(data, coordSys) {
  24553. var visualMetaList = data.getVisual('visualMeta');
  24554. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  24555. // When data.count() is 0, gradient range can not be calculated.
  24556. return;
  24557. }
  24558. var visualMeta;
  24559. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  24560. // Can only be x or y
  24561. if (visualMetaList[i].dimension < 2) {
  24562. visualMeta = visualMetaList[i];
  24563. break;
  24564. }
  24565. }
  24566. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  24567. if (__DEV__) {
  24568. console.warn('Visual map on line style only support x or y dimension.');
  24569. }
  24570. return;
  24571. }
  24572. // If the area to be rendered is bigger than area defined by LinearGradient,
  24573. // the canvas spec prescribes that the color of the first stop and the last
  24574. // stop should be used. But if two stops are added at offset 0, in effect
  24575. // browsers use the color of the second stop to render area outside
  24576. // LinearGradient. So we can only infinitesimally extend area defined in
  24577. // LinearGradient to render `outerColors`.
  24578. var dimension = visualMeta.dimension;
  24579. var dimName = data.dimensions[dimension];
  24580. var axis = coordSys.getAxis(dimName);
  24581. // dataToCoor mapping may not be linear, but must be monotonic.
  24582. var colorStops = map(visualMeta.stops, function (stop) {
  24583. return {
  24584. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  24585. color: stop.color
  24586. };
  24587. });
  24588. var stopLen = colorStops.length;
  24589. var outerColors = visualMeta.outerColors.slice();
  24590. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  24591. colorStops.reverse();
  24592. outerColors.reverse();
  24593. }
  24594. var tinyExtent = 10; // Arbitrary value: 10px
  24595. var minCoord = colorStops[0].coord - tinyExtent;
  24596. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  24597. var coordSpan = maxCoord - minCoord;
  24598. if (coordSpan < 1e-3) {
  24599. return 'transparent';
  24600. }
  24601. each$1(colorStops, function (stop) {
  24602. stop.offset = (stop.coord - minCoord) / coordSpan;
  24603. });
  24604. colorStops.push({
  24605. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  24606. color: outerColors[1] || 'transparent'
  24607. });
  24608. colorStops.unshift({ // notice colorStops.length have been changed.
  24609. offset: stopLen ? colorStops[0].offset : 0.5,
  24610. color: outerColors[0] || 'transparent'
  24611. });
  24612. // zrUtil.each(colorStops, function (colorStop) {
  24613. // // Make sure each offset has rounded px to avoid not sharp edge
  24614. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  24615. // });
  24616. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  24617. gradient[dimName] = minCoord;
  24618. gradient[dimName + '2'] = maxCoord;
  24619. return gradient;
  24620. }
  24621. Chart.extend({
  24622. type: 'line',
  24623. init: function () {
  24624. var lineGroup = new Group();
  24625. var symbolDraw = new SymbolDraw();
  24626. this.group.add(symbolDraw.group);
  24627. this._symbolDraw = symbolDraw;
  24628. this._lineGroup = lineGroup;
  24629. },
  24630. render: function (seriesModel, ecModel, api) {
  24631. var coordSys = seriesModel.coordinateSystem;
  24632. var group = this.group;
  24633. var data = seriesModel.getData();
  24634. var lineStyleModel = seriesModel.getModel('lineStyle.normal');
  24635. var areaStyleModel = seriesModel.getModel('areaStyle.normal');
  24636. var points = data.mapArray(data.getItemLayout, true);
  24637. var isCoordSysPolar = coordSys.type === 'polar';
  24638. var prevCoordSys = this._coordSys;
  24639. var symbolDraw = this._symbolDraw;
  24640. var polyline = this._polyline;
  24641. var polygon = this._polygon;
  24642. var lineGroup = this._lineGroup;
  24643. var hasAnimation = seriesModel.get('animation');
  24644. var isAreaChart = !areaStyleModel.isEmpty();
  24645. var stackedOnPoints = getStackedOnPoints(coordSys, data);
  24646. var showSymbol = seriesModel.get('showSymbol');
  24647. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  24648. && this._getSymbolIgnoreFunc(data, coordSys);
  24649. // Remove temporary symbols
  24650. var oldData = this._data;
  24651. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  24652. if (el.__temp) {
  24653. group.remove(el);
  24654. oldData.setItemGraphicEl(idx, null);
  24655. }
  24656. });
  24657. // Remove previous created symbols if showSymbol changed to false
  24658. if (!showSymbol) {
  24659. symbolDraw.remove();
  24660. }
  24661. group.add(lineGroup);
  24662. // FIXME step not support polar
  24663. var step = !isCoordSysPolar && seriesModel.get('step');
  24664. // Initialization animation or coordinate system changed
  24665. if (
  24666. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  24667. ) {
  24668. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  24669. if (step) {
  24670. // TODO If stacked series is not step
  24671. points = turnPointsIntoStep(points, coordSys, step);
  24672. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  24673. }
  24674. polyline = this._newPolyline(points, coordSys, hasAnimation);
  24675. if (isAreaChart) {
  24676. polygon = this._newPolygon(
  24677. points, stackedOnPoints,
  24678. coordSys, hasAnimation
  24679. );
  24680. }
  24681. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  24682. }
  24683. else {
  24684. if (isAreaChart && !polygon) {
  24685. // If areaStyle is added
  24686. polygon = this._newPolygon(
  24687. points, stackedOnPoints,
  24688. coordSys, hasAnimation
  24689. );
  24690. }
  24691. else if (polygon && !isAreaChart) {
  24692. // If areaStyle is removed
  24693. lineGroup.remove(polygon);
  24694. polygon = this._polygon = null;
  24695. }
  24696. // Update clipPath
  24697. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  24698. // Always update, or it is wrong in the case turning on legend
  24699. // because points are not changed
  24700. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  24701. // Stop symbol animation and sync with line points
  24702. // FIXME performance?
  24703. data.eachItemGraphicEl(function (el) {
  24704. el.stopAnimation(true);
  24705. });
  24706. // In the case data zoom triggerred refreshing frequently
  24707. // Data may not change if line has a category axis. So it should animate nothing
  24708. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  24709. || !isPointsSame(this._points, points)
  24710. ) {
  24711. if (hasAnimation) {
  24712. this._updateAnimation(
  24713. data, stackedOnPoints, coordSys, api, step
  24714. );
  24715. }
  24716. else {
  24717. // Not do it in update with animation
  24718. if (step) {
  24719. // TODO If stacked series is not step
  24720. points = turnPointsIntoStep(points, coordSys, step);
  24721. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  24722. }
  24723. polyline.setShape({
  24724. points: points
  24725. });
  24726. polygon && polygon.setShape({
  24727. points: points,
  24728. stackedOnPoints: stackedOnPoints
  24729. });
  24730. }
  24731. }
  24732. }
  24733. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  24734. polyline.useStyle(defaults(
  24735. // Use color in lineStyle first
  24736. lineStyleModel.getLineStyle(),
  24737. {
  24738. fill: 'none',
  24739. stroke: visualColor,
  24740. lineJoin: 'bevel'
  24741. }
  24742. ));
  24743. var smooth = seriesModel.get('smooth');
  24744. smooth = getSmooth(seriesModel.get('smooth'));
  24745. polyline.setShape({
  24746. smooth: smooth,
  24747. smoothMonotone: seriesModel.get('smoothMonotone'),
  24748. connectNulls: seriesModel.get('connectNulls')
  24749. });
  24750. if (polygon) {
  24751. var stackedOn = data.stackedOn;
  24752. var stackedOnSmooth = 0;
  24753. polygon.useStyle(defaults(
  24754. areaStyleModel.getAreaStyle(),
  24755. {
  24756. fill: visualColor,
  24757. opacity: 0.7,
  24758. lineJoin: 'bevel'
  24759. }
  24760. ));
  24761. if (stackedOn) {
  24762. var stackedOnSeries = stackedOn.hostModel;
  24763. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  24764. }
  24765. polygon.setShape({
  24766. smooth: smooth,
  24767. stackedOnSmooth: stackedOnSmooth,
  24768. smoothMonotone: seriesModel.get('smoothMonotone'),
  24769. connectNulls: seriesModel.get('connectNulls')
  24770. });
  24771. }
  24772. this._data = data;
  24773. // Save the coordinate system for transition animation when data changed
  24774. this._coordSys = coordSys;
  24775. this._stackedOnPoints = stackedOnPoints;
  24776. this._points = points;
  24777. this._step = step;
  24778. },
  24779. dispose: function () {},
  24780. highlight: function (seriesModel, ecModel, api, payload) {
  24781. var data = seriesModel.getData();
  24782. var dataIndex = queryDataIndex(data, payload);
  24783. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  24784. var symbol = data.getItemGraphicEl(dataIndex);
  24785. if (!symbol) {
  24786. // Create a temporary symbol if it is not exists
  24787. var pt = data.getItemLayout(dataIndex);
  24788. if (!pt) {
  24789. // Null data
  24790. return;
  24791. }
  24792. symbol = new SymbolClz$1(data, dataIndex);
  24793. symbol.position = pt;
  24794. symbol.setZ(
  24795. seriesModel.get('zlevel'),
  24796. seriesModel.get('z')
  24797. );
  24798. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  24799. symbol.__temp = true;
  24800. data.setItemGraphicEl(dataIndex, symbol);
  24801. // Stop scale animation
  24802. symbol.stopSymbolAnimation(true);
  24803. this.group.add(symbol);
  24804. }
  24805. symbol.highlight();
  24806. }
  24807. else {
  24808. // Highlight whole series
  24809. Chart.prototype.highlight.call(
  24810. this, seriesModel, ecModel, api, payload
  24811. );
  24812. }
  24813. },
  24814. downplay: function (seriesModel, ecModel, api, payload) {
  24815. var data = seriesModel.getData();
  24816. var dataIndex = queryDataIndex(data, payload);
  24817. if (dataIndex != null && dataIndex >= 0) {
  24818. var symbol = data.getItemGraphicEl(dataIndex);
  24819. if (symbol) {
  24820. if (symbol.__temp) {
  24821. data.setItemGraphicEl(dataIndex, null);
  24822. this.group.remove(symbol);
  24823. }
  24824. else {
  24825. symbol.downplay();
  24826. }
  24827. }
  24828. }
  24829. else {
  24830. // FIXME
  24831. // can not downplay completely.
  24832. // Downplay whole series
  24833. Chart.prototype.downplay.call(
  24834. this, seriesModel, ecModel, api, payload
  24835. );
  24836. }
  24837. },
  24838. /**
  24839. * @param {module:zrender/container/Group} group
  24840. * @param {Array.<Array.<number>>} points
  24841. * @private
  24842. */
  24843. _newPolyline: function (points) {
  24844. var polyline = this._polyline;
  24845. // Remove previous created polyline
  24846. if (polyline) {
  24847. this._lineGroup.remove(polyline);
  24848. }
  24849. polyline = new Polyline$1({
  24850. shape: {
  24851. points: points
  24852. },
  24853. silent: true,
  24854. z2: 10
  24855. });
  24856. this._lineGroup.add(polyline);
  24857. this._polyline = polyline;
  24858. return polyline;
  24859. },
  24860. /**
  24861. * @param {module:zrender/container/Group} group
  24862. * @param {Array.<Array.<number>>} stackedOnPoints
  24863. * @param {Array.<Array.<number>>} points
  24864. * @private
  24865. */
  24866. _newPolygon: function (points, stackedOnPoints) {
  24867. var polygon = this._polygon;
  24868. // Remove previous created polygon
  24869. if (polygon) {
  24870. this._lineGroup.remove(polygon);
  24871. }
  24872. polygon = new Polygon$1({
  24873. shape: {
  24874. points: points,
  24875. stackedOnPoints: stackedOnPoints
  24876. },
  24877. silent: true
  24878. });
  24879. this._lineGroup.add(polygon);
  24880. this._polygon = polygon;
  24881. return polygon;
  24882. },
  24883. /**
  24884. * @private
  24885. */
  24886. _getSymbolIgnoreFunc: function (data, coordSys) {
  24887. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  24888. // `getLabelInterval` is provided by echarts/component/axis
  24889. if (categoryAxis && categoryAxis.isLabelIgnored) {
  24890. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  24891. }
  24892. },
  24893. /**
  24894. * @private
  24895. */
  24896. // FIXME Two value axis
  24897. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  24898. var polyline = this._polyline;
  24899. var polygon = this._polygon;
  24900. var seriesModel = data.hostModel;
  24901. var diff = lineAnimationDiff(
  24902. this._data, data,
  24903. this._stackedOnPoints, stackedOnPoints,
  24904. this._coordSys, coordSys
  24905. );
  24906. var current = diff.current;
  24907. var stackedOnCurrent = diff.stackedOnCurrent;
  24908. var next = diff.next;
  24909. var stackedOnNext = diff.stackedOnNext;
  24910. if (step) {
  24911. // TODO If stacked series is not step
  24912. current = turnPointsIntoStep(diff.current, coordSys, step);
  24913. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  24914. next = turnPointsIntoStep(diff.next, coordSys, step);
  24915. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  24916. }
  24917. // `diff.current` is subset of `current` (which should be ensured by
  24918. // turnPointsIntoStep), so points in `__points` can be updated when
  24919. // points in `current` are update during animation.
  24920. polyline.shape.__points = diff.current;
  24921. polyline.shape.points = current;
  24922. updateProps(polyline, {
  24923. shape: {
  24924. points: next
  24925. }
  24926. }, seriesModel);
  24927. if (polygon) {
  24928. polygon.setShape({
  24929. points: current,
  24930. stackedOnPoints: stackedOnCurrent
  24931. });
  24932. updateProps(polygon, {
  24933. shape: {
  24934. points: next,
  24935. stackedOnPoints: stackedOnNext
  24936. }
  24937. }, seriesModel);
  24938. }
  24939. var updatedDataInfo = [];
  24940. var diffStatus = diff.status;
  24941. for (var i = 0; i < diffStatus.length; i++) {
  24942. var cmd = diffStatus[i].cmd;
  24943. if (cmd === '=') {
  24944. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  24945. if (el) {
  24946. updatedDataInfo.push({
  24947. el: el,
  24948. ptIdx: i // Index of points
  24949. });
  24950. }
  24951. }
  24952. }
  24953. if (polyline.animators && polyline.animators.length) {
  24954. polyline.animators[0].during(function () {
  24955. for (var i = 0; i < updatedDataInfo.length; i++) {
  24956. var el = updatedDataInfo[i].el;
  24957. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  24958. }
  24959. });
  24960. }
  24961. },
  24962. remove: function (ecModel) {
  24963. var group = this.group;
  24964. var oldData = this._data;
  24965. this._lineGroup.removeAll();
  24966. this._symbolDraw.remove(true);
  24967. // Remove temporary created elements when highlighting
  24968. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  24969. if (el.__temp) {
  24970. group.remove(el);
  24971. oldData.setItemGraphicEl(idx, null);
  24972. }
  24973. });
  24974. this._polyline =
  24975. this._polygon =
  24976. this._coordSys =
  24977. this._points =
  24978. this._stackedOnPoints =
  24979. this._data = null;
  24980. }
  24981. });
  24982. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol, ecModel, api) {
  24983. // Encoding visual for all series include which is filtered for legend drawing
  24984. ecModel.eachRawSeriesByType(seriesType, function (seriesModel) {
  24985. var data = seriesModel.getData();
  24986. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  24987. var symbolSize = seriesModel.get('symbolSize');
  24988. data.setVisual({
  24989. legendSymbol: legendSymbol || symbolType,
  24990. symbol: symbolType,
  24991. symbolSize: symbolSize
  24992. });
  24993. // Only visible series has each data be visual encoded
  24994. if (!ecModel.isSeriesFiltered(seriesModel)) {
  24995. if (typeof symbolSize === 'function') {
  24996. data.each(function (idx) {
  24997. var rawValue = seriesModel.getRawValue(idx);
  24998. // FIXME
  24999. var params = seriesModel.getDataParams(idx);
  25000. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  25001. });
  25002. }
  25003. data.each(function (idx) {
  25004. var itemModel = data.getItemModel(idx);
  25005. var itemSymbolType = itemModel.getShallow('symbol', true);
  25006. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  25007. // If has item symbol
  25008. if (itemSymbolType != null) {
  25009. data.setItemVisual(idx, 'symbol', itemSymbolType);
  25010. }
  25011. if (itemSymbolSize != null) {
  25012. // PENDING Transform symbolSize ?
  25013. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  25014. }
  25015. });
  25016. }
  25017. });
  25018. };
  25019. var layoutPoints = function (seriesType, ecModel) {
  25020. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25021. var data = seriesModel.getData();
  25022. var coordSys = seriesModel.coordinateSystem;
  25023. if (!coordSys) {
  25024. return;
  25025. }
  25026. var dims = [];
  25027. var coordDims = coordSys.dimensions;
  25028. for (var i = 0; i < coordDims.length; i++) {
  25029. dims.push(seriesModel.coordDimToDataDim(coordSys.dimensions[i])[0]);
  25030. }
  25031. if (dims.length === 1) {
  25032. data.each(dims[0], function (x, idx) {
  25033. // Also {Array.<number>}, not undefined to avoid if...else... statement
  25034. data.setItemLayout(idx, isNaN(x) ? [NaN, NaN] : coordSys.dataToPoint(x));
  25035. });
  25036. }
  25037. else if (dims.length === 2) {
  25038. data.each(dims, function (x, y, idx) {
  25039. // Also {Array.<number>}, not undefined to avoid if...else... statement
  25040. data.setItemLayout(
  25041. idx, (isNaN(x) || isNaN(y)) ? [NaN, NaN] : coordSys.dataToPoint([x, y])
  25042. );
  25043. }, true);
  25044. }
  25045. });
  25046. };
  25047. var samplers = {
  25048. average: function (frame) {
  25049. var sum = 0;
  25050. var count = 0;
  25051. for (var i = 0; i < frame.length; i++) {
  25052. if (!isNaN(frame[i])) {
  25053. sum += frame[i];
  25054. count++;
  25055. }
  25056. }
  25057. // Return NaN if count is 0
  25058. return count === 0 ? NaN : sum / count;
  25059. },
  25060. sum: function (frame) {
  25061. var sum = 0;
  25062. for (var i = 0; i < frame.length; i++) {
  25063. // Ignore NaN
  25064. sum += frame[i] || 0;
  25065. }
  25066. return sum;
  25067. },
  25068. max: function (frame) {
  25069. var max = -Infinity;
  25070. for (var i = 0; i < frame.length; i++) {
  25071. frame[i] > max && (max = frame[i]);
  25072. }
  25073. return max;
  25074. },
  25075. min: function (frame) {
  25076. var min = Infinity;
  25077. for (var i = 0; i < frame.length; i++) {
  25078. frame[i] < min && (min = frame[i]);
  25079. }
  25080. return min;
  25081. },
  25082. // TODO
  25083. // Median
  25084. nearest: function (frame) {
  25085. return frame[0];
  25086. }
  25087. };
  25088. var indexSampler = function (frame, value) {
  25089. return Math.round(frame.length / 2);
  25090. };
  25091. var dataSample = function (seriesType, ecModel, api) {
  25092. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25093. var data = seriesModel.getData();
  25094. var sampling = seriesModel.get('sampling');
  25095. var coordSys = seriesModel.coordinateSystem;
  25096. // Only cartesian2d support down sampling
  25097. if (coordSys.type === 'cartesian2d' && sampling) {
  25098. var baseAxis = coordSys.getBaseAxis();
  25099. var valueAxis = coordSys.getOtherAxis(baseAxis);
  25100. var extent = baseAxis.getExtent();
  25101. // Coordinste system has been resized
  25102. var size = extent[1] - extent[0];
  25103. var rate = Math.round(data.count() / size);
  25104. if (rate > 1) {
  25105. var sampler;
  25106. if (typeof sampling === 'string') {
  25107. sampler = samplers[sampling];
  25108. }
  25109. else if (typeof sampling === 'function') {
  25110. sampler = sampling;
  25111. }
  25112. if (sampler) {
  25113. data = data.downSample(
  25114. valueAxis.dim, 1 / rate, sampler, indexSampler
  25115. );
  25116. seriesModel.setData(data);
  25117. }
  25118. }
  25119. }
  25120. }, this);
  25121. };
  25122. /**
  25123. * Cartesian coordinate system
  25124. * @module echarts/coord/Cartesian
  25125. *
  25126. */
  25127. function dimAxisMapper(dim) {
  25128. return this._axes[dim];
  25129. }
  25130. /**
  25131. * @alias module:echarts/coord/Cartesian
  25132. * @constructor
  25133. */
  25134. var Cartesian = function (name) {
  25135. this._axes = {};
  25136. this._dimList = [];
  25137. /**
  25138. * @type {string}
  25139. */
  25140. this.name = name || '';
  25141. };
  25142. Cartesian.prototype = {
  25143. constructor: Cartesian,
  25144. type: 'cartesian',
  25145. /**
  25146. * Get axis
  25147. * @param {number|string} dim
  25148. * @return {module:echarts/coord/Cartesian~Axis}
  25149. */
  25150. getAxis: function (dim) {
  25151. return this._axes[dim];
  25152. },
  25153. /**
  25154. * Get axes list
  25155. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  25156. */
  25157. getAxes: function () {
  25158. return map(this._dimList, dimAxisMapper, this);
  25159. },
  25160. /**
  25161. * Get axes list by given scale type
  25162. */
  25163. getAxesByScale: function (scaleType) {
  25164. scaleType = scaleType.toLowerCase();
  25165. return filter(
  25166. this.getAxes(),
  25167. function (axis) {
  25168. return axis.scale.type === scaleType;
  25169. }
  25170. );
  25171. },
  25172. /**
  25173. * Add axis
  25174. * @param {module:echarts/coord/Cartesian.Axis}
  25175. */
  25176. addAxis: function (axis) {
  25177. var dim = axis.dim;
  25178. this._axes[dim] = axis;
  25179. this._dimList.push(dim);
  25180. },
  25181. /**
  25182. * Convert data to coord in nd space
  25183. * @param {Array.<number>|Object.<string, number>} val
  25184. * @return {Array.<number>|Object.<string, number>}
  25185. */
  25186. dataToCoord: function (val) {
  25187. return this._dataCoordConvert(val, 'dataToCoord');
  25188. },
  25189. /**
  25190. * Convert coord in nd space to data
  25191. * @param {Array.<number>|Object.<string, number>} val
  25192. * @return {Array.<number>|Object.<string, number>}
  25193. */
  25194. coordToData: function (val) {
  25195. return this._dataCoordConvert(val, 'coordToData');
  25196. },
  25197. _dataCoordConvert: function (input, method) {
  25198. var dimList = this._dimList;
  25199. var output = input instanceof Array ? [] : {};
  25200. for (var i = 0; i < dimList.length; i++) {
  25201. var dim = dimList[i];
  25202. var axis = this._axes[dim];
  25203. output[dim] = axis[method](input[dim]);
  25204. }
  25205. return output;
  25206. }
  25207. };
  25208. function Cartesian2D(name) {
  25209. Cartesian.call(this, name);
  25210. }
  25211. Cartesian2D.prototype = {
  25212. constructor: Cartesian2D,
  25213. type: 'cartesian2d',
  25214. /**
  25215. * @type {Array.<string>}
  25216. * @readOnly
  25217. */
  25218. dimensions: ['x', 'y'],
  25219. /**
  25220. * Base axis will be used on stacking.
  25221. *
  25222. * @return {module:echarts/coord/cartesian/Axis2D}
  25223. */
  25224. getBaseAxis: function () {
  25225. return this.getAxesByScale('ordinal')[0]
  25226. || this.getAxesByScale('time')[0]
  25227. || this.getAxis('x');
  25228. },
  25229. /**
  25230. * If contain point
  25231. * @param {Array.<number>} point
  25232. * @return {boolean}
  25233. */
  25234. containPoint: function (point) {
  25235. var axisX = this.getAxis('x');
  25236. var axisY = this.getAxis('y');
  25237. return axisX.contain(axisX.toLocalCoord(point[0]))
  25238. && axisY.contain(axisY.toLocalCoord(point[1]));
  25239. },
  25240. /**
  25241. * If contain data
  25242. * @param {Array.<number>} data
  25243. * @return {boolean}
  25244. */
  25245. containData: function (data) {
  25246. return this.getAxis('x').containData(data[0])
  25247. && this.getAxis('y').containData(data[1]);
  25248. },
  25249. /**
  25250. * @param {Array.<number>} data
  25251. * @param {boolean} [clamp=false]
  25252. * @return {Array.<number>}
  25253. */
  25254. dataToPoint: function (data, clamp) {
  25255. var xAxis = this.getAxis('x');
  25256. var yAxis = this.getAxis('y');
  25257. return [
  25258. xAxis.toGlobalCoord(xAxis.dataToCoord(data[0], clamp)),
  25259. yAxis.toGlobalCoord(yAxis.dataToCoord(data[1], clamp))
  25260. ];
  25261. },
  25262. /**
  25263. * @param {Array.<number>} point
  25264. * @param {boolean} [clamp=false]
  25265. * @return {Array.<number>}
  25266. */
  25267. pointToData: function (point, clamp) {
  25268. var xAxis = this.getAxis('x');
  25269. var yAxis = this.getAxis('y');
  25270. return [
  25271. xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp),
  25272. yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp)
  25273. ];
  25274. },
  25275. /**
  25276. * Get other axis
  25277. * @param {module:echarts/coord/cartesian/Axis2D} axis
  25278. */
  25279. getOtherAxis: function (axis) {
  25280. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  25281. }
  25282. };
  25283. inherits(Cartesian2D, Cartesian);
  25284. /**
  25285. * Extend axis 2d
  25286. * @constructor module:echarts/coord/cartesian/Axis2D
  25287. * @extends {module:echarts/coord/cartesian/Axis}
  25288. * @param {string} dim
  25289. * @param {*} scale
  25290. * @param {Array.<number>} coordExtent
  25291. * @param {string} axisType
  25292. * @param {string} position
  25293. */
  25294. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  25295. Axis.call(this, dim, scale, coordExtent);
  25296. /**
  25297. * Axis type
  25298. * - 'category'
  25299. * - 'value'
  25300. * - 'time'
  25301. * - 'log'
  25302. * @type {string}
  25303. */
  25304. this.type = axisType || 'value';
  25305. /**
  25306. * Axis position
  25307. * - 'top'
  25308. * - 'bottom'
  25309. * - 'left'
  25310. * - 'right'
  25311. */
  25312. this.position = position || 'bottom';
  25313. };
  25314. Axis2D.prototype = {
  25315. constructor: Axis2D,
  25316. /**
  25317. * Index of axis, can be used as key
  25318. */
  25319. index: 0,
  25320. /**
  25321. * If axis is on the zero position of the other axis
  25322. * @type {boolean}
  25323. */
  25324. onZero: false,
  25325. /**
  25326. * Axis model
  25327. * @param {module:echarts/coord/cartesian/AxisModel}
  25328. */
  25329. model: null,
  25330. isHorizontal: function () {
  25331. var position = this.position;
  25332. return position === 'top' || position === 'bottom';
  25333. },
  25334. /**
  25335. * Each item cooresponds to this.getExtent(), which
  25336. * means globalExtent[0] may greater than globalExtent[1],
  25337. * unless `asc` is input.
  25338. *
  25339. * @param {boolean} [asc]
  25340. * @return {Array.<number>}
  25341. */
  25342. getGlobalExtent: function (asc) {
  25343. var ret = this.getExtent();
  25344. ret[0] = this.toGlobalCoord(ret[0]);
  25345. ret[1] = this.toGlobalCoord(ret[1]);
  25346. asc && ret[0] > ret[1] && ret.reverse();
  25347. return ret;
  25348. },
  25349. getOtherAxis: function () {
  25350. this.grid.getOtherAxis();
  25351. },
  25352. /**
  25353. * If label is ignored.
  25354. * Automatically used when axis is category and label can not be all shown
  25355. * @param {number} idx
  25356. * @return {boolean}
  25357. */
  25358. isLabelIgnored: function (idx) {
  25359. if (this.type === 'category') {
  25360. var labelInterval = this.getLabelInterval();
  25361. return ((typeof labelInterval === 'function')
  25362. && !labelInterval(idx, this.scale.getLabel(idx)))
  25363. || idx % (labelInterval + 1);
  25364. }
  25365. },
  25366. /**
  25367. * @override
  25368. */
  25369. pointToData: function (point, clamp) {
  25370. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  25371. },
  25372. /**
  25373. * Transform global coord to local coord,
  25374. * i.e. var localCoord = axis.toLocalCoord(80);
  25375. * designate by module:echarts/coord/cartesian/Grid.
  25376. * @type {Function}
  25377. */
  25378. toLocalCoord: null,
  25379. /**
  25380. * Transform global coord to local coord,
  25381. * i.e. var globalCoord = axis.toLocalCoord(40);
  25382. * designate by module:echarts/coord/cartesian/Grid.
  25383. * @type {Function}
  25384. */
  25385. toGlobalCoord: null
  25386. };
  25387. inherits(Axis2D, Axis);
  25388. var defaultOption = {
  25389. show: true,
  25390. zlevel: 0, // 一级层叠
  25391. z: 0, // 二级层叠
  25392. // 反向坐标轴
  25393. inverse: false,
  25394. // 坐标轴名字,默认为空
  25395. name: '',
  25396. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  25397. nameLocation: 'end',
  25398. // 坐标轴名字旋转,degree。
  25399. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  25400. nameTruncate: {
  25401. maxWidth: null,
  25402. ellipsis: '...',
  25403. placeholder: '.'
  25404. },
  25405. // 坐标轴文字样式,默认取全局样式
  25406. nameTextStyle: {},
  25407. // 文字与轴线距离
  25408. nameGap: 15,
  25409. silent: false, // Default false to support tooltip.
  25410. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  25411. tooltip: {
  25412. show: false
  25413. },
  25414. axisPointer: {},
  25415. // 坐标轴线
  25416. axisLine: {
  25417. // 默认显示,属性show控制显示与否
  25418. show: true,
  25419. onZero: true,
  25420. onZeroAxisIndex: null,
  25421. // 属性lineStyle控制线条样式
  25422. lineStyle: {
  25423. color: '#333',
  25424. width: 1,
  25425. type: 'solid'
  25426. },
  25427. // 坐标轴两端的箭头
  25428. symbol: ['none', 'none'],
  25429. symbolSize: [10, 15]
  25430. },
  25431. // 坐标轴小标记
  25432. axisTick: {
  25433. // 属性show控制显示与否,默认显示
  25434. show: true,
  25435. // 控制小标记是否在grid里
  25436. inside: false,
  25437. // 属性length控制线长
  25438. length: 5,
  25439. // 属性lineStyle控制线条样式
  25440. lineStyle: {
  25441. width: 1
  25442. }
  25443. },
  25444. // 坐标轴文本标签,详见axis.axisLabel
  25445. axisLabel: {
  25446. show: true,
  25447. // 控制文本标签是否在grid里
  25448. inside: false,
  25449. rotate: 0,
  25450. showMinLabel: null, // true | false | null (auto)
  25451. showMaxLabel: null, // true | false | null (auto)
  25452. margin: 8,
  25453. // formatter: null,
  25454. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  25455. fontSize: 12
  25456. },
  25457. // 分隔线
  25458. splitLine: {
  25459. // 默认显示,属性show控制显示与否
  25460. show: true,
  25461. // 属性lineStyle(详见lineStyle)控制线条样式
  25462. lineStyle: {
  25463. color: ['#ccc'],
  25464. width: 1,
  25465. type: 'solid'
  25466. }
  25467. },
  25468. // 分隔区域
  25469. splitArea: {
  25470. // 默认不显示,属性show控制显示与否
  25471. show: false,
  25472. // 属性areaStyle(详见areaStyle)控制区域样式
  25473. areaStyle: {
  25474. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  25475. }
  25476. }
  25477. };
  25478. var axisDefault = {};
  25479. axisDefault.categoryAxis = merge({
  25480. // 类目起始和结束两端空白策略
  25481. boundaryGap: true,
  25482. // splitArea: {
  25483. // show: false
  25484. // },
  25485. splitLine: {
  25486. show: false
  25487. },
  25488. // 坐标轴小标记
  25489. axisTick: {
  25490. // If tick is align with label when boundaryGap is true
  25491. alignWithLabel: false,
  25492. interval: 'auto'
  25493. },
  25494. // 坐标轴文本标签,详见axis.axisLabel
  25495. axisLabel: {
  25496. interval: 'auto'
  25497. }
  25498. }, defaultOption);
  25499. axisDefault.valueAxis = merge({
  25500. // 数值起始和结束两端空白策略
  25501. boundaryGap: [0, 0],
  25502. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  25503. // min: null,
  25504. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  25505. // max: null,
  25506. // Readonly prop, specifies start value of the range when using data zoom.
  25507. // rangeStart: null
  25508. // Readonly prop, specifies end value of the range when using data zoom.
  25509. // rangeEnd: null
  25510. // 脱离0值比例,放大聚焦到最终_min,_max区间
  25511. // scale: false,
  25512. // 分割段数,默认为5
  25513. splitNumber: 5
  25514. // Minimum interval
  25515. // minInterval: null
  25516. // maxInterval: null
  25517. }, defaultOption);
  25518. // FIXME
  25519. axisDefault.timeAxis = defaults({
  25520. scale: true,
  25521. min: 'dataMin',
  25522. max: 'dataMax'
  25523. }, axisDefault.valueAxis);
  25524. axisDefault.logAxis = defaults({
  25525. scale: true,
  25526. logBase: 10
  25527. }, axisDefault.valueAxis);
  25528. // FIXME axisType is fixed ?
  25529. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  25530. /**
  25531. * Generate sub axis model class
  25532. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  25533. * @param {module:echarts/model/Component} BaseAxisModelClass
  25534. * @param {Function} axisTypeDefaulter
  25535. * @param {Object} [extraDefaultOption]
  25536. */
  25537. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  25538. each$1(AXIS_TYPES, function (axisType) {
  25539. BaseAxisModelClass.extend({
  25540. type: axisName + 'Axis.' + axisType,
  25541. mergeDefaultAndTheme: function (option, ecModel) {
  25542. var layoutMode = this.layoutMode;
  25543. var inputPositionParams = layoutMode
  25544. ? getLayoutParams(option) : {};
  25545. var themeModel = ecModel.getTheme();
  25546. merge(option, themeModel.get(axisType + 'Axis'));
  25547. merge(option, this.getDefaultOption());
  25548. option.type = axisTypeDefaulter(axisName, option);
  25549. if (layoutMode) {
  25550. mergeLayoutParam(option, inputPositionParams, layoutMode);
  25551. }
  25552. },
  25553. defaultOption: mergeAll(
  25554. [
  25555. {},
  25556. axisDefault[axisType + 'Axis'],
  25557. extraDefaultOption
  25558. ],
  25559. true
  25560. )
  25561. });
  25562. });
  25563. ComponentModel.registerSubTypeDefaulter(
  25564. axisName + 'Axis',
  25565. curry(axisTypeDefaulter, axisName)
  25566. );
  25567. };
  25568. var AxisModel = ComponentModel.extend({
  25569. type: 'cartesian2dAxis',
  25570. /**
  25571. * @type {module:echarts/coord/cartesian/Axis2D}
  25572. */
  25573. axis: null,
  25574. /**
  25575. * @override
  25576. */
  25577. init: function () {
  25578. AxisModel.superApply(this, 'init', arguments);
  25579. this.resetRange();
  25580. },
  25581. /**
  25582. * @override
  25583. */
  25584. mergeOption: function () {
  25585. AxisModel.superApply(this, 'mergeOption', arguments);
  25586. this.resetRange();
  25587. },
  25588. /**
  25589. * @override
  25590. */
  25591. restoreData: function () {
  25592. AxisModel.superApply(this, 'restoreData', arguments);
  25593. this.resetRange();
  25594. },
  25595. /**
  25596. * @override
  25597. * @return {module:echarts/model/Component}
  25598. */
  25599. getCoordSysModel: function () {
  25600. return this.ecModel.queryComponents({
  25601. mainType: 'grid',
  25602. index: this.option.gridIndex,
  25603. id: this.option.gridId
  25604. })[0];
  25605. }
  25606. });
  25607. function getAxisType(axisDim, option) {
  25608. // Default axis with data is category axis
  25609. return option.type || (option.data ? 'category' : 'value');
  25610. }
  25611. merge(AxisModel.prototype, axisModelCommonMixin);
  25612. var extraOption = {
  25613. // gridIndex: 0,
  25614. // gridId: '',
  25615. // Offset is for multiple axis on the same position
  25616. offset: 0
  25617. };
  25618. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  25619. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  25620. // Grid 是在有直角坐标系的时候必须要存在的
  25621. // 所以这里也要被 Cartesian2D 依赖
  25622. ComponentModel.extend({
  25623. type: 'grid',
  25624. dependencies: ['xAxis', 'yAxis'],
  25625. layoutMode: 'box',
  25626. /**
  25627. * @type {module:echarts/coord/cartesian/Grid}
  25628. */
  25629. coordinateSystem: null,
  25630. defaultOption: {
  25631. show: false,
  25632. zlevel: 0,
  25633. z: 0,
  25634. left: '10%',
  25635. top: 60,
  25636. right: '10%',
  25637. bottom: 60,
  25638. // If grid size contain label
  25639. containLabel: false,
  25640. // width: {totalWidth} - left - right,
  25641. // height: {totalHeight} - top - bottom,
  25642. backgroundColor: 'rgba(0,0,0,0)',
  25643. borderWidth: 1,
  25644. borderColor: '#ccc'
  25645. }
  25646. });
  25647. /**
  25648. * Grid is a region which contains at most 4 cartesian systems
  25649. *
  25650. * TODO Default cartesian
  25651. */
  25652. // Depends on GridModel, AxisModel, which performs preprocess.
  25653. var each$8 = each$1;
  25654. var ifAxisCrossZero$1 = ifAxisCrossZero;
  25655. var niceScaleExtent$1 = niceScaleExtent;
  25656. /**
  25657. * Check if the axis is used in the specified grid
  25658. * @inner
  25659. */
  25660. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  25661. return axisModel.getCoordSysModel() === gridModel;
  25662. }
  25663. function rotateTextRect(textRect, rotate) {
  25664. var rotateRadians = rotate * Math.PI / 180;
  25665. var boundingBox = textRect.plain();
  25666. var beforeWidth = boundingBox.width;
  25667. var beforeHeight = boundingBox.height;
  25668. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  25669. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  25670. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  25671. return rotatedRect;
  25672. }
  25673. function getLabelUnionRect(axis) {
  25674. var axisModel = axis.model;
  25675. var labels = axisModel.getFormattedLabels();
  25676. var axisLabelModel = axisModel.getModel('axisLabel');
  25677. var rect;
  25678. var step = 1;
  25679. var labelCount = labels.length;
  25680. if (labelCount > 40) {
  25681. // Simple optimization for large amount of labels
  25682. step = Math.ceil(labelCount / 40);
  25683. }
  25684. for (var i = 0; i < labelCount; i += step) {
  25685. if (!axis.isLabelIgnored(i)) {
  25686. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  25687. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  25688. rect ? rect.union(singleRect) : (rect = singleRect);
  25689. }
  25690. }
  25691. return rect;
  25692. }
  25693. function Grid(gridModel, ecModel, api) {
  25694. /**
  25695. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  25696. * @private
  25697. */
  25698. this._coordsMap = {};
  25699. /**
  25700. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  25701. * @private
  25702. */
  25703. this._coordsList = [];
  25704. /**
  25705. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  25706. * @private
  25707. */
  25708. this._axesMap = {};
  25709. /**
  25710. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  25711. * @private
  25712. */
  25713. this._axesList = [];
  25714. this._initCartesian(gridModel, ecModel, api);
  25715. this.model = gridModel;
  25716. }
  25717. var gridProto = Grid.prototype;
  25718. gridProto.type = 'grid';
  25719. gridProto.axisPointerEnabled = true;
  25720. gridProto.getRect = function () {
  25721. return this._rect;
  25722. };
  25723. gridProto.update = function (ecModel, api) {
  25724. var axesMap = this._axesMap;
  25725. this._updateScale(ecModel, this.model);
  25726. each$8(axesMap.x, function (xAxis) {
  25727. niceScaleExtent$1(xAxis.scale, xAxis.model);
  25728. });
  25729. each$8(axesMap.y, function (yAxis) {
  25730. niceScaleExtent$1(yAxis.scale, yAxis.model);
  25731. });
  25732. each$8(axesMap.x, function (xAxis) {
  25733. fixAxisOnZero(axesMap, 'y', xAxis);
  25734. });
  25735. each$8(axesMap.y, function (yAxis) {
  25736. fixAxisOnZero(axesMap, 'x', yAxis);
  25737. });
  25738. // Resize again if containLabel is enabled
  25739. // FIXME It may cause getting wrong grid size in data processing stage
  25740. this.resize(this.model, api);
  25741. };
  25742. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  25743. // onZero can not be enabled in these two situations:
  25744. // 1. When any other axis is a category axis.
  25745. // 2. When no axis is cross 0 point.
  25746. var axes = axesMap[otherAxisDim];
  25747. if (!axis.onZero) {
  25748. return;
  25749. }
  25750. var onZeroAxisIndex = axis.onZeroAxisIndex;
  25751. // If target axis is specified.
  25752. if (onZeroAxisIndex != null) {
  25753. var otherAxis = axes[onZeroAxisIndex];
  25754. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  25755. axis.onZero = false;
  25756. }
  25757. return;
  25758. }
  25759. for (var idx in axes) {
  25760. if (axes.hasOwnProperty(idx)) {
  25761. var otherAxis = axes[idx];
  25762. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  25763. onZeroAxisIndex = +idx;
  25764. break;
  25765. }
  25766. }
  25767. }
  25768. if (onZeroAxisIndex == null) {
  25769. axis.onZero = false;
  25770. }
  25771. axis.onZeroAxisIndex = onZeroAxisIndex;
  25772. }
  25773. function canNotOnZeroToAxis(axis) {
  25774. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  25775. }
  25776. /**
  25777. * Resize the grid
  25778. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  25779. * @param {module:echarts/ExtensionAPI} api
  25780. */
  25781. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  25782. var gridRect = getLayoutRect(
  25783. gridModel.getBoxLayoutParams(), {
  25784. width: api.getWidth(),
  25785. height: api.getHeight()
  25786. });
  25787. this._rect = gridRect;
  25788. var axesList = this._axesList;
  25789. adjustAxes();
  25790. // Minus label size
  25791. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  25792. each$8(axesList, function (axis) {
  25793. if (!axis.model.get('axisLabel.inside')) {
  25794. var labelUnionRect = getLabelUnionRect(axis);
  25795. if (labelUnionRect) {
  25796. var dim = axis.isHorizontal() ? 'height' : 'width';
  25797. var margin = axis.model.get('axisLabel.margin');
  25798. gridRect[dim] -= labelUnionRect[dim] + margin;
  25799. if (axis.position === 'top') {
  25800. gridRect.y += labelUnionRect.height + margin;
  25801. }
  25802. else if (axis.position === 'left') {
  25803. gridRect.x += labelUnionRect.width + margin;
  25804. }
  25805. }
  25806. }
  25807. });
  25808. adjustAxes();
  25809. }
  25810. function adjustAxes() {
  25811. each$8(axesList, function (axis) {
  25812. var isHorizontal = axis.isHorizontal();
  25813. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  25814. var idx = axis.inverse ? 1 : 0;
  25815. axis.setExtent(extent[idx], extent[1 - idx]);
  25816. updateAxisTransfrom(axis, isHorizontal ? gridRect.x : gridRect.y);
  25817. });
  25818. }
  25819. };
  25820. /**
  25821. * @param {string} axisType
  25822. * @param {number} [axisIndex]
  25823. */
  25824. gridProto.getAxis = function (axisType, axisIndex) {
  25825. var axesMapOnDim = this._axesMap[axisType];
  25826. if (axesMapOnDim != null) {
  25827. if (axisIndex == null) {
  25828. // Find first axis
  25829. for (var name in axesMapOnDim) {
  25830. if (axesMapOnDim.hasOwnProperty(name)) {
  25831. return axesMapOnDim[name];
  25832. }
  25833. }
  25834. }
  25835. return axesMapOnDim[axisIndex];
  25836. }
  25837. };
  25838. /**
  25839. * @return {Array.<module:echarts/coord/Axis>}
  25840. */
  25841. gridProto.getAxes = function () {
  25842. return this._axesList.slice();
  25843. };
  25844. /**
  25845. * Usage:
  25846. * grid.getCartesian(xAxisIndex, yAxisIndex);
  25847. * grid.getCartesian(xAxisIndex);
  25848. * grid.getCartesian(null, yAxisIndex);
  25849. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  25850. *
  25851. * @param {number|Object} [xAxisIndex]
  25852. * @param {number} [yAxisIndex]
  25853. */
  25854. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  25855. if (xAxisIndex != null && yAxisIndex != null) {
  25856. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  25857. return this._coordsMap[key];
  25858. }
  25859. if (isObject(xAxisIndex)) {
  25860. yAxisIndex = xAxisIndex.yAxisIndex;
  25861. xAxisIndex = xAxisIndex.xAxisIndex;
  25862. }
  25863. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  25864. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  25865. if (coordList[i].getAxis('x').index === xAxisIndex
  25866. || coordList[i].getAxis('y').index === yAxisIndex
  25867. ) {
  25868. return coordList[i];
  25869. }
  25870. }
  25871. };
  25872. gridProto.getCartesians = function () {
  25873. return this._coordsList.slice();
  25874. };
  25875. /**
  25876. * @implements
  25877. * see {module:echarts/CoodinateSystem}
  25878. */
  25879. gridProto.convertToPixel = function (ecModel, finder, value) {
  25880. var target = this._findConvertTarget(ecModel, finder);
  25881. return target.cartesian
  25882. ? target.cartesian.dataToPoint(value)
  25883. : target.axis
  25884. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  25885. : null;
  25886. };
  25887. /**
  25888. * @implements
  25889. * see {module:echarts/CoodinateSystem}
  25890. */
  25891. gridProto.convertFromPixel = function (ecModel, finder, value) {
  25892. var target = this._findConvertTarget(ecModel, finder);
  25893. return target.cartesian
  25894. ? target.cartesian.pointToData(value)
  25895. : target.axis
  25896. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  25897. : null;
  25898. };
  25899. /**
  25900. * @inner
  25901. */
  25902. gridProto._findConvertTarget = function (ecModel, finder) {
  25903. var seriesModel = finder.seriesModel;
  25904. var xAxisModel = finder.xAxisModel
  25905. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  25906. var yAxisModel = finder.yAxisModel
  25907. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  25908. var gridModel = finder.gridModel;
  25909. var coordsList = this._coordsList;
  25910. var cartesian;
  25911. var axis;
  25912. if (seriesModel) {
  25913. cartesian = seriesModel.coordinateSystem;
  25914. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  25915. }
  25916. else if (xAxisModel && yAxisModel) {
  25917. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  25918. }
  25919. else if (xAxisModel) {
  25920. axis = this.getAxis('x', xAxisModel.componentIndex);
  25921. }
  25922. else if (yAxisModel) {
  25923. axis = this.getAxis('y', yAxisModel.componentIndex);
  25924. }
  25925. // Lowest priority.
  25926. else if (gridModel) {
  25927. var grid = gridModel.coordinateSystem;
  25928. if (grid === this) {
  25929. cartesian = this._coordsList[0];
  25930. }
  25931. }
  25932. return {cartesian: cartesian, axis: axis};
  25933. };
  25934. /**
  25935. * @implements
  25936. * see {module:echarts/CoodinateSystem}
  25937. */
  25938. gridProto.containPoint = function (point) {
  25939. var coord = this._coordsList[0];
  25940. if (coord) {
  25941. return coord.containPoint(point);
  25942. }
  25943. };
  25944. /**
  25945. * Initialize cartesian coordinate systems
  25946. * @private
  25947. */
  25948. gridProto._initCartesian = function (gridModel, ecModel, api) {
  25949. var axisPositionUsed = {
  25950. left: false,
  25951. right: false,
  25952. top: false,
  25953. bottom: false
  25954. };
  25955. var axesMap = {
  25956. x: {},
  25957. y: {}
  25958. };
  25959. var axesCount = {
  25960. x: 0,
  25961. y: 0
  25962. };
  25963. /// Create axis
  25964. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  25965. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  25966. if (!axesCount.x || !axesCount.y) {
  25967. // Roll back when there no either x or y axis
  25968. this._axesMap = {};
  25969. this._axesList = [];
  25970. return;
  25971. }
  25972. this._axesMap = axesMap;
  25973. /// Create cartesian2d
  25974. each$8(axesMap.x, function (xAxis, xAxisIndex) {
  25975. each$8(axesMap.y, function (yAxis, yAxisIndex) {
  25976. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  25977. var cartesian = new Cartesian2D(key);
  25978. cartesian.grid = this;
  25979. cartesian.model = gridModel;
  25980. this._coordsMap[key] = cartesian;
  25981. this._coordsList.push(cartesian);
  25982. cartesian.addAxis(xAxis);
  25983. cartesian.addAxis(yAxis);
  25984. }, this);
  25985. }, this);
  25986. function createAxisCreator(axisType) {
  25987. return function (axisModel, idx) {
  25988. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  25989. return;
  25990. }
  25991. var axisPosition = axisModel.get('position');
  25992. if (axisType === 'x') {
  25993. // Fix position
  25994. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  25995. // Default bottom of X
  25996. axisPosition = 'bottom';
  25997. if (axisPositionUsed[axisPosition]) {
  25998. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  25999. }
  26000. }
  26001. }
  26002. else {
  26003. // Fix position
  26004. if (axisPosition !== 'left' && axisPosition !== 'right') {
  26005. // Default left of Y
  26006. axisPosition = 'left';
  26007. if (axisPositionUsed[axisPosition]) {
  26008. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  26009. }
  26010. }
  26011. }
  26012. axisPositionUsed[axisPosition] = true;
  26013. var axis = new Axis2D(
  26014. axisType, createScaleByModel(axisModel),
  26015. [0, 0],
  26016. axisModel.get('type'),
  26017. axisPosition
  26018. );
  26019. var isCategory = axis.type === 'category';
  26020. axis.onBand = isCategory && axisModel.get('boundaryGap');
  26021. axis.inverse = axisModel.get('inverse');
  26022. axis.onZero = axisModel.get('axisLine.onZero');
  26023. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  26024. // Inject axis into axisModel
  26025. axisModel.axis = axis;
  26026. // Inject axisModel into axis
  26027. axis.model = axisModel;
  26028. // Inject grid info axis
  26029. axis.grid = this;
  26030. // Index of axis, can be used as key
  26031. axis.index = idx;
  26032. this._axesList.push(axis);
  26033. axesMap[axisType][idx] = axis;
  26034. axesCount[axisType]++;
  26035. };
  26036. }
  26037. };
  26038. /**
  26039. * Update cartesian properties from series
  26040. * @param {module:echarts/model/Option} option
  26041. * @private
  26042. */
  26043. gridProto._updateScale = function (ecModel, gridModel) {
  26044. // Reset scale
  26045. each$1(this._axesList, function (axis) {
  26046. axis.scale.setExtent(Infinity, -Infinity);
  26047. });
  26048. ecModel.eachSeries(function (seriesModel) {
  26049. if (isCartesian2D(seriesModel)) {
  26050. var axesModels = findAxesModels(seriesModel, ecModel);
  26051. var xAxisModel = axesModels[0];
  26052. var yAxisModel = axesModels[1];
  26053. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  26054. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  26055. ) {
  26056. return;
  26057. }
  26058. var cartesian = this.getCartesian(
  26059. xAxisModel.componentIndex, yAxisModel.componentIndex
  26060. );
  26061. var data = seriesModel.getData();
  26062. var xAxis = cartesian.getAxis('x');
  26063. var yAxis = cartesian.getAxis('y');
  26064. if (data.type === 'list') {
  26065. unionExtent(data, xAxis, seriesModel);
  26066. unionExtent(data, yAxis, seriesModel);
  26067. }
  26068. }
  26069. }, this);
  26070. function unionExtent(data, axis, seriesModel) {
  26071. each$8(seriesModel.coordDimToDataDim(axis.dim), function (dim) {
  26072. axis.scale.unionExtentFromData(data, dim);
  26073. });
  26074. }
  26075. };
  26076. /**
  26077. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  26078. * @return {Object} {baseAxes: [], otherAxes: []}
  26079. */
  26080. gridProto.getTooltipAxes = function (dim) {
  26081. var baseAxes = [];
  26082. var otherAxes = [];
  26083. each$8(this.getCartesians(), function (cartesian) {
  26084. var baseAxis = (dim != null && dim !== 'auto')
  26085. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  26086. var otherAxis = cartesian.getOtherAxis(baseAxis);
  26087. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  26088. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  26089. });
  26090. return {baseAxes: baseAxes, otherAxes: otherAxes};
  26091. };
  26092. /**
  26093. * @inner
  26094. */
  26095. function updateAxisTransfrom(axis, coordBase) {
  26096. var axisExtent = axis.getExtent();
  26097. var axisExtentSum = axisExtent[0] + axisExtent[1];
  26098. // Fast transform
  26099. axis.toGlobalCoord = axis.dim === 'x'
  26100. ? function (coord) {
  26101. return coord + coordBase;
  26102. }
  26103. : function (coord) {
  26104. return axisExtentSum - coord + coordBase;
  26105. };
  26106. axis.toLocalCoord = axis.dim === 'x'
  26107. ? function (coord) {
  26108. return coord - coordBase;
  26109. }
  26110. : function (coord) {
  26111. return axisExtentSum - coord + coordBase;
  26112. };
  26113. }
  26114. var axesTypes = ['xAxis', 'yAxis'];
  26115. /**
  26116. * @inner
  26117. */
  26118. function findAxesModels(seriesModel, ecModel) {
  26119. return map(axesTypes, function (axisType) {
  26120. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  26121. if (__DEV__) {
  26122. if (!axisModel) {
  26123. throw new Error(axisType + ' "' + retrieve(
  26124. seriesModel.get(axisType + 'Index'),
  26125. seriesModel.get(axisType + 'Id'),
  26126. 0
  26127. ) + '" not found');
  26128. }
  26129. }
  26130. return axisModel;
  26131. });
  26132. }
  26133. /**
  26134. * @inner
  26135. */
  26136. function isCartesian2D(seriesModel) {
  26137. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  26138. }
  26139. Grid.create = function (ecModel, api) {
  26140. var grids = [];
  26141. ecModel.eachComponent('grid', function (gridModel, idx) {
  26142. var grid = new Grid(gridModel, ecModel, api);
  26143. grid.name = 'grid_' + idx;
  26144. // dataSampling requires axis extent, so resize
  26145. // should be performed in create stage.
  26146. grid.resize(gridModel, api, true);
  26147. gridModel.coordinateSystem = grid;
  26148. grids.push(grid);
  26149. });
  26150. // Inject the coordinateSystems into seriesModel
  26151. ecModel.eachSeries(function (seriesModel) {
  26152. if (!isCartesian2D(seriesModel)) {
  26153. return;
  26154. }
  26155. var axesModels = findAxesModels(seriesModel, ecModel);
  26156. var xAxisModel = axesModels[0];
  26157. var yAxisModel = axesModels[1];
  26158. var gridModel = xAxisModel.getCoordSysModel();
  26159. if (__DEV__) {
  26160. if (!gridModel) {
  26161. throw new Error(
  26162. 'Grid "' + retrieve(
  26163. xAxisModel.get('gridIndex'),
  26164. xAxisModel.get('gridId'),
  26165. 0
  26166. ) + '" not found'
  26167. );
  26168. }
  26169. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  26170. throw new Error('xAxis and yAxis must use the same grid');
  26171. }
  26172. }
  26173. var grid = gridModel.coordinateSystem;
  26174. seriesModel.coordinateSystem = grid.getCartesian(
  26175. xAxisModel.componentIndex, yAxisModel.componentIndex
  26176. );
  26177. });
  26178. return grids;
  26179. };
  26180. // For deciding which dimensions to use when creating list data
  26181. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  26182. CoordinateSystemManager.register('cartesian2d', Grid);
  26183. var PI$2 = Math.PI;
  26184. function makeAxisEventDataBase(axisModel) {
  26185. var eventData = {
  26186. componentType: axisModel.mainType
  26187. };
  26188. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  26189. return eventData;
  26190. }
  26191. /**
  26192. * A final axis is translated and rotated from a "standard axis".
  26193. * So opt.position and opt.rotation is required.
  26194. *
  26195. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  26196. * for example: (0, 0) ------------> (0, 50)
  26197. *
  26198. * nameDirection or tickDirection or labelDirection is 1 means tick
  26199. * or label is below the standard axis, whereas is -1 means above
  26200. * the standard axis. labelOffset means offset between label and axis,
  26201. * which is useful when 'onZero', where axisLabel is in the grid and
  26202. * label in outside grid.
  26203. *
  26204. * Tips: like always,
  26205. * positive rotation represents anticlockwise, and negative rotation
  26206. * represents clockwise.
  26207. * The direction of position coordinate is the same as the direction
  26208. * of screen coordinate.
  26209. *
  26210. * Do not need to consider axis 'inverse', which is auto processed by
  26211. * axis extent.
  26212. *
  26213. * @param {module:zrender/container/Group} group
  26214. * @param {Object} axisModel
  26215. * @param {Object} opt Standard axis parameters.
  26216. * @param {Array.<number>} opt.position [x, y]
  26217. * @param {number} opt.rotation by radian
  26218. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  26219. * @param {number} [opt.tickDirection=1] 1 or -1
  26220. * @param {number} [opt.labelDirection=1] 1 or -1
  26221. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  26222. * @param {string} [opt.axisLabelShow] default get from axisModel.
  26223. * @param {string} [opt.axisName] default get from axisModel.
  26224. * @param {number} [opt.axisNameAvailableWidth]
  26225. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  26226. * @param {number} [opt.labelInterval] Default label interval when label
  26227. * interval from model is null or 'auto'.
  26228. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  26229. * @param {number} [opt.nameTruncateMaxWidth]
  26230. */
  26231. var AxisBuilder = function (axisModel, opt) {
  26232. /**
  26233. * @readOnly
  26234. */
  26235. this.opt = opt;
  26236. /**
  26237. * @readOnly
  26238. */
  26239. this.axisModel = axisModel;
  26240. // Default value
  26241. defaults(
  26242. opt,
  26243. {
  26244. labelOffset: 0,
  26245. nameDirection: 1,
  26246. tickDirection: 1,
  26247. labelDirection: 1,
  26248. silent: true
  26249. }
  26250. );
  26251. /**
  26252. * @readOnly
  26253. */
  26254. this.group = new Group();
  26255. // FIXME Not use a seperate text group?
  26256. var dumbGroup = new Group({
  26257. position: opt.position.slice(),
  26258. rotation: opt.rotation
  26259. });
  26260. // this.group.add(dumbGroup);
  26261. // this._dumbGroup = dumbGroup;
  26262. dumbGroup.updateTransform();
  26263. this._transform = dumbGroup.transform;
  26264. this._dumbGroup = dumbGroup;
  26265. };
  26266. AxisBuilder.prototype = {
  26267. constructor: AxisBuilder,
  26268. hasBuilder: function (name) {
  26269. return !!builders[name];
  26270. },
  26271. add: function (name) {
  26272. builders[name].call(this);
  26273. },
  26274. getGroup: function () {
  26275. return this.group;
  26276. }
  26277. };
  26278. var builders = {
  26279. /**
  26280. * @private
  26281. */
  26282. axisLine: function () {
  26283. var opt = this.opt;
  26284. var axisModel = this.axisModel;
  26285. if (!axisModel.get('axisLine.show')) {
  26286. return;
  26287. }
  26288. var extent = this.axisModel.axis.getExtent();
  26289. var matrix = this._transform;
  26290. var pt1 = [extent[0], 0];
  26291. var pt2 = [extent[1], 0];
  26292. if (matrix) {
  26293. applyTransform(pt1, pt1, matrix);
  26294. applyTransform(pt2, pt2, matrix);
  26295. }
  26296. var lineStyle = extend(
  26297. {
  26298. lineCap: 'round'
  26299. },
  26300. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  26301. );
  26302. this.group.add(new Line(subPixelOptimizeLine({
  26303. // Id for animation
  26304. anid: 'line',
  26305. shape: {
  26306. x1: pt1[0],
  26307. y1: pt1[1],
  26308. x2: pt2[0],
  26309. y2: pt2[1]
  26310. },
  26311. style: lineStyle,
  26312. strokeContainThreshold: opt.strokeContainThreshold || 5,
  26313. silent: true,
  26314. z2: 1
  26315. })));
  26316. var arrows = axisModel.get('axisLine.symbol');
  26317. var arrowSize = axisModel.get('axisLine.symbolSize');
  26318. if (arrows != null) {
  26319. if (typeof arrows === 'string') {
  26320. // Use the same arrow for start and end point
  26321. arrows = [arrows, arrows];
  26322. }
  26323. if (typeof arrowSize === 'string'
  26324. || typeof arrowSize === 'number'
  26325. ) {
  26326. // Use the same size for width and height
  26327. arrowSize = [arrowSize, arrowSize];
  26328. }
  26329. var symbolWidth = arrowSize[0];
  26330. var symbolHeight = arrowSize[1];
  26331. each$1([
  26332. [opt.rotation + Math.PI / 2, pt1],
  26333. [opt.rotation - Math.PI / 2, pt2]
  26334. ], function (item, index) {
  26335. if (arrows[index] !== 'none' && arrows[index] != null) {
  26336. var symbol = createSymbol(
  26337. arrows[index],
  26338. -symbolWidth / 2,
  26339. -symbolHeight / 2,
  26340. symbolWidth,
  26341. symbolHeight,
  26342. lineStyle.stroke,
  26343. true
  26344. );
  26345. symbol.attr({
  26346. rotation: item[0],
  26347. position: item[1],
  26348. silent: true
  26349. });
  26350. this.group.add(symbol);
  26351. }
  26352. }, this);
  26353. }
  26354. },
  26355. /**
  26356. * @private
  26357. */
  26358. axisTickLabel: function () {
  26359. var axisModel = this.axisModel;
  26360. var opt = this.opt;
  26361. var tickEls = buildAxisTick(this, axisModel, opt);
  26362. var labelEls = buildAxisLabel(this, axisModel, opt);
  26363. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  26364. },
  26365. /**
  26366. * @private
  26367. */
  26368. axisName: function () {
  26369. var opt = this.opt;
  26370. var axisModel = this.axisModel;
  26371. var name = retrieve(opt.axisName, axisModel.get('name'));
  26372. if (!name) {
  26373. return;
  26374. }
  26375. var nameLocation = axisModel.get('nameLocation');
  26376. var nameDirection = opt.nameDirection;
  26377. var textStyleModel = axisModel.getModel('nameTextStyle');
  26378. var gap = axisModel.get('nameGap') || 0;
  26379. var extent = this.axisModel.axis.getExtent();
  26380. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  26381. var pos = [
  26382. nameLocation === 'start'
  26383. ? extent[0] - gapSignal * gap
  26384. : nameLocation === 'end'
  26385. ? extent[1] + gapSignal * gap
  26386. : (extent[0] + extent[1]) / 2, // 'middle'
  26387. // Reuse labelOffset.
  26388. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  26389. ];
  26390. var labelLayout;
  26391. var nameRotation = axisModel.get('nameRotate');
  26392. if (nameRotation != null) {
  26393. nameRotation = nameRotation * PI$2 / 180; // To radian.
  26394. }
  26395. var axisNameAvailableWidth;
  26396. if (isNameLocationCenter(nameLocation)) {
  26397. labelLayout = innerTextLayout(
  26398. opt.rotation,
  26399. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  26400. nameDirection
  26401. );
  26402. }
  26403. else {
  26404. labelLayout = endTextLayout(
  26405. opt, nameLocation, nameRotation || 0, extent
  26406. );
  26407. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  26408. if (axisNameAvailableWidth != null) {
  26409. axisNameAvailableWidth = Math.abs(
  26410. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  26411. );
  26412. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  26413. }
  26414. }
  26415. var textFont = textStyleModel.getFont();
  26416. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  26417. var ellipsis = truncateOpt.ellipsis;
  26418. var maxWidth = retrieve(
  26419. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  26420. );
  26421. // FIXME
  26422. // truncate rich text? (consider performance)
  26423. var truncatedText = (ellipsis != null && maxWidth != null)
  26424. ? truncateText$1(
  26425. name, maxWidth, textFont, ellipsis,
  26426. {minChar: 2, placeholder: truncateOpt.placeholder}
  26427. )
  26428. : name;
  26429. var tooltipOpt = axisModel.get('tooltip', true);
  26430. var mainType = axisModel.mainType;
  26431. var formatterParams = {
  26432. componentType: mainType,
  26433. name: name,
  26434. $vars: ['name']
  26435. };
  26436. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  26437. var textEl = new Text({
  26438. // Id for animation
  26439. anid: 'name',
  26440. __fullText: name,
  26441. __truncatedText: truncatedText,
  26442. position: pos,
  26443. rotation: labelLayout.rotation,
  26444. silent: isSilent(axisModel),
  26445. z2: 1,
  26446. tooltip: (tooltipOpt && tooltipOpt.show)
  26447. ? extend({
  26448. content: name,
  26449. formatter: function () {
  26450. return name;
  26451. },
  26452. formatterParams: formatterParams
  26453. }, tooltipOpt)
  26454. : null
  26455. });
  26456. setTextStyle(textEl.style, textStyleModel, {
  26457. text: truncatedText,
  26458. textFont: textFont,
  26459. textFill: textStyleModel.getTextColor()
  26460. || axisModel.get('axisLine.lineStyle.color'),
  26461. textAlign: labelLayout.textAlign,
  26462. textVerticalAlign: labelLayout.textVerticalAlign
  26463. });
  26464. if (axisModel.get('triggerEvent')) {
  26465. textEl.eventData = makeAxisEventDataBase(axisModel);
  26466. textEl.eventData.targetType = 'axisName';
  26467. textEl.eventData.name = name;
  26468. }
  26469. // FIXME
  26470. this._dumbGroup.add(textEl);
  26471. textEl.updateTransform();
  26472. this.group.add(textEl);
  26473. textEl.decomposeTransform();
  26474. }
  26475. };
  26476. /**
  26477. * @public
  26478. * @static
  26479. * @param {Object} opt
  26480. * @param {number} axisRotation in radian
  26481. * @param {number} textRotation in radian
  26482. * @param {number} direction
  26483. * @return {Object} {
  26484. * rotation, // according to axis
  26485. * textAlign,
  26486. * textVerticalAlign
  26487. * }
  26488. */
  26489. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  26490. var rotationDiff = remRadian(textRotation - axisRotation);
  26491. var textAlign;
  26492. var textVerticalAlign;
  26493. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  26494. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  26495. textAlign = 'center';
  26496. }
  26497. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  26498. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  26499. textAlign = 'center';
  26500. }
  26501. else {
  26502. textVerticalAlign = 'middle';
  26503. if (rotationDiff > 0 && rotationDiff < PI$2) {
  26504. textAlign = direction > 0 ? 'right' : 'left';
  26505. }
  26506. else {
  26507. textAlign = direction > 0 ? 'left' : 'right';
  26508. }
  26509. }
  26510. return {
  26511. rotation: rotationDiff,
  26512. textAlign: textAlign,
  26513. textVerticalAlign: textVerticalAlign
  26514. };
  26515. };
  26516. function endTextLayout(opt, textPosition, textRotate, extent) {
  26517. var rotationDiff = remRadian(textRotate - opt.rotation);
  26518. var textAlign;
  26519. var textVerticalAlign;
  26520. var inverse = extent[0] > extent[1];
  26521. var onLeft = (textPosition === 'start' && !inverse)
  26522. || (textPosition !== 'start' && inverse);
  26523. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  26524. textVerticalAlign = onLeft ? 'bottom' : 'top';
  26525. textAlign = 'center';
  26526. }
  26527. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  26528. textVerticalAlign = onLeft ? 'top' : 'bottom';
  26529. textAlign = 'center';
  26530. }
  26531. else {
  26532. textVerticalAlign = 'middle';
  26533. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  26534. textAlign = onLeft ? 'left' : 'right';
  26535. }
  26536. else {
  26537. textAlign = onLeft ? 'right' : 'left';
  26538. }
  26539. }
  26540. return {
  26541. rotation: rotationDiff,
  26542. textAlign: textAlign,
  26543. textVerticalAlign: textVerticalAlign
  26544. };
  26545. }
  26546. function isSilent(axisModel) {
  26547. var tooltipOpt = axisModel.get('tooltip');
  26548. return axisModel.get('silent')
  26549. // Consider mouse cursor, add these restrictions.
  26550. || !(
  26551. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  26552. );
  26553. }
  26554. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  26555. // If min or max are user set, we need to check
  26556. // If the tick on min(max) are overlap on their neighbour tick
  26557. // If they are overlapped, we need to hide the min(max) tick label
  26558. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26559. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26560. // FIXME
  26561. // Have not consider onBand yet, where tick els is more than label els.
  26562. labelEls = labelEls || [];
  26563. tickEls = tickEls || [];
  26564. var firstLabel = labelEls[0];
  26565. var nextLabel = labelEls[1];
  26566. var lastLabel = labelEls[labelEls.length - 1];
  26567. var prevLabel = labelEls[labelEls.length - 2];
  26568. var firstTick = tickEls[0];
  26569. var nextTick = tickEls[1];
  26570. var lastTick = tickEls[tickEls.length - 1];
  26571. var prevTick = tickEls[tickEls.length - 2];
  26572. if (showMinLabel === false) {
  26573. ignoreEl(firstLabel);
  26574. ignoreEl(firstTick);
  26575. }
  26576. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  26577. if (showMinLabel) {
  26578. ignoreEl(nextLabel);
  26579. ignoreEl(nextTick);
  26580. }
  26581. else {
  26582. ignoreEl(firstLabel);
  26583. ignoreEl(firstTick);
  26584. }
  26585. }
  26586. if (showMaxLabel === false) {
  26587. ignoreEl(lastLabel);
  26588. ignoreEl(lastTick);
  26589. }
  26590. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  26591. if (showMaxLabel) {
  26592. ignoreEl(prevLabel);
  26593. ignoreEl(prevTick);
  26594. }
  26595. else {
  26596. ignoreEl(lastLabel);
  26597. ignoreEl(lastTick);
  26598. }
  26599. }
  26600. }
  26601. function ignoreEl(el) {
  26602. el && (el.ignore = true);
  26603. }
  26604. function isTwoLabelOverlapped(current, next, labelLayout) {
  26605. // current and next has the same rotation.
  26606. var firstRect = current && current.getBoundingRect().clone();
  26607. var nextRect = next && next.getBoundingRect().clone();
  26608. if (!firstRect || !nextRect) {
  26609. return;
  26610. }
  26611. // When checking intersect of two rotated labels, we use mRotationBack
  26612. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  26613. var mRotationBack = identity([]);
  26614. rotate(mRotationBack, mRotationBack, -current.rotation);
  26615. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  26616. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  26617. return firstRect.intersect(nextRect);
  26618. }
  26619. function isNameLocationCenter(nameLocation) {
  26620. return nameLocation === 'middle' || nameLocation === 'center';
  26621. }
  26622. /**
  26623. * @static
  26624. */
  26625. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  26626. axis,
  26627. i,
  26628. interval,
  26629. ticksCnt,
  26630. showMinLabel,
  26631. showMaxLabel
  26632. ) {
  26633. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  26634. return false;
  26635. }
  26636. // FIXME
  26637. // Have not consider label overlap (if label is too long) yet.
  26638. var rawTick;
  26639. var scale$$1 = axis.scale;
  26640. return scale$$1.type === 'ordinal'
  26641. && (
  26642. typeof interval === 'function'
  26643. ? (
  26644. rawTick = scale$$1.getTicks()[i],
  26645. !interval(rawTick, scale$$1.getLabel(rawTick))
  26646. )
  26647. : i % (interval + 1)
  26648. );
  26649. };
  26650. /**
  26651. * @static
  26652. */
  26653. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  26654. var interval = model.get('interval');
  26655. if (interval == null || interval == 'auto') {
  26656. interval = labelInterval;
  26657. }
  26658. return interval;
  26659. };
  26660. function buildAxisTick(axisBuilder, axisModel, opt) {
  26661. var axis = axisModel.axis;
  26662. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  26663. return;
  26664. }
  26665. var tickModel = axisModel.getModel('axisTick');
  26666. var lineStyleModel = tickModel.getModel('lineStyle');
  26667. var tickLen = tickModel.get('length');
  26668. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  26669. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  26670. // FIXME
  26671. // Corresponds to ticksCoords ?
  26672. var ticks = axis.scale.getTicks();
  26673. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26674. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26675. var pt1 = [];
  26676. var pt2 = [];
  26677. var matrix = axisBuilder._transform;
  26678. var tickEls = [];
  26679. var ticksCnt = ticksCoords.length;
  26680. for (var i = 0; i < ticksCnt; i++) {
  26681. // Only ordinal scale support tick interval
  26682. if (ifIgnoreOnTick$1(
  26683. axis, i, tickInterval, ticksCnt,
  26684. showMinLabel, showMaxLabel
  26685. )) {
  26686. continue;
  26687. }
  26688. var tickCoord = ticksCoords[i];
  26689. pt1[0] = tickCoord;
  26690. pt1[1] = 0;
  26691. pt2[0] = tickCoord;
  26692. pt2[1] = opt.tickDirection * tickLen;
  26693. if (matrix) {
  26694. applyTransform(pt1, pt1, matrix);
  26695. applyTransform(pt2, pt2, matrix);
  26696. }
  26697. // Tick line, Not use group transform to have better line draw
  26698. var tickEl = new Line(subPixelOptimizeLine({
  26699. // Id for animation
  26700. anid: 'tick_' + ticks[i],
  26701. shape: {
  26702. x1: pt1[0],
  26703. y1: pt1[1],
  26704. x2: pt2[0],
  26705. y2: pt2[1]
  26706. },
  26707. style: defaults(
  26708. lineStyleModel.getLineStyle(),
  26709. {
  26710. stroke: axisModel.get('axisLine.lineStyle.color')
  26711. }
  26712. ),
  26713. z2: 2,
  26714. silent: true
  26715. }));
  26716. axisBuilder.group.add(tickEl);
  26717. tickEls.push(tickEl);
  26718. }
  26719. return tickEls;
  26720. }
  26721. function buildAxisLabel(axisBuilder, axisModel, opt) {
  26722. var axis = axisModel.axis;
  26723. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  26724. if (!show || axis.scale.isBlank()) {
  26725. return;
  26726. }
  26727. var labelModel = axisModel.getModel('axisLabel');
  26728. var labelMargin = labelModel.get('margin');
  26729. var ticks = axis.scale.getTicks();
  26730. var labels = axisModel.getFormattedLabels();
  26731. // Special label rotate.
  26732. var labelRotation = (
  26733. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  26734. ) * PI$2 / 180;
  26735. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  26736. var categoryData = axisModel.get('data');
  26737. var labelEls = [];
  26738. var silent = isSilent(axisModel);
  26739. var triggerEvent = axisModel.get('triggerEvent');
  26740. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  26741. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  26742. each$1(ticks, function (tickVal, index) {
  26743. if (ifIgnoreOnTick$1(
  26744. axis, index, opt.labelInterval, ticks.length,
  26745. showMinLabel, showMaxLabel
  26746. )) {
  26747. return;
  26748. }
  26749. var itemLabelModel = labelModel;
  26750. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  26751. itemLabelModel = new Model(
  26752. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  26753. );
  26754. }
  26755. var textColor = itemLabelModel.getTextColor()
  26756. || axisModel.get('axisLine.lineStyle.color');
  26757. var tickCoord = axis.dataToCoord(tickVal);
  26758. var pos = [
  26759. tickCoord,
  26760. opt.labelOffset + opt.labelDirection * labelMargin
  26761. ];
  26762. var labelStr = axis.scale.getLabel(tickVal);
  26763. var textEl = new Text({
  26764. // Id for animation
  26765. anid: 'label_' + tickVal,
  26766. position: pos,
  26767. rotation: labelLayout.rotation,
  26768. silent: silent,
  26769. z2: 10
  26770. });
  26771. setTextStyle(textEl.style, itemLabelModel, {
  26772. text: labels[index],
  26773. textAlign: itemLabelModel.getShallow('align', true)
  26774. || labelLayout.textAlign,
  26775. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  26776. || itemLabelModel.getShallow('baseline', true)
  26777. || labelLayout.textVerticalAlign,
  26778. textFill: typeof textColor === 'function'
  26779. ? textColor(
  26780. // (1) In category axis with data zoom, tick is not the original
  26781. // index of axis.data. So tick should not be exposed to user
  26782. // in category axis.
  26783. // (2) Compatible with previous version, which always returns labelStr.
  26784. // But in interval scale labelStr is like '223,445', which maked
  26785. // user repalce ','. So we modify it to return original val but remain
  26786. // it as 'string' to avoid error in replacing.
  26787. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  26788. index
  26789. )
  26790. : textColor
  26791. });
  26792. // Pack data for mouse event
  26793. if (triggerEvent) {
  26794. textEl.eventData = makeAxisEventDataBase(axisModel);
  26795. textEl.eventData.targetType = 'axisLabel';
  26796. textEl.eventData.value = labelStr;
  26797. }
  26798. // FIXME
  26799. axisBuilder._dumbGroup.add(textEl);
  26800. textEl.updateTransform();
  26801. labelEls.push(textEl);
  26802. axisBuilder.group.add(textEl);
  26803. textEl.decomposeTransform();
  26804. });
  26805. return labelEls;
  26806. }
  26807. var each$9 = each$1;
  26808. var curry$1 = curry;
  26809. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  26810. // allAxesInfo should be updated when setOption performed.
  26811. function collect(ecModel, api) {
  26812. var result = {
  26813. /**
  26814. * key: makeKey(axis.model)
  26815. * value: {
  26816. * axis,
  26817. * coordSys,
  26818. * axisPointerModel,
  26819. * triggerTooltip,
  26820. * involveSeries,
  26821. * snap,
  26822. * seriesModels,
  26823. * seriesDataCount
  26824. * }
  26825. */
  26826. axesInfo: {},
  26827. seriesInvolved: false,
  26828. /**
  26829. * key: makeKey(coordSys.model)
  26830. * value: Object: key makeKey(axis.model), value: axisInfo
  26831. */
  26832. coordSysAxesInfo: {},
  26833. coordSysMap: {}
  26834. };
  26835. collectAxesInfo(result, ecModel, api);
  26836. // Check seriesInvolved for performance, in case too many series in some chart.
  26837. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  26838. return result;
  26839. }
  26840. function collectAxesInfo(result, ecModel, api) {
  26841. var globalTooltipModel = ecModel.getComponent('tooltip');
  26842. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  26843. // links can only be set on global.
  26844. var linksOption = globalAxisPointerModel.get('link', true) || [];
  26845. var linkGroups = [];
  26846. // Collect axes info.
  26847. each$9(api.getCoordinateSystems(), function (coordSys) {
  26848. // Some coordinate system do not support axes, like geo.
  26849. if (!coordSys.axisPointerEnabled) {
  26850. return;
  26851. }
  26852. var coordSysKey = makeKey(coordSys.model);
  26853. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  26854. result.coordSysMap[coordSysKey] = coordSys;
  26855. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  26856. // for user. So we enable seting tooltip on coordSys model.
  26857. var coordSysModel = coordSys.model;
  26858. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  26859. each$9(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  26860. // If axis tooltip used, choose tooltip axis for each coordSys.
  26861. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  26862. if (coordSys.getTooltipAxes
  26863. && globalTooltipModel
  26864. // If tooltip.showContent is set as false, tooltip will not
  26865. // show but axisPointer will show as normal.
  26866. && baseTooltipModel.get('show')
  26867. ) {
  26868. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  26869. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  26870. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  26871. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  26872. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  26873. if (triggerAxis || cross) {
  26874. each$9(tooltipAxes.baseAxes, curry$1(
  26875. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  26876. ));
  26877. }
  26878. if (cross) {
  26879. each$9(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  26880. }
  26881. }
  26882. // fromTooltip: true | false | 'cross'
  26883. // triggerTooltip: true | false | null
  26884. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  26885. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  26886. var axisPointerShow = axisPointerModel.get('show');
  26887. if (!axisPointerShow || (
  26888. axisPointerShow === 'auto'
  26889. && !fromTooltip
  26890. && !isHandleTrigger(axisPointerModel)
  26891. )) {
  26892. return;
  26893. }
  26894. if (triggerTooltip == null) {
  26895. triggerTooltip = axisPointerModel.get('triggerTooltip');
  26896. }
  26897. axisPointerModel = fromTooltip
  26898. ? makeAxisPointerModel(
  26899. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  26900. fromTooltip, triggerTooltip
  26901. )
  26902. : axisPointerModel;
  26903. var snap = axisPointerModel.get('snap');
  26904. var key = makeKey(axis.model);
  26905. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  26906. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  26907. var axisInfo = result.axesInfo[key] = {
  26908. key: key,
  26909. axis: axis,
  26910. coordSys: coordSys,
  26911. axisPointerModel: axisPointerModel,
  26912. triggerTooltip: triggerTooltip,
  26913. involveSeries: involveSeries,
  26914. snap: snap,
  26915. useHandle: isHandleTrigger(axisPointerModel),
  26916. seriesModels: []
  26917. };
  26918. axesInfoInCoordSys[key] = axisInfo;
  26919. result.seriesInvolved |= involveSeries;
  26920. var groupIndex = getLinkGroupIndex(linksOption, axis);
  26921. if (groupIndex != null) {
  26922. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  26923. linkGroup.axesInfo[key] = axisInfo;
  26924. linkGroup.mapper = linksOption[groupIndex].mapper;
  26925. axisInfo.linkGroup = linkGroup;
  26926. }
  26927. }
  26928. });
  26929. }
  26930. function makeAxisPointerModel(
  26931. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  26932. ) {
  26933. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  26934. var volatileOption = {};
  26935. each$9(
  26936. [
  26937. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  26938. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  26939. ],
  26940. function (field) {
  26941. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  26942. }
  26943. );
  26944. // category axis do not auto snap, otherwise some tick that do not
  26945. // has value can not be hovered. value/time/log axis default snap if
  26946. // triggered from tooltip and trigger tooltip.
  26947. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  26948. // Compatibel with previous behavior, tooltip axis do not show label by default.
  26949. // Only these properties can be overrided from tooltip to axisPointer.
  26950. if (tooltipAxisPointerModel.get('type') === 'cross') {
  26951. volatileOption.type = 'line';
  26952. }
  26953. var labelOption = volatileOption.label || (volatileOption.label = {});
  26954. // Follow the convention, do not show label when triggered by tooltip by default.
  26955. labelOption.show == null && (labelOption.show = false);
  26956. if (fromTooltip === 'cross') {
  26957. // When 'cross', both axes show labels.
  26958. labelOption.show = true;
  26959. // If triggerTooltip, this is a base axis, which should better not use cross style
  26960. // (cross style is dashed by default)
  26961. if (!triggerTooltip) {
  26962. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  26963. crossStyle && defaults(labelOption, crossStyle.textStyle);
  26964. }
  26965. }
  26966. return axis.model.getModel(
  26967. 'axisPointer',
  26968. new Model(volatileOption, globalAxisPointerModel, ecModel)
  26969. );
  26970. }
  26971. function collectSeriesInfo(result, ecModel) {
  26972. // Prepare data for axis trigger
  26973. ecModel.eachSeries(function (seriesModel) {
  26974. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  26975. var coordSys = seriesModel.coordinateSystem;
  26976. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  26977. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  26978. if (!coordSys
  26979. || seriesTooltipTrigger === 'none'
  26980. || seriesTooltipTrigger === false
  26981. || seriesTooltipTrigger === 'item'
  26982. || seriesTooltipShow === false
  26983. || seriesModel.get('axisPointer.show', true) === false
  26984. ) {
  26985. return;
  26986. }
  26987. each$9(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  26988. var axis = axisInfo.axis;
  26989. if (coordSys.getAxis(axis.dim) === axis) {
  26990. axisInfo.seriesModels.push(seriesModel);
  26991. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  26992. axisInfo.seriesDataCount += seriesModel.getData().count();
  26993. }
  26994. });
  26995. }, this);
  26996. }
  26997. /**
  26998. * For example:
  26999. * {
  27000. * axisPointer: {
  27001. * links: [{
  27002. * xAxisIndex: [2, 4],
  27003. * yAxisIndex: 'all'
  27004. * }, {
  27005. * xAxisId: ['a5', 'a7'],
  27006. * xAxisName: 'xxx'
  27007. * }]
  27008. * }
  27009. * }
  27010. */
  27011. function getLinkGroupIndex(linksOption, axis) {
  27012. var axisModel = axis.model;
  27013. var dim = axis.dim;
  27014. for (var i = 0; i < linksOption.length; i++) {
  27015. var linkOption = linksOption[i] || {};
  27016. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  27017. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  27018. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  27019. ) {
  27020. return i;
  27021. }
  27022. }
  27023. }
  27024. function checkPropInLink(linkPropValue, axisPropValue) {
  27025. return linkPropValue === 'all'
  27026. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  27027. || linkPropValue === axisPropValue;
  27028. }
  27029. function fixValue(axisModel) {
  27030. var axisInfo = getAxisInfo(axisModel);
  27031. if (!axisInfo) {
  27032. return;
  27033. }
  27034. var axisPointerModel = axisInfo.axisPointerModel;
  27035. var scale = axisInfo.axis.scale;
  27036. var option = axisPointerModel.option;
  27037. var status = axisPointerModel.get('status');
  27038. var value = axisPointerModel.get('value');
  27039. // Parse init value for category and time axis.
  27040. if (value != null) {
  27041. value = scale.parse(value);
  27042. }
  27043. var useHandle = isHandleTrigger(axisPointerModel);
  27044. // If `handle` used, `axisPointer` will always be displayed, so value
  27045. // and status should be initialized.
  27046. if (status == null) {
  27047. option.status = useHandle ? 'show' : 'hide';
  27048. }
  27049. var extent = scale.getExtent().slice();
  27050. extent[0] > extent[1] && extent.reverse();
  27051. if (// Pick a value on axis when initializing.
  27052. value == null
  27053. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  27054. // where we should re-pick a value to keep `handle` displaying normally.
  27055. || value > extent[1]
  27056. ) {
  27057. // Make handle displayed on the end of the axis when init, which looks better.
  27058. value = extent[1];
  27059. }
  27060. if (value < extent[0]) {
  27061. value = extent[0];
  27062. }
  27063. option.value = value;
  27064. if (useHandle) {
  27065. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  27066. }
  27067. }
  27068. function getAxisInfo(axisModel) {
  27069. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  27070. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  27071. }
  27072. function getAxisPointerModel(axisModel) {
  27073. var axisInfo = getAxisInfo(axisModel);
  27074. return axisInfo && axisInfo.axisPointerModel;
  27075. }
  27076. function isHandleTrigger(axisPointerModel) {
  27077. return !!axisPointerModel.get('handle.show');
  27078. }
  27079. /**
  27080. * @param {module:echarts/model/Model} model
  27081. * @return {string} unique key
  27082. */
  27083. function makeKey(model) {
  27084. return model.type + '||' + model.id;
  27085. }
  27086. /**
  27087. * Base class of AxisView.
  27088. */
  27089. var AxisView = extendComponentView({
  27090. type: 'axis',
  27091. /**
  27092. * @private
  27093. */
  27094. _axisPointer: null,
  27095. /**
  27096. * @protected
  27097. * @type {string}
  27098. */
  27099. axisPointerClass: null,
  27100. /**
  27101. * @override
  27102. */
  27103. render: function (axisModel, ecModel, api, payload) {
  27104. // FIXME
  27105. // This process should proformed after coordinate systems updated
  27106. // (axis scale updated), and should be performed each time update.
  27107. // So put it here temporarily, although it is not appropriate to
  27108. // put a model-writing procedure in `view`.
  27109. this.axisPointerClass && fixValue(axisModel);
  27110. AxisView.superApply(this, 'render', arguments);
  27111. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  27112. },
  27113. /**
  27114. * Action handler.
  27115. * @public
  27116. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27117. * @param {module:echarts/model/Global} ecModel
  27118. * @param {module:echarts/ExtensionAPI} api
  27119. * @param {Object} payload
  27120. */
  27121. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  27122. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  27123. },
  27124. /**
  27125. * @override
  27126. */
  27127. remove: function (ecModel, api) {
  27128. var axisPointer = this._axisPointer;
  27129. axisPointer && axisPointer.remove(api);
  27130. AxisView.superApply(this, 'remove', arguments);
  27131. },
  27132. /**
  27133. * @override
  27134. */
  27135. dispose: function (ecModel, api) {
  27136. disposeAxisPointer(this, api);
  27137. AxisView.superApply(this, 'dispose', arguments);
  27138. }
  27139. });
  27140. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  27141. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  27142. if (!Clazz) {
  27143. return;
  27144. }
  27145. var axisPointerModel = getAxisPointerModel(axisModel);
  27146. axisPointerModel
  27147. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  27148. .render(axisModel, axisPointerModel, api, forceRender)
  27149. : disposeAxisPointer(axisView, api);
  27150. }
  27151. function disposeAxisPointer(axisView, ecModel, api) {
  27152. var axisPointer = axisView._axisPointer;
  27153. axisPointer && axisPointer.dispose(ecModel, api);
  27154. axisView._axisPointer = null;
  27155. }
  27156. var axisPointerClazz = [];
  27157. AxisView.registerAxisPointerClass = function (type, clazz) {
  27158. if (__DEV__) {
  27159. if (axisPointerClazz[type]) {
  27160. throw new Error('axisPointer ' + type + ' exists');
  27161. }
  27162. }
  27163. axisPointerClazz[type] = clazz;
  27164. };
  27165. AxisView.getAxisPointerClass = function (type) {
  27166. return type && axisPointerClazz[type];
  27167. };
  27168. /**
  27169. * @param {Object} opt {labelInside}
  27170. * @return {Object} {
  27171. * position, rotation, labelDirection, labelOffset,
  27172. * tickDirection, labelRotate, labelInterval, z2
  27173. * }
  27174. */
  27175. function layout(gridModel, axisModel, opt) {
  27176. opt = opt || {};
  27177. var grid = gridModel.coordinateSystem;
  27178. var axis = axisModel.axis;
  27179. var layout = {};
  27180. var rawAxisPosition = axis.position;
  27181. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  27182. var axisDim = axis.dim;
  27183. var rect = grid.getRect();
  27184. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  27185. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  27186. var axisOffset = axisModel.get('offset') || 0;
  27187. var posBound = axisDim === 'x'
  27188. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  27189. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  27190. if (axis.onZero) {
  27191. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  27192. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  27193. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  27194. }
  27195. // Axis position
  27196. layout.position = [
  27197. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  27198. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  27199. ];
  27200. // Axis rotation
  27201. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  27202. // Tick and label direction, x y is axisDim
  27203. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  27204. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  27205. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  27206. if (axisModel.get('axisTick.inside')) {
  27207. layout.tickDirection = -layout.tickDirection;
  27208. }
  27209. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  27210. layout.labelDirection = -layout.labelDirection;
  27211. }
  27212. // Special label rotation
  27213. var labelRotate = axisModel.get('axisLabel.rotate');
  27214. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  27215. // label interval when auto mode.
  27216. layout.labelInterval = axis.getLabelInterval();
  27217. // Over splitLine and splitArea
  27218. layout.z2 = 1;
  27219. return layout;
  27220. }
  27221. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  27222. var getInterval = AxisBuilder.getInterval;
  27223. var axisBuilderAttrs = [
  27224. 'axisLine', 'axisTickLabel', 'axisName'
  27225. ];
  27226. var selfBuilderAttrs = [
  27227. 'splitArea', 'splitLine'
  27228. ];
  27229. // function getAlignWithLabel(model, axisModel) {
  27230. // var alignWithLabel = model.get('alignWithLabel');
  27231. // if (alignWithLabel === 'auto') {
  27232. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  27233. // }
  27234. // return alignWithLabel;
  27235. // }
  27236. var CartesianAxisView = AxisView.extend({
  27237. type: 'cartesianAxis',
  27238. axisPointerClass: 'CartesianAxisPointer',
  27239. /**
  27240. * @override
  27241. */
  27242. render: function (axisModel, ecModel, api, payload) {
  27243. this.group.removeAll();
  27244. var oldAxisGroup = this._axisGroup;
  27245. this._axisGroup = new Group();
  27246. this.group.add(this._axisGroup);
  27247. if (!axisModel.get('show')) {
  27248. return;
  27249. }
  27250. var gridModel = axisModel.getCoordSysModel();
  27251. var layout$$1 = layout(gridModel, axisModel);
  27252. var axisBuilder = new AxisBuilder(axisModel, layout$$1);
  27253. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  27254. this._axisGroup.add(axisBuilder.getGroup());
  27255. each$1(selfBuilderAttrs, function (name) {
  27256. if (axisModel.get(name + '.show')) {
  27257. this['_' + name](axisModel, gridModel, layout$$1.labelInterval);
  27258. }
  27259. }, this);
  27260. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  27261. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  27262. },
  27263. /**
  27264. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27265. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  27266. * @param {number|Function} labelInterval
  27267. * @private
  27268. */
  27269. _splitLine: function (axisModel, gridModel, labelInterval) {
  27270. var axis = axisModel.axis;
  27271. if (axis.scale.isBlank()) {
  27272. return;
  27273. }
  27274. var splitLineModel = axisModel.getModel('splitLine');
  27275. var lineStyleModel = splitLineModel.getModel('lineStyle');
  27276. var lineColors = lineStyleModel.get('color');
  27277. var lineInterval = getInterval(splitLineModel, labelInterval);
  27278. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  27279. var gridRect = gridModel.coordinateSystem.getRect();
  27280. var isHorizontal = axis.isHorizontal();
  27281. var lineCount = 0;
  27282. var ticksCoords = axis.getTicksCoords(
  27283. // splitLineModel.get('alignWithLabel')
  27284. );
  27285. var ticks = axis.scale.getTicks();
  27286. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  27287. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  27288. var p1 = [];
  27289. var p2 = [];
  27290. // Simple optimization
  27291. // Batching the lines if color are the same
  27292. var lineStyle = lineStyleModel.getLineStyle();
  27293. for (var i = 0; i < ticksCoords.length; i++) {
  27294. if (ifIgnoreOnTick(
  27295. axis, i, lineInterval, ticksCoords.length,
  27296. showMinLabel, showMaxLabel
  27297. )) {
  27298. continue;
  27299. }
  27300. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  27301. if (isHorizontal) {
  27302. p1[0] = tickCoord;
  27303. p1[1] = gridRect.y;
  27304. p2[0] = tickCoord;
  27305. p2[1] = gridRect.y + gridRect.height;
  27306. }
  27307. else {
  27308. p1[0] = gridRect.x;
  27309. p1[1] = tickCoord;
  27310. p2[0] = gridRect.x + gridRect.width;
  27311. p2[1] = tickCoord;
  27312. }
  27313. var colorIndex = (lineCount++) % lineColors.length;
  27314. this._axisGroup.add(new Line(subPixelOptimizeLine({
  27315. anid: 'line_' + ticks[i],
  27316. shape: {
  27317. x1: p1[0],
  27318. y1: p1[1],
  27319. x2: p2[0],
  27320. y2: p2[1]
  27321. },
  27322. style: defaults({
  27323. stroke: lineColors[colorIndex]
  27324. }, lineStyle),
  27325. silent: true
  27326. })));
  27327. }
  27328. },
  27329. /**
  27330. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  27331. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  27332. * @param {number|Function} labelInterval
  27333. * @private
  27334. */
  27335. _splitArea: function (axisModel, gridModel, labelInterval) {
  27336. var axis = axisModel.axis;
  27337. if (axis.scale.isBlank()) {
  27338. return;
  27339. }
  27340. var splitAreaModel = axisModel.getModel('splitArea');
  27341. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  27342. var areaColors = areaStyleModel.get('color');
  27343. var gridRect = gridModel.coordinateSystem.getRect();
  27344. var ticksCoords = axis.getTicksCoords(
  27345. // splitAreaModel.get('alignWithLabel')
  27346. );
  27347. var ticks = axis.scale.getTicks();
  27348. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  27349. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  27350. var count = 0;
  27351. var areaInterval = getInterval(splitAreaModel, labelInterval);
  27352. var areaStyle = areaStyleModel.getAreaStyle();
  27353. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  27354. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  27355. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  27356. for (var i = 1; i < ticksCoords.length; i++) {
  27357. if (ifIgnoreOnTick(
  27358. axis, i, areaInterval, ticksCoords.length,
  27359. showMinLabel, showMaxLabel
  27360. )) {
  27361. continue;
  27362. }
  27363. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  27364. var x;
  27365. var y;
  27366. var width;
  27367. var height;
  27368. if (axis.isHorizontal()) {
  27369. x = prevX;
  27370. y = gridRect.y;
  27371. width = tickCoord - x;
  27372. height = gridRect.height;
  27373. }
  27374. else {
  27375. x = gridRect.x;
  27376. y = prevY;
  27377. width = gridRect.width;
  27378. height = tickCoord - y;
  27379. }
  27380. var colorIndex = (count++) % areaColors.length;
  27381. this._axisGroup.add(new Rect({
  27382. anid: 'area_' + ticks[i],
  27383. shape: {
  27384. x: x,
  27385. y: y,
  27386. width: width,
  27387. height: height
  27388. },
  27389. style: defaults({
  27390. fill: areaColors[colorIndex]
  27391. }, areaStyle),
  27392. silent: true
  27393. }));
  27394. prevX = x + width;
  27395. prevY = y + height;
  27396. }
  27397. }
  27398. });
  27399. CartesianAxisView.extend({
  27400. type: 'xAxis'
  27401. });
  27402. CartesianAxisView.extend({
  27403. type: 'yAxis'
  27404. });
  27405. // Grid view
  27406. extendComponentView({
  27407. type: 'grid',
  27408. render: function (gridModel, ecModel) {
  27409. this.group.removeAll();
  27410. if (gridModel.get('show')) {
  27411. this.group.add(new Rect({
  27412. shape: gridModel.coordinateSystem.getRect(),
  27413. style: defaults({
  27414. fill: gridModel.get('backgroundColor')
  27415. }, gridModel.getItemStyle()),
  27416. silent: true,
  27417. z2: -1
  27418. }));
  27419. }
  27420. }
  27421. });
  27422. registerPreprocessor(function (option) {
  27423. // Only create grid when need
  27424. if (option.xAxis && option.yAxis && !option.grid) {
  27425. option.grid = {};
  27426. }
  27427. });
  27428. // In case developer forget to include grid component
  27429. registerVisual(curry(
  27430. visualSymbol, 'line', 'circle', 'line'
  27431. ));
  27432. registerLayout(curry(
  27433. layoutPoints, 'line'
  27434. ));
  27435. // Down sample after filter
  27436. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, curry(
  27437. dataSample, 'line'
  27438. ));
  27439. var STACK_PREFIX = '__ec_stack_';
  27440. function getSeriesStackId(seriesModel) {
  27441. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  27442. }
  27443. function getAxisKey(axis) {
  27444. return axis.dim + axis.index;
  27445. }
  27446. /**
  27447. * @param {Object} opt
  27448. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  27449. * @param {number} opt.count Positive interger.
  27450. * @param {number} [opt.barWidth]
  27451. * @param {number} [opt.barMaxWidth]
  27452. * @param {number} [opt.barGap]
  27453. * @param {number} [opt.barCategoryGap]
  27454. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  27455. */
  27456. function getLayoutOnAxis(opt, api) {
  27457. var params = [];
  27458. var baseAxis = opt.axis;
  27459. var axisKey = 'axis0';
  27460. if (baseAxis.type !== 'category') {
  27461. return;
  27462. }
  27463. var bandWidth = baseAxis.getBandWidth();
  27464. for (var i = 0; i < opt.count || 0; i++) {
  27465. params.push(defaults({
  27466. bandWidth: bandWidth,
  27467. axisKey: axisKey,
  27468. stackId: STACK_PREFIX + i
  27469. }, opt));
  27470. }
  27471. var widthAndOffsets = doCalBarWidthAndOffset(params, api);
  27472. var result = [];
  27473. for (var i = 0; i < opt.count; i++) {
  27474. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  27475. item.offsetCenter = item.offset + item.width / 2;
  27476. result.push(item);
  27477. }
  27478. return result;
  27479. }
  27480. function calBarWidthAndOffset(barSeries, api) {
  27481. var seriesInfoList = map(barSeries, function (seriesModel) {
  27482. var data = seriesModel.getData();
  27483. var cartesian = seriesModel.coordinateSystem;
  27484. var baseAxis = cartesian.getBaseAxis();
  27485. var axisExtent = baseAxis.getExtent();
  27486. var bandWidth = baseAxis.type === 'category'
  27487. ? baseAxis.getBandWidth()
  27488. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  27489. var barWidth = parsePercent$1(
  27490. seriesModel.get('barWidth'), bandWidth
  27491. );
  27492. var barMaxWidth = parsePercent$1(
  27493. seriesModel.get('barMaxWidth'), bandWidth
  27494. );
  27495. var barGap = seriesModel.get('barGap');
  27496. var barCategoryGap = seriesModel.get('barCategoryGap');
  27497. return {
  27498. bandWidth: bandWidth,
  27499. barWidth: barWidth,
  27500. barMaxWidth: barMaxWidth,
  27501. barGap: barGap,
  27502. barCategoryGap: barCategoryGap,
  27503. axisKey: getAxisKey(baseAxis),
  27504. stackId: getSeriesStackId(seriesModel)
  27505. };
  27506. });
  27507. return doCalBarWidthAndOffset(seriesInfoList, api);
  27508. }
  27509. function doCalBarWidthAndOffset(seriesInfoList, api) {
  27510. // Columns info on each category axis. Key is cartesian name
  27511. var columnsMap = {};
  27512. each$1(seriesInfoList, function (seriesInfo, idx) {
  27513. var axisKey = seriesInfo.axisKey;
  27514. var bandWidth = seriesInfo.bandWidth;
  27515. var columnsOnAxis = columnsMap[axisKey] || {
  27516. bandWidth: bandWidth,
  27517. remainedWidth: bandWidth,
  27518. autoWidthCount: 0,
  27519. categoryGap: '20%',
  27520. gap: '30%',
  27521. stacks: {}
  27522. };
  27523. var stacks = columnsOnAxis.stacks;
  27524. columnsMap[axisKey] = columnsOnAxis;
  27525. var stackId = seriesInfo.stackId;
  27526. if (!stacks[stackId]) {
  27527. columnsOnAxis.autoWidthCount++;
  27528. }
  27529. stacks[stackId] = stacks[stackId] || {
  27530. width: 0,
  27531. maxWidth: 0
  27532. };
  27533. // Caution: In a single coordinate system, these barGrid attributes
  27534. // will be shared by series. Consider that they have default values,
  27535. // only the attributes set on the last series will work.
  27536. // Do not change this fact unless there will be a break change.
  27537. // TODO
  27538. var barWidth = seriesInfo.barWidth;
  27539. if (barWidth && !stacks[stackId].width) {
  27540. // See #6312, do not restrict width.
  27541. stacks[stackId].width = barWidth;
  27542. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  27543. columnsOnAxis.remainedWidth -= barWidth;
  27544. }
  27545. var barMaxWidth = seriesInfo.barMaxWidth;
  27546. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  27547. var barGap = seriesInfo.barGap;
  27548. (barGap != null) && (columnsOnAxis.gap = barGap);
  27549. var barCategoryGap = seriesInfo.barCategoryGap;
  27550. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  27551. });
  27552. var result = {};
  27553. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  27554. result[coordSysName] = {};
  27555. var stacks = columnsOnAxis.stacks;
  27556. var bandWidth = columnsOnAxis.bandWidth;
  27557. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  27558. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  27559. var remainedWidth = columnsOnAxis.remainedWidth;
  27560. var autoWidthCount = columnsOnAxis.autoWidthCount;
  27561. var autoWidth = (remainedWidth - categoryGap)
  27562. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27563. autoWidth = Math.max(autoWidth, 0);
  27564. // Find if any auto calculated bar exceeded maxBarWidth
  27565. each$1(stacks, function (column, stack) {
  27566. var maxWidth = column.maxWidth;
  27567. if (maxWidth && maxWidth < autoWidth) {
  27568. maxWidth = Math.min(maxWidth, remainedWidth);
  27569. if (column.width) {
  27570. maxWidth = Math.min(maxWidth, column.width);
  27571. }
  27572. remainedWidth -= maxWidth;
  27573. column.width = maxWidth;
  27574. autoWidthCount--;
  27575. }
  27576. });
  27577. // Recalculate width again
  27578. autoWidth = (remainedWidth - categoryGap)
  27579. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27580. autoWidth = Math.max(autoWidth, 0);
  27581. var widthSum = 0;
  27582. var lastColumn;
  27583. each$1(stacks, function (column, idx) {
  27584. if (!column.width) {
  27585. column.width = autoWidth;
  27586. }
  27587. lastColumn = column;
  27588. widthSum += column.width * (1 + barGapPercent);
  27589. });
  27590. if (lastColumn) {
  27591. widthSum -= lastColumn.width * barGapPercent;
  27592. }
  27593. var offset = -widthSum / 2;
  27594. each$1(stacks, function (column, stackId) {
  27595. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  27596. offset: offset,
  27597. width: column.width
  27598. };
  27599. offset += column.width * (1 + barGapPercent);
  27600. });
  27601. });
  27602. return result;
  27603. }
  27604. /**
  27605. * @param {string} seriesType
  27606. * @param {module:echarts/model/Global} ecModel
  27607. * @param {module:echarts/ExtensionAPI} api
  27608. */
  27609. function barLayoutGrid(seriesType, ecModel, api) {
  27610. var barWidthAndOffset = calBarWidthAndOffset(
  27611. filter(
  27612. ecModel.getSeriesByType(seriesType),
  27613. function (seriesModel) {
  27614. return !ecModel.isSeriesFiltered(seriesModel)
  27615. && seriesModel.coordinateSystem
  27616. && seriesModel.coordinateSystem.type === 'cartesian2d';
  27617. }
  27618. )
  27619. );
  27620. var lastStackCoords = {};
  27621. var lastStackCoordsOrigin = {};
  27622. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  27623. // Check series coordinate, do layout for cartesian2d only
  27624. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  27625. return;
  27626. }
  27627. var data = seriesModel.getData();
  27628. var cartesian = seriesModel.coordinateSystem;
  27629. var baseAxis = cartesian.getBaseAxis();
  27630. var stackId = getSeriesStackId(seriesModel);
  27631. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27632. var columnOffset = columnLayoutInfo.offset;
  27633. var columnWidth = columnLayoutInfo.width;
  27634. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27635. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27636. var valueAxisStart = baseAxis.onZero
  27637. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  27638. : valueAxis.getGlobalExtent()[0];
  27639. var coordDims = [
  27640. seriesModel.coordDimToDataDim('x')[0],
  27641. seriesModel.coordDimToDataDim('y')[0]
  27642. ];
  27643. var coords = data.mapArray(coordDims, function (x, y) {
  27644. return cartesian.dataToPoint([x, y]);
  27645. }, true);
  27646. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27647. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  27648. data.setLayout({
  27649. offset: columnOffset,
  27650. size: columnWidth
  27651. });
  27652. data.each(seriesModel.coordDimToDataDim(valueAxis.dim)[0], function (value, idx) {
  27653. if (isNaN(value)) {
  27654. return;
  27655. }
  27656. if (!lastStackCoords[stackId][idx]) {
  27657. lastStackCoords[stackId][idx] = {
  27658. p: valueAxisStart, // Positive stack
  27659. n: valueAxisStart // Negative stack
  27660. };
  27661. lastStackCoordsOrigin[stackId][idx] = {
  27662. p: valueAxisStart, // Positive stack
  27663. n: valueAxisStart // Negative stack
  27664. };
  27665. }
  27666. var sign = value >= 0 ? 'p' : 'n';
  27667. var coord = coords[idx];
  27668. var lastCoord = lastStackCoords[stackId][idx][sign];
  27669. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  27670. var x;
  27671. var y;
  27672. var width;
  27673. var height;
  27674. if (valueAxis.isHorizontal()) {
  27675. x = lastCoord;
  27676. y = coord[1] + columnOffset;
  27677. width = coord[0] - lastCoordOrigin;
  27678. height = columnWidth;
  27679. lastStackCoordsOrigin[stackId][idx][sign] += width;
  27680. if (Math.abs(width) < barMinHeight) {
  27681. width = (width < 0 ? -1 : 1) * barMinHeight;
  27682. }
  27683. lastStackCoords[stackId][idx][sign] += width;
  27684. }
  27685. else {
  27686. x = coord[0] + columnOffset;
  27687. y = lastCoord;
  27688. width = columnWidth;
  27689. height = coord[1] - lastCoordOrigin;
  27690. lastStackCoordsOrigin[stackId][idx][sign] += height;
  27691. if (Math.abs(height) < barMinHeight) {
  27692. // Include zero to has a positive bar
  27693. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27694. }
  27695. lastStackCoords[stackId][idx][sign] += height;
  27696. }
  27697. data.setItemLayout(idx, {
  27698. x: x,
  27699. y: y,
  27700. width: width,
  27701. height: height
  27702. });
  27703. }, true);
  27704. }, this);
  27705. }
  27706. barLayoutGrid.getLayoutOnAxis = getLayoutOnAxis;
  27707. var BaseBarSeries = SeriesModel.extend({
  27708. type: 'series.__base_bar__',
  27709. getInitialData: function (option, ecModel) {
  27710. return createListFromArray(option.data, this, ecModel);
  27711. },
  27712. getMarkerPosition: function (value) {
  27713. var coordSys = this.coordinateSystem;
  27714. if (coordSys) {
  27715. // PENDING if clamp ?
  27716. var pt = coordSys.dataToPoint(value, true);
  27717. var data = this.getData();
  27718. var offset = data.getLayout('offset');
  27719. var size = data.getLayout('size');
  27720. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  27721. pt[offsetIndex] += offset + size / 2;
  27722. return pt;
  27723. }
  27724. return [NaN, NaN];
  27725. },
  27726. defaultOption: {
  27727. zlevel: 0, // 一级层叠
  27728. z: 2, // 二级层叠
  27729. coordinateSystem: 'cartesian2d',
  27730. legendHoverLink: true,
  27731. // stack: null
  27732. // Cartesian coordinate system
  27733. // xAxisIndex: 0,
  27734. // yAxisIndex: 0,
  27735. // 最小高度改为0
  27736. barMinHeight: 0,
  27737. // 最小角度为0,仅对极坐标系下的柱状图有效
  27738. barMinAngle: 0,
  27739. // cursor: null,
  27740. // barMaxWidth: null,
  27741. // 默认自适应
  27742. // barWidth: null,
  27743. // 柱间距离,默认为柱形宽度的30%,可设固定值
  27744. // barGap: '30%',
  27745. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  27746. // barCategoryGap: '20%',
  27747. // label: {
  27748. // normal: {
  27749. // show: false
  27750. // }
  27751. // },
  27752. itemStyle: {
  27753. // normal: {
  27754. // color: '各异'
  27755. // },
  27756. // emphasis: {}
  27757. }
  27758. }
  27759. });
  27760. BaseBarSeries.extend({
  27761. type: 'series.bar',
  27762. dependencies: ['grid', 'polar'],
  27763. brushSelector: 'rect'
  27764. });
  27765. function setLabel(
  27766. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  27767. ) {
  27768. var labelModel = itemModel.getModel('label.normal');
  27769. var hoverLabelModel = itemModel.getModel('label.emphasis');
  27770. setLabelStyle(
  27771. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  27772. {
  27773. labelFetcher: seriesModel,
  27774. labelDataIndex: dataIndex,
  27775. defaultText: seriesModel.getRawValue(dataIndex),
  27776. isRectText: true,
  27777. autoColor: color
  27778. }
  27779. );
  27780. fixPosition(normalStyle);
  27781. fixPosition(hoverStyle);
  27782. }
  27783. function fixPosition(style, labelPositionOutside) {
  27784. if (style.textPosition === 'outside') {
  27785. style.textPosition = labelPositionOutside;
  27786. }
  27787. }
  27788. var getBarItemStyle = makeStyleMapper(
  27789. [
  27790. ['fill', 'color'],
  27791. ['stroke', 'borderColor'],
  27792. ['lineWidth', 'borderWidth'],
  27793. // Compatitable with 2
  27794. ['stroke', 'barBorderColor'],
  27795. ['lineWidth', 'barBorderWidth'],
  27796. ['opacity'],
  27797. ['shadowBlur'],
  27798. ['shadowOffsetX'],
  27799. ['shadowOffsetY'],
  27800. ['shadowColor']
  27801. ]
  27802. );
  27803. var barItemStyle = {
  27804. getBarItemStyle: function (excludes) {
  27805. var style = getBarItemStyle(this, excludes);
  27806. if (this.getBorderLineDash) {
  27807. var lineDash = this.getBorderLineDash();
  27808. lineDash && (style.lineDash = lineDash);
  27809. }
  27810. return style;
  27811. }
  27812. };
  27813. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'normal', 'barBorderWidth'];
  27814. // FIXME
  27815. // Just for compatible with ec2.
  27816. extend(Model.prototype, barItemStyle);
  27817. extendChartView({
  27818. type: 'bar',
  27819. render: function (seriesModel, ecModel, api) {
  27820. var coordinateSystemType = seriesModel.get('coordinateSystem');
  27821. if (coordinateSystemType === 'cartesian2d'
  27822. || coordinateSystemType === 'polar'
  27823. ) {
  27824. this._render(seriesModel, ecModel, api);
  27825. }
  27826. else if (__DEV__) {
  27827. console.warn('Only cartesian2d and polar supported for bar.');
  27828. }
  27829. return this.group;
  27830. },
  27831. dispose: noop,
  27832. _render: function (seriesModel, ecModel, api) {
  27833. var group = this.group;
  27834. var data = seriesModel.getData();
  27835. var oldData = this._data;
  27836. var coord = seriesModel.coordinateSystem;
  27837. var baseAxis = coord.getBaseAxis();
  27838. var isHorizontalOrRadial;
  27839. if (coord.type === 'cartesian2d') {
  27840. isHorizontalOrRadial = baseAxis.isHorizontal();
  27841. }
  27842. else if (coord.type === 'polar') {
  27843. isHorizontalOrRadial = baseAxis.dim === 'angle';
  27844. }
  27845. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  27846. data.diff(oldData)
  27847. .add(function (dataIndex) {
  27848. if (!data.hasValue(dataIndex)) {
  27849. return;
  27850. }
  27851. var itemModel = data.getItemModel(dataIndex);
  27852. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  27853. var el = elementCreator[coord.type](
  27854. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  27855. );
  27856. data.setItemGraphicEl(dataIndex, el);
  27857. group.add(el);
  27858. updateStyle(
  27859. el, data, dataIndex, itemModel, layout,
  27860. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  27861. );
  27862. })
  27863. .update(function (newIndex, oldIndex) {
  27864. var el = oldData.getItemGraphicEl(oldIndex);
  27865. if (!data.hasValue(newIndex)) {
  27866. group.remove(el);
  27867. return;
  27868. }
  27869. var itemModel = data.getItemModel(newIndex);
  27870. var layout = getLayout[coord.type](data, newIndex, itemModel);
  27871. if (el) {
  27872. updateProps(el, {shape: layout}, animationModel, newIndex);
  27873. }
  27874. else {
  27875. el = elementCreator[coord.type](
  27876. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  27877. );
  27878. }
  27879. data.setItemGraphicEl(newIndex, el);
  27880. // Add back
  27881. group.add(el);
  27882. updateStyle(
  27883. el, data, newIndex, itemModel, layout,
  27884. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  27885. );
  27886. })
  27887. .remove(function (dataIndex) {
  27888. var el = oldData.getItemGraphicEl(dataIndex);
  27889. if (coord.type === 'cartesian2d') {
  27890. el && removeRect(dataIndex, animationModel, el);
  27891. }
  27892. else {
  27893. el && removeSector(dataIndex, animationModel, el);
  27894. }
  27895. })
  27896. .execute();
  27897. this._data = data;
  27898. },
  27899. remove: function (ecModel, api) {
  27900. var group = this.group;
  27901. var data = this._data;
  27902. if (ecModel.get('animation')) {
  27903. if (data) {
  27904. data.eachItemGraphicEl(function (el) {
  27905. if (el.type === 'sector') {
  27906. removeSector(el.dataIndex, ecModel, el);
  27907. }
  27908. else {
  27909. removeRect(el.dataIndex, ecModel, el);
  27910. }
  27911. });
  27912. }
  27913. }
  27914. else {
  27915. group.removeAll();
  27916. }
  27917. }
  27918. });
  27919. var elementCreator = {
  27920. cartesian2d: function (
  27921. data, dataIndex, itemModel, layout, isHorizontal,
  27922. animationModel, isUpdate
  27923. ) {
  27924. var rect = new Rect({shape: extend({}, layout)});
  27925. // Animation
  27926. if (animationModel) {
  27927. var rectShape = rect.shape;
  27928. var animateProperty = isHorizontal ? 'height' : 'width';
  27929. var animateTarget = {};
  27930. rectShape[animateProperty] = 0;
  27931. animateTarget[animateProperty] = layout[animateProperty];
  27932. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  27933. shape: animateTarget
  27934. }, animationModel, dataIndex);
  27935. }
  27936. return rect;
  27937. },
  27938. polar: function (
  27939. data, dataIndex, itemModel, layout, isRadial,
  27940. animationModel, isUpdate
  27941. ) {
  27942. var sector = new Sector({shape: extend({}, layout)});
  27943. // Animation
  27944. if (animationModel) {
  27945. var sectorShape = sector.shape;
  27946. var animateProperty = isRadial ? 'r' : 'endAngle';
  27947. var animateTarget = {};
  27948. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  27949. animateTarget[animateProperty] = layout[animateProperty];
  27950. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  27951. shape: animateTarget
  27952. }, animationModel, dataIndex);
  27953. }
  27954. return sector;
  27955. }
  27956. };
  27957. function removeRect(dataIndex, animationModel, el) {
  27958. // Not show text when animating
  27959. el.style.text = null;
  27960. updateProps(el, {
  27961. shape: {
  27962. width: 0
  27963. }
  27964. }, animationModel, dataIndex, function () {
  27965. el.parent && el.parent.remove(el);
  27966. });
  27967. }
  27968. function removeSector(dataIndex, animationModel, el) {
  27969. // Not show text when animating
  27970. el.style.text = null;
  27971. updateProps(el, {
  27972. shape: {
  27973. r: el.shape.r0
  27974. }
  27975. }, animationModel, dataIndex, function () {
  27976. el.parent && el.parent.remove(el);
  27977. });
  27978. }
  27979. var getLayout = {
  27980. cartesian2d: function (data, dataIndex, itemModel) {
  27981. var layout = data.getItemLayout(dataIndex);
  27982. var fixedLineWidth = getLineWidth(itemModel, layout);
  27983. // fix layout with lineWidth
  27984. var signX = layout.width > 0 ? 1 : -1;
  27985. var signY = layout.height > 0 ? 1 : -1;
  27986. return {
  27987. x: layout.x + signX * fixedLineWidth / 2,
  27988. y: layout.y + signY * fixedLineWidth / 2,
  27989. width: layout.width - signX * fixedLineWidth,
  27990. height: layout.height - signY * fixedLineWidth
  27991. };
  27992. },
  27993. polar: function (data, dataIndex, itemModel) {
  27994. var layout = data.getItemLayout(dataIndex);
  27995. return {
  27996. cx: layout.cx,
  27997. cy: layout.cy,
  27998. r0: layout.r0,
  27999. r: layout.r,
  28000. startAngle: layout.startAngle,
  28001. endAngle: layout.endAngle
  28002. };
  28003. }
  28004. };
  28005. function updateStyle(
  28006. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  28007. ) {
  28008. var color = data.getItemVisual(dataIndex, 'color');
  28009. var opacity = data.getItemVisual(dataIndex, 'opacity');
  28010. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  28011. var hoverStyle = itemModel.getModel('itemStyle.emphasis').getBarItemStyle();
  28012. if (!isPolar) {
  28013. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  28014. }
  28015. el.useStyle(defaults(
  28016. {
  28017. fill: color,
  28018. opacity: opacity
  28019. },
  28020. itemStyleModel.getBarItemStyle()
  28021. ));
  28022. var cursorStyle = itemModel.getShallow('cursor');
  28023. cursorStyle && el.attr('cursor', cursorStyle);
  28024. var labelPositionOutside = isHorizontal
  28025. ? (layout.height > 0 ? 'bottom' : 'top')
  28026. : (layout.width > 0 ? 'left' : 'right');
  28027. if (!isPolar) {
  28028. setLabel(
  28029. el.style, hoverStyle, itemModel, color,
  28030. seriesModel, dataIndex, labelPositionOutside
  28031. );
  28032. }
  28033. setHoverStyle(el, hoverStyle);
  28034. }
  28035. // In case width or height are too small.
  28036. function getLineWidth(itemModel, rawLayout) {
  28037. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  28038. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  28039. }
  28040. // In case developer forget to include grid component
  28041. registerLayout(curry(barLayoutGrid, 'bar'));
  28042. // Visual coding for legend
  28043. registerVisual(function (ecModel) {
  28044. ecModel.eachSeriesByType('bar', function (seriesModel) {
  28045. var data = seriesModel.getData();
  28046. data.setVisual('legendSymbol', 'roundRect');
  28047. });
  28048. });
  28049. /**
  28050. * Data selectable mixin for chart series.
  28051. * To eanble data select, option of series must have `selectedMode`.
  28052. * And each data item will use `selected` to toggle itself selected status
  28053. */
  28054. var selectableMixin = {
  28055. updateSelectedMap: function (targetList) {
  28056. this._targetList = targetList.slice();
  28057. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  28058. targetMap.set(target.name, target);
  28059. return targetMap;
  28060. }, createHashMap());
  28061. },
  28062. /**
  28063. * Either name or id should be passed as input here.
  28064. * If both of them are defined, id is used.
  28065. *
  28066. * @param {string|undefined} name name of data
  28067. * @param {number|undefined} id dataIndex of data
  28068. */
  28069. // PENGING If selectedMode is null ?
  28070. select: function (name, id) {
  28071. var target = id != null
  28072. ? this._targetList[id]
  28073. : this._selectTargetMap.get(name);
  28074. var selectedMode = this.get('selectedMode');
  28075. if (selectedMode === 'single') {
  28076. this._selectTargetMap.each(function (target) {
  28077. target.selected = false;
  28078. });
  28079. }
  28080. target && (target.selected = true);
  28081. },
  28082. /**
  28083. * Either name or id should be passed as input here.
  28084. * If both of them are defined, id is used.
  28085. *
  28086. * @param {string|undefined} name name of data
  28087. * @param {number|undefined} id dataIndex of data
  28088. */
  28089. unSelect: function (name, id) {
  28090. var target = id != null
  28091. ? this._targetList[id]
  28092. : this._selectTargetMap.get(name);
  28093. // var selectedMode = this.get('selectedMode');
  28094. // selectedMode !== 'single' && target && (target.selected = false);
  28095. target && (target.selected = false);
  28096. },
  28097. /**
  28098. * Either name or id should be passed as input here.
  28099. * If both of them are defined, id is used.
  28100. *
  28101. * @param {string|undefined} name name of data
  28102. * @param {number|undefined} id dataIndex of data
  28103. */
  28104. toggleSelected: function (name, id) {
  28105. var target = id != null
  28106. ? this._targetList[id]
  28107. : this._selectTargetMap.get(name);
  28108. if (target != null) {
  28109. this[target.selected ? 'unSelect' : 'select'](name, id);
  28110. return target.selected;
  28111. }
  28112. },
  28113. /**
  28114. * Either name or id should be passed as input here.
  28115. * If both of them are defined, id is used.
  28116. *
  28117. * @param {string|undefined} name name of data
  28118. * @param {number|undefined} id dataIndex of data
  28119. */
  28120. isSelected: function (name, id) {
  28121. var target = id != null
  28122. ? this._targetList[id]
  28123. : this._selectTargetMap.get(name);
  28124. return target && target.selected;
  28125. }
  28126. };
  28127. var PieSeries = extendSeriesModel({
  28128. type: 'series.pie',
  28129. // Overwrite
  28130. init: function (option) {
  28131. PieSeries.superApply(this, 'init', arguments);
  28132. // Enable legend selection for each data item
  28133. // Use a function instead of direct access because data reference may changed
  28134. this.legendDataProvider = function () {
  28135. return this.getRawData();
  28136. };
  28137. this.updateSelectedMap(option.data);
  28138. this._defaultLabelLine(option);
  28139. },
  28140. // Overwrite
  28141. mergeOption: function (newOption) {
  28142. PieSeries.superCall(this, 'mergeOption', newOption);
  28143. this.updateSelectedMap(this.option.data);
  28144. },
  28145. getInitialData: function (option, ecModel) {
  28146. var dimensions = completeDimensions(['value'], option.data);
  28147. var list = new List(dimensions, this);
  28148. list.initData(option.data);
  28149. return list;
  28150. },
  28151. // Overwrite
  28152. getDataParams: function (dataIndex) {
  28153. var data = this.getData();
  28154. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  28155. // FIXME toFixed?
  28156. var valueList = [];
  28157. data.each('value', function (value) {
  28158. valueList.push(value);
  28159. });
  28160. params.percent = getPercentWithPrecision(
  28161. valueList,
  28162. dataIndex,
  28163. data.hostModel.get('percentPrecision')
  28164. );
  28165. params.$vars.push('percent');
  28166. return params;
  28167. },
  28168. _defaultLabelLine: function (option) {
  28169. // Extend labelLine emphasis
  28170. defaultEmphasis(option.labelLine, ['show']);
  28171. var labelLineNormalOpt = option.labelLine.normal;
  28172. var labelLineEmphasisOpt = option.labelLine.emphasis;
  28173. // Not show label line if `label.normal.show = false`
  28174. labelLineNormalOpt.show = labelLineNormalOpt.show
  28175. && option.label.normal.show;
  28176. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  28177. && option.label.emphasis.show;
  28178. },
  28179. defaultOption: {
  28180. zlevel: 0,
  28181. z: 2,
  28182. legendHoverLink: true,
  28183. hoverAnimation: true,
  28184. // 默认全局居中
  28185. center: ['50%', '50%'],
  28186. radius: [0, '75%'],
  28187. // 默认顺时针
  28188. clockwise: true,
  28189. startAngle: 90,
  28190. // 最小角度改为0
  28191. minAngle: 0,
  28192. // 选中时扇区偏移量
  28193. selectedOffset: 10,
  28194. // 高亮扇区偏移量
  28195. hoverOffset: 10,
  28196. // If use strategy to avoid label overlapping
  28197. avoidLabelOverlap: true,
  28198. // 选择模式,默认关闭,可选single,multiple
  28199. // selectedMode: false,
  28200. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  28201. // roseType: null,
  28202. percentPrecision: 2,
  28203. // If still show when all data zero.
  28204. stillShowZeroSum: true,
  28205. // cursor: null,
  28206. label: {
  28207. normal: {
  28208. // If rotate around circle
  28209. rotate: false,
  28210. show: true,
  28211. // 'outer', 'inside', 'center'
  28212. position: 'outer'
  28213. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  28214. // 默认使用全局文本样式,详见TEXTSTYLE
  28215. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  28216. },
  28217. emphasis: {}
  28218. },
  28219. // Enabled when label.normal.position is 'outer'
  28220. labelLine: {
  28221. normal: {
  28222. show: true,
  28223. // 引导线两段中的第一段长度
  28224. length: 15,
  28225. // 引导线两段中的第二段长度
  28226. length2: 15,
  28227. smooth: false,
  28228. lineStyle: {
  28229. // color: 各异,
  28230. width: 1,
  28231. type: 'solid'
  28232. }
  28233. }
  28234. },
  28235. itemStyle: {
  28236. normal: {
  28237. borderWidth: 1
  28238. },
  28239. emphasis: {}
  28240. },
  28241. // Animation type canbe expansion, scale
  28242. animationType: 'expansion',
  28243. animationEasing: 'cubicOut',
  28244. data: []
  28245. }
  28246. });
  28247. mixin(PieSeries, selectableMixin);
  28248. /**
  28249. * @param {module:echarts/model/Series} seriesModel
  28250. * @param {boolean} hasAnimation
  28251. * @inner
  28252. */
  28253. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  28254. var data = seriesModel.getData();
  28255. var dataIndex = this.dataIndex;
  28256. var name = data.getName(dataIndex);
  28257. var selectedOffset = seriesModel.get('selectedOffset');
  28258. api.dispatchAction({
  28259. type: 'pieToggleSelect',
  28260. from: uid,
  28261. name: name,
  28262. seriesId: seriesModel.id
  28263. });
  28264. data.each(function (idx) {
  28265. toggleItemSelected(
  28266. data.getItemGraphicEl(idx),
  28267. data.getItemLayout(idx),
  28268. seriesModel.isSelected(data.getName(idx)),
  28269. selectedOffset,
  28270. hasAnimation
  28271. );
  28272. });
  28273. }
  28274. /**
  28275. * @param {module:zrender/graphic/Sector} el
  28276. * @param {Object} layout
  28277. * @param {boolean} isSelected
  28278. * @param {number} selectedOffset
  28279. * @param {boolean} hasAnimation
  28280. * @inner
  28281. */
  28282. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  28283. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  28284. var dx = Math.cos(midAngle);
  28285. var dy = Math.sin(midAngle);
  28286. var offset = isSelected ? selectedOffset : 0;
  28287. var position = [dx * offset, dy * offset];
  28288. hasAnimation
  28289. // animateTo will stop revious animation like update transition
  28290. ? el.animate()
  28291. .when(200, {
  28292. position: position
  28293. })
  28294. .start('bounceOut')
  28295. : el.attr('position', position);
  28296. }
  28297. /**
  28298. * Piece of pie including Sector, Label, LabelLine
  28299. * @constructor
  28300. * @extends {module:zrender/graphic/Group}
  28301. */
  28302. function PiePiece(data, idx) {
  28303. Group.call(this);
  28304. var sector = new Sector({
  28305. z2: 2
  28306. });
  28307. var polyline = new Polyline();
  28308. var text = new Text();
  28309. this.add(sector);
  28310. this.add(polyline);
  28311. this.add(text);
  28312. this.updateData(data, idx, true);
  28313. // Hover to change label and labelLine
  28314. function onEmphasis() {
  28315. polyline.ignore = polyline.hoverIgnore;
  28316. text.ignore = text.hoverIgnore;
  28317. }
  28318. function onNormal() {
  28319. polyline.ignore = polyline.normalIgnore;
  28320. text.ignore = text.normalIgnore;
  28321. }
  28322. this.on('emphasis', onEmphasis)
  28323. .on('normal', onNormal)
  28324. .on('mouseover', onEmphasis)
  28325. .on('mouseout', onNormal);
  28326. }
  28327. var piePieceProto = PiePiece.prototype;
  28328. piePieceProto.updateData = function (data, idx, firstCreate) {
  28329. var sector = this.childAt(0);
  28330. var seriesModel = data.hostModel;
  28331. var itemModel = data.getItemModel(idx);
  28332. var layout = data.getItemLayout(idx);
  28333. var sectorShape = extend({}, layout);
  28334. sectorShape.label = null;
  28335. if (firstCreate) {
  28336. sector.setShape(sectorShape);
  28337. var animationType = seriesModel.getShallow('animationType');
  28338. if (animationType === 'scale') {
  28339. sector.shape.r = layout.r0;
  28340. initProps(sector, {
  28341. shape: {
  28342. r: layout.r
  28343. }
  28344. }, seriesModel, idx);
  28345. }
  28346. // Expansion
  28347. else {
  28348. sector.shape.endAngle = layout.startAngle;
  28349. updateProps(sector, {
  28350. shape: {
  28351. endAngle: layout.endAngle
  28352. }
  28353. }, seriesModel, idx);
  28354. }
  28355. }
  28356. else {
  28357. updateProps(sector, {
  28358. shape: sectorShape
  28359. }, seriesModel, idx);
  28360. }
  28361. // Update common style
  28362. var itemStyleModel = itemModel.getModel('itemStyle');
  28363. var visualColor = data.getItemVisual(idx, 'color');
  28364. sector.useStyle(
  28365. defaults(
  28366. {
  28367. lineJoin: 'bevel',
  28368. fill: visualColor
  28369. },
  28370. itemStyleModel.getModel('normal').getItemStyle()
  28371. )
  28372. );
  28373. sector.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  28374. var cursorStyle = itemModel.getShallow('cursor');
  28375. cursorStyle && sector.attr('cursor', cursorStyle);
  28376. // Toggle selected
  28377. toggleItemSelected(
  28378. this,
  28379. data.getItemLayout(idx),
  28380. itemModel.get('selected'),
  28381. seriesModel.get('selectedOffset'),
  28382. seriesModel.get('animation')
  28383. );
  28384. function onEmphasis() {
  28385. // Sector may has animation of updating data. Force to move to the last frame
  28386. // Or it may stopped on the wrong shape
  28387. sector.stopAnimation(true);
  28388. sector.animateTo({
  28389. shape: {
  28390. r: layout.r + seriesModel.get('hoverOffset')
  28391. }
  28392. }, 300, 'elasticOut');
  28393. }
  28394. function onNormal() {
  28395. sector.stopAnimation(true);
  28396. sector.animateTo({
  28397. shape: {
  28398. r: layout.r
  28399. }
  28400. }, 300, 'elasticOut');
  28401. }
  28402. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  28403. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  28404. sector
  28405. .on('mouseover', onEmphasis)
  28406. .on('mouseout', onNormal)
  28407. .on('emphasis', onEmphasis)
  28408. .on('normal', onNormal);
  28409. }
  28410. this._updateLabel(data, idx);
  28411. setHoverStyle(this);
  28412. };
  28413. piePieceProto._updateLabel = function (data, idx) {
  28414. var labelLine = this.childAt(1);
  28415. var labelText = this.childAt(2);
  28416. var seriesModel = data.hostModel;
  28417. var itemModel = data.getItemModel(idx);
  28418. var layout = data.getItemLayout(idx);
  28419. var labelLayout = layout.label;
  28420. var visualColor = data.getItemVisual(idx, 'color');
  28421. updateProps(labelLine, {
  28422. shape: {
  28423. points: labelLayout.linePoints || [
  28424. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  28425. ]
  28426. }
  28427. }, seriesModel, idx);
  28428. updateProps(labelText, {
  28429. style: {
  28430. x: labelLayout.x,
  28431. y: labelLayout.y
  28432. }
  28433. }, seriesModel, idx);
  28434. labelText.attr({
  28435. rotation: labelLayout.rotation,
  28436. origin: [labelLayout.x, labelLayout.y],
  28437. z2: 10
  28438. });
  28439. var labelModel = itemModel.getModel('label.normal');
  28440. var labelHoverModel = itemModel.getModel('label.emphasis');
  28441. var labelLineModel = itemModel.getModel('labelLine.normal');
  28442. var labelLineHoverModel = itemModel.getModel('labelLine.emphasis');
  28443. var visualColor = data.getItemVisual(idx, 'color');
  28444. setLabelStyle(
  28445. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  28446. {
  28447. labelFetcher: data.hostModel,
  28448. labelDataIndex: idx,
  28449. defaultText: data.getName(idx),
  28450. autoColor: visualColor,
  28451. useInsideStyle: !!labelLayout.inside
  28452. },
  28453. {
  28454. textAlign: labelLayout.textAlign,
  28455. textVerticalAlign: labelLayout.verticalAlign,
  28456. opacity: data.getItemVisual(idx, 'opacity')
  28457. }
  28458. );
  28459. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  28460. labelText.hoverIgnore = !labelHoverModel.get('show');
  28461. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  28462. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  28463. // Default use item visual color
  28464. labelLine.setStyle({
  28465. stroke: visualColor,
  28466. opacity: data.getItemVisual(idx, 'opacity')
  28467. });
  28468. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  28469. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  28470. var smooth = labelLineModel.get('smooth');
  28471. if (smooth && smooth === true) {
  28472. smooth = 0.4;
  28473. }
  28474. labelLine.setShape({
  28475. smooth: smooth
  28476. });
  28477. };
  28478. inherits(PiePiece, Group);
  28479. // Pie view
  28480. var PieView = Chart.extend({
  28481. type: 'pie',
  28482. init: function () {
  28483. var sectorGroup = new Group();
  28484. this._sectorGroup = sectorGroup;
  28485. },
  28486. render: function (seriesModel, ecModel, api, payload) {
  28487. if (payload && (payload.from === this.uid)) {
  28488. return;
  28489. }
  28490. var data = seriesModel.getData();
  28491. var oldData = this._data;
  28492. var group = this.group;
  28493. var hasAnimation = ecModel.get('animation');
  28494. var isFirstRender = !oldData;
  28495. var animationType = seriesModel.get('animationType');
  28496. var onSectorClick = curry(
  28497. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  28498. );
  28499. var selectedMode = seriesModel.get('selectedMode');
  28500. data.diff(oldData)
  28501. .add(function (idx) {
  28502. var piePiece = new PiePiece(data, idx);
  28503. // Default expansion animation
  28504. if (isFirstRender && animationType !== 'scale') {
  28505. piePiece.eachChild(function (child) {
  28506. child.stopAnimation(true);
  28507. });
  28508. }
  28509. selectedMode && piePiece.on('click', onSectorClick);
  28510. data.setItemGraphicEl(idx, piePiece);
  28511. group.add(piePiece);
  28512. })
  28513. .update(function (newIdx, oldIdx) {
  28514. var piePiece = oldData.getItemGraphicEl(oldIdx);
  28515. piePiece.updateData(data, newIdx);
  28516. piePiece.off('click');
  28517. selectedMode && piePiece.on('click', onSectorClick);
  28518. group.add(piePiece);
  28519. data.setItemGraphicEl(newIdx, piePiece);
  28520. })
  28521. .remove(function (idx) {
  28522. var piePiece = oldData.getItemGraphicEl(idx);
  28523. group.remove(piePiece);
  28524. })
  28525. .execute();
  28526. if (
  28527. hasAnimation && isFirstRender && data.count() > 0
  28528. // Default expansion animation
  28529. && animationType !== 'scale'
  28530. ) {
  28531. var shape = data.getItemLayout(0);
  28532. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  28533. var removeClipPath = bind(group.removeClipPath, group);
  28534. group.setClipPath(this._createClipPath(
  28535. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  28536. ));
  28537. }
  28538. this._data = data;
  28539. },
  28540. dispose: function () {},
  28541. _createClipPath: function (
  28542. cx, cy, r, startAngle, clockwise, cb, seriesModel
  28543. ) {
  28544. var clipPath = new Sector({
  28545. shape: {
  28546. cx: cx,
  28547. cy: cy,
  28548. r0: 0,
  28549. r: r,
  28550. startAngle: startAngle,
  28551. endAngle: startAngle,
  28552. clockwise: clockwise
  28553. }
  28554. });
  28555. initProps(clipPath, {
  28556. shape: {
  28557. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  28558. }
  28559. }, seriesModel, cb);
  28560. return clipPath;
  28561. },
  28562. /**
  28563. * @implement
  28564. */
  28565. containPoint: function (point, seriesModel) {
  28566. var data = seriesModel.getData();
  28567. var itemLayout = data.getItemLayout(0);
  28568. if (itemLayout) {
  28569. var dx = point[0] - itemLayout.cx;
  28570. var dy = point[1] - itemLayout.cy;
  28571. var radius = Math.sqrt(dx * dx + dy * dy);
  28572. return radius <= itemLayout.r && radius >= itemLayout.r0;
  28573. }
  28574. }
  28575. });
  28576. var createDataSelectAction = function (seriesType, actionInfos) {
  28577. each$1(actionInfos, function (actionInfo) {
  28578. actionInfo.update = 'updateView';
  28579. /**
  28580. * @payload
  28581. * @property {string} seriesName
  28582. * @property {string} name
  28583. */
  28584. registerAction(actionInfo, function (payload, ecModel) {
  28585. var selected = {};
  28586. ecModel.eachComponent(
  28587. {mainType: 'series', subType: seriesType, query: payload},
  28588. function (seriesModel) {
  28589. if (seriesModel[actionInfo.method]) {
  28590. seriesModel[actionInfo.method](
  28591. payload.name,
  28592. payload.dataIndex
  28593. );
  28594. }
  28595. var data = seriesModel.getData();
  28596. // Create selected map
  28597. data.each(function (idx) {
  28598. var name = data.getName(idx);
  28599. selected[name] = seriesModel.isSelected(name)
  28600. || false;
  28601. });
  28602. }
  28603. );
  28604. return {
  28605. name: payload.name,
  28606. selected: selected
  28607. };
  28608. });
  28609. });
  28610. };
  28611. // Pick color from palette for each data item.
  28612. // Applicable for charts that require applying color palette
  28613. // in data level (like pie, funnel, chord).
  28614. var dataColor = function (seriesType, ecModel) {
  28615. // Pie and funnel may use diferrent scope
  28616. var paletteScope = {};
  28617. ecModel.eachRawSeriesByType(seriesType, function (seriesModel) {
  28618. var dataAll = seriesModel.getRawData();
  28619. var idxMap = {};
  28620. if (!ecModel.isSeriesFiltered(seriesModel)) {
  28621. var data = seriesModel.getData();
  28622. data.each(function (idx) {
  28623. var rawIdx = data.getRawIndex(idx);
  28624. idxMap[rawIdx] = idx;
  28625. });
  28626. dataAll.each(function (rawIdx) {
  28627. var filteredIdx = idxMap[rawIdx];
  28628. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  28629. var singleDataColor = filteredIdx != null
  28630. && data.getItemVisual(filteredIdx, 'color', true);
  28631. if (!singleDataColor) {
  28632. // FIXME Performance
  28633. var itemModel = dataAll.getItemModel(rawIdx);
  28634. var color = itemModel.get('itemStyle.normal.color')
  28635. || seriesModel.getColorFromPalette(dataAll.getName(rawIdx), paletteScope);
  28636. // Legend may use the visual info in data before processed
  28637. dataAll.setItemVisual(rawIdx, 'color', color);
  28638. // Data is not filtered
  28639. if (filteredIdx != null) {
  28640. data.setItemVisual(filteredIdx, 'color', color);
  28641. }
  28642. }
  28643. else {
  28644. // Set data all color for legend
  28645. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  28646. }
  28647. });
  28648. }
  28649. });
  28650. };
  28651. // FIXME emphasis label position is not same with normal label position
  28652. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  28653. list.sort(function (a, b) {
  28654. return a.y - b.y;
  28655. });
  28656. // 压
  28657. function shiftDown(start, end, delta, dir) {
  28658. for (var j = start; j < end; j++) {
  28659. list[j].y += delta;
  28660. if (j > start
  28661. && j + 1 < end
  28662. && list[j + 1].y > list[j].y + list[j].height
  28663. ) {
  28664. shiftUp(j, delta / 2);
  28665. return;
  28666. }
  28667. }
  28668. shiftUp(end - 1, delta / 2);
  28669. }
  28670. // 弹
  28671. function shiftUp(end, delta) {
  28672. for (var j = end; j >= 0; j--) {
  28673. list[j].y -= delta;
  28674. if (j > 0
  28675. && list[j].y > list[j - 1].y + list[j - 1].height
  28676. ) {
  28677. break;
  28678. }
  28679. }
  28680. }
  28681. function changeX(list, isDownList, cx, cy, r, dir) {
  28682. var lastDeltaX = dir > 0
  28683. ? isDownList // 右侧
  28684. ? Number.MAX_VALUE // 下
  28685. : 0 // 上
  28686. : isDownList // 左侧
  28687. ? Number.MAX_VALUE // 下
  28688. : 0; // 上
  28689. for (var i = 0, l = list.length; i < l; i++) {
  28690. // Not change x for center label
  28691. if (list[i].position === 'center') {
  28692. continue;
  28693. }
  28694. var deltaY = Math.abs(list[i].y - cy);
  28695. var length = list[i].len;
  28696. var length2 = list[i].len2;
  28697. var deltaX = (deltaY < r + length)
  28698. ? Math.sqrt(
  28699. (r + length + length2) * (r + length + length2)
  28700. - deltaY * deltaY
  28701. )
  28702. : Math.abs(list[i].x - cx);
  28703. if (isDownList && deltaX >= lastDeltaX) {
  28704. // 右下,左下
  28705. deltaX = lastDeltaX - 10;
  28706. }
  28707. if (!isDownList && deltaX <= lastDeltaX) {
  28708. // 右上,左上
  28709. deltaX = lastDeltaX + 10;
  28710. }
  28711. list[i].x = cx + deltaX * dir;
  28712. lastDeltaX = deltaX;
  28713. }
  28714. }
  28715. var lastY = 0;
  28716. var delta;
  28717. var len = list.length;
  28718. var upList = [];
  28719. var downList = [];
  28720. for (var i = 0; i < len; i++) {
  28721. delta = list[i].y - lastY;
  28722. if (delta < 0) {
  28723. shiftDown(i, len, -delta, dir);
  28724. }
  28725. lastY = list[i].y + list[i].height;
  28726. }
  28727. if (viewHeight - lastY < 0) {
  28728. shiftUp(len - 1, lastY - viewHeight);
  28729. }
  28730. for (var i = 0; i < len; i++) {
  28731. if (list[i].y >= cy) {
  28732. downList.push(list[i]);
  28733. }
  28734. else {
  28735. upList.push(list[i]);
  28736. }
  28737. }
  28738. changeX(upList, false, cx, cy, r, dir);
  28739. changeX(downList, true, cx, cy, r, dir);
  28740. }
  28741. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  28742. var leftList = [];
  28743. var rightList = [];
  28744. for (var i = 0; i < labelLayoutList.length; i++) {
  28745. if (labelLayoutList[i].x < cx) {
  28746. leftList.push(labelLayoutList[i]);
  28747. }
  28748. else {
  28749. rightList.push(labelLayoutList[i]);
  28750. }
  28751. }
  28752. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  28753. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  28754. for (var i = 0; i < labelLayoutList.length; i++) {
  28755. var linePoints = labelLayoutList[i].linePoints;
  28756. if (linePoints) {
  28757. var dist = linePoints[1][0] - linePoints[2][0];
  28758. if (labelLayoutList[i].x < cx) {
  28759. linePoints[2][0] = labelLayoutList[i].x + 3;
  28760. }
  28761. else {
  28762. linePoints[2][0] = labelLayoutList[i].x - 3;
  28763. }
  28764. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  28765. linePoints[1][0] = linePoints[2][0] + dist;
  28766. }
  28767. }
  28768. }
  28769. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  28770. var data = seriesModel.getData();
  28771. var labelLayoutList = [];
  28772. var cx;
  28773. var cy;
  28774. var hasLabelRotate = false;
  28775. data.each(function (idx) {
  28776. var layout = data.getItemLayout(idx);
  28777. var itemModel = data.getItemModel(idx);
  28778. var labelModel = itemModel.getModel('label.normal');
  28779. // Use position in normal or emphasis
  28780. var labelPosition = labelModel.get('position') || itemModel.get('label.emphasis.position');
  28781. var labelLineModel = itemModel.getModel('labelLine.normal');
  28782. var labelLineLen = labelLineModel.get('length');
  28783. var labelLineLen2 = labelLineModel.get('length2');
  28784. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  28785. var dx = Math.cos(midAngle);
  28786. var dy = Math.sin(midAngle);
  28787. var textX;
  28788. var textY;
  28789. var linePoints;
  28790. var textAlign;
  28791. cx = layout.cx;
  28792. cy = layout.cy;
  28793. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  28794. if (labelPosition === 'center') {
  28795. textX = layout.cx;
  28796. textY = layout.cy;
  28797. textAlign = 'center';
  28798. }
  28799. else {
  28800. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  28801. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  28802. textX = x1 + dx * 3;
  28803. textY = y1 + dy * 3;
  28804. if (!isLabelInside) {
  28805. // For roseType
  28806. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  28807. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  28808. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  28809. var y3 = y2;
  28810. textX = x3 + (dx < 0 ? -5 : 5);
  28811. textY = y3;
  28812. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  28813. }
  28814. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  28815. }
  28816. var font = labelModel.getFont();
  28817. var labelRotate = labelModel.get('rotate')
  28818. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  28819. var text = seriesModel.getFormattedLabel(idx, 'normal')
  28820. || data.getName(idx);
  28821. var textRect = getBoundingRect(
  28822. text, font, textAlign, 'top'
  28823. );
  28824. hasLabelRotate = !!labelRotate;
  28825. layout.label = {
  28826. x: textX,
  28827. y: textY,
  28828. position: labelPosition,
  28829. height: textRect.height,
  28830. len: labelLineLen,
  28831. len2: labelLineLen2,
  28832. linePoints: linePoints,
  28833. textAlign: textAlign,
  28834. verticalAlign: 'middle',
  28835. rotation: labelRotate,
  28836. inside: isLabelInside
  28837. };
  28838. // Not layout the inside label
  28839. if (!isLabelInside) {
  28840. labelLayoutList.push(layout.label);
  28841. }
  28842. });
  28843. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  28844. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  28845. }
  28846. };
  28847. var PI2$4 = Math.PI * 2;
  28848. var RADIAN = Math.PI / 180;
  28849. var pieLayout = function (seriesType, ecModel, api, payload) {
  28850. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28851. var center = seriesModel.get('center');
  28852. var radius = seriesModel.get('radius');
  28853. if (!isArray(radius)) {
  28854. radius = [0, radius];
  28855. }
  28856. if (!isArray(center)) {
  28857. center = [center, center];
  28858. }
  28859. var width = api.getWidth();
  28860. var height = api.getHeight();
  28861. var size = Math.min(width, height);
  28862. var cx = parsePercent$1(center[0], width);
  28863. var cy = parsePercent$1(center[1], height);
  28864. var r0 = parsePercent$1(radius[0], size / 2);
  28865. var r = parsePercent$1(radius[1], size / 2);
  28866. var data = seriesModel.getData();
  28867. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  28868. var minAngle = seriesModel.get('minAngle') * RADIAN;
  28869. var validDataCount = 0;
  28870. data.each('value', function (value) {
  28871. !isNaN(value) && validDataCount++;
  28872. });
  28873. var sum = data.getSum('value');
  28874. // Sum may be 0
  28875. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  28876. var clockwise = seriesModel.get('clockwise');
  28877. var roseType = seriesModel.get('roseType');
  28878. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  28879. // [0...max]
  28880. var extent = data.getDataExtent('value');
  28881. extent[0] = 0;
  28882. // In the case some sector angle is smaller than minAngle
  28883. var restAngle = PI2$4;
  28884. var valueSumLargerThanMinAngle = 0;
  28885. var currentAngle = startAngle;
  28886. var dir = clockwise ? 1 : -1;
  28887. data.each('value', function (value, idx) {
  28888. var angle;
  28889. if (isNaN(value)) {
  28890. data.setItemLayout(idx, {
  28891. angle: NaN,
  28892. startAngle: NaN,
  28893. endAngle: NaN,
  28894. clockwise: clockwise,
  28895. cx: cx,
  28896. cy: cy,
  28897. r0: r0,
  28898. r: roseType
  28899. ? NaN
  28900. : r
  28901. });
  28902. return;
  28903. }
  28904. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  28905. if (roseType !== 'area') {
  28906. angle = (sum === 0 && stillShowZeroSum)
  28907. ? unitRadian : (value * unitRadian);
  28908. }
  28909. else {
  28910. angle = PI2$4 / validDataCount;
  28911. }
  28912. if (angle < minAngle) {
  28913. angle = minAngle;
  28914. restAngle -= minAngle;
  28915. }
  28916. else {
  28917. valueSumLargerThanMinAngle += value;
  28918. }
  28919. var endAngle = currentAngle + dir * angle;
  28920. data.setItemLayout(idx, {
  28921. angle: angle,
  28922. startAngle: currentAngle,
  28923. endAngle: endAngle,
  28924. clockwise: clockwise,
  28925. cx: cx,
  28926. cy: cy,
  28927. r0: r0,
  28928. r: roseType
  28929. ? linearMap(value, extent, [r0, r])
  28930. : r
  28931. });
  28932. currentAngle = endAngle;
  28933. }, true);
  28934. // Some sector is constrained by minAngle
  28935. // Rest sectors needs recalculate angle
  28936. if (restAngle < PI2$4 && validDataCount) {
  28937. // Average the angle if rest angle is not enough after all angles is
  28938. // Constrained by minAngle
  28939. if (restAngle <= 1e-3) {
  28940. var angle = PI2$4 / validDataCount;
  28941. data.each('value', function (value, idx) {
  28942. if (!isNaN(value)) {
  28943. var layout = data.getItemLayout(idx);
  28944. layout.angle = angle;
  28945. layout.startAngle = startAngle + dir * idx * angle;
  28946. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  28947. }
  28948. });
  28949. }
  28950. else {
  28951. unitRadian = restAngle / valueSumLargerThanMinAngle;
  28952. currentAngle = startAngle;
  28953. data.each('value', function (value, idx) {
  28954. if (!isNaN(value)) {
  28955. var layout = data.getItemLayout(idx);
  28956. var angle = layout.angle === minAngle
  28957. ? minAngle : value * unitRadian;
  28958. layout.startAngle = currentAngle;
  28959. layout.endAngle = currentAngle + dir * angle;
  28960. currentAngle += dir * angle;
  28961. }
  28962. });
  28963. }
  28964. }
  28965. labelLayout(seriesModel, r, width, height);
  28966. });
  28967. };
  28968. var dataFilter = function (seriesType, ecModel) {
  28969. var legendModels = ecModel.findComponents({
  28970. mainType: 'legend'
  28971. });
  28972. if (!legendModels || !legendModels.length) {
  28973. return;
  28974. }
  28975. ecModel.eachSeriesByType(seriesType, function (series) {
  28976. var data = series.getData();
  28977. data.filterSelf(function (idx) {
  28978. var name = data.getName(idx);
  28979. // If in any legend component the status is not selected.
  28980. for (var i = 0; i < legendModels.length; i++) {
  28981. if (!legendModels[i].isSelected(name)) {
  28982. return false;
  28983. }
  28984. }
  28985. return true;
  28986. }, this);
  28987. }, this);
  28988. };
  28989. createDataSelectAction('pie', [{
  28990. type: 'pieToggleSelect',
  28991. event: 'pieselectchanged',
  28992. method: 'toggleSelected'
  28993. }, {
  28994. type: 'pieSelect',
  28995. event: 'pieselected',
  28996. method: 'select'
  28997. }, {
  28998. type: 'pieUnSelect',
  28999. event: 'pieunselected',
  29000. method: 'unSelect'
  29001. }]);
  29002. registerVisual(curry(dataColor, 'pie'));
  29003. registerLayout(curry(pieLayout, 'pie'));
  29004. registerProcessor(curry(dataFilter, 'pie'));
  29005. SeriesModel.extend({
  29006. type: 'series.scatter',
  29007. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  29008. getInitialData: function (option, ecModel) {
  29009. return createListFromArray(option.data, this, ecModel);
  29010. },
  29011. brushSelector: 'point',
  29012. defaultOption: {
  29013. coordinateSystem: 'cartesian2d',
  29014. zlevel: 0,
  29015. z: 2,
  29016. legendHoverLink: true,
  29017. hoverAnimation: true,
  29018. // Cartesian coordinate system
  29019. // xAxisIndex: 0,
  29020. // yAxisIndex: 0,
  29021. // Polar coordinate system
  29022. // polarIndex: 0,
  29023. // Geo coordinate system
  29024. // geoIndex: 0,
  29025. // symbol: null, // 图形类型
  29026. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  29027. // symbolRotate: null, // 图形旋转控制
  29028. large: false,
  29029. // Available when large is true
  29030. largeThreshold: 2000,
  29031. // cursor: null,
  29032. // label: {
  29033. // normal: {
  29034. // show: false
  29035. // distance: 5,
  29036. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  29037. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  29038. // 'inside'|'left'|'right'|'top'|'bottom'
  29039. // 默认使用全局文本样式,详见TEXTSTYLE
  29040. // }
  29041. // },
  29042. itemStyle: {
  29043. normal: {
  29044. opacity: 0.8
  29045. // color: 各异
  29046. }
  29047. }
  29048. }
  29049. });
  29050. // TODO Batch by color
  29051. var LargeSymbolPath = extendShape({
  29052. shape: {
  29053. points: null,
  29054. sizes: null
  29055. },
  29056. symbolProxy: null,
  29057. buildPath: function (path, shape) {
  29058. var points = shape.points;
  29059. var sizes = shape.sizes;
  29060. var symbolProxy = this.symbolProxy;
  29061. var symbolProxyShape = symbolProxy.shape;
  29062. for (var i = 0; i < points.length; i++) {
  29063. var pt = points[i];
  29064. if (isNaN(pt[0]) || isNaN(pt[1])) {
  29065. continue;
  29066. }
  29067. var size = sizes[i];
  29068. if (size[0] < 4) {
  29069. // Optimize for small symbol
  29070. path.rect(
  29071. pt[0] - size[0] / 2, pt[1] - size[1] / 2,
  29072. size[0], size[1]
  29073. );
  29074. }
  29075. else {
  29076. symbolProxyShape.x = pt[0] - size[0] / 2;
  29077. symbolProxyShape.y = pt[1] - size[1] / 2;
  29078. symbolProxyShape.width = size[0];
  29079. symbolProxyShape.height = size[1];
  29080. symbolProxy.buildPath(path, symbolProxyShape, true);
  29081. }
  29082. }
  29083. },
  29084. findDataIndex: function (x, y) {
  29085. var shape = this.shape;
  29086. var points = shape.points;
  29087. var sizes = shape.sizes;
  29088. // Not consider transform
  29089. // Treat each element as a rect
  29090. // top down traverse
  29091. for (var i = points.length - 1; i >= 0; i--) {
  29092. var pt = points[i];
  29093. var size = sizes[i];
  29094. var x0 = pt[0] - size[0] / 2;
  29095. var y0 = pt[1] - size[1] / 2;
  29096. if (x >= x0 && y >= y0 && x <= x0 + size[0] && y <= y0 + size[1]) {
  29097. // i is dataIndex
  29098. return i;
  29099. }
  29100. }
  29101. return -1;
  29102. }
  29103. });
  29104. function LargeSymbolDraw() {
  29105. this.group = new Group();
  29106. this._symbolEl = new LargeSymbolPath({
  29107. // rectHover: true,
  29108. // cursor: 'default'
  29109. });
  29110. }
  29111. var largeSymbolProto = LargeSymbolDraw.prototype;
  29112. /**
  29113. * Update symbols draw by new data
  29114. * @param {module:echarts/data/List} data
  29115. */
  29116. largeSymbolProto.updateData = function (data) {
  29117. this.group.removeAll();
  29118. var symbolEl = this._symbolEl;
  29119. var seriesModel = data.hostModel;
  29120. symbolEl.setShape({
  29121. points: data.mapArray(data.getItemLayout),
  29122. sizes: data.mapArray(
  29123. function (idx) {
  29124. var size = data.getItemVisual(idx, 'symbolSize');
  29125. if (!(size instanceof Array)) {
  29126. size = [size, size];
  29127. }
  29128. return size;
  29129. }
  29130. )
  29131. });
  29132. // Create symbolProxy to build path for each data
  29133. symbolEl.symbolProxy = createSymbol(
  29134. data.getVisual('symbol'), 0, 0, 0, 0
  29135. );
  29136. // Use symbolProxy setColor method
  29137. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  29138. symbolEl.useStyle(
  29139. seriesModel.getModel('itemStyle.normal').getItemStyle(['color'])
  29140. );
  29141. var visualColor = data.getVisual('color');
  29142. if (visualColor) {
  29143. symbolEl.setColor(visualColor);
  29144. }
  29145. // Enable tooltip
  29146. // PENDING May have performance issue when path is extremely large
  29147. symbolEl.seriesIndex = seriesModel.seriesIndex;
  29148. symbolEl.on('mousemove', function (e) {
  29149. symbolEl.dataIndex = null;
  29150. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  29151. if (dataIndex >= 0) {
  29152. // Provide dataIndex for tooltip
  29153. symbolEl.dataIndex = dataIndex;
  29154. }
  29155. });
  29156. // Add back
  29157. this.group.add(symbolEl);
  29158. };
  29159. largeSymbolProto.updateLayout = function (seriesModel) {
  29160. var data = seriesModel.getData();
  29161. this._symbolEl.setShape({
  29162. points: data.mapArray(data.getItemLayout)
  29163. });
  29164. };
  29165. largeSymbolProto.remove = function () {
  29166. this.group.removeAll();
  29167. };
  29168. extendChartView({
  29169. type: 'scatter',
  29170. init: function () {
  29171. this._normalSymbolDraw = new SymbolDraw();
  29172. this._largeSymbolDraw = new LargeSymbolDraw();
  29173. },
  29174. render: function (seriesModel, ecModel, api) {
  29175. var data = seriesModel.getData();
  29176. var largeSymbolDraw = this._largeSymbolDraw;
  29177. var normalSymbolDraw = this._normalSymbolDraw;
  29178. var group = this.group;
  29179. var symbolDraw = seriesModel.get('large') && data.count() > seriesModel.get('largeThreshold')
  29180. ? largeSymbolDraw : normalSymbolDraw;
  29181. this._symbolDraw = symbolDraw;
  29182. symbolDraw.updateData(data);
  29183. group.add(symbolDraw.group);
  29184. group.remove(
  29185. symbolDraw === largeSymbolDraw
  29186. ? normalSymbolDraw.group : largeSymbolDraw.group
  29187. );
  29188. },
  29189. updateLayout: function (seriesModel) {
  29190. this._symbolDraw.updateLayout(seriesModel);
  29191. },
  29192. remove: function (ecModel, api) {
  29193. this._symbolDraw && this._symbolDraw.remove(api, true);
  29194. },
  29195. dispose: function () {}
  29196. });
  29197. // In case developer forget to include grid component
  29198. registerVisual(curry(visualSymbol, 'scatter', 'circle', null));
  29199. registerLayout(curry(layoutPoints, 'scatter'));
  29200. function IndicatorAxis(dim, scale, radiusExtent) {
  29201. Axis.call(this, dim, scale, radiusExtent);
  29202. /**
  29203. * Axis type
  29204. * - 'category'
  29205. * - 'value'
  29206. * - 'time'
  29207. * - 'log'
  29208. * @type {string}
  29209. */
  29210. this.type = 'value';
  29211. this.angle = 0;
  29212. /**
  29213. * Indicator name
  29214. * @type {string}
  29215. */
  29216. this.name = '';
  29217. /**
  29218. * @type {module:echarts/model/Model}
  29219. */
  29220. this.model;
  29221. }
  29222. inherits(IndicatorAxis, Axis);
  29223. // TODO clockwise
  29224. function Radar(radarModel, ecModel, api) {
  29225. this._model = radarModel;
  29226. /**
  29227. * Radar dimensions
  29228. * @type {Array.<string>}
  29229. */
  29230. this.dimensions = [];
  29231. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  29232. var dim = 'indicator_' + idx;
  29233. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  29234. indicatorAxis.name = indicatorModel.get('name');
  29235. // Inject model and axis
  29236. indicatorAxis.model = indicatorModel;
  29237. indicatorModel.axis = indicatorAxis;
  29238. this.dimensions.push(dim);
  29239. return indicatorAxis;
  29240. }, this);
  29241. this.resize(radarModel, api);
  29242. /**
  29243. * @type {number}
  29244. * @readOnly
  29245. */
  29246. this.cx;
  29247. /**
  29248. * @type {number}
  29249. * @readOnly
  29250. */
  29251. this.cy;
  29252. /**
  29253. * @type {number}
  29254. * @readOnly
  29255. */
  29256. this.r;
  29257. /**
  29258. * @type {number}
  29259. * @readOnly
  29260. */
  29261. this.startAngle;
  29262. }
  29263. Radar.prototype.getIndicatorAxes = function () {
  29264. return this._indicatorAxes;
  29265. };
  29266. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  29267. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  29268. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  29269. };
  29270. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  29271. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  29272. var angle = indicatorAxis.angle;
  29273. var x = this.cx + coord * Math.cos(angle);
  29274. var y = this.cy - coord * Math.sin(angle);
  29275. return [x, y];
  29276. };
  29277. Radar.prototype.pointToData = function (pt) {
  29278. var dx = pt[0] - this.cx;
  29279. var dy = pt[1] - this.cy;
  29280. var radius = Math.sqrt(dx * dx + dy * dy);
  29281. dx /= radius;
  29282. dy /= radius;
  29283. var radian = Math.atan2(-dy, dx);
  29284. // Find the closest angle
  29285. // FIXME index can calculated directly
  29286. var minRadianDiff = Infinity;
  29287. var closestAxis;
  29288. var closestAxisIdx = -1;
  29289. for (var i = 0; i < this._indicatorAxes.length; i++) {
  29290. var indicatorAxis = this._indicatorAxes[i];
  29291. var diff = Math.abs(radian - indicatorAxis.angle);
  29292. if (diff < minRadianDiff) {
  29293. closestAxis = indicatorAxis;
  29294. closestAxisIdx = i;
  29295. minRadianDiff = diff;
  29296. }
  29297. }
  29298. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  29299. };
  29300. Radar.prototype.resize = function (radarModel, api) {
  29301. var center = radarModel.get('center');
  29302. var viewWidth = api.getWidth();
  29303. var viewHeight = api.getHeight();
  29304. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  29305. this.cx = parsePercent$1(center[0], viewWidth);
  29306. this.cy = parsePercent$1(center[1], viewHeight);
  29307. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  29308. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  29309. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  29310. indicatorAxis.setExtent(0, this.r);
  29311. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  29312. // Normalize to [-PI, PI]
  29313. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  29314. indicatorAxis.angle = angle;
  29315. }, this);
  29316. };
  29317. Radar.prototype.update = function (ecModel, api) {
  29318. var indicatorAxes = this._indicatorAxes;
  29319. var radarModel = this._model;
  29320. each$1(indicatorAxes, function (indicatorAxis) {
  29321. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  29322. });
  29323. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  29324. if (radarSeries.get('coordinateSystem') !== 'radar'
  29325. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  29326. ) {
  29327. return;
  29328. }
  29329. var data = radarSeries.getData();
  29330. each$1(indicatorAxes, function (indicatorAxis) {
  29331. indicatorAxis.scale.unionExtentFromData(data, indicatorAxis.dim);
  29332. });
  29333. }, this);
  29334. var splitNumber = radarModel.get('splitNumber');
  29335. function increaseInterval(interval) {
  29336. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  29337. // Increase interval
  29338. var f = interval / exp10;
  29339. if (f === 2) {
  29340. f = 5;
  29341. }
  29342. else { // f is 2 or 5
  29343. f *= 2;
  29344. }
  29345. return f * exp10;
  29346. }
  29347. // Force all the axis fixing the maxSplitNumber.
  29348. each$1(indicatorAxes, function (indicatorAxis, idx) {
  29349. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  29350. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  29351. var axisModel = indicatorAxis.model;
  29352. var scale = indicatorAxis.scale;
  29353. var fixedMin = axisModel.getMin();
  29354. var fixedMax = axisModel.getMax();
  29355. var interval = scale.getInterval();
  29356. if (fixedMin != null && fixedMax != null) {
  29357. // User set min, max, divide to get new interval
  29358. scale.setExtent(+fixedMin, +fixedMax);
  29359. scale.setInterval(
  29360. (fixedMax - fixedMin) / splitNumber
  29361. );
  29362. }
  29363. else if (fixedMin != null) {
  29364. var max;
  29365. // User set min, expand extent on the other side
  29366. do {
  29367. max = fixedMin + interval * splitNumber;
  29368. scale.setExtent(+fixedMin, max);
  29369. // Interval must been set after extent
  29370. // FIXME
  29371. scale.setInterval(interval);
  29372. interval = increaseInterval(interval);
  29373. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  29374. }
  29375. else if (fixedMax != null) {
  29376. var min;
  29377. // User set min, expand extent on the other side
  29378. do {
  29379. min = fixedMax - interval * splitNumber;
  29380. scale.setExtent(min, +fixedMax);
  29381. scale.setInterval(interval);
  29382. interval = increaseInterval(interval);
  29383. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  29384. }
  29385. else {
  29386. var nicedSplitNumber = scale.getTicks().length - 1;
  29387. if (nicedSplitNumber > splitNumber) {
  29388. interval = increaseInterval(interval);
  29389. }
  29390. // PENDING
  29391. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  29392. var halfSplitNumber = Math.round(splitNumber / 2);
  29393. scale.setExtent(
  29394. round(center - halfSplitNumber * interval),
  29395. round(center + (splitNumber - halfSplitNumber) * interval)
  29396. );
  29397. scale.setInterval(interval);
  29398. }
  29399. });
  29400. };
  29401. /**
  29402. * Radar dimensions is based on the data
  29403. * @type {Array}
  29404. */
  29405. Radar.dimensions = [];
  29406. Radar.create = function (ecModel, api) {
  29407. var radarList = [];
  29408. ecModel.eachComponent('radar', function (radarModel) {
  29409. var radar = new Radar(radarModel, ecModel, api);
  29410. radarList.push(radar);
  29411. radarModel.coordinateSystem = radar;
  29412. });
  29413. ecModel.eachSeriesByType('radar', function (radarSeries) {
  29414. if (radarSeries.get('coordinateSystem') === 'radar') {
  29415. // Inject coordinate system
  29416. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  29417. }
  29418. });
  29419. return radarList;
  29420. };
  29421. CoordinateSystemManager.register('radar', Radar);
  29422. var valueAxisDefault = axisDefault.valueAxis;
  29423. function defaultsShow(opt, show) {
  29424. return defaults({
  29425. show: show
  29426. }, opt);
  29427. }
  29428. var RadarModel = extendComponentModel({
  29429. type: 'radar',
  29430. optionUpdated: function () {
  29431. var boundaryGap = this.get('boundaryGap');
  29432. var splitNumber = this.get('splitNumber');
  29433. var scale = this.get('scale');
  29434. var axisLine = this.get('axisLine');
  29435. var axisTick = this.get('axisTick');
  29436. var axisLabel = this.get('axisLabel');
  29437. var nameTextStyle = this.get('name');
  29438. var showName = this.get('name.show');
  29439. var nameFormatter = this.get('name.formatter');
  29440. var nameGap = this.get('nameGap');
  29441. var triggerEvent = this.get('triggerEvent');
  29442. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  29443. // PENDING
  29444. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  29445. indicatorOpt.min = 0;
  29446. }
  29447. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  29448. indicatorOpt.max = 0;
  29449. }
  29450. var iNameTextStyle = nameTextStyle;
  29451. if(indicatorOpt.color != null) {
  29452. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  29453. }
  29454. // Use same configuration
  29455. indicatorOpt = merge(clone(indicatorOpt), {
  29456. boundaryGap: boundaryGap,
  29457. splitNumber: splitNumber,
  29458. scale: scale,
  29459. axisLine: axisLine,
  29460. axisTick: axisTick,
  29461. axisLabel: axisLabel,
  29462. // Competitable with 2 and use text
  29463. name: indicatorOpt.text,
  29464. nameLocation: 'end',
  29465. nameGap: nameGap,
  29466. // min: 0,
  29467. nameTextStyle: iNameTextStyle,
  29468. triggerEvent: triggerEvent
  29469. }, false);
  29470. if (!showName) {
  29471. indicatorOpt.name = '';
  29472. }
  29473. if (typeof nameFormatter === 'string') {
  29474. var indName = indicatorOpt.name;
  29475. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  29476. }
  29477. else if (typeof nameFormatter === 'function') {
  29478. indicatorOpt.name = nameFormatter(
  29479. indicatorOpt.name, indicatorOpt
  29480. );
  29481. }
  29482. var model = extend(
  29483. new Model(indicatorOpt, null, this.ecModel),
  29484. axisModelCommonMixin
  29485. );
  29486. // For triggerEvent.
  29487. model.mainType = 'radar';
  29488. model.componentIndex = this.componentIndex;
  29489. return model;
  29490. }, this);
  29491. this.getIndicatorModels = function () {
  29492. return indicatorModels;
  29493. };
  29494. },
  29495. defaultOption: {
  29496. zlevel: 0,
  29497. z: 0,
  29498. center: ['50%', '50%'],
  29499. radius: '75%',
  29500. startAngle: 90,
  29501. name: {
  29502. show: true
  29503. // formatter: null
  29504. // textStyle: {}
  29505. },
  29506. boundaryGap: [0, 0],
  29507. splitNumber: 5,
  29508. nameGap: 15,
  29509. scale: false,
  29510. // Polygon or circle
  29511. shape: 'polygon',
  29512. axisLine: merge(
  29513. {
  29514. lineStyle: {
  29515. color: '#bbb'
  29516. }
  29517. },
  29518. valueAxisDefault.axisLine
  29519. ),
  29520. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  29521. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  29522. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  29523. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  29524. // {text, min, max}
  29525. indicator: []
  29526. }
  29527. });
  29528. var axisBuilderAttrs$1 = [
  29529. 'axisLine', 'axisTickLabel', 'axisName'
  29530. ];
  29531. extendComponentView({
  29532. type: 'radar',
  29533. render: function (radarModel, ecModel, api) {
  29534. var group = this.group;
  29535. group.removeAll();
  29536. this._buildAxes(radarModel);
  29537. this._buildSplitLineAndArea(radarModel);
  29538. },
  29539. _buildAxes: function (radarModel) {
  29540. var radar = radarModel.coordinateSystem;
  29541. var indicatorAxes = radar.getIndicatorAxes();
  29542. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  29543. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  29544. position: [radar.cx, radar.cy],
  29545. rotation: indicatorAxis.angle,
  29546. labelDirection: -1,
  29547. tickDirection: -1,
  29548. nameDirection: 1
  29549. });
  29550. return axisBuilder;
  29551. });
  29552. each$1(axisBuilders, function (axisBuilder) {
  29553. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  29554. this.group.add(axisBuilder.getGroup());
  29555. }, this);
  29556. },
  29557. _buildSplitLineAndArea: function (radarModel) {
  29558. var radar = radarModel.coordinateSystem;
  29559. var indicatorAxes = radar.getIndicatorAxes();
  29560. if (!indicatorAxes.length) {
  29561. return;
  29562. }
  29563. var shape = radarModel.get('shape');
  29564. var splitLineModel = radarModel.getModel('splitLine');
  29565. var splitAreaModel = radarModel.getModel('splitArea');
  29566. var lineStyleModel = splitLineModel.getModel('lineStyle');
  29567. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  29568. var showSplitLine = splitLineModel.get('show');
  29569. var showSplitArea = splitAreaModel.get('show');
  29570. var splitLineColors = lineStyleModel.get('color');
  29571. var splitAreaColors = areaStyleModel.get('color');
  29572. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  29573. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  29574. var splitLines = [];
  29575. var splitAreas = [];
  29576. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  29577. var colorIndex = idx % areaOrLineColorList.length;
  29578. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  29579. return colorIndex;
  29580. }
  29581. if (shape === 'circle') {
  29582. var ticksRadius = indicatorAxes[0].getTicksCoords();
  29583. var cx = radar.cx;
  29584. var cy = radar.cy;
  29585. for (var i = 0; i < ticksRadius.length; i++) {
  29586. if (showSplitLine) {
  29587. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  29588. splitLines[colorIndex].push(new Circle({
  29589. shape: {
  29590. cx: cx,
  29591. cy: cy,
  29592. r: ticksRadius[i]
  29593. }
  29594. }));
  29595. }
  29596. if (showSplitArea && i < ticksRadius.length - 1) {
  29597. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  29598. splitAreas[colorIndex].push(new Ring({
  29599. shape: {
  29600. cx: cx,
  29601. cy: cy,
  29602. r0: ticksRadius[i],
  29603. r: ticksRadius[i + 1]
  29604. }
  29605. }));
  29606. }
  29607. }
  29608. }
  29609. // Polyyon
  29610. else {
  29611. var realSplitNumber;
  29612. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  29613. var ticksCoords = indicatorAxis.getTicksCoords();
  29614. realSplitNumber = realSplitNumber == null
  29615. ? ticksCoords.length - 1
  29616. : Math.min(ticksCoords.length - 1, realSplitNumber);
  29617. return map(ticksCoords, function (tickCoord) {
  29618. return radar.coordToPoint(tickCoord, idx);
  29619. });
  29620. });
  29621. var prevPoints = [];
  29622. for (var i = 0; i <= realSplitNumber; i++) {
  29623. var points = [];
  29624. for (var j = 0; j < indicatorAxes.length; j++) {
  29625. points.push(axesTicksPoints[j][i]);
  29626. }
  29627. // Close
  29628. if (points[0]) {
  29629. points.push(points[0].slice());
  29630. }
  29631. else {
  29632. if (__DEV__) {
  29633. console.error('Can\'t draw value axis ' + i);
  29634. }
  29635. }
  29636. if (showSplitLine) {
  29637. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  29638. splitLines[colorIndex].push(new Polyline({
  29639. shape: {
  29640. points: points
  29641. }
  29642. }));
  29643. }
  29644. if (showSplitArea && prevPoints) {
  29645. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  29646. splitAreas[colorIndex].push(new Polygon({
  29647. shape: {
  29648. points: points.concat(prevPoints)
  29649. }
  29650. }));
  29651. }
  29652. prevPoints = points.slice().reverse();
  29653. }
  29654. }
  29655. var lineStyle = lineStyleModel.getLineStyle();
  29656. var areaStyle = areaStyleModel.getAreaStyle();
  29657. // Add splitArea before splitLine
  29658. each$1(splitAreas, function (splitAreas, idx) {
  29659. this.group.add(mergePath(
  29660. splitAreas, {
  29661. style: defaults({
  29662. stroke: 'none',
  29663. fill: splitAreaColors[idx % splitAreaColors.length]
  29664. }, areaStyle),
  29665. silent: true
  29666. }
  29667. ));
  29668. }, this);
  29669. each$1(splitLines, function (splitLines, idx) {
  29670. this.group.add(mergePath(
  29671. splitLines, {
  29672. style: defaults({
  29673. fill: 'none',
  29674. stroke: splitLineColors[idx % splitLineColors.length]
  29675. }, lineStyle),
  29676. silent: true
  29677. }
  29678. ));
  29679. }, this);
  29680. }
  29681. });
  29682. var RadarSeries = SeriesModel.extend({
  29683. type: 'series.radar',
  29684. dependencies: ['radar'],
  29685. // Overwrite
  29686. init: function (option) {
  29687. RadarSeries.superApply(this, 'init', arguments);
  29688. // Enable legend selection for each data item
  29689. // Use a function instead of direct access because data reference may changed
  29690. this.legendDataProvider = function () {
  29691. return this.getRawData();
  29692. };
  29693. },
  29694. getInitialData: function (option, ecModel) {
  29695. var data = option.data || [];
  29696. var dimensions = completeDimensions(
  29697. [], data, {extraPrefix: 'indicator_', extraFromZero: true}
  29698. );
  29699. var list = new List(dimensions, this);
  29700. list.initData(data);
  29701. return list;
  29702. },
  29703. formatTooltip: function (dataIndex) {
  29704. var value = this.getRawValue(dataIndex);
  29705. var coordSys = this.coordinateSystem;
  29706. var indicatorAxes = coordSys.getIndicatorAxes();
  29707. var name = this.getData().getName(dataIndex);
  29708. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  29709. + map(indicatorAxes, function (axis, idx) {
  29710. return encodeHTML(axis.name + ' : ' + value[idx]);
  29711. }).join('<br />');
  29712. },
  29713. defaultOption: {
  29714. zlevel: 0,
  29715. z: 2,
  29716. coordinateSystem: 'radar',
  29717. legendHoverLink: true,
  29718. radarIndex: 0,
  29719. lineStyle: {
  29720. normal: {
  29721. width: 2,
  29722. type: 'solid'
  29723. }
  29724. },
  29725. label: {
  29726. normal: {
  29727. position: 'top'
  29728. }
  29729. },
  29730. // areaStyle: {
  29731. // },
  29732. // itemStyle: {}
  29733. symbol: 'emptyCircle',
  29734. symbolSize: 4
  29735. // symbolRotate: null
  29736. }
  29737. });
  29738. function normalizeSymbolSize(symbolSize) {
  29739. if (!isArray(symbolSize)) {
  29740. symbolSize = [+symbolSize, +symbolSize];
  29741. }
  29742. return symbolSize;
  29743. }
  29744. extendChartView({
  29745. type: 'radar',
  29746. render: function (seriesModel, ecModel, api) {
  29747. var polar = seriesModel.coordinateSystem;
  29748. var group = this.group;
  29749. var data = seriesModel.getData();
  29750. var oldData = this._data;
  29751. function createSymbol$$1(data, idx) {
  29752. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29753. var color = data.getItemVisual(idx, 'color');
  29754. if (symbolType === 'none') {
  29755. return;
  29756. }
  29757. var symbolSize = normalizeSymbolSize(
  29758. data.getItemVisual(idx, 'symbolSize')
  29759. );
  29760. var symbolPath = createSymbol(
  29761. symbolType, -1, -1, 2, 2, color
  29762. );
  29763. symbolPath.attr({
  29764. style: {
  29765. strokeNoScale: true
  29766. },
  29767. z2: 100,
  29768. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  29769. });
  29770. return symbolPath;
  29771. }
  29772. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  29773. // Simply rerender all
  29774. symbolGroup.removeAll();
  29775. for (var i = 0; i < newPoints.length - 1; i++) {
  29776. var symbolPath = createSymbol$$1(data, idx);
  29777. if (symbolPath) {
  29778. symbolPath.__dimIdx = i;
  29779. if (oldPoints[i]) {
  29780. symbolPath.attr('position', oldPoints[i]);
  29781. graphic[isInit ? 'initProps' : 'updateProps'](
  29782. symbolPath, {
  29783. position: newPoints[i]
  29784. }, seriesModel, idx
  29785. );
  29786. }
  29787. else {
  29788. symbolPath.attr('position', newPoints[i]);
  29789. }
  29790. symbolGroup.add(symbolPath);
  29791. }
  29792. }
  29793. }
  29794. function getInitialPoints(points) {
  29795. return map(points, function (pt) {
  29796. return [polar.cx, polar.cy];
  29797. });
  29798. }
  29799. data.diff(oldData)
  29800. .add(function (idx) {
  29801. var points = data.getItemLayout(idx);
  29802. if (!points) {
  29803. return;
  29804. }
  29805. var polygon = new Polygon();
  29806. var polyline = new Polyline();
  29807. var target = {
  29808. shape: {
  29809. points: points
  29810. }
  29811. };
  29812. polygon.shape.points = getInitialPoints(points);
  29813. polyline.shape.points = getInitialPoints(points);
  29814. initProps(polygon, target, seriesModel, idx);
  29815. initProps(polyline, target, seriesModel, idx);
  29816. var itemGroup = new Group();
  29817. var symbolGroup = new Group();
  29818. itemGroup.add(polyline);
  29819. itemGroup.add(polygon);
  29820. itemGroup.add(symbolGroup);
  29821. updateSymbols(
  29822. polyline.shape.points, points, symbolGroup, data, idx, true
  29823. );
  29824. data.setItemGraphicEl(idx, itemGroup);
  29825. })
  29826. .update(function (newIdx, oldIdx) {
  29827. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  29828. var polyline = itemGroup.childAt(0);
  29829. var polygon = itemGroup.childAt(1);
  29830. var symbolGroup = itemGroup.childAt(2);
  29831. var target = {
  29832. shape: {
  29833. points: data.getItemLayout(newIdx)
  29834. }
  29835. };
  29836. if (!target.shape.points) {
  29837. return;
  29838. }
  29839. updateSymbols(
  29840. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  29841. );
  29842. updateProps(polyline, target, seriesModel);
  29843. updateProps(polygon, target, seriesModel);
  29844. data.setItemGraphicEl(newIdx, itemGroup);
  29845. })
  29846. .remove(function (idx) {
  29847. group.remove(oldData.getItemGraphicEl(idx));
  29848. })
  29849. .execute();
  29850. data.eachItemGraphicEl(function (itemGroup, idx) {
  29851. var itemModel = data.getItemModel(idx);
  29852. var polyline = itemGroup.childAt(0);
  29853. var polygon = itemGroup.childAt(1);
  29854. var symbolGroup = itemGroup.childAt(2);
  29855. var color = data.getItemVisual(idx, 'color');
  29856. group.add(itemGroup);
  29857. polyline.useStyle(
  29858. defaults(
  29859. itemModel.getModel('lineStyle.normal').getLineStyle(),
  29860. {
  29861. fill: 'none',
  29862. stroke: color
  29863. }
  29864. )
  29865. );
  29866. polyline.hoverStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  29867. var areaStyleModel = itemModel.getModel('areaStyle.normal');
  29868. var hoverAreaStyleModel = itemModel.getModel('areaStyle.emphasis');
  29869. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  29870. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  29871. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  29872. polygon.ignore = polygonIgnore;
  29873. polygon.useStyle(
  29874. defaults(
  29875. areaStyleModel.getAreaStyle(),
  29876. {
  29877. fill: color,
  29878. opacity: 0.7
  29879. }
  29880. )
  29881. );
  29882. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  29883. var itemStyle = itemModel.getModel('itemStyle.normal').getItemStyle(['color']);
  29884. var itemHoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  29885. var labelModel = itemModel.getModel('label.normal');
  29886. var labelHoverModel = itemModel.getModel('label.emphasis');
  29887. symbolGroup.eachChild(function (symbolPath) {
  29888. symbolPath.setStyle(itemStyle);
  29889. symbolPath.hoverStyle = clone(itemHoverStyle);
  29890. setLabelStyle(
  29891. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  29892. {
  29893. labelFetcher: data.hostModel,
  29894. labelDataIndex: idx,
  29895. labelDimIndex: symbolPath.__dimIdx,
  29896. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  29897. autoColor: color,
  29898. isRectText: true
  29899. }
  29900. );
  29901. });
  29902. function onEmphasis() {
  29903. polygon.attr('ignore', hoverPolygonIgnore);
  29904. }
  29905. function onNormal() {
  29906. polygon.attr('ignore', polygonIgnore);
  29907. }
  29908. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  29909. itemGroup.on('emphasis', onEmphasis)
  29910. .on('mouseover', onEmphasis)
  29911. .on('normal', onNormal)
  29912. .on('mouseout', onNormal);
  29913. setHoverStyle(itemGroup);
  29914. });
  29915. this._data = data;
  29916. },
  29917. remove: function () {
  29918. this.group.removeAll();
  29919. this._data = null;
  29920. },
  29921. dispose: function () {}
  29922. });
  29923. var radarLayout = function (ecModel) {
  29924. ecModel.eachSeriesByType('radar', function (seriesModel) {
  29925. var data = seriesModel.getData();
  29926. var points = [];
  29927. var coordSys = seriesModel.coordinateSystem;
  29928. if (!coordSys) {
  29929. return;
  29930. }
  29931. function pointsConverter(val, idx) {
  29932. points[idx] = points[idx] || [];
  29933. points[idx][i] = coordSys.dataToPoint(val, i);
  29934. }
  29935. for (var i = 0; i < coordSys.getIndicatorAxes().length; i++) {
  29936. var dim = data.dimensions[i];
  29937. data.each(dim, pointsConverter);
  29938. }
  29939. data.each(function (idx) {
  29940. // Close polygon
  29941. points[idx][0] && points[idx].push(points[idx][0].slice());
  29942. data.setItemLayout(idx, points[idx]);
  29943. });
  29944. });
  29945. };
  29946. // Backward compat for radar chart in 2
  29947. var backwardCompat$1 = function (option) {
  29948. var polarOptArr = option.polar;
  29949. if (polarOptArr) {
  29950. if (!isArray(polarOptArr)) {
  29951. polarOptArr = [polarOptArr];
  29952. }
  29953. var polarNotRadar = [];
  29954. each$1(polarOptArr, function (polarOpt, idx) {
  29955. if (polarOpt.indicator) {
  29956. if (polarOpt.type && !polarOpt.shape) {
  29957. polarOpt.shape = polarOpt.type;
  29958. }
  29959. option.radar = option.radar || [];
  29960. if (!isArray(option.radar)) {
  29961. option.radar = [option.radar];
  29962. }
  29963. option.radar.push(polarOpt);
  29964. }
  29965. else {
  29966. polarNotRadar.push(polarOpt);
  29967. }
  29968. });
  29969. option.polar = polarNotRadar;
  29970. }
  29971. each$1(option.series, function (seriesOpt) {
  29972. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  29973. seriesOpt.radarIndex = seriesOpt.polarIndex;
  29974. }
  29975. });
  29976. };
  29977. // Must use radar component
  29978. registerVisual(curry(dataColor, 'radar'));
  29979. registerVisual(curry(visualSymbol, 'radar', 'circle', null));
  29980. registerLayout(radarLayout);
  29981. registerProcessor(curry(dataFilter, 'radar'));
  29982. registerPreprocessor(backwardCompat$1);
  29983. /**
  29984. * Simple view coordinate system
  29985. * Mapping given x, y to transformd view x, y
  29986. */
  29987. var v2ApplyTransform$1 = applyTransform;
  29988. // Dummy transform node
  29989. function TransformDummy() {
  29990. Transformable.call(this);
  29991. }
  29992. mixin(TransformDummy, Transformable);
  29993. function View(name) {
  29994. /**
  29995. * @type {string}
  29996. */
  29997. this.name = name;
  29998. /**
  29999. * @type {Object}
  30000. */
  30001. this.zoomLimit;
  30002. Transformable.call(this);
  30003. this._roamTransform = new TransformDummy();
  30004. this._viewTransform = new TransformDummy();
  30005. this._center;
  30006. this._zoom;
  30007. }
  30008. View.prototype = {
  30009. constructor: View,
  30010. type: 'view',
  30011. /**
  30012. * @param {Array.<string>}
  30013. * @readOnly
  30014. */
  30015. dimensions: ['x', 'y'],
  30016. /**
  30017. * Set bounding rect
  30018. * @param {number} x
  30019. * @param {number} y
  30020. * @param {number} width
  30021. * @param {number} height
  30022. */
  30023. // PENDING to getRect
  30024. setBoundingRect: function (x, y, width, height) {
  30025. this._rect = new BoundingRect(x, y, width, height);
  30026. return this._rect;
  30027. },
  30028. /**
  30029. * @return {module:zrender/core/BoundingRect}
  30030. */
  30031. // PENDING to getRect
  30032. getBoundingRect: function () {
  30033. return this._rect;
  30034. },
  30035. /**
  30036. * @param {number} x
  30037. * @param {number} y
  30038. * @param {number} width
  30039. * @param {number} height
  30040. */
  30041. setViewRect: function (x, y, width, height) {
  30042. this.transformTo(x, y, width, height);
  30043. this._viewRect = new BoundingRect(x, y, width, height);
  30044. },
  30045. /**
  30046. * Transformed to particular position and size
  30047. * @param {number} x
  30048. * @param {number} y
  30049. * @param {number} width
  30050. * @param {number} height
  30051. */
  30052. transformTo: function (x, y, width, height) {
  30053. var rect = this.getBoundingRect();
  30054. var viewTransform = this._viewTransform;
  30055. viewTransform.transform = rect.calculateTransform(
  30056. new BoundingRect(x, y, width, height)
  30057. );
  30058. viewTransform.decomposeTransform();
  30059. this._updateTransform();
  30060. },
  30061. /**
  30062. * Set center of view
  30063. * @param {Array.<number>} [centerCoord]
  30064. */
  30065. setCenter: function (centerCoord) {
  30066. if (!centerCoord) {
  30067. return;
  30068. }
  30069. this._center = centerCoord;
  30070. this._updateCenterAndZoom();
  30071. },
  30072. /**
  30073. * @param {number} zoom
  30074. */
  30075. setZoom: function (zoom) {
  30076. zoom = zoom || 1;
  30077. var zoomLimit = this.zoomLimit;
  30078. if (zoomLimit) {
  30079. if (zoomLimit.max != null) {
  30080. zoom = Math.min(zoomLimit.max, zoom);
  30081. }
  30082. if (zoomLimit.min != null) {
  30083. zoom = Math.max(zoomLimit.min, zoom);
  30084. }
  30085. }
  30086. this._zoom = zoom;
  30087. this._updateCenterAndZoom();
  30088. },
  30089. /**
  30090. * Get default center without roam
  30091. */
  30092. getDefaultCenter: function () {
  30093. // Rect before any transform
  30094. var rawRect = this.getBoundingRect();
  30095. var cx = rawRect.x + rawRect.width / 2;
  30096. var cy = rawRect.y + rawRect.height / 2;
  30097. return [cx, cy];
  30098. },
  30099. getCenter: function () {
  30100. return this._center || this.getDefaultCenter();
  30101. },
  30102. getZoom: function () {
  30103. return this._zoom || 1;
  30104. },
  30105. /**
  30106. * @return {Array.<number}
  30107. */
  30108. getRoamTransform: function () {
  30109. return this._roamTransform;
  30110. },
  30111. _updateCenterAndZoom: function () {
  30112. // Must update after view transform updated
  30113. var viewTransformMatrix = this._viewTransform.getLocalTransform();
  30114. var roamTransform = this._roamTransform;
  30115. var defaultCenter = this.getDefaultCenter();
  30116. var center = this.getCenter();
  30117. var zoom = this.getZoom();
  30118. center = applyTransform([], center, viewTransformMatrix);
  30119. defaultCenter = applyTransform([], defaultCenter, viewTransformMatrix);
  30120. roamTransform.origin = center;
  30121. roamTransform.position = [
  30122. defaultCenter[0] - center[0],
  30123. defaultCenter[1] - center[1]
  30124. ];
  30125. roamTransform.scale = [zoom, zoom];
  30126. this._updateTransform();
  30127. },
  30128. /**
  30129. * Update transform from roam and mapLocation
  30130. * @private
  30131. */
  30132. _updateTransform: function () {
  30133. var roamTransform = this._roamTransform;
  30134. var viewTransform = this._viewTransform;
  30135. viewTransform.parent = roamTransform;
  30136. roamTransform.updateTransform();
  30137. viewTransform.updateTransform();
  30138. viewTransform.transform
  30139. && copy$1(this.transform || (this.transform = []), viewTransform.transform);
  30140. if (this.transform) {
  30141. this.invTransform = this.invTransform || [];
  30142. invert(this.invTransform, this.transform);
  30143. }
  30144. else {
  30145. this.invTransform = null;
  30146. }
  30147. this.decomposeTransform();
  30148. },
  30149. /**
  30150. * @return {module:zrender/core/BoundingRect}
  30151. */
  30152. getViewRect: function () {
  30153. return this._viewRect;
  30154. },
  30155. /**
  30156. * Get view rect after roam transform
  30157. * @return {module:zrender/core/BoundingRect}
  30158. */
  30159. getViewRectAfterRoam: function () {
  30160. var rect = this.getBoundingRect().clone();
  30161. rect.applyTransform(this.transform);
  30162. return rect;
  30163. },
  30164. /**
  30165. * Convert a single (lon, lat) data item to (x, y) point.
  30166. * @param {Array.<number>} data
  30167. * @return {Array.<number>}
  30168. */
  30169. dataToPoint: function (data) {
  30170. var transform = this.transform;
  30171. return transform
  30172. ? v2ApplyTransform$1([], data, transform)
  30173. : [data[0], data[1]];
  30174. },
  30175. /**
  30176. * Convert a (x, y) point to (lon, lat) data
  30177. * @param {Array.<number>} point
  30178. * @return {Array.<number>}
  30179. */
  30180. pointToData: function (point) {
  30181. var invTransform = this.invTransform;
  30182. return invTransform
  30183. ? v2ApplyTransform$1([], point, invTransform)
  30184. : [point[0], point[1]];
  30185. },
  30186. /**
  30187. * @implements
  30188. * see {module:echarts/CoodinateSystem}
  30189. */
  30190. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  30191. /**
  30192. * @implements
  30193. * see {module:echarts/CoodinateSystem}
  30194. */
  30195. convertFromPixel: curry(doConvert$1, 'pointToData'),
  30196. /**
  30197. * @implements
  30198. * see {module:echarts/CoodinateSystem}
  30199. */
  30200. containPoint: function (point) {
  30201. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  30202. }
  30203. /**
  30204. * @return {number}
  30205. */
  30206. // getScalarScale: function () {
  30207. // // Use determinant square root of transform to mutiply scalar
  30208. // var m = this.transform;
  30209. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  30210. // return det;
  30211. // }
  30212. };
  30213. mixin(View, Transformable);
  30214. function doConvert$1(methodName, ecModel, finder, value) {
  30215. var seriesModel = finder.seriesModel;
  30216. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  30217. return coordSys === this ? coordSys[methodName](value) : null;
  30218. }
  30219. // Fix for 南海诸岛
  30220. var geoCoord = [126, 25];
  30221. var points$1 = [
  30222. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  30223. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  30224. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  30225. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  30226. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  30227. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  30228. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  30229. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  30230. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  30231. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  30232. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  30233. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  30234. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  30235. [1,92.4],[1,3.5],[0,3.5]]
  30236. ];
  30237. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  30238. for (var k = 0; k < points$1[i$1].length; k++) {
  30239. points$1[i$1][k][0] /= 10.5;
  30240. points$1[i$1][k][1] /= -10.5 / 0.75;
  30241. points$1[i$1][k][0] += geoCoord[0];
  30242. points$1[i$1][k][1] += geoCoord[1];
  30243. }
  30244. }
  30245. var fixNanhai = function (geo) {
  30246. if (geo.map === 'china') {
  30247. geo.regions.push(new Region(
  30248. '南海诸岛',
  30249. map(points$1, function (exterior) {
  30250. return {
  30251. type: 'polygon',
  30252. exterior: exterior
  30253. };
  30254. }), geoCoord
  30255. ));
  30256. }
  30257. };
  30258. var coordsOffsetMap = {
  30259. '南海诸岛' : [32, 80],
  30260. // 全国
  30261. '广东': [0, -10],
  30262. '香港': [10, 5],
  30263. '澳门': [-10, 10],
  30264. //'北京': [-10, 0],
  30265. '天津': [5, 5]
  30266. };
  30267. var fixTextCoord = function (geo) {
  30268. each$1(geo.regions, function (region) {
  30269. var coordFix = coordsOffsetMap[region.name];
  30270. if (coordFix) {
  30271. var cp = region.center;
  30272. cp[0] += coordFix[0] / 10.5;
  30273. cp[1] += -coordFix[1] / (10.5 / 0.75);
  30274. }
  30275. });
  30276. };
  30277. var geoCoordMap = {
  30278. 'Russia': [100, 60],
  30279. 'United States': [-99, 38],
  30280. 'United States of America': [-99, 38]
  30281. };
  30282. var fixGeoCoord = function (geo) {
  30283. each$1(geo.regions, function (region) {
  30284. var geoCoord = geoCoordMap[region.name];
  30285. if (geoCoord) {
  30286. var cp = region.center;
  30287. cp[0] = geoCoord[0];
  30288. cp[1] = geoCoord[1];
  30289. }
  30290. });
  30291. };
  30292. // Fix for 钓鱼岛
  30293. // var Region = require('../Region');
  30294. // var zrUtil = require('zrender/src/core/util');
  30295. // var geoCoord = [126, 25];
  30296. var points$2 = [
  30297. [
  30298. [123.45165252685547, 25.73527164402261],
  30299. [123.49731445312499, 25.73527164402261],
  30300. [123.49731445312499, 25.750734064600884],
  30301. [123.45165252685547, 25.750734064600884],
  30302. [123.45165252685547, 25.73527164402261]
  30303. ]
  30304. ];
  30305. var fixDiaoyuIsland = function (geo) {
  30306. if (geo.map === 'china') {
  30307. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  30308. if (geo.regions[i].name === '台湾') {
  30309. geo.regions[i].geometries.push({
  30310. type: 'polygon',
  30311. exterior: points$2[0]
  30312. });
  30313. }
  30314. }
  30315. }
  30316. };
  30317. // Geo fix functions
  30318. var geoFixFuncs = [
  30319. fixNanhai,
  30320. fixTextCoord,
  30321. fixGeoCoord,
  30322. fixDiaoyuIsland
  30323. ];
  30324. /**
  30325. * [Geo description]
  30326. * @param {string} name Geo name
  30327. * @param {string} map Map type
  30328. * @param {Object} geoJson
  30329. * @param {Object} [specialAreas]
  30330. * Specify the positioned areas by left, top, width, height
  30331. * @param {Object.<string, string>} [nameMap]
  30332. * Specify name alias
  30333. */
  30334. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  30335. View.call(this, name);
  30336. /**
  30337. * Map type
  30338. * @type {string}
  30339. */
  30340. this.map = map$$1;
  30341. this._nameCoordMap = createHashMap();
  30342. this.loadGeoJson(geoJson, specialAreas, nameMap);
  30343. }
  30344. Geo.prototype = {
  30345. constructor: Geo,
  30346. type: 'geo',
  30347. /**
  30348. * @param {Array.<string>}
  30349. * @readOnly
  30350. */
  30351. dimensions: ['lng', 'lat'],
  30352. /**
  30353. * If contain given lng,lat coord
  30354. * @param {Array.<number>}
  30355. * @readOnly
  30356. */
  30357. containCoord: function (coord) {
  30358. var regions = this.regions;
  30359. for (var i = 0; i < regions.length; i++) {
  30360. if (regions[i].contain(coord)) {
  30361. return true;
  30362. }
  30363. }
  30364. return false;
  30365. },
  30366. /**
  30367. * @param {Object} geoJson
  30368. * @param {Object} [specialAreas]
  30369. * Specify the positioned areas by left, top, width, height
  30370. * @param {Object.<string, string>} [nameMap]
  30371. * Specify name alias
  30372. */
  30373. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  30374. // https://jsperf.com/try-catch-performance-overhead
  30375. try {
  30376. this.regions = geoJson ? parseGeoJson(geoJson) : [];
  30377. }
  30378. catch (e) {
  30379. throw 'Invalid geoJson format\n' + e.message;
  30380. }
  30381. specialAreas = specialAreas || {};
  30382. nameMap = nameMap || {};
  30383. var regions = this.regions;
  30384. var regionsMap = createHashMap();
  30385. for (var i = 0; i < regions.length; i++) {
  30386. var regionName = regions[i].name;
  30387. // Try use the alias in nameMap
  30388. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  30389. regions[i].name = regionName;
  30390. regionsMap.set(regionName, regions[i]);
  30391. // Add geoJson
  30392. this.addGeoCoord(regionName, regions[i].center);
  30393. // Some area like Alaska in USA map needs to be tansformed
  30394. // to look better
  30395. var specialArea = specialAreas[regionName];
  30396. if (specialArea) {
  30397. regions[i].transformTo(
  30398. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  30399. );
  30400. }
  30401. }
  30402. this._regionsMap = regionsMap;
  30403. this._rect = null;
  30404. each$1(geoFixFuncs, function (fixFunc) {
  30405. fixFunc(this);
  30406. }, this);
  30407. },
  30408. // Overwrite
  30409. transformTo: function (x, y, width, height) {
  30410. var rect = this.getBoundingRect();
  30411. rect = rect.clone();
  30412. // Longitute is inverted
  30413. rect.y = -rect.y - rect.height;
  30414. var viewTransform = this._viewTransform;
  30415. viewTransform.transform = rect.calculateTransform(
  30416. new BoundingRect(x, y, width, height)
  30417. );
  30418. viewTransform.decomposeTransform();
  30419. var scale = viewTransform.scale;
  30420. scale[1] = -scale[1];
  30421. viewTransform.updateTransform();
  30422. this._updateTransform();
  30423. },
  30424. /**
  30425. * @param {string} name
  30426. * @return {module:echarts/coord/geo/Region}
  30427. */
  30428. getRegion: function (name) {
  30429. return this._regionsMap.get(name);
  30430. },
  30431. getRegionByCoord: function (coord) {
  30432. var regions = this.regions;
  30433. for (var i = 0; i < regions.length; i++) {
  30434. if (regions[i].contain(coord)) {
  30435. return regions[i];
  30436. }
  30437. }
  30438. },
  30439. /**
  30440. * Add geoCoord for indexing by name
  30441. * @param {string} name
  30442. * @param {Array.<number>} geoCoord
  30443. */
  30444. addGeoCoord: function (name, geoCoord) {
  30445. this._nameCoordMap.set(name, geoCoord);
  30446. },
  30447. /**
  30448. * Get geoCoord by name
  30449. * @param {string} name
  30450. * @return {Array.<number>}
  30451. */
  30452. getGeoCoord: function (name) {
  30453. return this._nameCoordMap.get(name);
  30454. },
  30455. // Overwrite
  30456. getBoundingRect: function () {
  30457. if (this._rect) {
  30458. return this._rect;
  30459. }
  30460. var rect;
  30461. var regions = this.regions;
  30462. for (var i = 0; i < regions.length; i++) {
  30463. var regionRect = regions[i].getBoundingRect();
  30464. rect = rect || regionRect.clone();
  30465. rect.union(regionRect);
  30466. }
  30467. // FIXME Always return new ?
  30468. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  30469. },
  30470. /**
  30471. * @param {string|Array.<number>} data
  30472. * @return {Array.<number>}
  30473. */
  30474. dataToPoint: function (data) {
  30475. if (typeof data === 'string') {
  30476. // Map area name to geoCoord
  30477. data = this.getGeoCoord(data);
  30478. }
  30479. if (data) {
  30480. return View.prototype.dataToPoint.call(this, data);
  30481. }
  30482. },
  30483. /**
  30484. * @inheritDoc
  30485. */
  30486. convertToPixel: curry(doConvert, 'dataToPoint'),
  30487. /**
  30488. * @inheritDoc
  30489. */
  30490. convertFromPixel: curry(doConvert, 'pointToData')
  30491. };
  30492. mixin(Geo, View);
  30493. function doConvert(methodName, ecModel, finder, value) {
  30494. var geoModel = finder.geoModel;
  30495. var seriesModel = finder.seriesModel;
  30496. var coordSys = geoModel
  30497. ? geoModel.coordinateSystem
  30498. : seriesModel
  30499. ? (
  30500. seriesModel.coordinateSystem // For map.
  30501. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  30502. )
  30503. : null;
  30504. return coordSys === this ? coordSys[methodName](value) : null;
  30505. }
  30506. /**
  30507. * Resize method bound to the geo
  30508. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  30509. * @param {module:echarts/ExtensionAPI} api
  30510. */
  30511. function resizeGeo(geoModel, api) {
  30512. var boundingCoords = geoModel.get('boundingCoords');
  30513. if (boundingCoords != null) {
  30514. var leftTop = boundingCoords[0];
  30515. var rightBottom = boundingCoords[1];
  30516. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  30517. if (__DEV__) {
  30518. console.error('Invalid boundingCoords');
  30519. }
  30520. }
  30521. else {
  30522. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  30523. }
  30524. }
  30525. var rect = this.getBoundingRect();
  30526. var boxLayoutOption;
  30527. var center = geoModel.get('layoutCenter');
  30528. var size = geoModel.get('layoutSize');
  30529. var viewWidth = api.getWidth();
  30530. var viewHeight = api.getHeight();
  30531. var aspectScale = geoModel.get('aspectScale') || 0.75;
  30532. var aspect = rect.width / rect.height * aspectScale;
  30533. var useCenterAndSize = false;
  30534. if (center && size) {
  30535. center = [
  30536. parsePercent$1(center[0], viewWidth),
  30537. parsePercent$1(center[1], viewHeight)
  30538. ];
  30539. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  30540. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  30541. useCenterAndSize = true;
  30542. }
  30543. else {
  30544. if (__DEV__) {
  30545. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  30546. }
  30547. }
  30548. }
  30549. var viewRect;
  30550. if (useCenterAndSize) {
  30551. var viewRect = {};
  30552. if (aspect > 1) {
  30553. // Width is same with size
  30554. viewRect.width = size;
  30555. viewRect.height = size / aspect;
  30556. }
  30557. else {
  30558. viewRect.height = size;
  30559. viewRect.width = size * aspect;
  30560. }
  30561. viewRect.y = center[1] - viewRect.height / 2;
  30562. viewRect.x = center[0] - viewRect.width / 2;
  30563. }
  30564. else {
  30565. // Use left/top/width/height
  30566. boxLayoutOption = geoModel.getBoxLayoutParams();
  30567. // 0.75 rate
  30568. boxLayoutOption.aspect = aspect;
  30569. viewRect = getLayoutRect(boxLayoutOption, {
  30570. width: viewWidth,
  30571. height: viewHeight
  30572. });
  30573. }
  30574. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  30575. this.setCenter(geoModel.get('center'));
  30576. this.setZoom(geoModel.get('zoom'));
  30577. }
  30578. /**
  30579. * @param {module:echarts/coord/Geo} geo
  30580. * @param {module:echarts/model/Model} model
  30581. * @inner
  30582. */
  30583. function setGeoCoords(geo, model) {
  30584. each$1(model.get('geoCoord'), function (geoCoord, name) {
  30585. geo.addGeoCoord(name, geoCoord);
  30586. });
  30587. }
  30588. if (__DEV__) {
  30589. var mapNotExistsError = function (name) {
  30590. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  30591. };
  30592. }
  30593. var geoCreator = {
  30594. // For deciding which dimensions to use when creating list data
  30595. dimensions: Geo.prototype.dimensions,
  30596. create: function (ecModel, api) {
  30597. var geoList = [];
  30598. // FIXME Create each time may be slow
  30599. ecModel.eachComponent('geo', function (geoModel, idx) {
  30600. var name = geoModel.get('map');
  30601. var mapData = getMap(name);
  30602. if (__DEV__) {
  30603. if (!mapData) {
  30604. mapNotExistsError(name);
  30605. }
  30606. }
  30607. var geo = new Geo(
  30608. name + idx, name,
  30609. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  30610. geoModel.get('nameMap')
  30611. );
  30612. geo.zoomLimit = geoModel.get('scaleLimit');
  30613. geoList.push(geo);
  30614. setGeoCoords(geo, geoModel);
  30615. geoModel.coordinateSystem = geo;
  30616. geo.model = geoModel;
  30617. // Inject resize method
  30618. geo.resize = resizeGeo;
  30619. geo.resize(geoModel, api);
  30620. });
  30621. ecModel.eachSeries(function (seriesModel) {
  30622. var coordSys = seriesModel.get('coordinateSystem');
  30623. if (coordSys === 'geo') {
  30624. var geoIndex = seriesModel.get('geoIndex') || 0;
  30625. seriesModel.coordinateSystem = geoList[geoIndex];
  30626. }
  30627. });
  30628. // If has map series
  30629. var mapModelGroupBySeries = {};
  30630. ecModel.eachSeriesByType('map', function (seriesModel) {
  30631. if (!seriesModel.getHostGeoModel()) {
  30632. var mapType = seriesModel.getMapType();
  30633. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  30634. mapModelGroupBySeries[mapType].push(seriesModel);
  30635. }
  30636. });
  30637. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  30638. var mapData = getMap(mapType);
  30639. if (__DEV__) {
  30640. if (!mapData) {
  30641. mapNotExistsError(mapSeries[0].get('map'));
  30642. }
  30643. }
  30644. var nameMapList = map(mapSeries, function (singleMapSeries) {
  30645. return singleMapSeries.get('nameMap');
  30646. });
  30647. var geo = new Geo(
  30648. mapType, mapType,
  30649. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  30650. mergeAll(nameMapList)
  30651. );
  30652. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  30653. return singleMapSeries.get('scaleLimit');
  30654. }));
  30655. geoList.push(geo);
  30656. // Inject resize method
  30657. geo.resize = resizeGeo;
  30658. geo.resize(mapSeries[0], api);
  30659. each$1(mapSeries, function (singleMapSeries) {
  30660. singleMapSeries.coordinateSystem = geo;
  30661. setGeoCoords(geo, singleMapSeries);
  30662. });
  30663. });
  30664. return geoList;
  30665. },
  30666. /**
  30667. * Fill given regions array
  30668. * @param {Array.<Object>} originRegionArr
  30669. * @param {string} mapName
  30670. * @param {Object} [nameMap]
  30671. * @return {Array}
  30672. */
  30673. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  30674. // Not use the original
  30675. var regionsArr = (originRegionArr || []).slice();
  30676. nameMap = nameMap || {};
  30677. var map$$1 = getMap(mapName);
  30678. var geoJson = map$$1 && map$$1.geoJson;
  30679. if (!geoJson) {
  30680. if (__DEV__) {
  30681. mapNotExistsError(mapName);
  30682. }
  30683. return originRegionArr;
  30684. }
  30685. var dataNameMap = createHashMap();
  30686. var features = geoJson.features;
  30687. for (var i = 0; i < regionsArr.length; i++) {
  30688. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  30689. }
  30690. for (var i = 0; i < features.length; i++) {
  30691. var name = features[i].properties.name;
  30692. if (!dataNameMap.get(name)) {
  30693. if (nameMap.hasOwnProperty(name)) {
  30694. name = nameMap[name];
  30695. }
  30696. regionsArr.push({
  30697. name: name
  30698. });
  30699. }
  30700. }
  30701. return regionsArr;
  30702. }
  30703. };
  30704. registerCoordinateSystem('geo', geoCreator);
  30705. var MapSeries = SeriesModel.extend({
  30706. type: 'series.map',
  30707. dependencies: ['geo'],
  30708. layoutMode: 'box',
  30709. /**
  30710. * Only first map series of same mapType will drawMap
  30711. * @type {boolean}
  30712. */
  30713. needsDrawMap: false,
  30714. /**
  30715. * Group of all map series with same mapType
  30716. * @type {boolean}
  30717. */
  30718. seriesGroup: [],
  30719. init: function (option) {
  30720. this._fillOption(option, this.getMapType());
  30721. // this.option = option;
  30722. MapSeries.superApply(this, 'init', arguments);
  30723. this.updateSelectedMap(option.data);
  30724. },
  30725. getInitialData: function (option) {
  30726. var dimensions = completeDimensions(['value'], option.data || []);
  30727. var list = new List(dimensions, this);
  30728. list.initData(option.data);
  30729. return list;
  30730. },
  30731. mergeOption: function (newOption) {
  30732. this._fillOption(newOption, this.getMapType());
  30733. MapSeries.superApply(this, 'mergeOption', arguments);
  30734. this.updateSelectedMap(this.option.data);
  30735. },
  30736. /**
  30737. * If no host geo model, return null, which means using a
  30738. * inner exclusive geo model.
  30739. */
  30740. getHostGeoModel: function () {
  30741. var geoIndex = this.option.geoIndex;
  30742. return geoIndex != null
  30743. ? this.dependentModels.geo[geoIndex]
  30744. : null;
  30745. },
  30746. getMapType: function () {
  30747. return (this.getHostGeoModel() || this).option.map;
  30748. },
  30749. _fillOption: function (option, mapName) {
  30750. // Shallow clone
  30751. // option = zrUtil.extend({}, option);
  30752. option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  30753. // return option;
  30754. },
  30755. getRawValue: function (dataIndex) {
  30756. // Use value stored in data instead because it is calculated from multiple series
  30757. // FIXME Provide all value of multiple series ?
  30758. return this.getData().get('value', dataIndex);
  30759. },
  30760. /**
  30761. * Get model of region
  30762. * @param {string} name
  30763. * @return {module:echarts/model/Model}
  30764. */
  30765. getRegionModel: function (regionName) {
  30766. var data = this.getData();
  30767. return data.getItemModel(data.indexOfName(regionName));
  30768. },
  30769. /**
  30770. * Map tooltip formatter
  30771. *
  30772. * @param {number} dataIndex
  30773. */
  30774. formatTooltip: function (dataIndex) {
  30775. // FIXME orignalData and data is a bit confusing
  30776. var data = this.getData();
  30777. var formattedValue = addCommas(this.getRawValue(dataIndex));
  30778. var name = data.getName(dataIndex);
  30779. var seriesGroup = this.seriesGroup;
  30780. var seriesNames = [];
  30781. for (var i = 0; i < seriesGroup.length; i++) {
  30782. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  30783. if (!isNaN(seriesGroup[i].originalData.get('value', otherIndex))) {
  30784. seriesNames.push(
  30785. encodeHTML(seriesGroup[i].name)
  30786. );
  30787. }
  30788. }
  30789. return seriesNames.join(', ') + '<br />'
  30790. + encodeHTML(name + ' : ' + formattedValue);
  30791. },
  30792. /**
  30793. * @implement
  30794. */
  30795. getTooltipPosition: function (dataIndex) {
  30796. if (dataIndex != null) {
  30797. var name = this.getData().getName(dataIndex);
  30798. var geo = this.coordinateSystem;
  30799. var region = geo.getRegion(name);
  30800. return region && geo.dataToPoint(region.center);
  30801. }
  30802. },
  30803. setZoom: function (zoom) {
  30804. this.option.zoom = zoom;
  30805. },
  30806. setCenter: function (center) {
  30807. this.option.center = center;
  30808. },
  30809. defaultOption: {
  30810. // 一级层叠
  30811. zlevel: 0,
  30812. // 二级层叠
  30813. z: 2,
  30814. coordinateSystem: 'geo',
  30815. // map should be explicitly specified since ec3.
  30816. map: '',
  30817. // If `geoIndex` is not specified, a exclusive geo will be
  30818. // created. Otherwise use the specified geo component, and
  30819. // `map` and `mapType` are ignored.
  30820. // geoIndex: 0,
  30821. // 'center' | 'left' | 'right' | 'x%' | {number}
  30822. left: 'center',
  30823. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  30824. top: 'center',
  30825. // right
  30826. // bottom
  30827. // width:
  30828. // height
  30829. // Aspect is width / height. Inited to be geoJson bbox aspect
  30830. // This parameter is used for scale this aspect
  30831. aspectScale: 0.75,
  30832. ///// Layout with center and size
  30833. // If you wan't to put map in a fixed size box with right aspect ratio
  30834. // This two properties may more conveninet
  30835. // layoutCenter: [50%, 50%]
  30836. // layoutSize: 100
  30837. // 数值合并方式,默认加和,可选为:
  30838. // 'sum' | 'average' | 'max' | 'min'
  30839. // mapValueCalculation: 'sum',
  30840. // 地图数值计算结果小数精度
  30841. // mapValuePrecision: 0,
  30842. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  30843. showLegendSymbol: true,
  30844. // 选择模式,默认关闭,可选single,multiple
  30845. // selectedMode: false,
  30846. dataRangeHoverLink: true,
  30847. // 是否开启缩放及漫游模式
  30848. // roam: false,
  30849. // Define left-top, right-bottom coords to control view
  30850. // For example, [ [180, 90], [-180, -90] ],
  30851. // higher priority than center and zoom
  30852. boundingCoords: null,
  30853. // Default on center of map
  30854. center: null,
  30855. zoom: 1,
  30856. scaleLimit: null,
  30857. label: {
  30858. normal: {
  30859. show: false,
  30860. color: '#000'
  30861. },
  30862. emphasis: {
  30863. show: true,
  30864. color: 'rgb(100,0,0)'
  30865. }
  30866. },
  30867. // scaleLimit: null,
  30868. itemStyle: {
  30869. normal: {
  30870. // color: 各异,
  30871. borderWidth: 0.5,
  30872. borderColor: '#444',
  30873. areaColor: '#eee'
  30874. },
  30875. // 也是选中样式
  30876. emphasis: {
  30877. areaColor: 'rgba(255,215,0,0.8)'
  30878. }
  30879. }
  30880. }
  30881. });
  30882. mixin(MapSeries, selectableMixin);
  30883. var ATTR = '\0_ec_interaction_mutex';
  30884. function take(zr, resourceKey, userKey) {
  30885. var store = getStore(zr);
  30886. store[resourceKey] = userKey;
  30887. }
  30888. function release(zr, resourceKey, userKey) {
  30889. var store = getStore(zr);
  30890. var uKey = store[resourceKey];
  30891. if (uKey === userKey) {
  30892. store[resourceKey] = null;
  30893. }
  30894. }
  30895. function isTaken(zr, resourceKey) {
  30896. return !!getStore(zr)[resourceKey];
  30897. }
  30898. function getStore(zr) {
  30899. return zr[ATTR] || (zr[ATTR] = {});
  30900. }
  30901. /**
  30902. * payload: {
  30903. * type: 'takeGlobalCursor',
  30904. * key: 'dataZoomSelect', or 'brush', or ...,
  30905. * If no userKey, release global cursor.
  30906. * }
  30907. */
  30908. registerAction(
  30909. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  30910. function () {}
  30911. );
  30912. /**
  30913. * @alias module:echarts/component/helper/RoamController
  30914. * @constructor
  30915. * @mixin {module:zrender/mixin/Eventful}
  30916. *
  30917. * @param {module:zrender/zrender~ZRender} zr
  30918. */
  30919. function RoamController(zr) {
  30920. /**
  30921. * @type {Function}
  30922. */
  30923. this.pointerChecker;
  30924. /**
  30925. * @type {module:zrender}
  30926. */
  30927. this._zr = zr;
  30928. /**
  30929. * @type {Object}
  30930. */
  30931. this._opt = {};
  30932. // Avoid two roamController bind the same handler
  30933. var bind$$1 = bind;
  30934. var mousedownHandler = bind$$1(mousedown, this);
  30935. var mousemoveHandler = bind$$1(mousemove, this);
  30936. var mouseupHandler = bind$$1(mouseup, this);
  30937. var mousewheelHandler = bind$$1(mousewheel, this);
  30938. var pinchHandler = bind$$1(pinch, this);
  30939. Eventful.call(this);
  30940. /**
  30941. * @param {Function} pointerChecker
  30942. * input: x, y
  30943. * output: boolean
  30944. */
  30945. this.setPointerChecker = function (pointerChecker) {
  30946. this.pointerChecker = pointerChecker;
  30947. };
  30948. /**
  30949. * Notice: only enable needed types. For example, if 'zoom'
  30950. * is not needed, 'zoom' should not be enabled, otherwise
  30951. * default mousewheel behaviour (scroll page) will be disabled.
  30952. *
  30953. * @param {boolean|string} [controlType=true] Specify the control type,
  30954. * which can be null/undefined or true/false
  30955. * or 'pan/move' or 'zoom'/'scale'
  30956. * @param {Object} [opt]
  30957. * @param {Object} [opt.zoomOnMouseWheel=true]
  30958. * @param {Object} [opt.moveOnMouseMove=true]
  30959. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  30960. */
  30961. this.enable = function (controlType, opt) {
  30962. // Disable previous first
  30963. this.disable();
  30964. this._opt = defaults(clone(opt) || {}, {
  30965. zoomOnMouseWheel: true,
  30966. moveOnMouseMove: true,
  30967. preventDefaultMouseMove: true
  30968. });
  30969. if (controlType == null) {
  30970. controlType = true;
  30971. }
  30972. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  30973. zr.on('mousedown', mousedownHandler);
  30974. zr.on('mousemove', mousemoveHandler);
  30975. zr.on('mouseup', mouseupHandler);
  30976. }
  30977. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  30978. zr.on('mousewheel', mousewheelHandler);
  30979. zr.on('pinch', pinchHandler);
  30980. }
  30981. };
  30982. this.disable = function () {
  30983. zr.off('mousedown', mousedownHandler);
  30984. zr.off('mousemove', mousemoveHandler);
  30985. zr.off('mouseup', mouseupHandler);
  30986. zr.off('mousewheel', mousewheelHandler);
  30987. zr.off('pinch', pinchHandler);
  30988. };
  30989. this.dispose = this.disable;
  30990. this.isDragging = function () {
  30991. return this._dragging;
  30992. };
  30993. this.isPinching = function () {
  30994. return this._pinching;
  30995. };
  30996. }
  30997. mixin(RoamController, Eventful);
  30998. function mousedown(e) {
  30999. if (notLeftMouse(e)
  31000. || (e.target && e.target.draggable)
  31001. ) {
  31002. return;
  31003. }
  31004. var x = e.offsetX;
  31005. var y = e.offsetY;
  31006. // Only check on mosedown, but not mousemove.
  31007. // Mouse can be out of target when mouse moving.
  31008. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  31009. this._x = x;
  31010. this._y = y;
  31011. this._dragging = true;
  31012. }
  31013. }
  31014. function mousemove(e) {
  31015. if (notLeftMouse(e)
  31016. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  31017. || !this._dragging
  31018. || e.gestureEvent === 'pinch'
  31019. || isTaken(this._zr, 'globalPan')
  31020. ) {
  31021. return;
  31022. }
  31023. var x = e.offsetX;
  31024. var y = e.offsetY;
  31025. var oldX = this._x;
  31026. var oldY = this._y;
  31027. var dx = x - oldX;
  31028. var dy = y - oldY;
  31029. this._x = x;
  31030. this._y = y;
  31031. this._opt.preventDefaultMouseMove && stop(e.event);
  31032. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  31033. }
  31034. function mouseup(e) {
  31035. if (!notLeftMouse(e)) {
  31036. this._dragging = false;
  31037. }
  31038. }
  31039. function mousewheel(e) {
  31040. // wheelDelta maybe -0 in chrome mac.
  31041. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  31042. return;
  31043. }
  31044. // Convenience:
  31045. // Mac and VM Windows on Mac: scroll up: zoom out.
  31046. // Windows: scroll up: zoom in.
  31047. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  31048. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  31049. }
  31050. function pinch(e) {
  31051. if (isTaken(this._zr, 'globalPan')) {
  31052. return;
  31053. }
  31054. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  31055. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  31056. }
  31057. function zoom(e, zoomDelta, zoomX, zoomY) {
  31058. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  31059. // When mouse is out of roamController rect,
  31060. // default befavoius should not be be disabled, otherwise
  31061. // page sliding is disabled, contrary to expectation.
  31062. stop(e.event);
  31063. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  31064. }
  31065. }
  31066. function checkKeyBinding(roamController, prop, e) {
  31067. var setting = roamController._opt[prop];
  31068. return setting
  31069. && (!isString(setting) || e.event[setting + 'Key']);
  31070. }
  31071. /**
  31072. * For geo and graph.
  31073. *
  31074. * @param {Object} controllerHost
  31075. * @param {module:zrender/Element} controllerHost.target
  31076. */
  31077. function updateViewOnPan(controllerHost, dx, dy) {
  31078. var target = controllerHost.target;
  31079. var pos = target.position;
  31080. pos[0] += dx;
  31081. pos[1] += dy;
  31082. target.dirty();
  31083. }
  31084. /**
  31085. * For geo and graph.
  31086. *
  31087. * @param {Object} controllerHost
  31088. * @param {module:zrender/Element} controllerHost.target
  31089. * @param {number} controllerHost.zoom
  31090. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  31091. */
  31092. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  31093. var target = controllerHost.target;
  31094. var zoomLimit = controllerHost.zoomLimit;
  31095. var pos = target.position;
  31096. var scale = target.scale;
  31097. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  31098. newZoom *= zoomDelta;
  31099. if (zoomLimit) {
  31100. var zoomMin = zoomLimit.min || 0;
  31101. var zoomMax = zoomLimit.max || Infinity;
  31102. newZoom = Math.max(
  31103. Math.min(zoomMax, newZoom),
  31104. zoomMin
  31105. );
  31106. }
  31107. var zoomScale = newZoom / controllerHost.zoom;
  31108. controllerHost.zoom = newZoom;
  31109. // Keep the mouse center when scaling
  31110. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  31111. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  31112. scale[0] *= zoomScale;
  31113. scale[1] *= zoomScale;
  31114. target.dirty();
  31115. }
  31116. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  31117. /**
  31118. * Avoid that: mouse click on a elements that is over geo or graph,
  31119. * but roam is triggered.
  31120. */
  31121. function onIrrelevantElement(e, api, targetCoordSysModel) {
  31122. var model = api.getComponentByElement(e.topTarget);
  31123. // If model is axisModel, it works only if it is injected with coordinateSystem.
  31124. var coordSys = model && model.coordinateSystem;
  31125. return model
  31126. && model !== targetCoordSysModel
  31127. && !IRRELEVANT_EXCLUDES[model.mainType]
  31128. && (coordSys && coordSys.model !== targetCoordSysModel);
  31129. }
  31130. function getFixedItemStyle(model, scale) {
  31131. var itemStyle = model.getItemStyle();
  31132. var areaColor = model.get('areaColor');
  31133. // If user want the color not to be changed when hover,
  31134. // they should both set areaColor and color to be null.
  31135. if (areaColor != null) {
  31136. itemStyle.fill = areaColor;
  31137. }
  31138. return itemStyle;
  31139. }
  31140. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  31141. group.off('click');
  31142. group.off('mousedown');
  31143. if (mapOrGeoModel.get('selectedMode')) {
  31144. group.on('mousedown', function () {
  31145. mapDraw._mouseDownFlag = true;
  31146. });
  31147. group.on('click', function (e) {
  31148. if (!mapDraw._mouseDownFlag) {
  31149. return;
  31150. }
  31151. mapDraw._mouseDownFlag = false;
  31152. var el = e.target;
  31153. while (!el.__regions) {
  31154. el = el.parent;
  31155. }
  31156. if (!el) {
  31157. return;
  31158. }
  31159. var action = {
  31160. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  31161. batch: map(el.__regions, function (region) {
  31162. return {
  31163. name: region.name,
  31164. from: fromView.uid
  31165. };
  31166. })
  31167. };
  31168. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  31169. api.dispatchAction(action);
  31170. updateMapSelected(mapOrGeoModel, group);
  31171. });
  31172. }
  31173. }
  31174. function updateMapSelected(mapOrGeoModel, group) {
  31175. // FIXME
  31176. group.eachChild(function (otherRegionEl) {
  31177. each$1(otherRegionEl.__regions, function (region) {
  31178. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  31179. });
  31180. });
  31181. }
  31182. /**
  31183. * @alias module:echarts/component/helper/MapDraw
  31184. * @param {module:echarts/ExtensionAPI} api
  31185. * @param {boolean} updateGroup
  31186. */
  31187. function MapDraw(api, updateGroup) {
  31188. var group = new Group();
  31189. /**
  31190. * @type {module:echarts/component/helper/RoamController}
  31191. * @private
  31192. */
  31193. this._controller = new RoamController(api.getZr());
  31194. /**
  31195. * @type {Object} {target, zoom, zoomLimit}
  31196. * @private
  31197. */
  31198. this._controllerHost = {target: updateGroup ? group : null};
  31199. /**
  31200. * @type {module:zrender/container/Group}
  31201. * @readOnly
  31202. */
  31203. this.group = group;
  31204. /**
  31205. * @type {boolean}
  31206. * @private
  31207. */
  31208. this._updateGroup = updateGroup;
  31209. /**
  31210. * This flag is used to make sure that only one among
  31211. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  31212. * action may be triggered when `pan`, which is unexpected.
  31213. * @type {booelan}
  31214. */
  31215. this._mouseDownFlag;
  31216. }
  31217. MapDraw.prototype = {
  31218. constructor: MapDraw,
  31219. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  31220. var isGeo = mapOrGeoModel.mainType === 'geo';
  31221. // Map series has data. GEO model that controlled by map series
  31222. // will be assigned with map data. Other GEO model has no data.
  31223. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  31224. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  31225. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  31226. data = mapSeries.getData();
  31227. }
  31228. });
  31229. var geo = mapOrGeoModel.coordinateSystem;
  31230. var group = this.group;
  31231. var scale = geo.scale;
  31232. var groupNewProp = {
  31233. position: geo.position,
  31234. scale: scale
  31235. };
  31236. // No animation when first draw or in action
  31237. if (!group.childAt(0) || payload) {
  31238. group.attr(groupNewProp);
  31239. }
  31240. else {
  31241. updateProps(group, groupNewProp, mapOrGeoModel);
  31242. }
  31243. group.removeAll();
  31244. var itemStyleAccessPath = ['itemStyle', 'normal'];
  31245. var hoverItemStyleAccessPath = ['itemStyle', 'emphasis'];
  31246. var labelAccessPath = ['label', 'normal'];
  31247. var hoverLabelAccessPath = ['label', 'emphasis'];
  31248. var nameMap = createHashMap();
  31249. each$1(geo.regions, function (region) {
  31250. // Consider in GeoJson properties.name may be duplicated, for example,
  31251. // there is multiple region named "United Kindom" or "France" (so many
  31252. // colonies). And it is not appropriate to merge them in geo, which
  31253. // will make them share the same label and bring trouble in label
  31254. // location calculation.
  31255. var regionGroup = nameMap.get(region.name)
  31256. || nameMap.set(region.name, new Group());
  31257. var compoundPath = new CompoundPath({
  31258. shape: {
  31259. paths: []
  31260. }
  31261. });
  31262. regionGroup.add(compoundPath);
  31263. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  31264. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  31265. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  31266. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  31267. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  31268. var labelModel = regionModel.getModel(labelAccessPath);
  31269. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  31270. var dataIdx;
  31271. // Use the itemStyle in data if has data
  31272. if (data) {
  31273. dataIdx = data.indexOfName(region.name);
  31274. // Only visual color of each item will be used. It can be encoded by dataRange
  31275. // But visual color of series is used in symbol drawing
  31276. //
  31277. // Visual color for each series is for the symbol draw
  31278. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  31279. if (visualColor) {
  31280. itemStyle.fill = visualColor;
  31281. }
  31282. }
  31283. each$1(region.geometries, function (geometry) {
  31284. if (geometry.type !== 'polygon') {
  31285. return;
  31286. }
  31287. compoundPath.shape.paths.push(new Polygon({
  31288. shape: {
  31289. points: geometry.exterior
  31290. }
  31291. }));
  31292. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  31293. compoundPath.shape.paths.push(new Polygon({
  31294. shape: {
  31295. points: geometry.interiors[i]
  31296. }
  31297. }));
  31298. }
  31299. });
  31300. compoundPath.setStyle(itemStyle);
  31301. compoundPath.style.strokeNoScale = true;
  31302. compoundPath.culling = true;
  31303. // Label
  31304. var showLabel = labelModel.get('show');
  31305. var hoverShowLabel = hoverLabelModel.get('show');
  31306. var isDataNaN = data && isNaN(data.get('value', dataIdx));
  31307. var itemLayout = data && data.getItemLayout(dataIdx);
  31308. // In the following cases label will be drawn
  31309. // 1. In map series and data value is NaN
  31310. // 2. In geo component
  31311. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  31312. if (
  31313. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  31314. || (itemLayout && itemLayout.showLabel)
  31315. ) {
  31316. var query = !isGeo ? dataIdx : region.name;
  31317. var labelFetcher;
  31318. // Consider dataIdx not found.
  31319. if (!data || dataIdx >= 0) {
  31320. labelFetcher = mapOrGeoModel;
  31321. }
  31322. var textEl = new Text({
  31323. position: region.center.slice(),
  31324. scale: [1 / scale[0], 1 / scale[1]],
  31325. z2: 10,
  31326. silent: true
  31327. });
  31328. setLabelStyle(
  31329. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  31330. {
  31331. labelFetcher: labelFetcher,
  31332. labelDataIndex: query,
  31333. defaultText: region.name,
  31334. useInsideStyle: false
  31335. },
  31336. {
  31337. textAlign: 'center',
  31338. textVerticalAlign: 'middle'
  31339. }
  31340. );
  31341. regionGroup.add(textEl);
  31342. }
  31343. // setItemGraphicEl, setHoverStyle after all polygons and labels
  31344. // are added to the rigionGroup
  31345. if (data) {
  31346. data.setItemGraphicEl(dataIdx, regionGroup);
  31347. }
  31348. else {
  31349. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  31350. // Package custom mouse event for geo component
  31351. compoundPath.eventData = {
  31352. componentType: 'geo',
  31353. geoIndex: mapOrGeoModel.componentIndex,
  31354. name: region.name,
  31355. region: (regionModel && regionModel.option) || {}
  31356. };
  31357. }
  31358. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  31359. groupRegions.push(region);
  31360. setHoverStyle(
  31361. regionGroup,
  31362. hoverItemStyle,
  31363. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  31364. );
  31365. group.add(regionGroup);
  31366. });
  31367. this._updateController(mapOrGeoModel, ecModel, api);
  31368. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  31369. updateMapSelected(mapOrGeoModel, group);
  31370. },
  31371. remove: function () {
  31372. this.group.removeAll();
  31373. this._controller.dispose();
  31374. this._controllerHost = {};
  31375. },
  31376. _updateController: function (mapOrGeoModel, ecModel, api) {
  31377. var geo = mapOrGeoModel.coordinateSystem;
  31378. var controller = this._controller;
  31379. var controllerHost = this._controllerHost;
  31380. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  31381. controllerHost.zoom = geo.getZoom();
  31382. // roamType is will be set default true if it is null
  31383. controller.enable(mapOrGeoModel.get('roam') || false);
  31384. var mainType = mapOrGeoModel.mainType;
  31385. function makeActionBase() {
  31386. var action = {
  31387. type: 'geoRoam',
  31388. componentType: mainType
  31389. };
  31390. action[mainType + 'Id'] = mapOrGeoModel.id;
  31391. return action;
  31392. }
  31393. controller.off('pan').on('pan', function (dx, dy) {
  31394. this._mouseDownFlag = false;
  31395. updateViewOnPan(controllerHost, dx, dy);
  31396. api.dispatchAction(extend(makeActionBase(), {
  31397. dx: dx,
  31398. dy: dy
  31399. }));
  31400. }, this);
  31401. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  31402. this._mouseDownFlag = false;
  31403. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  31404. api.dispatchAction(extend(makeActionBase(), {
  31405. zoom: zoom,
  31406. originX: mouseX,
  31407. originY: mouseY
  31408. }));
  31409. if (this._updateGroup) {
  31410. var group = this.group;
  31411. var scale = group.scale;
  31412. group.traverse(function (el) {
  31413. if (el.type === 'text') {
  31414. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  31415. }
  31416. });
  31417. }
  31418. }, this);
  31419. controller.setPointerChecker(function (e, x, y) {
  31420. return geo.getViewRectAfterRoam().contain(x, y)
  31421. && !onIrrelevantElement(e, api, mapOrGeoModel);
  31422. });
  31423. }
  31424. };
  31425. extendChartView({
  31426. type: 'map',
  31427. render: function (mapModel, ecModel, api, payload) {
  31428. // Not render if it is an toggleSelect action from self
  31429. if (payload && payload.type === 'mapToggleSelect'
  31430. && payload.from === this.uid
  31431. ) {
  31432. return;
  31433. }
  31434. var group = this.group;
  31435. group.removeAll();
  31436. if (mapModel.getHostGeoModel()) {
  31437. return;
  31438. }
  31439. // Not update map if it is an roam action from self
  31440. if (!(payload && payload.type === 'geoRoam'
  31441. && payload.componentType === 'series'
  31442. && payload.seriesId === mapModel.id
  31443. )
  31444. ) {
  31445. if (mapModel.needsDrawMap) {
  31446. var mapDraw = this._mapDraw || new MapDraw(api, true);
  31447. group.add(mapDraw.group);
  31448. mapDraw.draw(mapModel, ecModel, api, this, payload);
  31449. this._mapDraw = mapDraw;
  31450. }
  31451. else {
  31452. // Remove drawed map
  31453. this._mapDraw && this._mapDraw.remove();
  31454. this._mapDraw = null;
  31455. }
  31456. }
  31457. else {
  31458. var mapDraw = this._mapDraw;
  31459. mapDraw && group.add(mapDraw.group);
  31460. }
  31461. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  31462. && this._renderSymbols(mapModel, ecModel, api);
  31463. },
  31464. remove: function () {
  31465. this._mapDraw && this._mapDraw.remove();
  31466. this._mapDraw = null;
  31467. this.group.removeAll();
  31468. },
  31469. dispose: function () {
  31470. this._mapDraw && this._mapDraw.remove();
  31471. this._mapDraw = null;
  31472. },
  31473. _renderSymbols: function (mapModel, ecModel, api) {
  31474. var originalData = mapModel.originalData;
  31475. var group = this.group;
  31476. originalData.each('value', function (value, idx) {
  31477. if (isNaN(value)) {
  31478. return;
  31479. }
  31480. var layout = originalData.getItemLayout(idx);
  31481. if (!layout || !layout.point) {
  31482. // Not exists in map
  31483. return;
  31484. }
  31485. var point = layout.point;
  31486. var offset = layout.offset;
  31487. var circle = new Circle({
  31488. style: {
  31489. // Because the special of map draw.
  31490. // Which needs statistic of multiple series and draw on one map.
  31491. // And each series also need a symbol with legend color
  31492. //
  31493. // Layout and visual are put one the different data
  31494. fill: mapModel.getData().getVisual('color')
  31495. },
  31496. shape: {
  31497. cx: point[0] + offset * 9,
  31498. cy: point[1],
  31499. r: 3
  31500. },
  31501. silent: true,
  31502. // Do not overlap the first series, on which labels are displayed.
  31503. z2: !offset ? 10 : 8
  31504. });
  31505. // First data on the same region
  31506. if (!offset) {
  31507. var fullData = mapModel.mainSeries.getData();
  31508. var name = originalData.getName(idx);
  31509. var fullIndex = fullData.indexOfName(name);
  31510. var itemModel = originalData.getItemModel(idx);
  31511. var labelModel = itemModel.getModel('label.normal');
  31512. var hoverLabelModel = itemModel.getModel('label.emphasis');
  31513. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  31514. var normalText = retrieve2(
  31515. mapModel.getFormattedLabel(idx, 'normal'),
  31516. name
  31517. );
  31518. var emphasisText = retrieve2(
  31519. mapModel.getFormattedLabel(idx, 'emphasis'),
  31520. normalText
  31521. );
  31522. var onEmphasis = function () {
  31523. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  31524. text: hoverLabelModel.get('show') ? emphasisText : null
  31525. }, {isRectText: true, useInsideStyle: false}, true);
  31526. circle.style.extendFrom(hoverStyle);
  31527. // Make label upper than others if overlaps.
  31528. circle.__mapOriginalZ2 = circle.z2;
  31529. circle.z2 += 1;
  31530. };
  31531. var onNormal = function () {
  31532. setTextStyle(circle.style, labelModel, {
  31533. text: labelModel.get('show') ? normalText : null,
  31534. textPosition: labelModel.getShallow('position') || 'bottom'
  31535. }, {isRectText: true, useInsideStyle: false});
  31536. if (circle.__mapOriginalZ2 != null) {
  31537. circle.z2 = circle.__mapOriginalZ2;
  31538. circle.__mapOriginalZ2 = null;
  31539. }
  31540. };
  31541. polygonGroups.on('mouseover', onEmphasis)
  31542. .on('mouseout', onNormal)
  31543. .on('emphasis', onEmphasis)
  31544. .on('normal', onNormal);
  31545. onNormal();
  31546. }
  31547. group.add(circle);
  31548. });
  31549. }
  31550. });
  31551. /**
  31552. * @param {module:echarts/coord/View} view
  31553. * @param {Object} payload
  31554. * @param {Object} [zoomLimit]
  31555. */
  31556. function updateCenterAndZoom(
  31557. view, payload, zoomLimit
  31558. ) {
  31559. var previousZoom = view.getZoom();
  31560. var center = view.getCenter();
  31561. var zoom = payload.zoom;
  31562. var point = view.dataToPoint(center);
  31563. if (payload.dx != null && payload.dy != null) {
  31564. point[0] -= payload.dx;
  31565. point[1] -= payload.dy;
  31566. var center = view.pointToData(point);
  31567. view.setCenter(center);
  31568. }
  31569. if (zoom != null) {
  31570. if (zoomLimit) {
  31571. var zoomMin = zoomLimit.min || 0;
  31572. var zoomMax = zoomLimit.max || Infinity;
  31573. zoom = Math.max(
  31574. Math.min(previousZoom * zoom, zoomMax),
  31575. zoomMin
  31576. ) / previousZoom;
  31577. }
  31578. // Zoom on given point(originX, originY)
  31579. view.scale[0] *= zoom;
  31580. view.scale[1] *= zoom;
  31581. var position = view.position;
  31582. var fixX = (payload.originX - position[0]) * (zoom - 1);
  31583. var fixY = (payload.originY - position[1]) * (zoom - 1);
  31584. position[0] -= fixX;
  31585. position[1] -= fixY;
  31586. view.updateTransform();
  31587. // Get the new center
  31588. var center = view.pointToData(point);
  31589. view.setCenter(center);
  31590. view.setZoom(zoom * previousZoom);
  31591. }
  31592. return {
  31593. center: view.getCenter(),
  31594. zoom: view.getZoom()
  31595. };
  31596. }
  31597. /**
  31598. * @payload
  31599. * @property {string} [componentType=series]
  31600. * @property {number} [dx]
  31601. * @property {number} [dy]
  31602. * @property {number} [zoom]
  31603. * @property {number} [originX]
  31604. * @property {number} [originY]
  31605. */
  31606. registerAction({
  31607. type: 'geoRoam',
  31608. event: 'geoRoam',
  31609. update: 'updateLayout'
  31610. }, function (payload, ecModel) {
  31611. var componentType = payload.componentType || 'series';
  31612. ecModel.eachComponent(
  31613. { mainType: componentType, query: payload },
  31614. function (componentModel) {
  31615. var geo = componentModel.coordinateSystem;
  31616. if (geo.type !== 'geo') {
  31617. return;
  31618. }
  31619. var res = updateCenterAndZoom(
  31620. geo, payload, componentModel.get('scaleLimit')
  31621. );
  31622. componentModel.setCenter
  31623. && componentModel.setCenter(res.center);
  31624. componentModel.setZoom
  31625. && componentModel.setZoom(res.zoom);
  31626. // All map series with same `map` use the same geo coordinate system
  31627. // So the center and zoom must be in sync. Include the series not selected by legend
  31628. if (componentType === 'series') {
  31629. each$1(componentModel.seriesGroup, function (seriesModel) {
  31630. seriesModel.setCenter(res.center);
  31631. seriesModel.setZoom(res.zoom);
  31632. });
  31633. }
  31634. }
  31635. );
  31636. });
  31637. var mapSymbolLayout = function (ecModel) {
  31638. var processedMapType = {};
  31639. ecModel.eachSeriesByType('map', function (mapSeries) {
  31640. var mapType = mapSeries.getMapType();
  31641. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  31642. return;
  31643. }
  31644. var mapSymbolOffsets = {};
  31645. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  31646. var geo = subMapSeries.coordinateSystem;
  31647. var data = subMapSeries.originalData;
  31648. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  31649. data.each('value', function (value, idx) {
  31650. var name = data.getName(idx);
  31651. var region = geo.getRegion(name);
  31652. // If input series.data is [11, 22, '-'/null/undefined, 44],
  31653. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  31654. // not be drawn. So here must validate if value is NaN.
  31655. if (!region || isNaN(value)) {
  31656. return;
  31657. }
  31658. var offset = mapSymbolOffsets[name] || 0;
  31659. var point = geo.dataToPoint(region.center);
  31660. mapSymbolOffsets[name] = offset + 1;
  31661. data.setItemLayout(idx, {
  31662. point: point,
  31663. offset: offset
  31664. });
  31665. });
  31666. }
  31667. });
  31668. // Show label of those region not has legendSymbol(which is offset 0)
  31669. var data = mapSeries.getData();
  31670. data.each(function (idx) {
  31671. var name = data.getName(idx);
  31672. var layout = data.getItemLayout(idx) || {};
  31673. layout.showLabel = !mapSymbolOffsets[name];
  31674. data.setItemLayout(idx, layout);
  31675. });
  31676. processedMapType[mapType] = true;
  31677. });
  31678. };
  31679. var mapVisual = function (ecModel) {
  31680. ecModel.eachSeriesByType('map', function (seriesModel) {
  31681. var colorList = seriesModel.get('color');
  31682. var itemStyleModel = seriesModel.getModel('itemStyle.normal');
  31683. var areaColor = itemStyleModel.get('areaColor');
  31684. var color = itemStyleModel.get('color')
  31685. || colorList[seriesModel.seriesIndex % colorList.length];
  31686. seriesModel.getData().setVisual({
  31687. 'areaColor': areaColor,
  31688. 'color': color
  31689. });
  31690. });
  31691. };
  31692. // FIXME 公用?
  31693. /**
  31694. * @param {Array.<module:echarts/data/List>} datas
  31695. * @param {string} statisticType 'average' 'sum'
  31696. * @inner
  31697. */
  31698. function dataStatistics(datas, statisticType) {
  31699. var dataNameMap = {};
  31700. var dims = ['value'];
  31701. each$1(datas, function (data) {
  31702. data.each(dims, function (value, idx) {
  31703. // Add prefix to avoid conflict with Object.prototype.
  31704. var mapKey = 'ec-' + data.getName(idx);
  31705. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  31706. if (!isNaN(value)) {
  31707. dataNameMap[mapKey].push(value);
  31708. }
  31709. });
  31710. });
  31711. return datas[0].map(dims, function (value, idx) {
  31712. var mapKey = 'ec-' + datas[0].getName(idx);
  31713. var sum = 0;
  31714. var min = Infinity;
  31715. var max = -Infinity;
  31716. var len = dataNameMap[mapKey].length;
  31717. for (var i = 0; i < len; i++) {
  31718. min = Math.min(min, dataNameMap[mapKey][i]);
  31719. max = Math.max(max, dataNameMap[mapKey][i]);
  31720. sum += dataNameMap[mapKey][i];
  31721. }
  31722. var result;
  31723. if (statisticType === 'min') {
  31724. result = min;
  31725. }
  31726. else if (statisticType === 'max') {
  31727. result = max;
  31728. }
  31729. else if (statisticType === 'average') {
  31730. result = sum / len;
  31731. }
  31732. else {
  31733. result = sum;
  31734. }
  31735. return len === 0 ? NaN : result;
  31736. });
  31737. }
  31738. var mapDataStatistic = function (ecModel) {
  31739. var seriesGroups = {};
  31740. ecModel.eachSeriesByType('map', function (seriesModel) {
  31741. var hostGeoModel = seriesModel.getHostGeoModel();
  31742. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  31743. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  31744. });
  31745. each$1(seriesGroups, function (seriesList, key) {
  31746. var data = dataStatistics(
  31747. map(seriesList, function (seriesModel) {
  31748. return seriesModel.getData();
  31749. }),
  31750. seriesList[0].get('mapValueCalculation')
  31751. );
  31752. for (var i = 0; i < seriesList.length; i++) {
  31753. seriesList[i].originalData = seriesList[i].getData();
  31754. }
  31755. // FIXME Put where?
  31756. for (var i = 0; i < seriesList.length; i++) {
  31757. seriesList[i].seriesGroup = seriesList;
  31758. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  31759. seriesList[i].setData(data.cloneShallow());
  31760. seriesList[i].mainSeries = seriesList[0];
  31761. }
  31762. });
  31763. };
  31764. var backwardCompat$2 = function (option) {
  31765. // Save geoCoord
  31766. var mapSeries = [];
  31767. each$1(option.series, function (seriesOpt) {
  31768. if (seriesOpt && seriesOpt.type === 'map') {
  31769. mapSeries.push(seriesOpt);
  31770. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  31771. // Put x, y, width, height, x2, y2 in the top level
  31772. defaults(seriesOpt, seriesOpt.mapLocation);
  31773. }
  31774. });
  31775. };
  31776. registerLayout(mapSymbolLayout);
  31777. registerVisual(mapVisual);
  31778. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  31779. registerPreprocessor(backwardCompat$2);
  31780. createDataSelectAction('map', [{
  31781. type: 'mapToggleSelect',
  31782. event: 'mapselectchanged',
  31783. method: 'toggleSelected'
  31784. }, {
  31785. type: 'mapSelect',
  31786. event: 'mapselected',
  31787. method: 'select'
  31788. }, {
  31789. type: 'mapUnSelect',
  31790. event: 'mapunselected',
  31791. method: 'unSelect'
  31792. }]);
  31793. /**
  31794. * Link lists and struct (graph or tree)
  31795. */
  31796. var each$10 = each$1;
  31797. var DATAS = '\0__link_datas';
  31798. var MAIN_DATA = '\0__link_mainData';
  31799. // Caution:
  31800. // In most case, either list or its shallow clones (see list.cloneShallow)
  31801. // is active in echarts process. So considering heap memory consumption,
  31802. // we do not clone tree or graph, but share them among list and its shallow clones.
  31803. // But in some rare case, we have to keep old list (like do animation in chart). So
  31804. // please take care that both the old list and the new list share the same tree/graph.
  31805. /**
  31806. * @param {Object} opt
  31807. * @param {module:echarts/data/List} opt.mainData
  31808. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  31809. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  31810. * @param {Object} [opt.datas] {dataType: data},
  31811. * like: {node: nodeList, edge: edgeList}.
  31812. * Should contain mainData.
  31813. * @param {Object} [opt.datasAttr] {dataType: attr},
  31814. * designation: struct[datasAttr[dataType]] = list;
  31815. */
  31816. function linkList(opt) {
  31817. var mainData = opt.mainData;
  31818. var datas = opt.datas;
  31819. if (!datas) {
  31820. datas = {main: mainData};
  31821. opt.datasAttr = {main: 'data'};
  31822. }
  31823. opt.datas = opt.mainData = null;
  31824. linkAll(mainData, datas, opt);
  31825. // Porxy data original methods.
  31826. each$10(datas, function (data) {
  31827. each$10(mainData.TRANSFERABLE_METHODS, function (methodName) {
  31828. data.wrapMethod(methodName, curry(transferInjection, opt));
  31829. });
  31830. });
  31831. // Beyond transfer, additional features should be added to `cloneShallow`.
  31832. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  31833. // Only mainData trigger change, because struct.update may trigger
  31834. // another changable methods, which may bring about dead lock.
  31835. each$10(mainData.CHANGABLE_METHODS, function (methodName) {
  31836. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  31837. });
  31838. // Make sure datas contains mainData.
  31839. assert(datas[mainData.dataType] === mainData);
  31840. }
  31841. function transferInjection(opt, res) {
  31842. if (isMainData(this)) {
  31843. // Transfer datas to new main data.
  31844. var datas = extend({}, this[DATAS]);
  31845. datas[this.dataType] = res;
  31846. linkAll(res, datas, opt);
  31847. }
  31848. else {
  31849. // Modify the reference in main data to point newData.
  31850. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  31851. }
  31852. return res;
  31853. }
  31854. function changeInjection(opt, res) {
  31855. opt.struct && opt.struct.update(this);
  31856. return res;
  31857. }
  31858. function cloneShallowInjection(opt, res) {
  31859. // cloneShallow, which brings about some fragilities, may be inappropriate
  31860. // to be exposed as an API. So for implementation simplicity we can make
  31861. // the restriction that cloneShallow of not-mainData should not be invoked
  31862. // outside, but only be invoked here.
  31863. each$10(res[DATAS], function (data, dataType) {
  31864. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  31865. });
  31866. return res;
  31867. }
  31868. /**
  31869. * Supplement method to List.
  31870. *
  31871. * @public
  31872. * @param {string} [dataType] If not specified, return mainData.
  31873. * @return {module:echarts/data/List}
  31874. */
  31875. function getLinkedData(dataType) {
  31876. var mainData = this[MAIN_DATA];
  31877. return (dataType == null || mainData == null)
  31878. ? mainData
  31879. : mainData[DATAS][dataType];
  31880. }
  31881. function isMainData(data) {
  31882. return data[MAIN_DATA] === data;
  31883. }
  31884. function linkAll(mainData, datas, opt) {
  31885. mainData[DATAS] = {};
  31886. each$10(datas, function (data, dataType) {
  31887. linkSingle(data, dataType, mainData, opt);
  31888. });
  31889. }
  31890. function linkSingle(data, dataType, mainData, opt) {
  31891. mainData[DATAS][dataType] = data;
  31892. data[MAIN_DATA] = mainData;
  31893. data.dataType = dataType;
  31894. if (opt.struct) {
  31895. data[opt.structAttr] = opt.struct;
  31896. opt.struct[opt.datasAttr[dataType]] = data;
  31897. }
  31898. // Supplement method.
  31899. data.getLinkedData = getLinkedData;
  31900. }
  31901. /**
  31902. * Tree data structure
  31903. *
  31904. * @module echarts/data/Tree
  31905. */
  31906. /**
  31907. * @constructor module:echarts/data/Tree~TreeNode
  31908. * @param {string} name
  31909. * @param {module:echarts/data/Tree} hostTree
  31910. */
  31911. var TreeNode = function (name, hostTree) {
  31912. /**
  31913. * @type {string}
  31914. */
  31915. this.name = name || '';
  31916. /**
  31917. * Depth of node
  31918. *
  31919. * @type {number}
  31920. * @readOnly
  31921. */
  31922. this.depth = 0;
  31923. /**
  31924. * Height of the subtree rooted at this node.
  31925. * @type {number}
  31926. * @readOnly
  31927. */
  31928. this.height = 0;
  31929. /**
  31930. * @type {module:echarts/data/Tree~TreeNode}
  31931. * @readOnly
  31932. */
  31933. this.parentNode = null;
  31934. /**
  31935. * Reference to list item.
  31936. * Do not persistent dataIndex outside,
  31937. * besause it may be changed by list.
  31938. * If dataIndex -1,
  31939. * this node is logical deleted (filtered) in list.
  31940. *
  31941. * @type {Object}
  31942. * @readOnly
  31943. */
  31944. this.dataIndex = -1;
  31945. /**
  31946. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  31947. * @readOnly
  31948. */
  31949. this.children = [];
  31950. /**
  31951. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  31952. * @pubilc
  31953. */
  31954. this.viewChildren = [];
  31955. /**
  31956. * @type {moduel:echarts/data/Tree}
  31957. * @readOnly
  31958. */
  31959. this.hostTree = hostTree;
  31960. };
  31961. TreeNode.prototype = {
  31962. constructor: TreeNode,
  31963. /**
  31964. * The node is removed.
  31965. * @return {boolean} is removed.
  31966. */
  31967. isRemoved: function () {
  31968. return this.dataIndex < 0;
  31969. },
  31970. /**
  31971. * Travel this subtree (include this node).
  31972. * Usage:
  31973. * node.eachNode(function () { ... }); // preorder
  31974. * node.eachNode('preorder', function () { ... }); // preorder
  31975. * node.eachNode('postorder', function () { ... }); // postorder
  31976. * node.eachNode(
  31977. * {order: 'postorder', attr: 'viewChildren'},
  31978. * function () { ... }
  31979. * ); // postorder
  31980. *
  31981. * @param {(Object|string)} options If string, means order.
  31982. * @param {string=} options.order 'preorder' or 'postorder'
  31983. * @param {string=} options.attr 'children' or 'viewChildren'
  31984. * @param {Function} cb If in preorder and return false,
  31985. * its subtree will not be visited.
  31986. * @param {Object} [context]
  31987. */
  31988. eachNode: function (options, cb, context) {
  31989. if (typeof options === 'function') {
  31990. context = cb;
  31991. cb = options;
  31992. options = null;
  31993. }
  31994. options = options || {};
  31995. if (isString(options)) {
  31996. options = {order: options};
  31997. }
  31998. var order = options.order || 'preorder';
  31999. var children = this[options.attr || 'children'];
  32000. var suppressVisitSub;
  32001. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  32002. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  32003. children[i].eachNode(options, cb, context);
  32004. }
  32005. order === 'postorder' && cb.call(context, this);
  32006. },
  32007. /**
  32008. * Update depth and height of this subtree.
  32009. *
  32010. * @param {number} depth
  32011. */
  32012. updateDepthAndHeight: function (depth) {
  32013. var height = 0;
  32014. this.depth = depth;
  32015. for (var i = 0; i < this.children.length; i++) {
  32016. var child = this.children[i];
  32017. child.updateDepthAndHeight(depth + 1);
  32018. if (child.height > height) {
  32019. height = child.height;
  32020. }
  32021. }
  32022. this.height = height + 1;
  32023. },
  32024. /**
  32025. * @param {string} id
  32026. * @return {module:echarts/data/Tree~TreeNode}
  32027. */
  32028. getNodeById: function (id) {
  32029. if (this.getId() === id) {
  32030. return this;
  32031. }
  32032. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  32033. var res = children[i].getNodeById(id);
  32034. if (res) {
  32035. return res;
  32036. }
  32037. }
  32038. },
  32039. /**
  32040. * @param {module:echarts/data/Tree~TreeNode} node
  32041. * @return {boolean}
  32042. */
  32043. contains: function (node) {
  32044. if (node === this) {
  32045. return true;
  32046. }
  32047. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  32048. var res = children[i].contains(node);
  32049. if (res) {
  32050. return res;
  32051. }
  32052. }
  32053. },
  32054. /**
  32055. * @param {boolean} includeSelf Default false.
  32056. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  32057. */
  32058. getAncestors: function (includeSelf) {
  32059. var ancestors = [];
  32060. var node = includeSelf ? this : this.parentNode;
  32061. while (node) {
  32062. ancestors.push(node);
  32063. node = node.parentNode;
  32064. }
  32065. ancestors.reverse();
  32066. return ancestors;
  32067. },
  32068. /**
  32069. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  32070. * @return {number} Value.
  32071. */
  32072. getValue: function (dimension) {
  32073. var data = this.hostTree.data;
  32074. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  32075. },
  32076. /**
  32077. * @param {Object} layout
  32078. * @param {boolean=} [merge=false]
  32079. */
  32080. setLayout: function (layout, merge$$1) {
  32081. this.dataIndex >= 0
  32082. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  32083. },
  32084. /**
  32085. * @return {Object} layout
  32086. */
  32087. getLayout: function () {
  32088. return this.hostTree.data.getItemLayout(this.dataIndex);
  32089. },
  32090. /**
  32091. * @param {string} [path]
  32092. * @return {module:echarts/model/Model}
  32093. */
  32094. getModel: function (path) {
  32095. if (this.dataIndex < 0) {
  32096. return;
  32097. }
  32098. var hostTree = this.hostTree;
  32099. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  32100. var levelModel = this.getLevelModel();
  32101. var leavesModel;
  32102. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  32103. leavesModel = this.getLeavesModel();
  32104. }
  32105. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  32106. },
  32107. /**
  32108. * @return {module:echarts/model/Model}
  32109. */
  32110. getLevelModel: function () {
  32111. return (this.hostTree.levelModels || [])[this.depth];
  32112. },
  32113. /**
  32114. * @return {module:echarts/model/Model}
  32115. */
  32116. getLeavesModel: function () {
  32117. return this.hostTree.leavesModel;
  32118. },
  32119. /**
  32120. * @example
  32121. * setItemVisual('color', color);
  32122. * setItemVisual({
  32123. * 'color': color
  32124. * });
  32125. */
  32126. setVisual: function (key, value) {
  32127. this.dataIndex >= 0
  32128. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  32129. },
  32130. /**
  32131. * Get item visual
  32132. */
  32133. getVisual: function (key, ignoreParent) {
  32134. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  32135. },
  32136. /**
  32137. * @public
  32138. * @return {number}
  32139. */
  32140. getRawIndex: function () {
  32141. return this.hostTree.data.getRawIndex(this.dataIndex);
  32142. },
  32143. /**
  32144. * @public
  32145. * @return {string}
  32146. */
  32147. getId: function () {
  32148. return this.hostTree.data.getId(this.dataIndex);
  32149. }
  32150. };
  32151. /**
  32152. * @constructor
  32153. * @alias module:echarts/data/Tree
  32154. * @param {module:echarts/model/Model} hostModel
  32155. * @param {Array.<Object>} levelOptions
  32156. * @param {Object} leavesOption
  32157. */
  32158. function Tree(hostModel, levelOptions, leavesOption) {
  32159. /**
  32160. * @type {module:echarts/data/Tree~TreeNode}
  32161. * @readOnly
  32162. */
  32163. this.root;
  32164. /**
  32165. * @type {module:echarts/data/List}
  32166. * @readOnly
  32167. */
  32168. this.data;
  32169. /**
  32170. * Index of each item is the same as the raw index of coresponding list item.
  32171. * @private
  32172. * @type {Array.<module:echarts/data/Tree~TreeNode}
  32173. */
  32174. this._nodes = [];
  32175. /**
  32176. * @private
  32177. * @readOnly
  32178. * @type {module:echarts/model/Model}
  32179. */
  32180. this.hostModel = hostModel;
  32181. /**
  32182. * @private
  32183. * @readOnly
  32184. * @type {Array.<module:echarts/model/Model}
  32185. */
  32186. this.levelModels = map(levelOptions || [], function (levelDefine) {
  32187. return new Model(levelDefine, hostModel, hostModel.ecModel);
  32188. });
  32189. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  32190. }
  32191. Tree.prototype = {
  32192. constructor: Tree,
  32193. type: 'tree',
  32194. /**
  32195. * Travel this subtree (include this node).
  32196. * Usage:
  32197. * node.eachNode(function () { ... }); // preorder
  32198. * node.eachNode('preorder', function () { ... }); // preorder
  32199. * node.eachNode('postorder', function () { ... }); // postorder
  32200. * node.eachNode(
  32201. * {order: 'postorder', attr: 'viewChildren'},
  32202. * function () { ... }
  32203. * ); // postorder
  32204. *
  32205. * @param {(Object|string)} options If string, means order.
  32206. * @param {string=} options.order 'preorder' or 'postorder'
  32207. * @param {string=} options.attr 'children' or 'viewChildren'
  32208. * @param {Function} cb
  32209. * @param {Object} [context]
  32210. */
  32211. eachNode: function(options, cb, context) {
  32212. this.root.eachNode(options, cb, context);
  32213. },
  32214. /**
  32215. * @param {number} dataIndex
  32216. * @return {module:echarts/data/Tree~TreeNode}
  32217. */
  32218. getNodeByDataIndex: function (dataIndex) {
  32219. var rawIndex = this.data.getRawIndex(dataIndex);
  32220. return this._nodes[rawIndex];
  32221. },
  32222. /**
  32223. * @param {string} name
  32224. * @return {module:echarts/data/Tree~TreeNode}
  32225. */
  32226. getNodeByName: function (name) {
  32227. return this.root.getNodeByName(name);
  32228. },
  32229. /**
  32230. * Update item available by list,
  32231. * when list has been performed options like 'filterSelf' or 'map'.
  32232. */
  32233. update: function () {
  32234. var data = this.data;
  32235. var nodes = this._nodes;
  32236. for (var i = 0, len = nodes.length; i < len; i++) {
  32237. nodes[i].dataIndex = -1;
  32238. }
  32239. for (var i = 0, len = data.count(); i < len; i++) {
  32240. nodes[data.getRawIndex(i)].dataIndex = i;
  32241. }
  32242. },
  32243. /**
  32244. * Clear all layouts
  32245. */
  32246. clearLayouts: function () {
  32247. this.data.clearItemLayouts();
  32248. }
  32249. };
  32250. /**
  32251. * data node format:
  32252. * {
  32253. * name: ...
  32254. * value: ...
  32255. * children: [
  32256. * {
  32257. * name: ...
  32258. * value: ...
  32259. * children: ...
  32260. * },
  32261. * ...
  32262. * ]
  32263. * }
  32264. *
  32265. * @static
  32266. * @param {Object} dataRoot Root node.
  32267. * @param {module:echarts/model/Model} hostModel
  32268. * @param {Object} treeOptions
  32269. * @param {Array.<Object>} treeOptions.levels
  32270. * @param {Array.<Object>} treeOptions.leaves
  32271. * @return module:echarts/data/Tree
  32272. */
  32273. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  32274. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  32275. var listData = [];
  32276. var dimMax = 1;
  32277. buildHierarchy(dataRoot);
  32278. function buildHierarchy(dataNode, parentNode) {
  32279. var value = dataNode.value;
  32280. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  32281. listData.push(dataNode);
  32282. var node = new TreeNode(dataNode.name, tree);
  32283. parentNode
  32284. ? addChild(node, parentNode)
  32285. : (tree.root = node);
  32286. tree._nodes.push(node);
  32287. var children = dataNode.children;
  32288. if (children) {
  32289. for (var i = 0; i < children.length; i++) {
  32290. buildHierarchy(children[i], node);
  32291. }
  32292. }
  32293. }
  32294. tree.root.updateDepthAndHeight(0);
  32295. var dimensions = completeDimensions([{name: 'value'}], listData, {dimCount: dimMax});
  32296. var list = new List(dimensions, hostModel);
  32297. list.initData(listData);
  32298. linkList({
  32299. mainData: list,
  32300. struct: tree,
  32301. structAttr: 'tree'
  32302. });
  32303. tree.update();
  32304. return tree;
  32305. };
  32306. /**
  32307. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  32308. * so this function is not ready and not necessary to be public.
  32309. *
  32310. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  32311. */
  32312. function addChild(child, node) {
  32313. var children = node.children;
  32314. if (child.parentNode === node) {
  32315. return;
  32316. }
  32317. children.push(child);
  32318. child.parentNode = node;
  32319. }
  32320. /**
  32321. * @file Create data struct and define tree view's series model
  32322. */
  32323. SeriesModel.extend({
  32324. type: 'series.tree',
  32325. layoutInfo: null,
  32326. // can support the position parameters 'left', 'top','right','bottom', 'width',
  32327. // 'height' in the setOption() with 'merge' mode normal.
  32328. layoutMode: 'box',
  32329. /**
  32330. * Init a tree data structure from data in option series
  32331. * @param {Object} option the object used to config echarts view
  32332. * @return {module:echarts/data/List} storage initial data
  32333. */
  32334. getInitialData: function (option) {
  32335. //create an virtual root
  32336. var root = {name: option.name, children: option.data};
  32337. var leaves = option.leaves || {};
  32338. var treeOption = {};
  32339. treeOption.leaves = leaves;
  32340. var tree = Tree.createTree(root, this, treeOption);
  32341. var treeDepth = 0;
  32342. tree.eachNode('preorder', function (node) {
  32343. if (node.depth > treeDepth) {
  32344. treeDepth = node.depth;
  32345. }
  32346. });
  32347. var expandAndCollapse = option.expandAndCollapse;
  32348. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  32349. ? option.initialTreeDepth : treeDepth;
  32350. tree.root.eachNode('preorder', function (node) {
  32351. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  32352. node.isExpand = (item && item.collapsed != null)
  32353. ? !item.collapsed
  32354. : node.depth <= expandTreeDepth;
  32355. });
  32356. return tree.data;
  32357. },
  32358. /**
  32359. * @override
  32360. * @param {number} dataIndex
  32361. */
  32362. formatTooltip: function (dataIndex) {
  32363. var tree = this.getData().tree;
  32364. var realRoot = tree.root.children[0];
  32365. var node = tree.getNodeByDataIndex(dataIndex);
  32366. var value = node.getValue();
  32367. var name = node.name;
  32368. while (node && (node !== realRoot)) {
  32369. name = node.parentNode.name + '.' + name;
  32370. node = node.parentNode;
  32371. }
  32372. return encodeHTML(name + (
  32373. (isNaN(value) || value == null) ? '' : ' : ' + value
  32374. ));
  32375. },
  32376. defaultOption: {
  32377. zlevel: 0,
  32378. z: 2,
  32379. // the position of the whole view
  32380. left: '12%',
  32381. top: '12%',
  32382. right: '12%',
  32383. bottom: '12%',
  32384. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  32385. layout: 'orthogonal',
  32386. // the orient of orthoginal layout, can be setted to 'horizontal' or 'vertical'
  32387. orient: 'horizontal',
  32388. symbol: 'emptyCircle',
  32389. symbolSize: 7,
  32390. expandAndCollapse: true,
  32391. initialTreeDepth: 2,
  32392. lineStyle: {
  32393. normal: {
  32394. color: '#ccc',
  32395. width: 1.5,
  32396. curveness: 0.5
  32397. }
  32398. },
  32399. itemStyle: {
  32400. normal: {
  32401. color: 'lightsteelblue',
  32402. borderColor: '#c23531',
  32403. borderWidth: 1.5
  32404. }
  32405. },
  32406. label: {
  32407. normal: {
  32408. show: true,
  32409. color: '#555'
  32410. }
  32411. },
  32412. leaves: {
  32413. label: {
  32414. normal: {
  32415. show: true
  32416. }
  32417. }
  32418. },
  32419. animationEasing: 'linear',
  32420. animationDuration: 700,
  32421. animationDurationUpdate: 1000
  32422. }
  32423. });
  32424. /**
  32425. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  32426. * the tree.
  32427. * @see https://github.com/d3/d3-hierarchy
  32428. */
  32429. /**
  32430. * Initialize all computational message for following algorithm
  32431. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  32432. */
  32433. function init$2(root) {
  32434. root.hierNode = {
  32435. defaultAncestor: null,
  32436. ancestor: root,
  32437. prelim: 0,
  32438. modifier: 0,
  32439. change: 0,
  32440. shift: 0,
  32441. i: 0,
  32442. thread: null
  32443. };
  32444. var nodes = [root];
  32445. var node;
  32446. var children;
  32447. while (node = nodes.pop()) { // jshint ignore:line
  32448. children = node.children;
  32449. if (node.isExpand && children.length) {
  32450. var n = children.length;
  32451. for (var i = n - 1; i >= 0; i--) {
  32452. var child = children[i];
  32453. child.hierNode = {
  32454. defaultAncestor: null,
  32455. ancestor: child,
  32456. prelim: 0,
  32457. modifier: 0,
  32458. change: 0,
  32459. shift: 0,
  32460. i: i,
  32461. thread: null
  32462. };
  32463. nodes.push(child);
  32464. }
  32465. }
  32466. }
  32467. }
  32468. /**
  32469. * Computes a preliminary x coordinate for node. Before that, this function is
  32470. * applied recursively to the children of node, as well as the function
  32471. * apportion(). After spacing out the children by calling executeShifts(), the
  32472. * node is placed to the midpoint of its outermost children.
  32473. * @param {module:echarts/data/Tree~TreeNode} node
  32474. * @param {Function} separation
  32475. */
  32476. function firstWalk(node, separation) {
  32477. var children = node.isExpand ? node.children : [];
  32478. var siblings = node.parentNode.children;
  32479. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  32480. if (children.length) {
  32481. executeShifts(node);
  32482. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  32483. if (subtreeW) {
  32484. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  32485. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  32486. }
  32487. else {
  32488. node.hierNode.prelim = midPoint;
  32489. }
  32490. }
  32491. else if (subtreeW) {
  32492. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  32493. }
  32494. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  32495. }
  32496. /**
  32497. * Computes all real x-coordinates by summing up the modifiers recursively.
  32498. * @param {module:echarts/data/Tree~TreeNode} node
  32499. */
  32500. function secondWalk(node) {
  32501. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  32502. node.setLayout({x: nodeX}, true);
  32503. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  32504. }
  32505. function separation(cb) {
  32506. return arguments.length ? cb : defaultSeparation;
  32507. }
  32508. /**
  32509. * Transform the common coordinate to radial coordinate
  32510. * @param {number} x
  32511. * @param {number} y
  32512. * @return {Object}
  32513. */
  32514. function radialCoordinate(x, y) {
  32515. var radialCoor = {};
  32516. x -= Math.PI / 2;
  32517. radialCoor.x = y * Math.cos(x);
  32518. radialCoor.y = y * Math.sin(x);
  32519. return radialCoor;
  32520. }
  32521. /**
  32522. * Get the layout position of the whole view
  32523. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  32524. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  32525. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  32526. */
  32527. function getViewRect(seriesModel, api) {
  32528. return getLayoutRect(
  32529. seriesModel.getBoxLayoutParams(), {
  32530. width: api.getWidth(),
  32531. height: api.getHeight()
  32532. }
  32533. );
  32534. }
  32535. /**
  32536. * All other shifts, applied to the smaller subtrees between w- and w+, are
  32537. * performed by this function.
  32538. * @param {module:echarts/data/Tree~TreeNode} node
  32539. */
  32540. function executeShifts(node) {
  32541. var children = node.children;
  32542. var n = children.length;
  32543. var shift = 0;
  32544. var change = 0;
  32545. while (--n >= 0) {
  32546. var child = children[n];
  32547. child.hierNode.prelim += shift;
  32548. child.hierNode.modifier += shift;
  32549. change += child.hierNode.change;
  32550. shift += child.hierNode.shift + change;
  32551. }
  32552. }
  32553. /**
  32554. * The core of the algorithm. Here, a new subtree is combined with the
  32555. * previous subtrees. Threads are used to traverse the inside and outside
  32556. * contours of the left and right subtree up to the highest common level.
  32557. * Whenever two nodes of the inside contours conflict, we compute the left
  32558. * one of the greatest uncommon ancestors using the function nextAncestor()
  32559. * and call moveSubtree() to shift the subtree and prepare the shifts of
  32560. * smaller subtrees. Finally, we add a new thread (if necessary).
  32561. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  32562. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  32563. * @param {module:echarts/data/Tree~TreeNode} ancestor
  32564. * @param {Function} separation
  32565. * @return {module:echarts/data/Tree~TreeNode}
  32566. */
  32567. function apportion(subtreeV, subtreeW, ancestor, separation) {
  32568. if (subtreeW) {
  32569. var nodeOutRight = subtreeV;
  32570. var nodeInRight = subtreeV;
  32571. var nodeOutLeft = nodeInRight.parentNode.children[0];
  32572. var nodeInLeft = subtreeW;
  32573. var sumOutRight = nodeOutRight.hierNode.modifier;
  32574. var sumInRight = nodeInRight.hierNode.modifier;
  32575. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  32576. var sumInLeft = nodeInLeft.hierNode.modifier;
  32577. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  32578. nodeOutRight = nextRight(nodeOutRight);
  32579. nodeOutLeft = nextLeft(nodeOutLeft);
  32580. nodeOutRight.hierNode.ancestor = subtreeV;
  32581. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  32582. - sumInRight + separation(nodeInLeft, nodeInRight);
  32583. if (shift > 0) {
  32584. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  32585. sumInRight += shift;
  32586. sumOutRight += shift;
  32587. }
  32588. sumInLeft += nodeInLeft.hierNode.modifier;
  32589. sumInRight += nodeInRight.hierNode.modifier;
  32590. sumOutRight += nodeOutRight.hierNode.modifier;
  32591. sumOutLeft += nodeOutLeft.hierNode.modifier;
  32592. }
  32593. if (nodeInLeft && !nextRight(nodeOutRight)) {
  32594. nodeOutRight.hierNode.thread = nodeInLeft;
  32595. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  32596. }
  32597. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  32598. nodeOutLeft.hierNode.thread = nodeInRight;
  32599. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  32600. ancestor = subtreeV;
  32601. }
  32602. }
  32603. return ancestor;
  32604. }
  32605. /**
  32606. * This function is used to traverse the right contour of a subtree.
  32607. * It returns the rightmost child of node or the thread of node. The function
  32608. * returns null if and only if node is on the highest depth of its subtree.
  32609. * @param {module:echarts/data/Tree~TreeNode} node
  32610. * @return {module:echarts/data/Tree~TreeNode}
  32611. */
  32612. function nextRight(node) {
  32613. var children = node.children;
  32614. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  32615. }
  32616. /**
  32617. * This function is used to traverse the left contour of a subtree (or a subforest).
  32618. * It returns the leftmost child of node or the thread of node. The function
  32619. * returns null if and only if node is on the highest depth of its subtree.
  32620. * @param {module:echarts/data/Tree~TreeNode} node
  32621. * @return {module:echarts/data/Tree~TreeNode}
  32622. */
  32623. function nextLeft(node) {
  32624. var children = node.children;
  32625. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  32626. }
  32627. /**
  32628. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  32629. * Otherwise, returns the specified ancestor.
  32630. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  32631. * @param {module:echarts/data/Tree~TreeNode} node
  32632. * @param {module:echarts/data/Tree~TreeNode} ancestor
  32633. * @return {module:echarts/data/Tree~TreeNode}
  32634. */
  32635. function nextAncestor(nodeInLeft, node, ancestor) {
  32636. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  32637. ? nodeInLeft.hierNode.ancestor : ancestor;
  32638. }
  32639. /**
  32640. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  32641. * @param {module:echarts/data/Tree~TreeNode} wl
  32642. * @param {module:echarts/data/Tree~TreeNode} wr
  32643. * @param {number} shift [description]
  32644. */
  32645. function moveSubtree(wl, wr,shift) {
  32646. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  32647. wr.hierNode.change -= change;
  32648. wr.hierNode.shift += shift;
  32649. wr.hierNode.modifier += shift;
  32650. wr.hierNode.prelim += shift;
  32651. wl.hierNode.change += change;
  32652. }
  32653. function defaultSeparation(node1, node2) {
  32654. return node1.parentNode === node2.parentNode ? 1 : 2;
  32655. }
  32656. /**
  32657. * @file This file used to draw tree view
  32658. */
  32659. extendChartView({
  32660. type: 'tree',
  32661. /**
  32662. * Init the chart
  32663. * @override
  32664. * @param {module:echarts/model/Global} ecModel
  32665. * @param {module:echarts/ExtensionAPI} api
  32666. */
  32667. init: function (ecModel, api) {
  32668. /**
  32669. * @private
  32670. * @type {module:echarts/data/Tree}
  32671. */
  32672. this._oldTree;
  32673. /**
  32674. * @private
  32675. * @type {module:zrender/container/Group}
  32676. */
  32677. this._mainGroup = new Group();
  32678. this.group.add(this._mainGroup);
  32679. },
  32680. render: function (seriesModel, ecModel, api, payload) {
  32681. var data = seriesModel.getData();
  32682. var layoutInfo = seriesModel.layoutInfo;
  32683. var group = this._mainGroup;
  32684. var layout = seriesModel.get('layout');
  32685. if (layout === 'radial') {
  32686. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  32687. }
  32688. else {
  32689. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  32690. }
  32691. var oldData = this._data;
  32692. var seriesScope = {
  32693. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  32694. layout: layout,
  32695. orient: seriesModel.get('orient'),
  32696. curvature: seriesModel.get('lineStyle.normal.curveness'),
  32697. symbolRotate: seriesModel.get('symbolRotate'),
  32698. symbolOffset: seriesModel.get('symbolOffset'),
  32699. hoverAnimation: seriesModel.get('hoverAnimation'),
  32700. useNameLabel: true,
  32701. fadeIn: true
  32702. };
  32703. data.diff(oldData)
  32704. .add(function (newIdx) {
  32705. if (symbolNeedsDraw$1(data, newIdx)) {
  32706. // create node and edge
  32707. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  32708. }
  32709. })
  32710. .update(function (newIdx, oldIdx) {
  32711. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32712. if (!symbolNeedsDraw$1(data, newIdx)) {
  32713. symbolEl && removeNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  32714. return;
  32715. }
  32716. // update node and edge
  32717. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  32718. })
  32719. .remove(function (oldIdx) {
  32720. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  32721. removeNode(data, oldIdx, symbolEl, group, seriesModel, seriesScope);
  32722. })
  32723. .execute();
  32724. if (seriesScope.expandAndCollapse === true) {
  32725. data.eachItemGraphicEl(function (el, dataIndex) {
  32726. el.off('click').on('click', function () {
  32727. api.dispatchAction({
  32728. type: 'treeExpandAndCollapse',
  32729. seriesId: seriesModel.id,
  32730. dataIndex: dataIndex
  32731. });
  32732. });
  32733. });
  32734. }
  32735. this._data = data;
  32736. },
  32737. dispose: function () {},
  32738. remove: function () {
  32739. this._mainGroup.removeAll();
  32740. this._data = null;
  32741. }
  32742. });
  32743. function symbolNeedsDraw$1(data, dataIndex) {
  32744. var layout = data.getItemLayout(dataIndex);
  32745. return layout
  32746. && !isNaN(layout.x) && !isNaN(layout.y)
  32747. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  32748. }
  32749. function getTreeNodeStyle(node, itemModel, seriesScope) {
  32750. seriesScope.itemModel = itemModel;
  32751. seriesScope.itemStyle = itemModel.getModel('itemStyle.normal').getItemStyle();
  32752. seriesScope.hoverItemStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  32753. seriesScope.lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  32754. seriesScope.labelModel = itemModel.getModel('label.normal');
  32755. seriesScope.hoverLabelModel = itemModel.getModel('label.emphasis');
  32756. if (node.isExpand === false && node.children.length !== 0) {
  32757. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  32758. }
  32759. else {
  32760. seriesScope.symbolInnerColor = '#fff';
  32761. }
  32762. return seriesScope;
  32763. }
  32764. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  32765. var isInit = !symbolEl;
  32766. var node = data.tree.getNodeByDataIndex(dataIndex);
  32767. var itemModel = node.getModel();
  32768. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  32769. var virtualRoot = data.tree.root;
  32770. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  32771. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  32772. var sourceLayout = source.getLayout();
  32773. var sourceOldLayout = sourceSymbolEl
  32774. ? {
  32775. x: sourceSymbolEl.position[0],
  32776. y: sourceSymbolEl.position[1],
  32777. rawX: sourceSymbolEl.__radialOldRawX,
  32778. rawY: sourceSymbolEl.__radialOldRawY
  32779. }
  32780. : sourceLayout;
  32781. var targetLayout = node.getLayout();
  32782. if (isInit) {
  32783. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  32784. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  32785. }
  32786. else {
  32787. symbolEl.updateData(data, dataIndex, seriesScope);
  32788. }
  32789. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  32790. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  32791. symbolEl.__radialRawX = targetLayout.rawX;
  32792. symbolEl.__radialRawY = targetLayout.rawY;
  32793. group.add(symbolEl);
  32794. data.setItemGraphicEl(dataIndex, symbolEl);
  32795. updateProps(symbolEl, {
  32796. position: [targetLayout.x, targetLayout.y]
  32797. }, seriesModel);
  32798. var symbolPath = symbolEl.getSymbolPath();
  32799. if (seriesScope.layout === 'radial') {
  32800. var realRoot = virtualRoot.children[0];
  32801. var rootLayout = realRoot.getLayout();
  32802. var length = realRoot.children.length;
  32803. var rad;
  32804. var isLeft;
  32805. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  32806. var center = {};
  32807. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  32808. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  32809. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  32810. if (rad < 0) {
  32811. rad = Math.PI * 2 + rad;
  32812. }
  32813. isLeft = center.x < rootLayout.x;
  32814. if (isLeft) {
  32815. rad = rad - Math.PI;
  32816. }
  32817. }
  32818. else {
  32819. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  32820. if (rad < 0) {
  32821. rad = Math.PI * 2 + rad;
  32822. }
  32823. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  32824. isLeft = targetLayout.x < rootLayout.x;
  32825. if (isLeft) {
  32826. rad = rad - Math.PI;
  32827. }
  32828. }
  32829. else {
  32830. isLeft = targetLayout.x > rootLayout.x;
  32831. if (!isLeft) {
  32832. rad = rad - Math.PI;
  32833. }
  32834. }
  32835. }
  32836. var textPosition = isLeft ? 'left' : 'right';
  32837. symbolPath.setStyle({
  32838. textPosition: textPosition,
  32839. textRotation: -rad,
  32840. textOrigin: 'center',
  32841. verticalAlign: 'middle'
  32842. });
  32843. }
  32844. if (node.parentNode && node.parentNode !== virtualRoot) {
  32845. var edge = symbolEl.__edge;
  32846. if (!edge) {
  32847. edge = symbolEl.__edge = new BezierCurve({
  32848. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  32849. style: defaults({opacity: 0}, seriesScope.lineStyle)
  32850. });
  32851. }
  32852. updateProps(edge, {
  32853. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  32854. style: {opacity: 1}
  32855. }, seriesModel);
  32856. group.add(edge);
  32857. }
  32858. }
  32859. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  32860. var node = data.tree.getNodeByDataIndex(dataIndex);
  32861. var virtualRoot = data.tree.root;
  32862. var itemModel = node.getModel();
  32863. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  32864. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  32865. var sourceLayout;
  32866. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  32867. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  32868. }
  32869. updateProps(symbolEl, {
  32870. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  32871. }, seriesModel, function () {
  32872. group.remove(symbolEl);
  32873. data.setItemGraphicEl(dataIndex, null);
  32874. });
  32875. symbolEl.fadeOut(null, {keepLabel: true});
  32876. var edge = symbolEl.__edge;
  32877. if (edge) {
  32878. updateProps(edge, {
  32879. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  32880. style: {
  32881. opacity: 0
  32882. }
  32883. }, seriesModel, function () {
  32884. group.remove(edge);
  32885. });
  32886. }
  32887. }
  32888. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  32889. var cpx1;
  32890. var cpy1;
  32891. var cpx2;
  32892. var cpy2;
  32893. var orient = seriesScope.orient;
  32894. if (seriesScope.layout === 'radial') {
  32895. var x1 = sourceLayout.rawX;
  32896. var y1 = sourceLayout.rawY;
  32897. var x2 = targetLayout.rawX;
  32898. var y2 = targetLayout.rawY;
  32899. var radialCoor1 = radialCoordinate(x1, y1);
  32900. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  32901. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  32902. var radialCoor4 = radialCoordinate(x2, y2);
  32903. return {
  32904. x1: radialCoor1.x,
  32905. y1: radialCoor1.y,
  32906. x2: radialCoor4.x,
  32907. y2: radialCoor4.y,
  32908. cpx1: radialCoor2.x,
  32909. cpy1: radialCoor2.y,
  32910. cpx2: radialCoor3.x,
  32911. cpy2: radialCoor3.y
  32912. };
  32913. }
  32914. else {
  32915. var x1 = sourceLayout.x;
  32916. var y1 = sourceLayout.y;
  32917. var x2 = targetLayout.x;
  32918. var y2 = targetLayout.y;
  32919. if (orient === 'horizontal') {
  32920. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  32921. cpy1 = y1;
  32922. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  32923. cpy2 = y2;
  32924. }
  32925. if (orient === 'vertical') {
  32926. cpx1 = x1;
  32927. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  32928. cpx2 = x2;
  32929. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  32930. }
  32931. return {
  32932. x1: x1,
  32933. y1: y1,
  32934. x2: x2,
  32935. y2: y2,
  32936. cpx1: cpx1,
  32937. cpy1: cpy1,
  32938. cpx2: cpx2,
  32939. cpy2: cpy2
  32940. };
  32941. }
  32942. }
  32943. registerAction({
  32944. type: 'treeExpandAndCollapse',
  32945. event: 'treeExpandAndCollapse',
  32946. update: 'update'
  32947. }, function (payload, ecModel) {
  32948. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  32949. var dataIndex = payload.dataIndex;
  32950. var tree = seriesModel.getData().tree;
  32951. var node = tree.getNodeByDataIndex(dataIndex);
  32952. node.isExpand = !node.isExpand;
  32953. });
  32954. });
  32955. /**
  32956. * Traverse the tree from bottom to top and do something
  32957. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  32958. * @param {Function} callback
  32959. */
  32960. function eachAfter (root, callback, separation) {
  32961. var nodes = [root];
  32962. var next = [];
  32963. var node;
  32964. while (node = nodes.pop()) { // jshint ignore:line
  32965. next.push(node);
  32966. if (node.isExpand) {
  32967. var children = node.children;
  32968. if (children.length) {
  32969. for (var i = 0; i < children.length; i++) {
  32970. nodes.push(children[i]);
  32971. }
  32972. }
  32973. }
  32974. }
  32975. while (node = next.pop()) { // jshint ignore:line
  32976. callback(node, separation);
  32977. }
  32978. }
  32979. /**
  32980. * Traverse the tree from top to bottom and do something
  32981. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  32982. * @param {Function} callback
  32983. */
  32984. function eachBefore (root, callback) {
  32985. var nodes = [root];
  32986. var node;
  32987. while (node = nodes.pop()) { // jshint ignore:line
  32988. callback(node);
  32989. if (node.isExpand) {
  32990. var children = node.children;
  32991. if (children.length) {
  32992. for (var i = children.length - 1; i >= 0; i--) {
  32993. nodes.push(children[i]);
  32994. }
  32995. }
  32996. }
  32997. }
  32998. }
  32999. var commonLayout = function (seriesModel, api) {
  33000. var layoutInfo = getViewRect(seriesModel, api);
  33001. seriesModel.layoutInfo = layoutInfo;
  33002. var layout = seriesModel.get('layout');
  33003. var width = 0;
  33004. var height = 0;
  33005. var separation$$1 = null;
  33006. if (layout === 'radial') {
  33007. width = 2 * Math.PI;
  33008. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  33009. separation$$1 = separation(function (node1, node2) {
  33010. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  33011. });
  33012. }
  33013. else {
  33014. width = layoutInfo.width;
  33015. height = layoutInfo.height;
  33016. separation$$1 = separation();
  33017. }
  33018. var virtualRoot = seriesModel.getData().tree.root;
  33019. var realRoot = virtualRoot.children[0];
  33020. init$2(virtualRoot);
  33021. eachAfter(realRoot, firstWalk, separation$$1);
  33022. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  33023. eachBefore(realRoot, secondWalk);
  33024. var left = realRoot;
  33025. var right = realRoot;
  33026. var bottom = realRoot;
  33027. eachBefore(realRoot, function (node) {
  33028. var x = node.getLayout().x;
  33029. if (x < left.getLayout().x) {
  33030. left = node;
  33031. }
  33032. if (x > right.getLayout().x) {
  33033. right = node;
  33034. }
  33035. if (node.depth > bottom.depth) {
  33036. bottom = node;
  33037. }
  33038. });
  33039. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  33040. var tx = delta - left.getLayout().x;
  33041. var kx = 0;
  33042. var ky = 0;
  33043. var coorX = 0;
  33044. var coorY = 0;
  33045. if (layout === 'radial') {
  33046. kx = width / (right.getLayout().x + delta + tx);
  33047. // here we use (node.depth - 1), bucause the real root's depth is 1
  33048. ky = height/ ((bottom.depth - 1) || 1);
  33049. eachBefore(realRoot, function (node) {
  33050. coorX = (node.getLayout().x + tx) * kx;
  33051. coorY = (node.depth - 1) * ky;
  33052. var finalCoor = radialCoordinate(coorX, coorY);
  33053. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  33054. });
  33055. }
  33056. else {
  33057. if (seriesModel.get('orient') === 'horizontal') {
  33058. ky = height / (right.getLayout().x + delta + tx);
  33059. kx = width / ((bottom.depth - 1) || 1);
  33060. eachBefore(realRoot, function (node) {
  33061. coorY = (node.getLayout().x + tx) * ky;
  33062. coorX = (node.depth - 1) * kx;
  33063. node.setLayout({x: coorX, y: coorY}, true);
  33064. });
  33065. }
  33066. else {
  33067. kx = width / (right.getLayout().x + delta + tx);
  33068. ky = height / ((bottom.depth - 1) || 1);
  33069. eachBefore(realRoot, function (node) {
  33070. coorX = (node.getLayout().x + tx) * kx;
  33071. coorY = (node.depth - 1) * ky;
  33072. node.setLayout({x: coorX, y: coorY}, true);
  33073. });
  33074. }
  33075. }
  33076. };
  33077. var orthogonalLayout = function (ecModel, api) {
  33078. ecModel.eachSeriesByType('tree', function (seriesModel) {
  33079. commonLayout(seriesModel, api);
  33080. });
  33081. };
  33082. var radialLayout = function (ecModel, api) {
  33083. ecModel.eachSeriesByType('tree', function (seriesModel) {
  33084. commonLayout(seriesModel, api);
  33085. });
  33086. };
  33087. registerVisual(curry(visualSymbol, 'tree', 'circle', null));
  33088. registerLayout(orthogonalLayout);
  33089. registerLayout(radialLayout);
  33090. function retrieveTargetInfo(payload, seriesModel) {
  33091. if (payload
  33092. && (
  33093. payload.type === 'treemapZoomToNode'
  33094. || payload.type === 'treemapRootToNode'
  33095. )
  33096. ) {
  33097. var root = seriesModel.getData().tree.root;
  33098. var targetNode = payload.targetNode;
  33099. if (targetNode && root.contains(targetNode)) {
  33100. return {node: targetNode};
  33101. }
  33102. var targetNodeId = payload.targetNodeId;
  33103. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  33104. return {node: targetNode};
  33105. }
  33106. }
  33107. }
  33108. // Not includes the given node at the last item.
  33109. function getPathToRoot(node) {
  33110. var path = [];
  33111. while (node) {
  33112. node = node.parentNode;
  33113. node && path.push(node);
  33114. }
  33115. return path.reverse();
  33116. }
  33117. function aboveViewRoot(viewRoot, node) {
  33118. var viewPath = getPathToRoot(viewRoot);
  33119. return indexOf(viewPath, node) >= 0;
  33120. }
  33121. // From root to the input node (the input node will be included).
  33122. function wrapTreePathInfo(node, seriesModel) {
  33123. var treePathInfo = [];
  33124. while (node) {
  33125. var nodeDataIndex = node.dataIndex;
  33126. treePathInfo.push({
  33127. name: node.name,
  33128. dataIndex: nodeDataIndex,
  33129. value: seriesModel.getRawValue(nodeDataIndex)
  33130. });
  33131. node = node.parentNode;
  33132. }
  33133. treePathInfo.reverse();
  33134. return treePathInfo;
  33135. }
  33136. SeriesModel.extend({
  33137. type: 'series.treemap',
  33138. layoutMode: 'box',
  33139. dependencies: ['grid', 'polar'],
  33140. /**
  33141. * @type {module:echarts/data/Tree~Node}
  33142. */
  33143. _viewRoot: null,
  33144. defaultOption: {
  33145. // Disable progressive rendering
  33146. progressive: 0,
  33147. hoverLayerThreshold: Infinity,
  33148. // center: ['50%', '50%'], // not supported in ec3.
  33149. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  33150. left: 'center',
  33151. top: 'middle',
  33152. right: null,
  33153. bottom: null,
  33154. width: '80%',
  33155. height: '80%',
  33156. sort: true, // Can be null or false or true
  33157. // (order by desc default, asc not supported yet (strange effect))
  33158. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  33159. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  33160. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  33161. // Count from zero (zero represents only view root).
  33162. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  33163. // to align specialized icon. ▷▶❒❐▼✚
  33164. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  33165. // target node area in the view area.
  33166. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  33167. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  33168. // If leafDepth is set and clicking a node which has children but
  33169. // be on left depth, the behaviour would be changing root. Otherwise
  33170. // use behavious defined above.
  33171. animation: true,
  33172. animationDurationUpdate: 900,
  33173. animationEasing: 'quinticInOut',
  33174. breadcrumb: {
  33175. show: true,
  33176. height: 22,
  33177. left: 'center',
  33178. top: 'bottom',
  33179. // right
  33180. // bottom
  33181. emptyItemWidth: 25, // Width of empty node.
  33182. itemStyle: {
  33183. normal: {
  33184. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  33185. borderColor: 'rgba(255,255,255,0.7)',
  33186. borderWidth: 1,
  33187. shadowColor: 'rgba(150,150,150,1)',
  33188. shadowBlur: 3,
  33189. shadowOffsetX: 0,
  33190. shadowOffsetY: 0,
  33191. textStyle: {
  33192. color: '#fff'
  33193. }
  33194. },
  33195. emphasis: {
  33196. textStyle: {}
  33197. }
  33198. }
  33199. },
  33200. label: {
  33201. normal: {
  33202. show: true,
  33203. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  33204. distance: 0,
  33205. padding: 5,
  33206. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  33207. // formatter: null,
  33208. color: '#fff',
  33209. ellipsis: true
  33210. // align
  33211. // verticalAlign
  33212. }
  33213. },
  33214. upperLabel: { // Label when node is parent.
  33215. normal: {
  33216. show: false,
  33217. position: [0, '50%'],
  33218. height: 20,
  33219. // formatter: null,
  33220. color: '#fff',
  33221. ellipsis: true,
  33222. // align: null,
  33223. verticalAlign: 'middle'
  33224. },
  33225. emphasis: {
  33226. show: true,
  33227. position: [0, '50%'],
  33228. color: '#fff',
  33229. ellipsis: true,
  33230. verticalAlign: 'middle'
  33231. }
  33232. },
  33233. itemStyle: {
  33234. normal: {
  33235. color: null, // Can be 'none' if not necessary.
  33236. colorAlpha: null, // Can be 'none' if not necessary.
  33237. colorSaturation: null, // Can be 'none' if not necessary.
  33238. borderWidth: 0,
  33239. gapWidth: 0,
  33240. borderColor: '#fff',
  33241. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  33242. // border color is evaluated by color of current node and
  33243. // borderColorSaturation.
  33244. },
  33245. emphasis: {
  33246. }
  33247. },
  33248. visualDimension: 0, // Can be 0, 1, 2, 3.
  33249. visualMin: null,
  33250. visualMax: null,
  33251. color: [], // + treemapSeries.color should not be modified. Please only modified
  33252. // level[n].color (if necessary).
  33253. // + Specify color list of each level. level[0].color would be global
  33254. // color list if not specified. (see method `setDefault`).
  33255. // + But set as a empty array to forbid fetch color from global palette
  33256. // when using nodeModel.get('color'), otherwise nodes on deep level
  33257. // will always has color palette set and are not able to inherit color
  33258. // from parent node.
  33259. // + TreemapSeries.color can not be set as 'none', otherwise effect
  33260. // legend color fetching (see seriesColor.js).
  33261. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  33262. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  33263. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  33264. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  33265. // be rendered. Only works when sort is 'asc' or 'desc'.
  33266. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  33267. // grandchildren will not show.
  33268. // Why grandchildren? If not grandchildren but children,
  33269. // some siblings show children and some not,
  33270. // the appearance may be mess and not consistent,
  33271. levels: [] // Each item: {
  33272. // visibleMin, itemStyle, visualDimension, label
  33273. // }
  33274. // data: {
  33275. // value: [],
  33276. // children: [],
  33277. // link: 'http://xxx.xxx.xxx',
  33278. // target: 'blank' or 'self'
  33279. // }
  33280. },
  33281. /**
  33282. * @override
  33283. */
  33284. getInitialData: function (option, ecModel) {
  33285. // Create a virtual root.
  33286. var root = {name: option.name, children: option.data};
  33287. completeTreeValue(root);
  33288. var levels = option.levels || [];
  33289. levels = option.levels = setDefault(levels, ecModel);
  33290. var treeOption = {};
  33291. treeOption.levels = levels;
  33292. // Make sure always a new tree is created when setOption,
  33293. // in TreemapView, we check whether oldTree === newTree
  33294. // to choose mappings approach among old shapes and new shapes.
  33295. return Tree.createTree(root, this, treeOption).data;
  33296. },
  33297. optionUpdated: function () {
  33298. this.resetViewRoot();
  33299. },
  33300. /**
  33301. * @override
  33302. * @param {number} dataIndex
  33303. * @param {boolean} [mutipleSeries=false]
  33304. */
  33305. formatTooltip: function (dataIndex) {
  33306. var data = this.getData();
  33307. var value = this.getRawValue(dataIndex);
  33308. var formattedValue = isArray(value)
  33309. ? addCommas(value[0]) : addCommas(value);
  33310. var name = data.getName(dataIndex);
  33311. return encodeHTML(name + ': ' + formattedValue);
  33312. },
  33313. /**
  33314. * Add tree path to tooltip param
  33315. *
  33316. * @override
  33317. * @param {number} dataIndex
  33318. * @return {Object}
  33319. */
  33320. getDataParams: function (dataIndex) {
  33321. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  33322. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  33323. params.treePathInfo = wrapTreePathInfo(node, this);
  33324. return params;
  33325. },
  33326. /**
  33327. * @public
  33328. * @param {Object} layoutInfo {
  33329. * x: containerGroup x
  33330. * y: containerGroup y
  33331. * width: containerGroup width
  33332. * height: containerGroup height
  33333. * }
  33334. */
  33335. setLayoutInfo: function (layoutInfo) {
  33336. /**
  33337. * @readOnly
  33338. * @type {Object}
  33339. */
  33340. this.layoutInfo = this.layoutInfo || {};
  33341. extend(this.layoutInfo, layoutInfo);
  33342. },
  33343. /**
  33344. * @param {string} id
  33345. * @return {number} index
  33346. */
  33347. mapIdToIndex: function (id) {
  33348. // A feature is implemented:
  33349. // index is monotone increasing with the sequence of
  33350. // input id at the first time.
  33351. // This feature can make sure that each data item and its
  33352. // mapped color have the same index between data list and
  33353. // color list at the beginning, which is useful for user
  33354. // to adjust data-color mapping.
  33355. /**
  33356. * @private
  33357. * @type {Object}
  33358. */
  33359. var idIndexMap = this._idIndexMap;
  33360. if (!idIndexMap) {
  33361. idIndexMap = this._idIndexMap = createHashMap();
  33362. /**
  33363. * @private
  33364. * @type {number}
  33365. */
  33366. this._idIndexMapCount = 0;
  33367. }
  33368. var index = idIndexMap.get(id);
  33369. if (index == null) {
  33370. idIndexMap.set(id, index = this._idIndexMapCount++);
  33371. }
  33372. return index;
  33373. },
  33374. getViewRoot: function () {
  33375. return this._viewRoot;
  33376. },
  33377. /**
  33378. * @param {module:echarts/data/Tree~Node} [viewRoot]
  33379. */
  33380. resetViewRoot: function (viewRoot) {
  33381. viewRoot
  33382. ? (this._viewRoot = viewRoot)
  33383. : (viewRoot = this._viewRoot);
  33384. var root = this.getData().tree.root;
  33385. if (!viewRoot
  33386. || (viewRoot !== root && !root.contains(viewRoot))
  33387. ) {
  33388. this._viewRoot = root;
  33389. }
  33390. }
  33391. });
  33392. /**
  33393. * @param {Object} dataNode
  33394. */
  33395. function completeTreeValue(dataNode) {
  33396. // Postorder travel tree.
  33397. // If value of none-leaf node is not set,
  33398. // calculate it by suming up the value of all children.
  33399. var sum = 0;
  33400. each$1(dataNode.children, function (child) {
  33401. completeTreeValue(child);
  33402. var childValue = child.value;
  33403. isArray(childValue) && (childValue = childValue[0]);
  33404. sum += childValue;
  33405. });
  33406. var thisValue = dataNode.value;
  33407. if (isArray(thisValue)) {
  33408. thisValue = thisValue[0];
  33409. }
  33410. if (thisValue == null || isNaN(thisValue)) {
  33411. thisValue = sum;
  33412. }
  33413. // Value should not less than 0.
  33414. if (thisValue < 0) {
  33415. thisValue = 0;
  33416. }
  33417. isArray(dataNode.value)
  33418. ? (dataNode.value[0] = thisValue)
  33419. : (dataNode.value = thisValue);
  33420. }
  33421. /**
  33422. * set default to level configuration
  33423. */
  33424. function setDefault(levels, ecModel) {
  33425. var globalColorList = ecModel.get('color');
  33426. if (!globalColorList) {
  33427. return;
  33428. }
  33429. levels = levels || [];
  33430. var hasColorDefine;
  33431. each$1(levels, function (levelDefine) {
  33432. var model = new Model(levelDefine);
  33433. var modelColor = model.get('color');
  33434. if (model.get('itemStyle.normal.color')
  33435. || (modelColor && modelColor !== 'none')
  33436. ) {
  33437. hasColorDefine = true;
  33438. }
  33439. });
  33440. if (!hasColorDefine) {
  33441. var level0 = levels[0] || (levels[0] = {});
  33442. level0.color = globalColorList.slice();
  33443. }
  33444. return levels;
  33445. }
  33446. var TEXT_PADDING = 8;
  33447. var ITEM_GAP = 8;
  33448. var ARRAY_LENGTH = 5;
  33449. function Breadcrumb(containerGroup) {
  33450. /**
  33451. * @private
  33452. * @type {module:zrender/container/Group}
  33453. */
  33454. this.group = new Group();
  33455. containerGroup.add(this.group);
  33456. }
  33457. Breadcrumb.prototype = {
  33458. constructor: Breadcrumb,
  33459. render: function (seriesModel, api, targetNode, onSelect) {
  33460. var model = seriesModel.getModel('breadcrumb');
  33461. var thisGroup = this.group;
  33462. thisGroup.removeAll();
  33463. if (!model.get('show') || !targetNode) {
  33464. return;
  33465. }
  33466. var normalStyleModel = model.getModel('itemStyle.normal');
  33467. // var emphasisStyleModel = model.getModel('itemStyle.emphasis');
  33468. var textStyleModel = normalStyleModel.getModel('textStyle');
  33469. var layoutParam = {
  33470. pos: {
  33471. left: model.get('left'),
  33472. right: model.get('right'),
  33473. top: model.get('top'),
  33474. bottom: model.get('bottom')
  33475. },
  33476. box: {
  33477. width: api.getWidth(),
  33478. height: api.getHeight()
  33479. },
  33480. emptyItemWidth: model.get('emptyItemWidth'),
  33481. totalWidth: 0,
  33482. renderList: []
  33483. };
  33484. this._prepare(targetNode, layoutParam, textStyleModel);
  33485. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  33486. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  33487. },
  33488. /**
  33489. * Prepare render list and total width
  33490. * @private
  33491. */
  33492. _prepare: function (targetNode, layoutParam, textStyleModel) {
  33493. for (var node = targetNode; node; node = node.parentNode) {
  33494. var text = node.getModel().get('name');
  33495. var textRect = textStyleModel.getTextRect(text);
  33496. var itemWidth = Math.max(
  33497. textRect.width + TEXT_PADDING * 2,
  33498. layoutParam.emptyItemWidth
  33499. );
  33500. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  33501. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  33502. }
  33503. },
  33504. /**
  33505. * @private
  33506. */
  33507. _renderContent: function (
  33508. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  33509. ) {
  33510. // Start rendering.
  33511. var lastX = 0;
  33512. var emptyItemWidth = layoutParam.emptyItemWidth;
  33513. var height = seriesModel.get('breadcrumb.height');
  33514. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  33515. var totalWidth = layoutParam.totalWidth;
  33516. var renderList = layoutParam.renderList;
  33517. for (var i = renderList.length - 1; i >= 0; i--) {
  33518. var item = renderList[i];
  33519. var itemNode = item.node;
  33520. var itemWidth = item.width;
  33521. var text = item.text;
  33522. // Hdie text and shorten width if necessary.
  33523. if (totalWidth > availableSize.width) {
  33524. totalWidth -= itemWidth - emptyItemWidth;
  33525. itemWidth = emptyItemWidth;
  33526. text = null;
  33527. }
  33528. var el = new Polygon({
  33529. shape: {
  33530. points: makeItemPoints(
  33531. lastX, 0, itemWidth, height,
  33532. i === renderList.length - 1, i === 0
  33533. )
  33534. },
  33535. style: defaults(
  33536. normalStyleModel.getItemStyle(),
  33537. {
  33538. lineJoin: 'bevel',
  33539. text: text,
  33540. textFill: textStyleModel.getTextColor(),
  33541. textFont: textStyleModel.getFont()
  33542. }
  33543. ),
  33544. z: 10,
  33545. onclick: curry(onSelect, itemNode)
  33546. });
  33547. this.group.add(el);
  33548. packEventData(el, seriesModel, itemNode);
  33549. lastX += itemWidth + ITEM_GAP;
  33550. }
  33551. },
  33552. /**
  33553. * @override
  33554. */
  33555. remove: function () {
  33556. this.group.removeAll();
  33557. }
  33558. };
  33559. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  33560. var points = [
  33561. [head ? x : x - ARRAY_LENGTH, y],
  33562. [x + itemWidth, y],
  33563. [x + itemWidth, y + itemHeight],
  33564. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  33565. ];
  33566. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  33567. !head && points.push([x, y + itemHeight / 2]);
  33568. return points;
  33569. }
  33570. // Package custom mouse event.
  33571. function packEventData(el, seriesModel, itemNode) {
  33572. el.eventData = {
  33573. componentType: 'series',
  33574. componentSubType: 'treemap',
  33575. seriesIndex: seriesModel.componentIndex,
  33576. seriesName: seriesModel.name,
  33577. seriesType: 'treemap',
  33578. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  33579. nodeData: {
  33580. dataIndex: itemNode && itemNode.dataIndex,
  33581. name: itemNode && itemNode.name
  33582. },
  33583. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  33584. };
  33585. }
  33586. /**
  33587. * @param {number} [time=500] Time in ms
  33588. * @param {string} [easing='linear']
  33589. * @param {number} [delay=0]
  33590. * @param {Function} [callback]
  33591. *
  33592. * @example
  33593. * // Animate position
  33594. * animation
  33595. * .createWrap()
  33596. * .add(el1, {position: [10, 10]})
  33597. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  33598. * .done(function () { // done })
  33599. * .start('cubicOut');
  33600. */
  33601. function createWrap() {
  33602. var storage = [];
  33603. var elExistsMap = {};
  33604. var doneCallback;
  33605. return {
  33606. /**
  33607. * Caution: a el can only be added once, otherwise 'done'
  33608. * might not be called. This method checks this (by el.id),
  33609. * suppresses adding and returns false when existing el found.
  33610. *
  33611. * @param {modele:zrender/Element} el
  33612. * @param {Object} target
  33613. * @param {number} [time=500]
  33614. * @param {number} [delay=0]
  33615. * @param {string} [easing='linear']
  33616. * @return {boolean} Whether adding succeeded.
  33617. *
  33618. * @example
  33619. * add(el, target, time, delay, easing);
  33620. * add(el, target, time, easing);
  33621. * add(el, target, time);
  33622. * add(el, target);
  33623. */
  33624. add: function (el, target, time, delay, easing) {
  33625. if (isString(delay)) {
  33626. easing = delay;
  33627. delay = 0;
  33628. }
  33629. if (elExistsMap[el.id]) {
  33630. return false;
  33631. }
  33632. elExistsMap[el.id] = 1;
  33633. storage.push(
  33634. {el: el, target: target, time: time, delay: delay, easing: easing}
  33635. );
  33636. return true;
  33637. },
  33638. /**
  33639. * Only execute when animation finished. Will not execute when any
  33640. * of 'stop' or 'stopAnimation' called.
  33641. *
  33642. * @param {Function} callback
  33643. */
  33644. done: function (callback) {
  33645. doneCallback = callback;
  33646. return this;
  33647. },
  33648. /**
  33649. * Will stop exist animation firstly.
  33650. */
  33651. start: function () {
  33652. var count = storage.length;
  33653. for (var i = 0, len = storage.length; i < len; i++) {
  33654. var item = storage[i];
  33655. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  33656. }
  33657. return this;
  33658. function done() {
  33659. count--;
  33660. if (!count) {
  33661. storage.length = 0;
  33662. elExistsMap = {};
  33663. doneCallback && doneCallback();
  33664. }
  33665. }
  33666. }
  33667. };
  33668. }
  33669. var bind$1 = bind;
  33670. var Group$2 = Group;
  33671. var Rect$1 = Rect;
  33672. var each$11 = each$1;
  33673. var DRAG_THRESHOLD = 3;
  33674. var PATH_LABEL_NOAMAL = ['label', 'normal'];
  33675. var PATH_LABEL_EMPHASIS = ['label', 'emphasis'];
  33676. var PATH_UPPERLABEL_NORMAL = ['upperLabel', 'normal'];
  33677. var PATH_UPPERLABEL_EMPHASIS = ['upperLabel', 'emphasis'];
  33678. var Z_BASE = 10; // Should bigger than every z.
  33679. var Z_BG = 1;
  33680. var Z_CONTENT = 2;
  33681. var getItemStyleEmphasis = makeStyleMapper([
  33682. ['fill', 'color'],
  33683. // `borderColor` and `borderWidth` has been occupied,
  33684. // so use `stroke` to indicate the stroke of the rect.
  33685. ['stroke', 'strokeColor'],
  33686. ['lineWidth', 'strokeWidth'],
  33687. ['shadowBlur'],
  33688. ['shadowOffsetX'],
  33689. ['shadowOffsetY'],
  33690. ['shadowColor']
  33691. ]);
  33692. var getItemStyleNormal = function (model) {
  33693. // Normal style props should include emphasis style props.
  33694. var itemStyle = getItemStyleEmphasis(model);
  33695. // Clear styles set by emphasis.
  33696. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  33697. return itemStyle;
  33698. };
  33699. extendChartView({
  33700. type: 'treemap',
  33701. /**
  33702. * @override
  33703. */
  33704. init: function (o, api) {
  33705. /**
  33706. * @private
  33707. * @type {module:zrender/container/Group}
  33708. */
  33709. this._containerGroup;
  33710. /**
  33711. * @private
  33712. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  33713. */
  33714. this._storage = createStorage();
  33715. /**
  33716. * @private
  33717. * @type {module:echarts/data/Tree}
  33718. */
  33719. this._oldTree;
  33720. /**
  33721. * @private
  33722. * @type {module:echarts/chart/treemap/Breadcrumb}
  33723. */
  33724. this._breadcrumb;
  33725. /**
  33726. * @private
  33727. * @type {module:echarts/component/helper/RoamController}
  33728. */
  33729. this._controller;
  33730. /**
  33731. * 'ready', 'animating'
  33732. * @private
  33733. */
  33734. this._state = 'ready';
  33735. },
  33736. /**
  33737. * @override
  33738. */
  33739. render: function (seriesModel, ecModel, api, payload) {
  33740. var models = ecModel.findComponents({
  33741. mainType: 'series', subType: 'treemap', query: payload
  33742. });
  33743. if (indexOf(models, seriesModel) < 0) {
  33744. return;
  33745. }
  33746. this.seriesModel = seriesModel;
  33747. this.api = api;
  33748. this.ecModel = ecModel;
  33749. var targetInfo = retrieveTargetInfo(payload, seriesModel);
  33750. var payloadType = payload && payload.type;
  33751. var layoutInfo = seriesModel.layoutInfo;
  33752. var isInit = !this._oldTree;
  33753. var thisStorage = this._storage;
  33754. // Mark new root when action is treemapRootToNode.
  33755. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  33756. ? {
  33757. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  33758. direction: payload.direction
  33759. }
  33760. : null;
  33761. var containerGroup = this._giveContainerGroup(layoutInfo);
  33762. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  33763. (
  33764. !isInit && (
  33765. !payloadType
  33766. || payloadType === 'treemapZoomToNode'
  33767. || payloadType === 'treemapRootToNode'
  33768. )
  33769. )
  33770. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  33771. : renderResult.renderFinally();
  33772. this._resetController(api);
  33773. this._renderBreadcrumb(seriesModel, api, targetInfo);
  33774. },
  33775. /**
  33776. * @private
  33777. */
  33778. _giveContainerGroup: function (layoutInfo) {
  33779. var containerGroup = this._containerGroup;
  33780. if (!containerGroup) {
  33781. // FIXME
  33782. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  33783. containerGroup = this._containerGroup = new Group$2();
  33784. this._initEvents(containerGroup);
  33785. this.group.add(containerGroup);
  33786. }
  33787. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  33788. return containerGroup;
  33789. },
  33790. /**
  33791. * @private
  33792. */
  33793. _doRender: function (containerGroup, seriesModel, reRoot) {
  33794. var thisTree = seriesModel.getData().tree;
  33795. var oldTree = this._oldTree;
  33796. // Clear last shape records.
  33797. var lastsForAnimation = createStorage();
  33798. var thisStorage = createStorage();
  33799. var oldStorage = this._storage;
  33800. var willInvisibleEls = [];
  33801. var doRenderNode = curry(
  33802. renderNode, seriesModel,
  33803. thisStorage, oldStorage, reRoot,
  33804. lastsForAnimation, willInvisibleEls
  33805. );
  33806. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  33807. // the oldTree is actually losted, so we can not find all of the old graphic
  33808. // elements from tree. So we use this stragegy: make element storage, move
  33809. // from old storage to new storage, clear old storage.
  33810. dualTravel(
  33811. thisTree.root ? [thisTree.root] : [],
  33812. (oldTree && oldTree.root) ? [oldTree.root] : [],
  33813. containerGroup,
  33814. thisTree === oldTree || !oldTree,
  33815. 0
  33816. );
  33817. // Process all removing.
  33818. var willDeleteEls = clearStorage(oldStorage);
  33819. this._oldTree = thisTree;
  33820. this._storage = thisStorage;
  33821. return {
  33822. lastsForAnimation: lastsForAnimation,
  33823. willDeleteEls: willDeleteEls,
  33824. renderFinally: renderFinally
  33825. };
  33826. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  33827. // When 'render' is triggered by action,
  33828. // 'this' and 'old' may be the same tree,
  33829. // we use rawIndex in that case.
  33830. if (sameTree) {
  33831. oldViewChildren = thisViewChildren;
  33832. each$11(thisViewChildren, function (child, index) {
  33833. !child.isRemoved() && processNode(index, index);
  33834. });
  33835. }
  33836. // Diff hierarchically (diff only in each subtree, but not whole).
  33837. // because, consistency of view is important.
  33838. else {
  33839. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  33840. .add(processNode)
  33841. .update(processNode)
  33842. .remove(curry(processNode, null))
  33843. .execute();
  33844. }
  33845. function getKey(node) {
  33846. // Identify by name or raw index.
  33847. return node.getId();
  33848. }
  33849. function processNode(newIndex, oldIndex) {
  33850. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  33851. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  33852. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  33853. group && dualTravel(
  33854. thisNode && thisNode.viewChildren || [],
  33855. oldNode && oldNode.viewChildren || [],
  33856. group,
  33857. sameTree,
  33858. depth + 1
  33859. );
  33860. }
  33861. }
  33862. function clearStorage(storage) {
  33863. var willDeleteEls = createStorage();
  33864. storage && each$11(storage, function (store, storageName) {
  33865. var delEls = willDeleteEls[storageName];
  33866. each$11(store, function (el) {
  33867. el && (delEls.push(el), el.__tmWillDelete = 1);
  33868. });
  33869. });
  33870. return willDeleteEls;
  33871. }
  33872. function renderFinally() {
  33873. each$11(willDeleteEls, function (els) {
  33874. each$11(els, function (el) {
  33875. el.parent && el.parent.remove(el);
  33876. });
  33877. });
  33878. each$11(willInvisibleEls, function (el) {
  33879. el.invisible = true;
  33880. // Setting invisible is for optimizing, so no need to set dirty,
  33881. // just mark as invisible.
  33882. el.dirty();
  33883. });
  33884. }
  33885. },
  33886. /**
  33887. * @private
  33888. */
  33889. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  33890. if (!seriesModel.get('animation')) {
  33891. return;
  33892. }
  33893. var duration = seriesModel.get('animationDurationUpdate');
  33894. var easing = seriesModel.get('animationEasing');
  33895. var animationWrap = createWrap();
  33896. // Make delete animations.
  33897. each$11(renderResult.willDeleteEls, function (store, storageName) {
  33898. each$11(store, function (el, rawIndex) {
  33899. if (el.invisible) {
  33900. return;
  33901. }
  33902. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  33903. var target;
  33904. if (reRoot && reRoot.direction === 'drillDown') {
  33905. target = parent === reRoot.rootNodeGroup
  33906. // This is the content element of view root.
  33907. // Only `content` will enter this branch, because
  33908. // `background` and `nodeGroup` will not be deleted.
  33909. ? {
  33910. shape: {
  33911. x: 0,
  33912. y: 0,
  33913. width: parent.__tmNodeWidth,
  33914. height: parent.__tmNodeHeight
  33915. },
  33916. style: {
  33917. opacity: 0
  33918. }
  33919. }
  33920. // Others.
  33921. : {style: {opacity: 0}};
  33922. }
  33923. else {
  33924. var targetX = 0;
  33925. var targetY = 0;
  33926. if (!parent.__tmWillDelete) {
  33927. // Let node animate to right-bottom corner, cooperating with fadeout,
  33928. // which is appropriate for user understanding.
  33929. // Divided by 2 for reRoot rolling up effect.
  33930. targetX = parent.__tmNodeWidth / 2;
  33931. targetY = parent.__tmNodeHeight / 2;
  33932. }
  33933. target = storageName === 'nodeGroup'
  33934. ? {position: [targetX, targetY], style: {opacity: 0}}
  33935. : {
  33936. shape: {x: targetX, y: targetY, width: 0, height: 0},
  33937. style: {opacity: 0}
  33938. };
  33939. }
  33940. target && animationWrap.add(el, target, duration, easing);
  33941. });
  33942. });
  33943. // Make other animations
  33944. each$11(this._storage, function (store, storageName) {
  33945. each$11(store, function (el, rawIndex) {
  33946. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  33947. var target = {};
  33948. if (!last) {
  33949. return;
  33950. }
  33951. if (storageName === 'nodeGroup') {
  33952. if (last.old) {
  33953. target.position = el.position.slice();
  33954. el.attr('position', last.old);
  33955. }
  33956. }
  33957. else {
  33958. if (last.old) {
  33959. target.shape = extend({}, el.shape);
  33960. el.setShape(last.old);
  33961. }
  33962. if (last.fadein) {
  33963. el.setStyle('opacity', 0);
  33964. target.style = {opacity: 1};
  33965. }
  33966. // When animation is stopped for succedent animation starting,
  33967. // el.style.opacity might not be 1
  33968. else if (el.style.opacity !== 1) {
  33969. target.style = {opacity: 1};
  33970. }
  33971. }
  33972. animationWrap.add(el, target, duration, easing);
  33973. });
  33974. }, this);
  33975. this._state = 'animating';
  33976. animationWrap
  33977. .done(bind$1(function () {
  33978. this._state = 'ready';
  33979. renderResult.renderFinally();
  33980. }, this))
  33981. .start();
  33982. },
  33983. /**
  33984. * @private
  33985. */
  33986. _resetController: function (api) {
  33987. var controller = this._controller;
  33988. // Init controller.
  33989. if (!controller) {
  33990. controller = this._controller = new RoamController(api.getZr());
  33991. controller.enable(this.seriesModel.get('roam'));
  33992. controller.on('pan', bind$1(this._onPan, this));
  33993. controller.on('zoom', bind$1(this._onZoom, this));
  33994. }
  33995. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  33996. controller.setPointerChecker(function (e, x, y) {
  33997. return rect.contain(x, y);
  33998. });
  33999. },
  34000. /**
  34001. * @private
  34002. */
  34003. _clearController: function () {
  34004. var controller = this._controller;
  34005. if (controller) {
  34006. controller.dispose();
  34007. controller = null;
  34008. }
  34009. },
  34010. /**
  34011. * @private
  34012. */
  34013. _onPan: function (dx, dy) {
  34014. if (this._state !== 'animating'
  34015. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  34016. ) {
  34017. // These param must not be cached.
  34018. var root = this.seriesModel.getData().tree.root;
  34019. if (!root) {
  34020. return;
  34021. }
  34022. var rootLayout = root.getLayout();
  34023. if (!rootLayout) {
  34024. return;
  34025. }
  34026. this.api.dispatchAction({
  34027. type: 'treemapMove',
  34028. from: this.uid,
  34029. seriesId: this.seriesModel.id,
  34030. rootRect: {
  34031. x: rootLayout.x + dx, y: rootLayout.y + dy,
  34032. width: rootLayout.width, height: rootLayout.height
  34033. }
  34034. });
  34035. }
  34036. },
  34037. /**
  34038. * @private
  34039. */
  34040. _onZoom: function (scale, mouseX, mouseY) {
  34041. if (this._state !== 'animating') {
  34042. // These param must not be cached.
  34043. var root = this.seriesModel.getData().tree.root;
  34044. if (!root) {
  34045. return;
  34046. }
  34047. var rootLayout = root.getLayout();
  34048. if (!rootLayout) {
  34049. return;
  34050. }
  34051. var rect = new BoundingRect(
  34052. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  34053. );
  34054. var layoutInfo = this.seriesModel.layoutInfo;
  34055. // Transform mouse coord from global to containerGroup.
  34056. mouseX -= layoutInfo.x;
  34057. mouseY -= layoutInfo.y;
  34058. // Scale root bounding rect.
  34059. var m = create$1();
  34060. translate(m, m, [-mouseX, -mouseY]);
  34061. scale$1(m, m, [scale, scale]);
  34062. translate(m, m, [mouseX, mouseY]);
  34063. rect.applyTransform(m);
  34064. this.api.dispatchAction({
  34065. type: 'treemapRender',
  34066. from: this.uid,
  34067. seriesId: this.seriesModel.id,
  34068. rootRect: {
  34069. x: rect.x, y: rect.y,
  34070. width: rect.width, height: rect.height
  34071. }
  34072. });
  34073. }
  34074. },
  34075. /**
  34076. * @private
  34077. */
  34078. _initEvents: function (containerGroup) {
  34079. containerGroup.on('click', function (e) {
  34080. if (this._state !== 'ready') {
  34081. return;
  34082. }
  34083. var nodeClick = this.seriesModel.get('nodeClick', true);
  34084. if (!nodeClick) {
  34085. return;
  34086. }
  34087. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  34088. if (!targetInfo) {
  34089. return;
  34090. }
  34091. var node = targetInfo.node;
  34092. if (node.getLayout().isLeafRoot) {
  34093. this._rootToNode(targetInfo);
  34094. }
  34095. else {
  34096. if (nodeClick === 'zoomToNode') {
  34097. this._zoomToNode(targetInfo);
  34098. }
  34099. else if (nodeClick === 'link') {
  34100. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  34101. var link = itemModel.get('link', true);
  34102. var linkTarget = itemModel.get('target', true) || 'blank';
  34103. link && window.open(link, linkTarget);
  34104. }
  34105. }
  34106. }, this);
  34107. },
  34108. /**
  34109. * @private
  34110. */
  34111. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  34112. if (!targetInfo) {
  34113. targetInfo = seriesModel.get('leafDepth', true) != null
  34114. ? {node: seriesModel.getViewRoot()}
  34115. // FIXME
  34116. // better way?
  34117. // Find breadcrumb tail on center of containerGroup.
  34118. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  34119. if (!targetInfo) {
  34120. targetInfo = {node: seriesModel.getData().tree.root};
  34121. }
  34122. }
  34123. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  34124. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  34125. function onSelect(node) {
  34126. if (this._state !== 'animating') {
  34127. aboveViewRoot(seriesModel.getViewRoot(), node)
  34128. ? this._rootToNode({node: node})
  34129. : this._zoomToNode({node: node});
  34130. }
  34131. }
  34132. },
  34133. /**
  34134. * @override
  34135. */
  34136. remove: function () {
  34137. this._clearController();
  34138. this._containerGroup && this._containerGroup.removeAll();
  34139. this._storage = createStorage();
  34140. this._state = 'ready';
  34141. this._breadcrumb && this._breadcrumb.remove();
  34142. },
  34143. dispose: function () {
  34144. this._clearController();
  34145. },
  34146. /**
  34147. * @private
  34148. */
  34149. _zoomToNode: function (targetInfo) {
  34150. this.api.dispatchAction({
  34151. type: 'treemapZoomToNode',
  34152. from: this.uid,
  34153. seriesId: this.seriesModel.id,
  34154. targetNode: targetInfo.node
  34155. });
  34156. },
  34157. /**
  34158. * @private
  34159. */
  34160. _rootToNode: function (targetInfo) {
  34161. this.api.dispatchAction({
  34162. type: 'treemapRootToNode',
  34163. from: this.uid,
  34164. seriesId: this.seriesModel.id,
  34165. targetNode: targetInfo.node
  34166. });
  34167. },
  34168. /**
  34169. * @public
  34170. * @param {number} x Global coord x.
  34171. * @param {number} y Global coord y.
  34172. * @return {Object} info If not found, return undefined;
  34173. * @return {number} info.node Target node.
  34174. * @return {number} info.offsetX x refer to target node.
  34175. * @return {number} info.offsetY y refer to target node.
  34176. */
  34177. findTarget: function (x, y) {
  34178. var targetInfo;
  34179. var viewRoot = this.seriesModel.getViewRoot();
  34180. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  34181. var bgEl = this._storage.background[node.getRawIndex()];
  34182. // If invisible, there might be no element.
  34183. if (bgEl) {
  34184. var point = bgEl.transformCoordToLocal(x, y);
  34185. var shape = bgEl.shape;
  34186. // For performance consideration, dont use 'getBoundingRect'.
  34187. if (shape.x <= point[0]
  34188. && point[0] <= shape.x + shape.width
  34189. && shape.y <= point[1]
  34190. && point[1] <= shape.y + shape.height
  34191. ) {
  34192. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  34193. }
  34194. else {
  34195. return false; // Suppress visit subtree.
  34196. }
  34197. }
  34198. }, this);
  34199. return targetInfo;
  34200. }
  34201. });
  34202. /**
  34203. * @inner
  34204. */
  34205. function createStorage() {
  34206. return {nodeGroup: [], background: [], content: []};
  34207. }
  34208. /**
  34209. * @inner
  34210. * @return Return undefined means do not travel further.
  34211. */
  34212. function renderNode(
  34213. seriesModel, thisStorage, oldStorage, reRoot,
  34214. lastsForAnimation, willInvisibleEls,
  34215. thisNode, oldNode, parentGroup, depth
  34216. ) {
  34217. // Whether under viewRoot.
  34218. if (!thisNode) {
  34219. // Deleting nodes will be performed finally. This method just find
  34220. // element from old storage, or create new element, set them to new
  34221. // storage, and set styles.
  34222. return;
  34223. }
  34224. // -------------------------------------------------------------------
  34225. // Start of closure variables available in "Procedures in renderNode".
  34226. var thisLayout = thisNode.getLayout();
  34227. if (!thisLayout || !thisLayout.isInView) {
  34228. return;
  34229. }
  34230. var thisWidth = thisLayout.width;
  34231. var thisHeight = thisLayout.height;
  34232. var borderWidth = thisLayout.borderWidth;
  34233. var thisInvisible = thisLayout.invisible;
  34234. var thisRawIndex = thisNode.getRawIndex();
  34235. var oldRawIndex = oldNode && oldNode.getRawIndex();
  34236. var thisViewChildren = thisNode.viewChildren;
  34237. var upperHeight = thisLayout.upperHeight;
  34238. var isParent = thisViewChildren && thisViewChildren.length;
  34239. var itemStyleNormalModel = thisNode.getModel('itemStyle.normal');
  34240. var itemStyleEmphasisModel = thisNode.getModel('itemStyle.emphasis');
  34241. // End of closure ariables available in "Procedures in renderNode".
  34242. // -----------------------------------------------------------------
  34243. // Node group
  34244. var group = giveGraphic('nodeGroup', Group$2);
  34245. if (!group) {
  34246. return;
  34247. }
  34248. parentGroup.add(group);
  34249. // x,y are not set when el is above view root.
  34250. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  34251. group.__tmNodeWidth = thisWidth;
  34252. group.__tmNodeHeight = thisHeight;
  34253. if (thisLayout.isAboveViewRoot) {
  34254. return group;
  34255. }
  34256. // Background
  34257. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  34258. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  34259. // No children, render content.
  34260. if (!isParent) {
  34261. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  34262. content && renderContent(group, content);
  34263. }
  34264. return group;
  34265. // ----------------------------
  34266. // | Procedures in renderNode |
  34267. // ----------------------------
  34268. function renderBackground(group, bg, useUpperLabel) {
  34269. // For tooltip.
  34270. bg.dataIndex = thisNode.dataIndex;
  34271. bg.seriesIndex = seriesModel.seriesIndex;
  34272. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  34273. var visualBorderColor = thisNode.getVisual('borderColor', true);
  34274. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  34275. updateStyle(bg, function () {
  34276. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  34277. normalStyle.fill = visualBorderColor;
  34278. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  34279. emphasisStyle.fill = emphasisBorderColor;
  34280. if (useUpperLabel) {
  34281. var upperLabelWidth = thisWidth - 2 * borderWidth;
  34282. prepareText(
  34283. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  34284. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  34285. );
  34286. }
  34287. // For old bg.
  34288. else {
  34289. normalStyle.text = emphasisStyle.text = null;
  34290. }
  34291. bg.setStyle(normalStyle);
  34292. setHoverStyle(bg, emphasisStyle);
  34293. });
  34294. group.add(bg);
  34295. }
  34296. function renderContent(group, content) {
  34297. // For tooltip.
  34298. content.dataIndex = thisNode.dataIndex;
  34299. content.seriesIndex = seriesModel.seriesIndex;
  34300. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  34301. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  34302. content.culling = true;
  34303. content.setShape({
  34304. x: borderWidth,
  34305. y: borderWidth,
  34306. width: contentWidth,
  34307. height: contentHeight
  34308. });
  34309. var visualColor = thisNode.getVisual('color', true);
  34310. updateStyle(content, function () {
  34311. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  34312. normalStyle.fill = visualColor;
  34313. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  34314. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  34315. content.setStyle(normalStyle);
  34316. setHoverStyle(content, emphasisStyle);
  34317. });
  34318. group.add(content);
  34319. }
  34320. function updateStyle(element, cb) {
  34321. if (!thisInvisible) {
  34322. // If invisible, do not set visual, otherwise the element will
  34323. // change immediately before animation. We think it is OK to
  34324. // remain its origin color when moving out of the view window.
  34325. cb();
  34326. if (!element.__tmWillVisible) {
  34327. element.invisible = false;
  34328. }
  34329. }
  34330. else {
  34331. // Delay invisible setting utill animation finished,
  34332. // avoid element vanish suddenly before animation.
  34333. !element.invisible && willInvisibleEls.push(element);
  34334. }
  34335. }
  34336. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  34337. var nodeModel = thisNode.getModel();
  34338. var text = retrieve(
  34339. seriesModel.getFormattedLabel(
  34340. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  34341. ),
  34342. nodeModel.get('name')
  34343. );
  34344. if (!upperLabelRect && thisLayout.isLeafRoot) {
  34345. var iconChar = seriesModel.get('drillDownIcon', true);
  34346. text = iconChar ? iconChar + ' ' + text : text;
  34347. }
  34348. var normalLabelModel = nodeModel.getModel(
  34349. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  34350. );
  34351. var emphasisLabelModel = nodeModel.getModel(
  34352. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  34353. );
  34354. var isShow = normalLabelModel.getShallow('show');
  34355. setLabelStyle(
  34356. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  34357. {
  34358. defaultText: isShow ? text : null,
  34359. autoColor: visualColor,
  34360. isRectText: true
  34361. }
  34362. );
  34363. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  34364. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  34365. ? {
  34366. outerWidth: width,
  34367. outerHeight: height,
  34368. minChar: 2
  34369. }
  34370. : null;
  34371. }
  34372. function giveGraphic(storageName, Ctor, depth, z) {
  34373. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  34374. var lasts = lastsForAnimation[storageName];
  34375. if (element) {
  34376. // Remove from oldStorage
  34377. oldStorage[storageName][oldRawIndex] = null;
  34378. prepareAnimationWhenHasOld(lasts, element, storageName);
  34379. }
  34380. // If invisible and no old element, do not create new element (for optimizing).
  34381. else if (!thisInvisible) {
  34382. element = new Ctor({z: calculateZ(depth, z)});
  34383. element.__tmDepth = depth;
  34384. element.__tmStorageName = storageName;
  34385. prepareAnimationWhenNoOld(lasts, element, storageName);
  34386. }
  34387. // Set to thisStorage
  34388. return (thisStorage[storageName][thisRawIndex] = element);
  34389. }
  34390. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  34391. var lastCfg = lasts[thisRawIndex] = {};
  34392. lastCfg.old = storageName === 'nodeGroup'
  34393. ? element.position.slice()
  34394. : extend({}, element.shape);
  34395. }
  34396. // If a element is new, we need to find the animation start point carefully,
  34397. // otherwise it will looks strange when 'zoomToNode'.
  34398. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  34399. var lastCfg = lasts[thisRawIndex] = {};
  34400. var parentNode = thisNode.parentNode;
  34401. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  34402. var parentOldX = 0;
  34403. var parentOldY = 0;
  34404. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  34405. // For convenience, get old bounding rect from background.
  34406. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  34407. if (!reRoot && parentOldBg && parentOldBg.old) {
  34408. parentOldX = parentOldBg.old.width;
  34409. parentOldY = parentOldBg.old.height;
  34410. }
  34411. // When no parent old shape found, its parent is new too,
  34412. // so we can just use {x:0, y:0}.
  34413. lastCfg.old = storageName === 'nodeGroup'
  34414. ? [0, parentOldY]
  34415. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  34416. }
  34417. // Fade in, user can be aware that these nodes are new.
  34418. lastCfg.fadein = storageName !== 'nodeGroup';
  34419. }
  34420. }
  34421. // We can not set all backgroud with the same z, Because the behaviour of
  34422. // drill down and roll up differ background creation sequence from tree
  34423. // hierarchy sequence, which cause that lowser background element overlap
  34424. // upper ones. So we calculate z based on depth.
  34425. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  34426. // treemap with large z overlaps other components.
  34427. function calculateZ(depth, zInLevel) {
  34428. var zb = depth * Z_BASE + zInLevel;
  34429. return (zb - 1) / zb;
  34430. }
  34431. /**
  34432. * @file Treemap action
  34433. */
  34434. var noop$1 = function () {};
  34435. var actionTypes = [
  34436. 'treemapZoomToNode',
  34437. 'treemapRender',
  34438. 'treemapMove'
  34439. ];
  34440. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  34441. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  34442. }
  34443. registerAction(
  34444. {type: 'treemapRootToNode', update: 'updateView'},
  34445. function (payload, ecModel) {
  34446. ecModel.eachComponent(
  34447. {mainType: 'series', subType: 'treemap', query: payload},
  34448. handleRootToNode
  34449. );
  34450. function handleRootToNode(model, index) {
  34451. var targetInfo = retrieveTargetInfo(payload, model);
  34452. if (targetInfo) {
  34453. var originViewRoot = model.getViewRoot();
  34454. if (originViewRoot) {
  34455. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  34456. ? 'rollUp' : 'drillDown';
  34457. }
  34458. model.resetViewRoot(targetInfo.node);
  34459. }
  34460. }
  34461. }
  34462. );
  34463. var each$12 = each$1;
  34464. var isObject$5 = isObject;
  34465. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  34466. /**
  34467. * @param {Object} option
  34468. * @param {string} [option.type] See visualHandlers.
  34469. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  34470. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  34471. * required when mappingMethod is 'linear'
  34472. * @param {Array.<Object>=} [option.pieceList] [
  34473. * {value: someValue},
  34474. * {interval: [min1, max1], visual: {...}},
  34475. * {interval: [min2, max2]}
  34476. * ],
  34477. * required when mappingMethod is 'piecewise'.
  34478. * Visual for only each piece can be specified.
  34479. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  34480. * required when mappingMethod is 'category'.
  34481. * If no option.categories, categories is set
  34482. * as [0, 1, 2, ...].
  34483. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  34484. * @param {(Array|Object|*)} [option.visual] Visual data.
  34485. * when mappingMethod is 'category',
  34486. * visual data can be array or object
  34487. * (like: {cate1: '#222', none: '#fff'})
  34488. * or primary types (which represents
  34489. * defualt category visual), otherwise visual
  34490. * can be array or primary (which will be
  34491. * normalized to array).
  34492. *
  34493. */
  34494. var VisualMapping = function (option) {
  34495. var mappingMethod = option.mappingMethod;
  34496. var visualType = option.type;
  34497. /**
  34498. * @readOnly
  34499. * @type {Object}
  34500. */
  34501. var thisOption = this.option = clone(option);
  34502. /**
  34503. * @readOnly
  34504. * @type {string}
  34505. */
  34506. this.type = visualType;
  34507. /**
  34508. * @readOnly
  34509. * @type {string}
  34510. */
  34511. this.mappingMethod = mappingMethod;
  34512. /**
  34513. * @private
  34514. * @type {Function}
  34515. */
  34516. this._normalizeData = normalizers[mappingMethod];
  34517. var visualHandler = visualHandlers[visualType];
  34518. /**
  34519. * @public
  34520. * @type {Function}
  34521. */
  34522. this.applyVisual = visualHandler.applyVisual;
  34523. /**
  34524. * @public
  34525. * @type {Function}
  34526. */
  34527. this.getColorMapper = visualHandler.getColorMapper;
  34528. /**
  34529. * @private
  34530. * @type {Function}
  34531. */
  34532. this._doMap = visualHandler._doMap[mappingMethod];
  34533. if (mappingMethod === 'piecewise') {
  34534. normalizeVisualRange(thisOption);
  34535. preprocessForPiecewise(thisOption);
  34536. }
  34537. else if (mappingMethod === 'category') {
  34538. thisOption.categories
  34539. ? preprocessForSpecifiedCategory(thisOption)
  34540. // categories is ordinal when thisOption.categories not specified,
  34541. // which need no more preprocess except normalize visual.
  34542. : normalizeVisualRange(thisOption, true);
  34543. }
  34544. else { // mappingMethod === 'linear' or 'fixed'
  34545. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  34546. normalizeVisualRange(thisOption);
  34547. }
  34548. };
  34549. VisualMapping.prototype = {
  34550. constructor: VisualMapping,
  34551. mapValueToVisual: function (value) {
  34552. var normalized = this._normalizeData(value);
  34553. return this._doMap(normalized, value);
  34554. },
  34555. getNormalizer: function () {
  34556. return bind(this._normalizeData, this);
  34557. }
  34558. };
  34559. var visualHandlers = VisualMapping.visualHandlers = {
  34560. color: {
  34561. applyVisual: makeApplyVisual('color'),
  34562. /**
  34563. * Create a mapper function
  34564. * @return {Function}
  34565. */
  34566. getColorMapper: function () {
  34567. var thisOption = this.option;
  34568. return bind(
  34569. thisOption.mappingMethod === 'category'
  34570. ? function (value, isNormalized) {
  34571. !isNormalized && (value = this._normalizeData(value));
  34572. return doMapCategory.call(this, value);
  34573. }
  34574. : function (value, isNormalized, out) {
  34575. // If output rgb array
  34576. // which will be much faster and useful in pixel manipulation
  34577. var returnRGBArray = !!out;
  34578. !isNormalized && (value = this._normalizeData(value));
  34579. out = fastLerp(value, thisOption.parsedVisual, out);
  34580. return returnRGBArray ? out : stringify(out, 'rgba');
  34581. },
  34582. this
  34583. );
  34584. },
  34585. _doMap: {
  34586. linear: function (normalized) {
  34587. return stringify(
  34588. fastLerp(normalized, this.option.parsedVisual),
  34589. 'rgba'
  34590. );
  34591. },
  34592. category: doMapCategory,
  34593. piecewise: function (normalized, value) {
  34594. var result = getSpecifiedVisual.call(this, value);
  34595. if (result == null) {
  34596. result = stringify(
  34597. fastLerp(normalized, this.option.parsedVisual),
  34598. 'rgba'
  34599. );
  34600. }
  34601. return result;
  34602. },
  34603. fixed: doMapFixed
  34604. }
  34605. },
  34606. colorHue: makePartialColorVisualHandler(function (color, value) {
  34607. return modifyHSL(color, value);
  34608. }),
  34609. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  34610. return modifyHSL(color, null, value);
  34611. }),
  34612. colorLightness: makePartialColorVisualHandler(function (color, value) {
  34613. return modifyHSL(color, null, null, value);
  34614. }),
  34615. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  34616. return modifyAlpha(color, value);
  34617. }),
  34618. opacity: {
  34619. applyVisual: makeApplyVisual('opacity'),
  34620. _doMap: makeDoMap([0, 1])
  34621. },
  34622. symbol: {
  34623. applyVisual: function (value, getter, setter) {
  34624. var symbolCfg = this.mapValueToVisual(value);
  34625. if (isString(symbolCfg)) {
  34626. setter('symbol', symbolCfg);
  34627. }
  34628. else if (isObject$5(symbolCfg)) {
  34629. for (var name in symbolCfg) {
  34630. if (symbolCfg.hasOwnProperty(name)) {
  34631. setter(name, symbolCfg[name]);
  34632. }
  34633. }
  34634. }
  34635. },
  34636. _doMap: {
  34637. linear: doMapToArray,
  34638. category: doMapCategory,
  34639. piecewise: function (normalized, value) {
  34640. var result = getSpecifiedVisual.call(this, value);
  34641. if (result == null) {
  34642. result = doMapToArray.call(this, normalized);
  34643. }
  34644. return result;
  34645. },
  34646. fixed: doMapFixed
  34647. }
  34648. },
  34649. symbolSize: {
  34650. applyVisual: makeApplyVisual('symbolSize'),
  34651. _doMap: makeDoMap([0, 1])
  34652. }
  34653. };
  34654. function preprocessForPiecewise(thisOption) {
  34655. var pieceList = thisOption.pieceList;
  34656. thisOption.hasSpecialVisual = false;
  34657. each$1(pieceList, function (piece, index) {
  34658. piece.originIndex = index;
  34659. // piece.visual is "result visual value" but not
  34660. // a visual range, so it does not need to be normalized.
  34661. if (piece.visual != null) {
  34662. thisOption.hasSpecialVisual = true;
  34663. }
  34664. });
  34665. }
  34666. function preprocessForSpecifiedCategory(thisOption) {
  34667. // Hash categories.
  34668. var categories = thisOption.categories;
  34669. var visual = thisOption.visual;
  34670. var categoryMap = thisOption.categoryMap = {};
  34671. each$12(categories, function (cate, index) {
  34672. categoryMap[cate] = index;
  34673. });
  34674. // Process visual map input.
  34675. if (!isArray(visual)) {
  34676. var visualArr = [];
  34677. if (isObject(visual)) {
  34678. each$12(visual, function (v, cate) {
  34679. var index = categoryMap[cate];
  34680. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  34681. });
  34682. }
  34683. else { // Is primary type, represents default visual.
  34684. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  34685. }
  34686. visual = setVisualToOption(thisOption, visualArr);
  34687. }
  34688. // Remove categories that has no visual,
  34689. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  34690. for (var i = categories.length - 1; i >= 0; i--) {
  34691. if (visual[i] == null) {
  34692. delete categoryMap[categories[i]];
  34693. categories.pop();
  34694. }
  34695. }
  34696. }
  34697. function normalizeVisualRange(thisOption, isCategory) {
  34698. var visual = thisOption.visual;
  34699. var visualArr = [];
  34700. if (isObject(visual)) {
  34701. each$12(visual, function (v) {
  34702. visualArr.push(v);
  34703. });
  34704. }
  34705. else if (visual != null) {
  34706. visualArr.push(visual);
  34707. }
  34708. var doNotNeedPair = {color: 1, symbol: 1};
  34709. if (!isCategory
  34710. && visualArr.length === 1
  34711. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  34712. ) {
  34713. // Do not care visualArr.length === 0, which is illegal.
  34714. visualArr[1] = visualArr[0];
  34715. }
  34716. setVisualToOption(thisOption, visualArr);
  34717. }
  34718. function makePartialColorVisualHandler(applyValue) {
  34719. return {
  34720. applyVisual: function (value, getter, setter) {
  34721. value = this.mapValueToVisual(value);
  34722. // Must not be array value
  34723. setter('color', applyValue(getter('color'), value));
  34724. },
  34725. _doMap: makeDoMap([0, 1])
  34726. };
  34727. }
  34728. function doMapToArray(normalized) {
  34729. var visual = this.option.visual;
  34730. return visual[
  34731. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  34732. ] || {};
  34733. }
  34734. function makeApplyVisual(visualType) {
  34735. return function (value, getter, setter) {
  34736. setter(visualType, this.mapValueToVisual(value));
  34737. };
  34738. }
  34739. function doMapCategory(normalized) {
  34740. var visual = this.option.visual;
  34741. return visual[
  34742. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  34743. ? normalized % visual.length
  34744. : normalized
  34745. ];
  34746. }
  34747. function doMapFixed() {
  34748. return this.option.visual[0];
  34749. }
  34750. function makeDoMap(sourceExtent) {
  34751. return {
  34752. linear: function (normalized) {
  34753. return linearMap(normalized, sourceExtent, this.option.visual, true);
  34754. },
  34755. category: doMapCategory,
  34756. piecewise: function (normalized, value) {
  34757. var result = getSpecifiedVisual.call(this, value);
  34758. if (result == null) {
  34759. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  34760. }
  34761. return result;
  34762. },
  34763. fixed: doMapFixed
  34764. };
  34765. }
  34766. function getSpecifiedVisual(value) {
  34767. var thisOption = this.option;
  34768. var pieceList = thisOption.pieceList;
  34769. if (thisOption.hasSpecialVisual) {
  34770. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  34771. var piece = pieceList[pieceIndex];
  34772. if (piece && piece.visual) {
  34773. return piece.visual[this.type];
  34774. }
  34775. }
  34776. }
  34777. function setVisualToOption(thisOption, visualArr) {
  34778. thisOption.visual = visualArr;
  34779. if (thisOption.type === 'color') {
  34780. thisOption.parsedVisual = map(visualArr, function (item) {
  34781. return parse(item);
  34782. });
  34783. }
  34784. return visualArr;
  34785. }
  34786. /**
  34787. * Normalizers by mapping methods.
  34788. */
  34789. var normalizers = {
  34790. linear: function (value) {
  34791. return linearMap(value, this.option.dataExtent, [0, 1], true);
  34792. },
  34793. piecewise: function (value) {
  34794. var pieceList = this.option.pieceList;
  34795. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  34796. if (pieceIndex != null) {
  34797. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  34798. }
  34799. },
  34800. category: function (value) {
  34801. var index = this.option.categories
  34802. ? this.option.categoryMap[value]
  34803. : value; // ordinal
  34804. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  34805. },
  34806. fixed: noop
  34807. };
  34808. /**
  34809. * List available visual types.
  34810. *
  34811. * @public
  34812. * @return {Array.<string>}
  34813. */
  34814. VisualMapping.listVisualTypes = function () {
  34815. var visualTypes = [];
  34816. each$1(visualHandlers, function (handler, key) {
  34817. visualTypes.push(key);
  34818. });
  34819. return visualTypes;
  34820. };
  34821. /**
  34822. * @public
  34823. */
  34824. VisualMapping.addVisualHandler = function (name, handler) {
  34825. visualHandlers[name] = handler;
  34826. };
  34827. /**
  34828. * @public
  34829. */
  34830. VisualMapping.isValidType = function (visualType) {
  34831. return visualHandlers.hasOwnProperty(visualType);
  34832. };
  34833. /**
  34834. * Convinent method.
  34835. * Visual can be Object or Array or primary type.
  34836. *
  34837. * @public
  34838. */
  34839. VisualMapping.eachVisual = function (visual, callback, context) {
  34840. if (isObject(visual)) {
  34841. each$1(visual, callback, context);
  34842. }
  34843. else {
  34844. callback.call(context, visual);
  34845. }
  34846. };
  34847. VisualMapping.mapVisual = function (visual, callback, context) {
  34848. var isPrimary;
  34849. var newVisual = isArray(visual)
  34850. ? []
  34851. : isObject(visual)
  34852. ? {}
  34853. : (isPrimary = true, null);
  34854. VisualMapping.eachVisual(visual, function (v, key) {
  34855. var newVal = callback.call(context, v, key);
  34856. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  34857. });
  34858. return newVisual;
  34859. };
  34860. /**
  34861. * @public
  34862. * @param {Object} obj
  34863. * @return {Object} new object containers visual values.
  34864. * If no visuals, return null.
  34865. */
  34866. VisualMapping.retrieveVisuals = function (obj) {
  34867. var ret = {};
  34868. var hasVisual;
  34869. obj && each$12(visualHandlers, function (h, visualType) {
  34870. if (obj.hasOwnProperty(visualType)) {
  34871. ret[visualType] = obj[visualType];
  34872. hasVisual = true;
  34873. }
  34874. });
  34875. return hasVisual ? ret : null;
  34876. };
  34877. /**
  34878. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  34879. *
  34880. * @public
  34881. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  34882. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  34883. * @return {Array.<string>} Sorted visual types.
  34884. */
  34885. VisualMapping.prepareVisualTypes = function (visualTypes) {
  34886. if (isObject$5(visualTypes)) {
  34887. var types = [];
  34888. each$12(visualTypes, function (item, type) {
  34889. types.push(type);
  34890. });
  34891. visualTypes = types;
  34892. }
  34893. else if (isArray(visualTypes)) {
  34894. visualTypes = visualTypes.slice();
  34895. }
  34896. else {
  34897. return [];
  34898. }
  34899. visualTypes.sort(function (type1, type2) {
  34900. // color should be front of colorSaturation, colorAlpha, ...
  34901. // symbol and symbolSize do not matter.
  34902. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  34903. ? 1 : -1;
  34904. });
  34905. return visualTypes;
  34906. };
  34907. /**
  34908. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  34909. * Other visuals are only depends on themself.
  34910. *
  34911. * @public
  34912. * @param {string} visualType1
  34913. * @param {string} visualType2
  34914. * @return {boolean}
  34915. */
  34916. VisualMapping.dependsOn = function (visualType1, visualType2) {
  34917. return visualType2 === 'color'
  34918. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  34919. : visualType1 === visualType2;
  34920. };
  34921. /**
  34922. * @param {number} value
  34923. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  34924. * Always from small to big.
  34925. * @param {boolean} [findClosestWhenOutside=false]
  34926. * @return {number} index
  34927. */
  34928. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  34929. var possibleI;
  34930. var abs = Infinity;
  34931. // value has the higher priority.
  34932. for (var i = 0, len = pieceList.length; i < len; i++) {
  34933. var pieceValue = pieceList[i].value;
  34934. if (pieceValue != null) {
  34935. if (pieceValue === value
  34936. // FIXME
  34937. // It is supposed to compare value according to value type of dimension,
  34938. // but currently value type can exactly be string or number.
  34939. // Compromise for numeric-like string (like '12'), especially
  34940. // in the case that visualMap.categories is ['22', '33'].
  34941. || (typeof pieceValue === 'string' && pieceValue === value + '')
  34942. ) {
  34943. return i;
  34944. }
  34945. findClosestWhenOutside && updatePossible(pieceValue, i);
  34946. }
  34947. }
  34948. for (var i = 0, len = pieceList.length; i < len; i++) {
  34949. var piece = pieceList[i];
  34950. var interval = piece.interval;
  34951. var close = piece.close;
  34952. if (interval) {
  34953. if (interval[0] === -Infinity) {
  34954. if (littleThan(close[1], value, interval[1])) {
  34955. return i;
  34956. }
  34957. }
  34958. else if (interval[1] === Infinity) {
  34959. if (littleThan(close[0], interval[0], value)) {
  34960. return i;
  34961. }
  34962. }
  34963. else if (
  34964. littleThan(close[0], interval[0], value)
  34965. && littleThan(close[1], value, interval[1])
  34966. ) {
  34967. return i;
  34968. }
  34969. findClosestWhenOutside && updatePossible(interval[0], i);
  34970. findClosestWhenOutside && updatePossible(interval[1], i);
  34971. }
  34972. }
  34973. if (findClosestWhenOutside) {
  34974. return value === Infinity
  34975. ? pieceList.length - 1
  34976. : value === -Infinity
  34977. ? 0
  34978. : possibleI;
  34979. }
  34980. function updatePossible(val, index) {
  34981. var newAbs = Math.abs(val - value);
  34982. if (newAbs < abs) {
  34983. abs = newAbs;
  34984. possibleI = index;
  34985. }
  34986. }
  34987. };
  34988. function littleThan(close, a, b) {
  34989. return close ? a <= b : a < b;
  34990. }
  34991. var isArray$2 = isArray;
  34992. var ITEM_STYLE_NORMAL = 'itemStyle.normal';
  34993. var treemapVisual = function (ecModel, api, payload) {
  34994. var condition = {mainType: 'series', subType: 'treemap', query: payload};
  34995. ecModel.eachComponent(condition, function (seriesModel) {
  34996. var tree = seriesModel.getData().tree;
  34997. var root = tree.root;
  34998. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  34999. if (root.isRemoved()) {
  35000. return;
  35001. }
  35002. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  35003. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  35004. });
  35005. travelTree(
  35006. root, // Visual should calculate from tree root but not view root.
  35007. {},
  35008. levelItemStyles,
  35009. seriesItemStyleModel,
  35010. seriesModel.getViewRoot().getAncestors(),
  35011. seriesModel
  35012. );
  35013. });
  35014. };
  35015. function travelTree(
  35016. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  35017. viewRootAncestors, seriesModel
  35018. ) {
  35019. var nodeModel = node.getModel();
  35020. var nodeLayout = node.getLayout();
  35021. // Optimize
  35022. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  35023. return;
  35024. }
  35025. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  35026. var levelItemStyle = levelItemStyles[node.depth];
  35027. var visuals = buildVisuals(
  35028. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  35029. );
  35030. // calculate border color
  35031. var borderColor = nodeItemStyleModel.get('borderColor');
  35032. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  35033. var thisNodeColor;
  35034. if (borderColorSaturation != null) {
  35035. // For performance, do not always execute 'calculateColor'.
  35036. thisNodeColor = calculateColor(visuals, node);
  35037. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  35038. }
  35039. node.setVisual('borderColor', borderColor);
  35040. var viewChildren = node.viewChildren;
  35041. if (!viewChildren || !viewChildren.length) {
  35042. thisNodeColor = calculateColor(visuals, node);
  35043. // Apply visual to this node.
  35044. node.setVisual('color', thisNodeColor);
  35045. }
  35046. else {
  35047. var mapping = buildVisualMapping(
  35048. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  35049. );
  35050. // Designate visual to children.
  35051. each$1(viewChildren, function (child, index) {
  35052. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  35053. if (child.depth >= viewRootAncestors.length
  35054. || child === viewRootAncestors[child.depth]
  35055. ) {
  35056. var childVisual = mapVisual$1(
  35057. nodeModel, visuals, child, index, mapping, seriesModel
  35058. );
  35059. travelTree(
  35060. child, childVisual, levelItemStyles, seriesItemStyleModel,
  35061. viewRootAncestors, seriesModel
  35062. );
  35063. }
  35064. });
  35065. }
  35066. }
  35067. function buildVisuals(
  35068. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  35069. ) {
  35070. var visuals = extend({}, designatedVisual);
  35071. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  35072. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  35073. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  35074. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  35075. val == null && (val = designatedVisual[visualName]);
  35076. val == null && (val = seriesItemStyleModel.get(visualName));
  35077. val != null && (visuals[visualName] = val);
  35078. });
  35079. return visuals;
  35080. }
  35081. function calculateColor(visuals) {
  35082. var color = getValueVisualDefine(visuals, 'color');
  35083. if (color) {
  35084. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  35085. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  35086. if (colorSaturation) {
  35087. color = modifyHSL(color, null, null, colorSaturation);
  35088. }
  35089. if (colorAlpha) {
  35090. color = modifyAlpha(color, colorAlpha);
  35091. }
  35092. return color;
  35093. }
  35094. }
  35095. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  35096. return thisNodeColor != null
  35097. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  35098. : null;
  35099. }
  35100. function getValueVisualDefine(visuals, name) {
  35101. var value = visuals[name];
  35102. if (value != null && value !== 'none') {
  35103. return value;
  35104. }
  35105. }
  35106. function buildVisualMapping(
  35107. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  35108. ) {
  35109. if (!viewChildren || !viewChildren.length) {
  35110. return;
  35111. }
  35112. var rangeVisual = getRangeVisual(nodeModel, 'color')
  35113. || (
  35114. visuals.color != null
  35115. && visuals.color !== 'none'
  35116. && (
  35117. getRangeVisual(nodeModel, 'colorAlpha')
  35118. || getRangeVisual(nodeModel, 'colorSaturation')
  35119. )
  35120. );
  35121. if (!rangeVisual) {
  35122. return;
  35123. }
  35124. var visualMin = nodeModel.get('visualMin');
  35125. var visualMax = nodeModel.get('visualMax');
  35126. var dataExtent = nodeLayout.dataExtent.slice();
  35127. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  35128. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  35129. var colorMappingBy = nodeModel.get('colorMappingBy');
  35130. var opt = {
  35131. type: rangeVisual.name,
  35132. dataExtent: dataExtent,
  35133. visual: rangeVisual.range
  35134. };
  35135. if (opt.type === 'color'
  35136. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  35137. ) {
  35138. opt.mappingMethod = 'category';
  35139. opt.loop = true;
  35140. // categories is ordinal, so do not set opt.categories.
  35141. }
  35142. else {
  35143. opt.mappingMethod = 'linear';
  35144. }
  35145. var mapping = new VisualMapping(opt);
  35146. mapping.__drColorMappingBy = colorMappingBy;
  35147. return mapping;
  35148. }
  35149. // Notice: If we dont have the attribute 'colorRange', but only use
  35150. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  35151. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  35152. // this problem will be encountered:
  35153. // If a level-1 node dont have children, and its siblings has children,
  35154. // and colorRange is set on level-1, then the node can not be colored.
  35155. // So we separate 'colorRange' and 'color' to different attributes.
  35156. function getRangeVisual(nodeModel, name) {
  35157. // 'colorRange', 'colorARange', 'colorSRange'.
  35158. // If not exsits on this node, fetch from levels and series.
  35159. var range = nodeModel.get(name);
  35160. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  35161. }
  35162. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  35163. var childVisuals = extend({}, visuals);
  35164. if (mapping) {
  35165. var mappingType = mapping.type;
  35166. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  35167. var value =
  35168. colorMappingBy === 'index'
  35169. ? index
  35170. : colorMappingBy === 'id'
  35171. ? seriesModel.mapIdToIndex(child.getId())
  35172. : child.getValue(nodeModel.get('visualDimension'));
  35173. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  35174. }
  35175. return childVisuals;
  35176. }
  35177. var mathMax$4 = Math.max;
  35178. var mathMin$4 = Math.min;
  35179. var retrieveValue$1 = retrieve;
  35180. var each$13 = each$1;
  35181. var PATH_BORDER_WIDTH = ['itemStyle', 'normal', 'borderWidth'];
  35182. var PATH_GAP_WIDTH = ['itemStyle', 'normal', 'gapWidth'];
  35183. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'normal', 'show'];
  35184. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'normal', 'height'];
  35185. /**
  35186. * @public
  35187. */
  35188. var treemapLayout = function (ecModel, api, payload) {
  35189. // Layout result in each node:
  35190. // {x, y, width, height, area, borderWidth}
  35191. var condition = {mainType: 'series', subType: 'treemap', query: payload};
  35192. ecModel.eachComponent(condition, function (seriesModel) {
  35193. var ecWidth = api.getWidth();
  35194. var ecHeight = api.getHeight();
  35195. var seriesOption = seriesModel.option;
  35196. var layoutInfo = getLayoutRect(
  35197. seriesModel.getBoxLayoutParams(),
  35198. {
  35199. width: api.getWidth(),
  35200. height: api.getHeight()
  35201. }
  35202. );
  35203. var size = seriesOption.size || []; // Compatible with ec2.
  35204. var containerWidth = parsePercent$1(
  35205. retrieveValue$1(layoutInfo.width, size[0]),
  35206. ecWidth
  35207. );
  35208. var containerHeight = parsePercent$1(
  35209. retrieveValue$1(layoutInfo.height, size[1]),
  35210. ecHeight
  35211. );
  35212. // Fetch payload info.
  35213. var payloadType = payload && payload.type;
  35214. var targetInfo = retrieveTargetInfo(payload, seriesModel);
  35215. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  35216. ? payload.rootRect : null;
  35217. var viewRoot = seriesModel.getViewRoot();
  35218. var viewAbovePath = getPathToRoot(viewRoot);
  35219. if (payloadType !== 'treemapMove') {
  35220. var rootSize = payloadType === 'treemapZoomToNode'
  35221. ? estimateRootSize(
  35222. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  35223. )
  35224. : rootRect
  35225. ? [rootRect.width, rootRect.height]
  35226. : [containerWidth, containerHeight];
  35227. var sort = seriesOption.sort;
  35228. if (sort && sort !== 'asc' && sort !== 'desc') {
  35229. sort = 'desc';
  35230. }
  35231. var options = {
  35232. squareRatio: seriesOption.squareRatio,
  35233. sort: sort,
  35234. leafDepth: seriesOption.leafDepth
  35235. };
  35236. // layout should be cleared because using updateView but not update.
  35237. viewRoot.hostTree.clearLayouts();
  35238. // TODO
  35239. // optimize: if out of view clip, do not layout.
  35240. // But take care that if do not render node out of view clip,
  35241. // how to calculate start po
  35242. var viewRootLayout = {
  35243. x: 0, y: 0,
  35244. width: rootSize[0], height: rootSize[1],
  35245. area: rootSize[0] * rootSize[1]
  35246. };
  35247. viewRoot.setLayout(viewRootLayout);
  35248. squarify(viewRoot, options, false, 0);
  35249. // Supplement layout.
  35250. var viewRootLayout = viewRoot.getLayout();
  35251. each$13(viewAbovePath, function (node, index) {
  35252. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  35253. node.setLayout(extend(
  35254. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  35255. viewRootLayout
  35256. ));
  35257. });
  35258. }
  35259. var treeRoot = seriesModel.getData().tree.root;
  35260. treeRoot.setLayout(
  35261. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  35262. true
  35263. );
  35264. seriesModel.setLayoutInfo(layoutInfo);
  35265. // FIXME
  35266. // 现在没有clip功能,暂时取ec高宽。
  35267. prunning(
  35268. treeRoot,
  35269. // Transform to base element coordinate system.
  35270. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  35271. viewAbovePath,
  35272. viewRoot,
  35273. 0
  35274. );
  35275. });
  35276. };
  35277. /**
  35278. * Layout treemap with squarify algorithm.
  35279. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  35280. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  35281. *
  35282. * @protected
  35283. * @param {module:echarts/data/Tree~TreeNode} node
  35284. * @param {Object} options
  35285. * @param {string} options.sort 'asc' or 'desc'
  35286. * @param {number} options.squareRatio
  35287. * @param {boolean} hideChildren
  35288. * @param {number} depth
  35289. */
  35290. function squarify(node, options, hideChildren, depth) {
  35291. var width;
  35292. var height;
  35293. if (node.isRemoved()) {
  35294. return;
  35295. }
  35296. var thisLayout = node.getLayout();
  35297. width = thisLayout.width;
  35298. height = thisLayout.height;
  35299. // Considering border and gap
  35300. var nodeModel = node.getModel();
  35301. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  35302. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  35303. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  35304. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  35305. var layoutOffset = borderWidth - halfGapWidth;
  35306. var layoutOffsetUpper = upperHeight - halfGapWidth;
  35307. var nodeModel = node.getModel();
  35308. node.setLayout({
  35309. borderWidth: borderWidth,
  35310. upperHeight: upperHeight,
  35311. upperLabelHeight: upperLabelHeight
  35312. }, true);
  35313. width = mathMax$4(width - 2 * layoutOffset, 0);
  35314. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  35315. var totalArea = width * height;
  35316. var viewChildren = initChildren(
  35317. node, nodeModel, totalArea, options, hideChildren, depth
  35318. );
  35319. if (!viewChildren.length) {
  35320. return;
  35321. }
  35322. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  35323. var rowFixedLength = mathMin$4(width, height);
  35324. var best = Infinity; // the best row score so far
  35325. var row = [];
  35326. row.area = 0;
  35327. for (var i = 0, len = viewChildren.length; i < len;) {
  35328. var child = viewChildren[i];
  35329. row.push(child);
  35330. row.area += child.getLayout().area;
  35331. var score = worst(row, rowFixedLength, options.squareRatio);
  35332. // continue with this orientation
  35333. if (score <= best) {
  35334. i++;
  35335. best = score;
  35336. }
  35337. // abort, and try a different orientation
  35338. else {
  35339. row.area -= row.pop().getLayout().area;
  35340. position(row, rowFixedLength, rect, halfGapWidth, false);
  35341. rowFixedLength = mathMin$4(rect.width, rect.height);
  35342. row.length = row.area = 0;
  35343. best = Infinity;
  35344. }
  35345. }
  35346. if (row.length) {
  35347. position(row, rowFixedLength, rect, halfGapWidth, true);
  35348. }
  35349. if (!hideChildren) {
  35350. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  35351. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  35352. hideChildren = true;
  35353. }
  35354. }
  35355. for (var i = 0, len = viewChildren.length; i < len; i++) {
  35356. squarify(viewChildren[i], options, hideChildren, depth + 1);
  35357. }
  35358. }
  35359. /**
  35360. * Set area to each child, and calculate data extent for visual coding.
  35361. */
  35362. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  35363. var viewChildren = node.children || [];
  35364. var orderBy = options.sort;
  35365. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  35366. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  35367. // leafDepth has higher priority.
  35368. if (hideChildren && !overLeafDepth) {
  35369. return (node.viewChildren = []);
  35370. }
  35371. // Sort children, order by desc.
  35372. viewChildren = filter(viewChildren, function (child) {
  35373. return !child.isRemoved();
  35374. });
  35375. sort$1(viewChildren, orderBy);
  35376. var info = statistic(nodeModel, viewChildren, orderBy);
  35377. if (info.sum === 0) {
  35378. return (node.viewChildren = []);
  35379. }
  35380. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  35381. if (info.sum === 0) {
  35382. return (node.viewChildren = []);
  35383. }
  35384. // Set area to each child.
  35385. for (var i = 0, len = viewChildren.length; i < len; i++) {
  35386. var area = viewChildren[i].getValue() / info.sum * totalArea;
  35387. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  35388. viewChildren[i].setLayout({area: area});
  35389. }
  35390. if (overLeafDepth) {
  35391. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  35392. viewChildren.length = 0;
  35393. }
  35394. node.viewChildren = viewChildren;
  35395. node.setLayout({dataExtent: info.dataExtent}, true);
  35396. return viewChildren;
  35397. }
  35398. /**
  35399. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  35400. */
  35401. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  35402. // visibleMin is not supported yet when no option.sort.
  35403. if (!orderBy) {
  35404. return sum;
  35405. }
  35406. var visibleMin = nodeModel.get('visibleMin');
  35407. var len = orderedChildren.length;
  35408. var deletePoint = len;
  35409. // Always travel from little value to big value.
  35410. for (var i = len - 1; i >= 0; i--) {
  35411. var value = orderedChildren[
  35412. orderBy === 'asc' ? len - i - 1 : i
  35413. ].getValue();
  35414. if (value / sum * totalArea < visibleMin) {
  35415. deletePoint = i;
  35416. sum -= value;
  35417. }
  35418. }
  35419. orderBy === 'asc'
  35420. ? orderedChildren.splice(0, len - deletePoint)
  35421. : orderedChildren.splice(deletePoint, len - deletePoint);
  35422. return sum;
  35423. }
  35424. /**
  35425. * Sort
  35426. */
  35427. function sort$1(viewChildren, orderBy) {
  35428. if (orderBy) {
  35429. viewChildren.sort(function (a, b) {
  35430. var diff = orderBy === 'asc'
  35431. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  35432. return diff === 0
  35433. ? (orderBy === 'asc'
  35434. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  35435. )
  35436. : diff;
  35437. });
  35438. }
  35439. return viewChildren;
  35440. }
  35441. /**
  35442. * Statistic
  35443. */
  35444. function statistic(nodeModel, children, orderBy) {
  35445. // Calculate sum.
  35446. var sum = 0;
  35447. for (var i = 0, len = children.length; i < len; i++) {
  35448. sum += children[i].getValue();
  35449. }
  35450. // Statistic data extent for latter visual coding.
  35451. // Notice: data extent should be calculate based on raw children
  35452. // but not filtered view children, otherwise visual mapping will not
  35453. // be stable when zoom (where children is filtered by visibleMin).
  35454. var dimension = nodeModel.get('visualDimension');
  35455. var dataExtent;
  35456. // The same as area dimension.
  35457. if (!children || !children.length) {
  35458. dataExtent = [NaN, NaN];
  35459. }
  35460. else if (dimension === 'value' && orderBy) {
  35461. dataExtent = [
  35462. children[children.length - 1].getValue(),
  35463. children[0].getValue()
  35464. ];
  35465. orderBy === 'asc' && dataExtent.reverse();
  35466. }
  35467. // Other dimension.
  35468. else {
  35469. var dataExtent = [Infinity, -Infinity];
  35470. each$13(children, function (child) {
  35471. var value = child.getValue(dimension);
  35472. value < dataExtent[0] && (dataExtent[0] = value);
  35473. value > dataExtent[1] && (dataExtent[1] = value);
  35474. });
  35475. }
  35476. return {sum: sum, dataExtent: dataExtent};
  35477. }
  35478. /**
  35479. * Computes the score for the specified row,
  35480. * as the worst aspect ratio.
  35481. */
  35482. function worst(row, rowFixedLength, ratio) {
  35483. var areaMax = 0;
  35484. var areaMin = Infinity;
  35485. for (var i = 0, area, len = row.length; i < len; i++) {
  35486. area = row[i].getLayout().area;
  35487. if (area) {
  35488. area < areaMin && (areaMin = area);
  35489. area > areaMax && (areaMax = area);
  35490. }
  35491. }
  35492. var squareArea = row.area * row.area;
  35493. var f = rowFixedLength * rowFixedLength * ratio;
  35494. return squareArea
  35495. ? mathMax$4(
  35496. (f * areaMax) / squareArea,
  35497. squareArea / (f * areaMin)
  35498. )
  35499. : Infinity;
  35500. }
  35501. /**
  35502. * Positions the specified row of nodes. Modifies `rect`.
  35503. */
  35504. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  35505. // When rowFixedLength === rect.width,
  35506. // it is horizontal subdivision,
  35507. // rowFixedLength is the width of the subdivision,
  35508. // rowOtherLength is the height of the subdivision,
  35509. // and nodes will be positioned from left to right.
  35510. // wh[idx0WhenH] means: when horizontal,
  35511. // wh[idx0WhenH] => wh[0] => 'width'.
  35512. // xy[idx1WhenH] => xy[1] => 'y'.
  35513. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  35514. var idx1WhenH = 1 - idx0WhenH;
  35515. var xy = ['x', 'y'];
  35516. var wh = ['width', 'height'];
  35517. var last = rect[xy[idx0WhenH]];
  35518. var rowOtherLength = rowFixedLength
  35519. ? row.area / rowFixedLength : 0;
  35520. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  35521. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  35522. }
  35523. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  35524. var node = row[i];
  35525. var nodeLayout = {};
  35526. var step = rowOtherLength
  35527. ? node.getLayout().area / rowOtherLength : 0;
  35528. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  35529. // We use Math.max/min to avoid negative width/height when considering gap width.
  35530. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  35531. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  35532. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  35533. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  35534. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  35535. last += modWH;
  35536. node.setLayout(nodeLayout, true);
  35537. }
  35538. rect[xy[idx1WhenH]] += rowOtherLength;
  35539. rect[wh[idx1WhenH]] -= rowOtherLength;
  35540. }
  35541. // Return [containerWidth, containerHeight] as defualt.
  35542. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  35543. // If targetInfo.node exists, we zoom to the node,
  35544. // so estimate whold width and heigth by target node.
  35545. var currNode = (targetInfo || {}).node;
  35546. var defaultSize = [containerWidth, containerHeight];
  35547. if (!currNode || currNode === viewRoot) {
  35548. return defaultSize;
  35549. }
  35550. var parent;
  35551. var viewArea = containerWidth * containerHeight;
  35552. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  35553. while (parent = currNode.parentNode) { // jshint ignore:line
  35554. var sum = 0;
  35555. var siblings = parent.children;
  35556. for (var i = 0, len = siblings.length; i < len; i++) {
  35557. sum += siblings[i].getValue();
  35558. }
  35559. var currNodeValue = currNode.getValue();
  35560. if (currNodeValue === 0) {
  35561. return defaultSize;
  35562. }
  35563. area *= sum / currNodeValue;
  35564. // Considering border, suppose aspect ratio is 1.
  35565. var parentModel = parent.getModel();
  35566. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  35567. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  35568. area += 4 * borderWidth * borderWidth
  35569. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  35570. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  35571. currNode = parent;
  35572. }
  35573. area < viewArea && (area = viewArea);
  35574. var scale = Math.pow(area / viewArea, 0.5);
  35575. return [containerWidth * scale, containerHeight * scale];
  35576. }
  35577. // Root postion base on coord of containerGroup
  35578. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  35579. if (rootRect) {
  35580. return {x: rootRect.x, y: rootRect.y};
  35581. }
  35582. var defaultPosition = {x: 0, y: 0};
  35583. if (!targetInfo) {
  35584. return defaultPosition;
  35585. }
  35586. // If targetInfo is fetched by 'retrieveTargetInfo',
  35587. // old tree and new tree are the same tree,
  35588. // so the node still exists and we can visit it.
  35589. var targetNode = targetInfo.node;
  35590. var layout = targetNode.getLayout();
  35591. if (!layout) {
  35592. return defaultPosition;
  35593. }
  35594. // Transform coord from local to container.
  35595. var targetCenter = [layout.width / 2, layout.height / 2];
  35596. var node = targetNode;
  35597. while (node) {
  35598. var nodeLayout = node.getLayout();
  35599. targetCenter[0] += nodeLayout.x;
  35600. targetCenter[1] += nodeLayout.y;
  35601. node = node.parentNode;
  35602. }
  35603. return {
  35604. x: layoutInfo.width / 2 - targetCenter[0],
  35605. y: layoutInfo.height / 2 - targetCenter[1]
  35606. };
  35607. }
  35608. // Mark nodes visible for prunning when visual coding and rendering.
  35609. // Prunning depends on layout and root position, so we have to do it after layout.
  35610. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  35611. var nodeLayout = node.getLayout();
  35612. var nodeInViewAbovePath = viewAbovePath[depth];
  35613. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  35614. if (
  35615. (nodeInViewAbovePath && !isAboveViewRoot)
  35616. || (depth === viewAbovePath.length && node !== viewRoot)
  35617. ) {
  35618. return;
  35619. }
  35620. node.setLayout({
  35621. // isInView means: viewRoot sub tree + viewAbovePath
  35622. isInView: true,
  35623. // invisible only means: outside view clip so that the node can not
  35624. // see but still layout for animation preparation but not render.
  35625. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  35626. isAboveViewRoot: isAboveViewRoot
  35627. }, true);
  35628. // Transform to child coordinate.
  35629. var childClipRect = new BoundingRect(
  35630. clipRect.x - nodeLayout.x,
  35631. clipRect.y - nodeLayout.y,
  35632. clipRect.width,
  35633. clipRect.height
  35634. );
  35635. each$13(node.viewChildren || [], function (child) {
  35636. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  35637. });
  35638. }
  35639. function getUpperLabelHeight(model) {
  35640. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  35641. }
  35642. registerVisual(treemapVisual);
  35643. registerLayout(treemapLayout);
  35644. /**
  35645. * Graph data structure
  35646. *
  35647. * @module echarts/data/Graph
  35648. * @author Yi Shen(https://www.github.com/pissang)
  35649. */
  35650. // id may be function name of Object, add a prefix to avoid this problem.
  35651. function generateNodeKey (id) {
  35652. return '_EC_' + id;
  35653. }
  35654. /**
  35655. * @alias module:echarts/data/Graph
  35656. * @constructor
  35657. * @param {boolean} directed
  35658. */
  35659. var Graph = function(directed) {
  35660. /**
  35661. * 是否是有向图
  35662. * @type {boolean}
  35663. * @private
  35664. */
  35665. this._directed = directed || false;
  35666. /**
  35667. * @type {Array.<module:echarts/data/Graph.Node>}
  35668. * @readOnly
  35669. */
  35670. this.nodes = [];
  35671. /**
  35672. * @type {Array.<module:echarts/data/Graph.Edge>}
  35673. * @readOnly
  35674. */
  35675. this.edges = [];
  35676. /**
  35677. * @type {Object.<string, module:echarts/data/Graph.Node>}
  35678. * @private
  35679. */
  35680. this._nodesMap = {};
  35681. /**
  35682. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  35683. * @private
  35684. */
  35685. this._edgesMap = {};
  35686. /**
  35687. * @type {module:echarts/data/List}
  35688. * @readOnly
  35689. */
  35690. this.data;
  35691. /**
  35692. * @type {module:echarts/data/List}
  35693. * @readOnly
  35694. */
  35695. this.edgeData;
  35696. };
  35697. var graphProto = Graph.prototype;
  35698. /**
  35699. * @type {string}
  35700. */
  35701. graphProto.type = 'graph';
  35702. /**
  35703. * If is directed graph
  35704. * @return {boolean}
  35705. */
  35706. graphProto.isDirected = function () {
  35707. return this._directed;
  35708. };
  35709. /**
  35710. * Add a new node
  35711. * @param {string} id
  35712. * @param {number} [dataIndex]
  35713. */
  35714. graphProto.addNode = function (id, dataIndex) {
  35715. id = id || ('' + dataIndex);
  35716. var nodesMap = this._nodesMap;
  35717. if (nodesMap[generateNodeKey(id)]) {
  35718. if (__DEV__) {
  35719. console.error('Graph nodes have duplicate name or id');
  35720. }
  35721. return;
  35722. }
  35723. var node = new Node(id, dataIndex);
  35724. node.hostGraph = this;
  35725. this.nodes.push(node);
  35726. nodesMap[generateNodeKey(id)] = node;
  35727. return node;
  35728. };
  35729. /**
  35730. * Get node by data index
  35731. * @param {number} dataIndex
  35732. * @return {module:echarts/data/Graph~Node}
  35733. */
  35734. graphProto.getNodeByIndex = function (dataIndex) {
  35735. var rawIdx = this.data.getRawIndex(dataIndex);
  35736. return this.nodes[rawIdx];
  35737. };
  35738. /**
  35739. * Get node by id
  35740. * @param {string} id
  35741. * @return {module:echarts/data/Graph.Node}
  35742. */
  35743. graphProto.getNodeById = function (id) {
  35744. return this._nodesMap[generateNodeKey(id)];
  35745. };
  35746. /**
  35747. * Add a new edge
  35748. * @param {number|string|module:echarts/data/Graph.Node} n1
  35749. * @param {number|string|module:echarts/data/Graph.Node} n2
  35750. * @param {number} [dataIndex=-1]
  35751. * @return {module:echarts/data/Graph.Edge}
  35752. */
  35753. graphProto.addEdge = function (n1, n2, dataIndex) {
  35754. var nodesMap = this._nodesMap;
  35755. var edgesMap = this._edgesMap;
  35756. // PNEDING
  35757. if (typeof n1 === 'number') {
  35758. n1 = this.nodes[n1];
  35759. }
  35760. if (typeof n2 === 'number') {
  35761. n2 = this.nodes[n2];
  35762. }
  35763. if (!(n1 instanceof Node)) {
  35764. n1 = nodesMap[generateNodeKey(n1)];
  35765. }
  35766. if (!(n2 instanceof Node)) {
  35767. n2 = nodesMap[generateNodeKey(n2)];
  35768. }
  35769. if (!n1 || !n2) {
  35770. return;
  35771. }
  35772. var key = n1.id + '-' + n2.id;
  35773. // PENDING
  35774. if (edgesMap[key]) {
  35775. return;
  35776. }
  35777. var edge = new Edge(n1, n2, dataIndex);
  35778. edge.hostGraph = this;
  35779. if (this._directed) {
  35780. n1.outEdges.push(edge);
  35781. n2.inEdges.push(edge);
  35782. }
  35783. n1.edges.push(edge);
  35784. if (n1 !== n2) {
  35785. n2.edges.push(edge);
  35786. }
  35787. this.edges.push(edge);
  35788. edgesMap[key] = edge;
  35789. return edge;
  35790. };
  35791. /**
  35792. * Get edge by data index
  35793. * @param {number} dataIndex
  35794. * @return {module:echarts/data/Graph~Node}
  35795. */
  35796. graphProto.getEdgeByIndex = function (dataIndex) {
  35797. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  35798. return this.edges[rawIdx];
  35799. };
  35800. /**
  35801. * Get edge by two linked nodes
  35802. * @param {module:echarts/data/Graph.Node|string} n1
  35803. * @param {module:echarts/data/Graph.Node|string} n2
  35804. * @return {module:echarts/data/Graph.Edge}
  35805. */
  35806. graphProto.getEdge = function (n1, n2) {
  35807. if (n1 instanceof Node) {
  35808. n1 = n1.id;
  35809. }
  35810. if (n2 instanceof Node) {
  35811. n2 = n2.id;
  35812. }
  35813. var edgesMap = this._edgesMap;
  35814. if (this._directed) {
  35815. return edgesMap[n1 + '-' + n2];
  35816. } else {
  35817. return edgesMap[n1 + '-' + n2]
  35818. || edgesMap[n2 + '-' + n1];
  35819. }
  35820. };
  35821. /**
  35822. * Iterate all nodes
  35823. * @param {Function} cb
  35824. * @param {*} [context]
  35825. */
  35826. graphProto.eachNode = function (cb, context) {
  35827. var nodes = this.nodes;
  35828. var len = nodes.length;
  35829. for (var i = 0; i < len; i++) {
  35830. if (nodes[i].dataIndex >= 0) {
  35831. cb.call(context, nodes[i], i);
  35832. }
  35833. }
  35834. };
  35835. /**
  35836. * Iterate all edges
  35837. * @param {Function} cb
  35838. * @param {*} [context]
  35839. */
  35840. graphProto.eachEdge = function (cb, context) {
  35841. var edges = this.edges;
  35842. var len = edges.length;
  35843. for (var i = 0; i < len; i++) {
  35844. if (edges[i].dataIndex >= 0
  35845. && edges[i].node1.dataIndex >= 0
  35846. && edges[i].node2.dataIndex >= 0
  35847. ) {
  35848. cb.call(context, edges[i], i);
  35849. }
  35850. }
  35851. };
  35852. /**
  35853. * Breadth first traverse
  35854. * @param {Function} cb
  35855. * @param {module:echarts/data/Graph.Node} startNode
  35856. * @param {string} [direction='none'] 'none'|'in'|'out'
  35857. * @param {*} [context]
  35858. */
  35859. graphProto.breadthFirstTraverse = function (
  35860. cb, startNode, direction, context
  35861. ) {
  35862. if (!(startNode instanceof Node)) {
  35863. startNode = this._nodesMap[generateNodeKey(startNode)];
  35864. }
  35865. if (!startNode) {
  35866. return;
  35867. }
  35868. var edgeType = direction === 'out'
  35869. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  35870. for (var i = 0; i < this.nodes.length; i++) {
  35871. this.nodes[i].__visited = false;
  35872. }
  35873. if (cb.call(context, startNode, null)) {
  35874. return;
  35875. }
  35876. var queue = [startNode];
  35877. while (queue.length) {
  35878. var currentNode = queue.shift();
  35879. var edges = currentNode[edgeType];
  35880. for (var i = 0; i < edges.length; i++) {
  35881. var e = edges[i];
  35882. var otherNode = e.node1 === currentNode
  35883. ? e.node2 : e.node1;
  35884. if (!otherNode.__visited) {
  35885. if (cb.call(context, otherNode, currentNode)) {
  35886. // Stop traversing
  35887. return;
  35888. }
  35889. queue.push(otherNode);
  35890. otherNode.__visited = true;
  35891. }
  35892. }
  35893. }
  35894. };
  35895. // TODO
  35896. // graphProto.depthFirstTraverse = function (
  35897. // cb, startNode, direction, context
  35898. // ) {
  35899. // };
  35900. // Filter update
  35901. graphProto.update = function () {
  35902. var data = this.data;
  35903. var edgeData = this.edgeData;
  35904. var nodes = this.nodes;
  35905. var edges = this.edges;
  35906. for (var i = 0, len = nodes.length; i < len; i++) {
  35907. nodes[i].dataIndex = -1;
  35908. }
  35909. for (var i = 0, len = data.count(); i < len; i++) {
  35910. nodes[data.getRawIndex(i)].dataIndex = i;
  35911. }
  35912. edgeData.filterSelf(function (idx) {
  35913. var edge = edges[edgeData.getRawIndex(idx)];
  35914. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  35915. });
  35916. // Update edge
  35917. for (var i = 0, len = edges.length; i < len; i++) {
  35918. edges[i].dataIndex = -1;
  35919. }
  35920. for (var i = 0, len = edgeData.count(); i < len; i++) {
  35921. edges[edgeData.getRawIndex(i)].dataIndex = i;
  35922. }
  35923. };
  35924. /**
  35925. * @return {module:echarts/data/Graph}
  35926. */
  35927. graphProto.clone = function () {
  35928. var graph = new Graph(this._directed);
  35929. var nodes = this.nodes;
  35930. var edges = this.edges;
  35931. for (var i = 0; i < nodes.length; i++) {
  35932. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  35933. }
  35934. for (var i = 0; i < edges.length; i++) {
  35935. var e = edges[i];
  35936. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  35937. }
  35938. return graph;
  35939. };
  35940. /**
  35941. * @alias module:echarts/data/Graph.Node
  35942. */
  35943. function Node(id, dataIndex) {
  35944. /**
  35945. * @type {string}
  35946. */
  35947. this.id = id == null ? '' : id;
  35948. /**
  35949. * @type {Array.<module:echarts/data/Graph.Edge>}
  35950. */
  35951. this.inEdges = [];
  35952. /**
  35953. * @type {Array.<module:echarts/data/Graph.Edge>}
  35954. */
  35955. this.outEdges = [];
  35956. /**
  35957. * @type {Array.<module:echarts/data/Graph.Edge>}
  35958. */
  35959. this.edges = [];
  35960. /**
  35961. * @type {module:echarts/data/Graph}
  35962. */
  35963. this.hostGraph;
  35964. /**
  35965. * @type {number}
  35966. */
  35967. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  35968. }
  35969. Node.prototype = {
  35970. constructor: Node,
  35971. /**
  35972. * @return {number}
  35973. */
  35974. degree: function () {
  35975. return this.edges.length;
  35976. },
  35977. /**
  35978. * @return {number}
  35979. */
  35980. inDegree: function () {
  35981. return this.inEdges.length;
  35982. },
  35983. /**
  35984. * @return {number}
  35985. */
  35986. outDegree: function () {
  35987. return this.outEdges.length;
  35988. },
  35989. /**
  35990. * @param {string} [path]
  35991. * @return {module:echarts/model/Model}
  35992. */
  35993. getModel: function (path) {
  35994. if (this.dataIndex < 0) {
  35995. return;
  35996. }
  35997. var graph = this.hostGraph;
  35998. var itemModel = graph.data.getItemModel(this.dataIndex);
  35999. return itemModel.getModel(path);
  36000. }
  36001. };
  36002. /**
  36003. * 图边
  36004. * @alias module:echarts/data/Graph.Edge
  36005. * @param {module:echarts/data/Graph.Node} n1
  36006. * @param {module:echarts/data/Graph.Node} n2
  36007. * @param {number} [dataIndex=-1]
  36008. */
  36009. function Edge(n1, n2, dataIndex) {
  36010. /**
  36011. * 节点1,如果是有向图则为源节点
  36012. * @type {module:echarts/data/Graph.Node}
  36013. */
  36014. this.node1 = n1;
  36015. /**
  36016. * 节点2,如果是有向图则为目标节点
  36017. * @type {module:echarts/data/Graph.Node}
  36018. */
  36019. this.node2 = n2;
  36020. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  36021. }
  36022. /**
  36023. * @param {string} [path]
  36024. * @return {module:echarts/model/Model}
  36025. */
  36026. Edge.prototype.getModel = function (path) {
  36027. if (this.dataIndex < 0) {
  36028. return;
  36029. }
  36030. var graph = this.hostGraph;
  36031. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  36032. return itemModel.getModel(path);
  36033. };
  36034. var createGraphDataProxyMixin = function (hostName, dataName) {
  36035. return {
  36036. /**
  36037. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  36038. * @return {number}
  36039. */
  36040. getValue: function (dimension) {
  36041. var data = this[hostName][dataName];
  36042. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  36043. },
  36044. /**
  36045. * @param {Object|string} key
  36046. * @param {*} [value]
  36047. */
  36048. setVisual: function (key, value) {
  36049. this.dataIndex >= 0
  36050. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  36051. },
  36052. /**
  36053. * @param {string} key
  36054. * @return {boolean}
  36055. */
  36056. getVisual: function (key, ignoreParent) {
  36057. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  36058. },
  36059. /**
  36060. * @param {Object} layout
  36061. * @return {boolean} [merge=false]
  36062. */
  36063. setLayout: function (layout, merge$$1) {
  36064. this.dataIndex >= 0
  36065. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  36066. },
  36067. /**
  36068. * @return {Object}
  36069. */
  36070. getLayout: function () {
  36071. return this[hostName][dataName].getItemLayout(this.dataIndex);
  36072. },
  36073. /**
  36074. * @return {module:zrender/Element}
  36075. */
  36076. getGraphicEl: function () {
  36077. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  36078. },
  36079. /**
  36080. * @return {number}
  36081. */
  36082. getRawIndex: function () {
  36083. return this[hostName][dataName].getRawIndex(this.dataIndex);
  36084. }
  36085. };
  36086. };
  36087. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  36088. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  36089. Graph.Node = Node;
  36090. Graph.Edge = Edge;
  36091. var createGraphFromNodeEdge = function (nodes, edges, hostModel, directed, beforeLink) {
  36092. var graph = new Graph(directed);
  36093. for (var i = 0; i < nodes.length; i++) {
  36094. graph.addNode(retrieve(
  36095. // Id, name, dataIndex
  36096. nodes[i].id, nodes[i].name, i
  36097. ), i);
  36098. }
  36099. var linkNameList = [];
  36100. var validEdges = [];
  36101. var linkCount = 0;
  36102. for (var i = 0; i < edges.length; i++) {
  36103. var link = edges[i];
  36104. var source = link.source;
  36105. var target = link.target;
  36106. // addEdge may fail when source or target not exists
  36107. if (graph.addEdge(source, target, linkCount)) {
  36108. validEdges.push(link);
  36109. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  36110. linkCount++;
  36111. }
  36112. }
  36113. var coordSys = hostModel.get('coordinateSystem');
  36114. var nodeData;
  36115. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  36116. nodeData = createListFromArray(nodes, hostModel, hostModel.ecModel);
  36117. }
  36118. else {
  36119. // FIXME
  36120. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  36121. // FIXME
  36122. var dimensionNames = completeDimensions(
  36123. ((coordSysCtor && coordSysCtor.type !== 'view') ? (coordSysCtor.dimensions || []) : []).concat(['value']),
  36124. nodes
  36125. );
  36126. nodeData = new List(dimensionNames, hostModel);
  36127. nodeData.initData(nodes);
  36128. }
  36129. var edgeData = new List(['value'], hostModel);
  36130. edgeData.initData(validEdges, linkNameList);
  36131. beforeLink && beforeLink(nodeData, edgeData);
  36132. linkList({
  36133. mainData: nodeData,
  36134. struct: graph,
  36135. structAttr: 'graph',
  36136. datas: {node: nodeData, edge: edgeData},
  36137. datasAttr: {node: 'data', edge: 'edgeData'}
  36138. });
  36139. // Update dataIndex of nodes and edges because invalid edge may be removed
  36140. graph.update();
  36141. return graph;
  36142. };
  36143. var GraphSeries = extendSeriesModel({
  36144. type: 'series.graph',
  36145. init: function (option) {
  36146. GraphSeries.superApply(this, 'init', arguments);
  36147. // Provide data for legend select
  36148. this.legendDataProvider = function () {
  36149. return this._categoriesData;
  36150. };
  36151. this.fillDataTextStyle(option.edges || option.links);
  36152. this._updateCategoriesData();
  36153. },
  36154. mergeOption: function (option) {
  36155. GraphSeries.superApply(this, 'mergeOption', arguments);
  36156. this.fillDataTextStyle(option.edges || option.links);
  36157. this._updateCategoriesData();
  36158. },
  36159. mergeDefaultAndTheme: function (option) {
  36160. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  36161. defaultEmphasis(option.edgeLabel, ['show']);
  36162. },
  36163. getInitialData: function (option, ecModel) {
  36164. var edges = option.edges || option.links || [];
  36165. var nodes = option.data || option.nodes || [];
  36166. var self = this;
  36167. if (nodes && edges) {
  36168. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  36169. }
  36170. function beforeLink(nodeData, edgeData) {
  36171. // Overwrite nodeData.getItemModel to
  36172. nodeData.wrapMethod('getItemModel', function (model) {
  36173. var categoriesModels = self._categoriesModels;
  36174. var categoryIdx = model.getShallow('category');
  36175. var categoryModel = categoriesModels[categoryIdx];
  36176. if (categoryModel) {
  36177. categoryModel.parentModel = model.parentModel;
  36178. model.parentModel = categoryModel;
  36179. }
  36180. return model;
  36181. });
  36182. var edgeLabelModel = self.getModel('edgeLabel');
  36183. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  36184. var fakeSeriesModel = new Model(
  36185. {label: edgeLabelModel.option},
  36186. edgeLabelModel.parentModel,
  36187. ecModel
  36188. );
  36189. edgeData.wrapMethod('getItemModel', function (model) {
  36190. model.customizeGetParent(edgeGetParent);
  36191. return model;
  36192. });
  36193. function edgeGetParent(path) {
  36194. path = this.parsePath(path);
  36195. return (path && path[0] === 'label')
  36196. ? fakeSeriesModel
  36197. : this.parentModel;
  36198. }
  36199. }
  36200. },
  36201. /**
  36202. * @return {module:echarts/data/Graph}
  36203. */
  36204. getGraph: function () {
  36205. return this.getData().graph;
  36206. },
  36207. /**
  36208. * @return {module:echarts/data/List}
  36209. */
  36210. getEdgeData: function () {
  36211. return this.getGraph().edgeData;
  36212. },
  36213. /**
  36214. * @return {module:echarts/data/List}
  36215. */
  36216. getCategoriesData: function () {
  36217. return this._categoriesData;
  36218. },
  36219. /**
  36220. * @override
  36221. */
  36222. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  36223. if (dataType === 'edge') {
  36224. var nodeData = this.getData();
  36225. var params = this.getDataParams(dataIndex, dataType);
  36226. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  36227. var sourceName = nodeData.getName(edge.node1.dataIndex);
  36228. var targetName = nodeData.getName(edge.node2.dataIndex);
  36229. var html = [];
  36230. sourceName != null && html.push(sourceName);
  36231. targetName != null && html.push(targetName);
  36232. html = encodeHTML(html.join(' > '));
  36233. if (params.value) {
  36234. html += ' : ' + encodeHTML(params.value);
  36235. }
  36236. return html;
  36237. }
  36238. else { // dataType === 'node' or empty
  36239. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  36240. }
  36241. },
  36242. _updateCategoriesData: function () {
  36243. var categories = map(this.option.categories || [], function (category) {
  36244. // Data must has value
  36245. return category.value != null ? category : extend({
  36246. value: 0
  36247. }, category);
  36248. });
  36249. var categoriesData = new List(['value'], this);
  36250. categoriesData.initData(categories);
  36251. this._categoriesData = categoriesData;
  36252. this._categoriesModels = categoriesData.mapArray(function (idx) {
  36253. return categoriesData.getItemModel(idx, true);
  36254. });
  36255. },
  36256. setZoom: function (zoom) {
  36257. this.option.zoom = zoom;
  36258. },
  36259. setCenter: function (center) {
  36260. this.option.center = center;
  36261. },
  36262. isAnimationEnabled: function () {
  36263. return GraphSeries.superCall(this, 'isAnimationEnabled')
  36264. // Not enable animation when do force layout
  36265. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  36266. },
  36267. defaultOption: {
  36268. zlevel: 0,
  36269. z: 2,
  36270. coordinateSystem: 'view',
  36271. // Default option for all coordinate systems
  36272. // xAxisIndex: 0,
  36273. // yAxisIndex: 0,
  36274. // polarIndex: 0,
  36275. // geoIndex: 0,
  36276. legendHoverLink: true,
  36277. hoverAnimation: true,
  36278. layout: null,
  36279. focusNodeAdjacency: false,
  36280. // Configuration of circular layout
  36281. circular: {
  36282. rotateLabel: false
  36283. },
  36284. // Configuration of force directed layout
  36285. force: {
  36286. initLayout: null,
  36287. // Node repulsion. Can be an array to represent range.
  36288. repulsion: [0, 50],
  36289. gravity: 0.1,
  36290. // Edge length. Can be an array to represent range.
  36291. edgeLength: 30,
  36292. layoutAnimation: true
  36293. },
  36294. left: 'center',
  36295. top: 'center',
  36296. // right: null,
  36297. // bottom: null,
  36298. // width: '80%',
  36299. // height: '80%',
  36300. symbol: 'circle',
  36301. symbolSize: 10,
  36302. edgeSymbol: ['none', 'none'],
  36303. edgeSymbolSize: 10,
  36304. edgeLabel: {
  36305. normal: {
  36306. position: 'middle'
  36307. },
  36308. emphasis: {}
  36309. },
  36310. draggable: false,
  36311. roam: false,
  36312. // Default on center of graph
  36313. center: null,
  36314. zoom: 1,
  36315. // Symbol size scale ratio in roam
  36316. nodeScaleRatio: 0.6,
  36317. // cursor: null,
  36318. // categories: [],
  36319. // data: []
  36320. // Or
  36321. // nodes: []
  36322. //
  36323. // links: []
  36324. // Or
  36325. // edges: []
  36326. label: {
  36327. normal: {
  36328. show: false,
  36329. formatter: '{b}'
  36330. },
  36331. emphasis: {
  36332. show: true
  36333. }
  36334. },
  36335. itemStyle: {
  36336. normal: {},
  36337. emphasis: {}
  36338. },
  36339. lineStyle: {
  36340. normal: {
  36341. color: '#aaa',
  36342. width: 1,
  36343. curveness: 0,
  36344. opacity: 0.5
  36345. },
  36346. emphasis: {}
  36347. }
  36348. }
  36349. });
  36350. /**
  36351. * Line path for bezier and straight line draw
  36352. */
  36353. var straightLineProto = Line.prototype;
  36354. var bezierCurveProto = BezierCurve.prototype;
  36355. function isLine(shape) {
  36356. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  36357. }
  36358. var LinePath = extendShape({
  36359. type: 'ec-line',
  36360. style: {
  36361. stroke: '#000',
  36362. fill: null
  36363. },
  36364. shape: {
  36365. x1: 0,
  36366. y1: 0,
  36367. x2: 0,
  36368. y2: 0,
  36369. percent: 1,
  36370. cpx1: null,
  36371. cpy1: null
  36372. },
  36373. buildPath: function (ctx, shape) {
  36374. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  36375. },
  36376. pointAt: function (t) {
  36377. return isLine(this.shape)
  36378. ? straightLineProto.pointAt.call(this, t)
  36379. : bezierCurveProto.pointAt.call(this, t);
  36380. },
  36381. tangentAt: function (t) {
  36382. var shape = this.shape;
  36383. var p = isLine(shape)
  36384. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  36385. : bezierCurveProto.tangentAt.call(this, t);
  36386. return normalize(p, p);
  36387. }
  36388. });
  36389. /**
  36390. * @module echarts/chart/helper/Line
  36391. */
  36392. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  36393. function makeSymbolTypeKey(symbolCategory) {
  36394. return '_' + symbolCategory + 'Type';
  36395. }
  36396. /**
  36397. * @inner
  36398. */
  36399. function createSymbol$1(name, lineData, idx) {
  36400. var color = lineData.getItemVisual(idx, 'color');
  36401. var symbolType = lineData.getItemVisual(idx, name);
  36402. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  36403. if (!symbolType || symbolType === 'none') {
  36404. return;
  36405. }
  36406. if (!isArray(symbolSize)) {
  36407. symbolSize = [symbolSize, symbolSize];
  36408. }
  36409. var symbolPath = createSymbol(
  36410. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  36411. symbolSize[0], symbolSize[1], color
  36412. );
  36413. symbolPath.name = name;
  36414. return symbolPath;
  36415. }
  36416. function createLine(points) {
  36417. var line = new LinePath({
  36418. name: 'line'
  36419. });
  36420. setLinePoints(line.shape, points);
  36421. return line;
  36422. }
  36423. function setLinePoints(targetShape, points) {
  36424. var p1 = points[0];
  36425. var p2 = points[1];
  36426. var cp1 = points[2];
  36427. targetShape.x1 = p1[0];
  36428. targetShape.y1 = p1[1];
  36429. targetShape.x2 = p2[0];
  36430. targetShape.y2 = p2[1];
  36431. targetShape.percent = 1;
  36432. if (cp1) {
  36433. targetShape.cpx1 = cp1[0];
  36434. targetShape.cpy1 = cp1[1];
  36435. }
  36436. else {
  36437. targetShape.cpx1 = NaN;
  36438. targetShape.cpy1 = NaN;
  36439. }
  36440. }
  36441. function updateSymbolAndLabelBeforeLineUpdate () {
  36442. var lineGroup = this;
  36443. var symbolFrom = lineGroup.childOfName('fromSymbol');
  36444. var symbolTo = lineGroup.childOfName('toSymbol');
  36445. var label = lineGroup.childOfName('label');
  36446. // Quick reject
  36447. if (!symbolFrom && !symbolTo && label.ignore) {
  36448. return;
  36449. }
  36450. var invScale = 1;
  36451. var parentNode = this.parent;
  36452. while (parentNode) {
  36453. if (parentNode.scale) {
  36454. invScale /= parentNode.scale[0];
  36455. }
  36456. parentNode = parentNode.parent;
  36457. }
  36458. var line = lineGroup.childOfName('line');
  36459. // If line not changed
  36460. // FIXME Parent scale changed
  36461. if (!this.__dirty && !line.__dirty) {
  36462. return;
  36463. }
  36464. var percent = line.shape.percent;
  36465. var fromPos = line.pointAt(0);
  36466. var toPos = line.pointAt(percent);
  36467. var d = sub([], toPos, fromPos);
  36468. normalize(d, d);
  36469. if (symbolFrom) {
  36470. symbolFrom.attr('position', fromPos);
  36471. var tangent = line.tangentAt(0);
  36472. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  36473. tangent[1], tangent[0]
  36474. ));
  36475. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  36476. }
  36477. if (symbolTo) {
  36478. symbolTo.attr('position', toPos);
  36479. var tangent = line.tangentAt(1);
  36480. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  36481. tangent[1], tangent[0]
  36482. ));
  36483. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  36484. }
  36485. if (!label.ignore) {
  36486. label.attr('position', toPos);
  36487. var textPosition;
  36488. var textAlign;
  36489. var textVerticalAlign;
  36490. var distance$$1 = 5 * invScale;
  36491. // End
  36492. if (label.__position === 'end') {
  36493. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  36494. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  36495. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  36496. }
  36497. // Middle
  36498. else if (label.__position === 'middle') {
  36499. var halfPercent = percent / 2;
  36500. var tangent = line.tangentAt(halfPercent);
  36501. var n = [tangent[1], -tangent[0]];
  36502. var cp = line.pointAt(halfPercent);
  36503. if (n[1] > 0) {
  36504. n[0] = -n[0];
  36505. n[1] = -n[1];
  36506. }
  36507. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  36508. textAlign = 'center';
  36509. textVerticalAlign = 'bottom';
  36510. var rotation = -Math.atan2(tangent[1], tangent[0]);
  36511. if (toPos[0] < fromPos[0]) {
  36512. rotation = Math.PI + rotation;
  36513. }
  36514. label.attr('rotation', rotation);
  36515. }
  36516. // Start
  36517. else {
  36518. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  36519. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  36520. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  36521. }
  36522. label.attr({
  36523. style: {
  36524. // Use the user specified text align and baseline first
  36525. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  36526. textAlign: label.__textAlign || textAlign
  36527. },
  36528. position: textPosition,
  36529. scale: [invScale, invScale]
  36530. });
  36531. }
  36532. }
  36533. /**
  36534. * @constructor
  36535. * @extends {module:zrender/graphic/Group}
  36536. * @alias {module:echarts/chart/helper/Line}
  36537. */
  36538. function Line$1(lineData, idx, seriesScope) {
  36539. Group.call(this);
  36540. this._createLine(lineData, idx, seriesScope);
  36541. }
  36542. var lineProto = Line$1.prototype;
  36543. // Update symbol position and rotation
  36544. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  36545. lineProto._createLine = function (lineData, idx, seriesScope) {
  36546. var seriesModel = lineData.hostModel;
  36547. var linePoints = lineData.getItemLayout(idx);
  36548. var line = createLine(linePoints);
  36549. line.shape.percent = 0;
  36550. initProps(line, {
  36551. shape: {
  36552. percent: 1
  36553. }
  36554. }, seriesModel, idx);
  36555. this.add(line);
  36556. var label = new Text({
  36557. name: 'label'
  36558. });
  36559. this.add(label);
  36560. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36561. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  36562. // symbols must added after line to make sure
  36563. // it will be updated after line#update.
  36564. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  36565. this.add(symbol);
  36566. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  36567. }, this);
  36568. this._updateCommonStl(lineData, idx, seriesScope);
  36569. };
  36570. lineProto.updateData = function (lineData, idx, seriesScope) {
  36571. var seriesModel = lineData.hostModel;
  36572. var line = this.childOfName('line');
  36573. var linePoints = lineData.getItemLayout(idx);
  36574. var target = {
  36575. shape: {}
  36576. };
  36577. setLinePoints(target.shape, linePoints);
  36578. updateProps(line, target, seriesModel, idx);
  36579. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36580. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  36581. var key = makeSymbolTypeKey(symbolCategory);
  36582. // Symbol changed
  36583. if (this[key] !== symbolType) {
  36584. this.remove(this.childOfName(symbolCategory));
  36585. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  36586. this.add(symbol);
  36587. }
  36588. this[key] = symbolType;
  36589. }, this);
  36590. this._updateCommonStl(lineData, idx, seriesScope);
  36591. };
  36592. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  36593. var seriesModel = lineData.hostModel;
  36594. var line = this.childOfName('line');
  36595. var lineStyle = seriesScope && seriesScope.lineStyle;
  36596. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  36597. var labelModel = seriesScope && seriesScope.labelModel;
  36598. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  36599. // Optimization for large dataset
  36600. if (!seriesScope || lineData.hasItemOption) {
  36601. var itemModel = lineData.getItemModel(idx);
  36602. lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  36603. hoverLineStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  36604. labelModel = itemModel.getModel('label.normal');
  36605. hoverLabelModel = itemModel.getModel('label.emphasis');
  36606. }
  36607. var visualColor = lineData.getItemVisual(idx, 'color');
  36608. var visualOpacity = retrieve3(
  36609. lineData.getItemVisual(idx, 'opacity'),
  36610. lineStyle.opacity,
  36611. 1
  36612. );
  36613. line.useStyle(defaults(
  36614. {
  36615. strokeNoScale: true,
  36616. fill: 'none',
  36617. stroke: visualColor,
  36618. opacity: visualOpacity
  36619. },
  36620. lineStyle
  36621. ));
  36622. line.hoverStyle = hoverLineStyle;
  36623. // Update symbol
  36624. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  36625. var symbol = this.childOfName(symbolCategory);
  36626. if (symbol) {
  36627. symbol.setColor(visualColor);
  36628. symbol.setStyle({
  36629. opacity: visualOpacity
  36630. });
  36631. }
  36632. }, this);
  36633. var showLabel = labelModel.getShallow('show');
  36634. var hoverShowLabel = hoverLabelModel.getShallow('show');
  36635. var label = this.childOfName('label');
  36636. var defaultLabelColor;
  36637. var defaultText;
  36638. var normalText;
  36639. var emphasisText;
  36640. if (showLabel || hoverShowLabel) {
  36641. var rawVal = seriesModel.getRawValue(idx);
  36642. defaultText = rawVal == null
  36643. ? defaultText = lineData.getName(idx)
  36644. : isFinite(rawVal)
  36645. ? round(rawVal)
  36646. : rawVal;
  36647. defaultLabelColor = visualColor || '#000';
  36648. normalText = retrieve2(
  36649. seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType),
  36650. defaultText
  36651. );
  36652. emphasisText = retrieve2(
  36653. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  36654. normalText
  36655. );
  36656. }
  36657. // label.afterUpdate = lineAfterUpdate;
  36658. if (showLabel) {
  36659. var labelStyle = setTextStyle(label.style, labelModel, {
  36660. text: normalText
  36661. }, {
  36662. autoColor: defaultLabelColor
  36663. });
  36664. label.__textAlign = labelStyle.textAlign;
  36665. label.__verticalAlign = labelStyle.textVerticalAlign;
  36666. // 'start', 'middle', 'end'
  36667. label.__position = labelModel.get('position') || 'middle';
  36668. }
  36669. else {
  36670. label.setStyle('text', null);
  36671. }
  36672. if (hoverShowLabel) {
  36673. // Only these properties supported in this emphasis style here.
  36674. label.hoverStyle = {
  36675. text: emphasisText,
  36676. textFill: hoverLabelModel.getTextColor(true),
  36677. // For merging hover style to normal style, do not use
  36678. // `hoverLabelModel.getFont()` here.
  36679. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  36680. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  36681. fontSize: hoverLabelModel.getShallow('fontSize'),
  36682. fontFamily: hoverLabelModel.getShallow('fontFamily')
  36683. };
  36684. }
  36685. else {
  36686. label.hoverStyle = {
  36687. text: null
  36688. };
  36689. }
  36690. label.ignore = !showLabel && !hoverShowLabel;
  36691. setHoverStyle(this);
  36692. };
  36693. lineProto.highlight = function () {
  36694. this.trigger('emphasis');
  36695. };
  36696. lineProto.downplay = function () {
  36697. this.trigger('normal');
  36698. };
  36699. lineProto.updateLayout = function (lineData, idx) {
  36700. this.setLinePoints(lineData.getItemLayout(idx));
  36701. };
  36702. lineProto.setLinePoints = function (points) {
  36703. var linePath = this.childOfName('line');
  36704. setLinePoints(linePath.shape, points);
  36705. linePath.dirty();
  36706. };
  36707. inherits(Line$1, Group);
  36708. /**
  36709. * @module echarts/chart/helper/LineDraw
  36710. */
  36711. function isPointNaN(pt) {
  36712. return isNaN(pt[0]) || isNaN(pt[1]);
  36713. }
  36714. function lineNeedsDraw(pts) {
  36715. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  36716. }
  36717. /**
  36718. * @alias module:echarts/component/marker/LineDraw
  36719. * @constructor
  36720. */
  36721. function LineDraw(ctor) {
  36722. this._ctor = ctor || Line$1;
  36723. this.group = new Group();
  36724. }
  36725. var lineDrawProto = LineDraw.prototype;
  36726. /**
  36727. * @param {module:echarts/data/List} lineData
  36728. */
  36729. lineDrawProto.updateData = function (lineData) {
  36730. var oldLineData = this._lineData;
  36731. var group = this.group;
  36732. var LineCtor = this._ctor;
  36733. var hostModel = lineData.hostModel;
  36734. var seriesScope = {
  36735. lineStyle: hostModel.getModel('lineStyle.normal').getLineStyle(),
  36736. hoverLineStyle: hostModel.getModel('lineStyle.emphasis').getLineStyle(),
  36737. labelModel: hostModel.getModel('label.normal'),
  36738. hoverLabelModel: hostModel.getModel('label.emphasis')
  36739. };
  36740. lineData.diff(oldLineData)
  36741. .add(function (idx) {
  36742. if (!lineNeedsDraw(lineData.getItemLayout(idx))) {
  36743. return;
  36744. }
  36745. var lineGroup = new LineCtor(lineData, idx, seriesScope);
  36746. lineData.setItemGraphicEl(idx, lineGroup);
  36747. group.add(lineGroup);
  36748. })
  36749. .update(function (newIdx, oldIdx) {
  36750. var lineGroup = oldLineData.getItemGraphicEl(oldIdx);
  36751. if (!lineNeedsDraw(lineData.getItemLayout(newIdx))) {
  36752. group.remove(lineGroup);
  36753. return;
  36754. }
  36755. if (!lineGroup) {
  36756. lineGroup = new LineCtor(lineData, newIdx, seriesScope);
  36757. }
  36758. else {
  36759. lineGroup.updateData(lineData, newIdx, seriesScope);
  36760. }
  36761. lineData.setItemGraphicEl(newIdx, lineGroup);
  36762. group.add(lineGroup);
  36763. })
  36764. .remove(function (idx) {
  36765. group.remove(oldLineData.getItemGraphicEl(idx));
  36766. })
  36767. .execute();
  36768. this._lineData = lineData;
  36769. };
  36770. lineDrawProto.updateLayout = function () {
  36771. var lineData = this._lineData;
  36772. lineData.eachItemGraphicEl(function (el, idx) {
  36773. el.updateLayout(lineData, idx);
  36774. }, this);
  36775. };
  36776. lineDrawProto.remove = function () {
  36777. this.group.removeAll();
  36778. };
  36779. var v1 = [];
  36780. var v2 = [];
  36781. var v3 = [];
  36782. var quadraticAt$1 = quadraticAt;
  36783. var v2DistSquare = distSquare;
  36784. var mathAbs$1 = Math.abs;
  36785. function intersectCurveCircle(curvePoints, center, radius) {
  36786. var p0 = curvePoints[0];
  36787. var p1 = curvePoints[1];
  36788. var p2 = curvePoints[2];
  36789. var d = Infinity;
  36790. var t;
  36791. var radiusSquare = radius * radius;
  36792. var interval = 0.1;
  36793. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  36794. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  36795. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  36796. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  36797. if (diff < d) {
  36798. d = diff;
  36799. t = _t;
  36800. }
  36801. }
  36802. // Assume the segment is monotone,Find root through Bisection method
  36803. // At most 32 iteration
  36804. for (var i = 0; i < 32; i++) {
  36805. // var prev = t - interval;
  36806. var next = t + interval;
  36807. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  36808. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  36809. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  36810. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  36811. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  36812. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  36813. var diff = v2DistSquare(v2, center) - radiusSquare;
  36814. if (mathAbs$1(diff) < 1e-2) {
  36815. break;
  36816. }
  36817. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  36818. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  36819. interval /= 2;
  36820. if (diff < 0) {
  36821. if (nextDiff >= 0) {
  36822. t = t + interval;
  36823. }
  36824. else {
  36825. t = t - interval;
  36826. }
  36827. }
  36828. else {
  36829. if (nextDiff >= 0) {
  36830. t = t - interval;
  36831. }
  36832. else {
  36833. t = t + interval;
  36834. }
  36835. }
  36836. }
  36837. return t;
  36838. }
  36839. // Adjust edge to avoid
  36840. var adjustEdge = function (graph, scale$$1) {
  36841. var tmp0 = [];
  36842. var quadraticSubdivide$$1 = quadraticSubdivide;
  36843. var pts = [[], [], []];
  36844. var pts2 = [[], []];
  36845. var v = [];
  36846. scale$$1 /= 2;
  36847. function getSymbolSize(node) {
  36848. var symbolSize = node.getVisual('symbolSize');
  36849. if (symbolSize instanceof Array) {
  36850. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  36851. }
  36852. return symbolSize;
  36853. }
  36854. graph.eachEdge(function (edge, idx) {
  36855. var linePoints = edge.getLayout();
  36856. var fromSymbol = edge.getVisual('fromSymbol');
  36857. var toSymbol = edge.getVisual('toSymbol');
  36858. if (!linePoints.__original) {
  36859. linePoints.__original = [
  36860. clone$1(linePoints[0]),
  36861. clone$1(linePoints[1])
  36862. ];
  36863. if (linePoints[2]) {
  36864. linePoints.__original.push(clone$1(linePoints[2]));
  36865. }
  36866. }
  36867. var originalPoints = linePoints.__original;
  36868. // Quadratic curve
  36869. if (linePoints[2] != null) {
  36870. copy(pts[0], originalPoints[0]);
  36871. copy(pts[1], originalPoints[2]);
  36872. copy(pts[2], originalPoints[1]);
  36873. if (fromSymbol && fromSymbol != 'none') {
  36874. var symbolSize = getSymbolSize(edge.node1);
  36875. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  36876. // Subdivide and get the second
  36877. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  36878. pts[0][0] = tmp0[3];
  36879. pts[1][0] = tmp0[4];
  36880. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  36881. pts[0][1] = tmp0[3];
  36882. pts[1][1] = tmp0[4];
  36883. }
  36884. if (toSymbol && toSymbol != 'none') {
  36885. var symbolSize = getSymbolSize(edge.node2);
  36886. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  36887. // Subdivide and get the first
  36888. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  36889. pts[1][0] = tmp0[1];
  36890. pts[2][0] = tmp0[2];
  36891. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  36892. pts[1][1] = tmp0[1];
  36893. pts[2][1] = tmp0[2];
  36894. }
  36895. // Copy back to layout
  36896. copy(linePoints[0], pts[0]);
  36897. copy(linePoints[1], pts[2]);
  36898. copy(linePoints[2], pts[1]);
  36899. }
  36900. // Line
  36901. else {
  36902. copy(pts2[0], originalPoints[0]);
  36903. copy(pts2[1], originalPoints[1]);
  36904. sub(v, pts2[1], pts2[0]);
  36905. normalize(v, v);
  36906. if (fromSymbol && fromSymbol != 'none') {
  36907. var symbolSize = getSymbolSize(edge.node1);
  36908. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  36909. }
  36910. if (toSymbol && toSymbol != 'none') {
  36911. var symbolSize = getSymbolSize(edge.node2);
  36912. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  36913. }
  36914. copy(linePoints[0], pts2[0]);
  36915. copy(linePoints[1], pts2[1]);
  36916. }
  36917. });
  36918. };
  36919. var nodeOpacityPath = ['itemStyle', 'normal', 'opacity'];
  36920. var lineOpacityPath = ['lineStyle', 'normal', 'opacity'];
  36921. function getItemOpacity(item, opacityPath) {
  36922. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  36923. }
  36924. function fadeOutItem(item, opacityPath, opacityRatio) {
  36925. var el = item.getGraphicEl();
  36926. var opacity = getItemOpacity(item, opacityPath);
  36927. if (opacityRatio != null) {
  36928. opacity == null && (opacity = 1);
  36929. opacity *= opacityRatio;
  36930. }
  36931. el.downplay && el.downplay();
  36932. el.traverse(function (child) {
  36933. if (child.type !== 'group') {
  36934. child.setStyle('opacity', opacity);
  36935. }
  36936. });
  36937. }
  36938. function fadeInItem(item, opacityPath) {
  36939. var opacity = getItemOpacity(item, opacityPath);
  36940. var el = item.getGraphicEl();
  36941. el.highlight && el.highlight();
  36942. el.traverse(function (child) {
  36943. if (child.type !== 'group') {
  36944. child.setStyle('opacity', opacity);
  36945. }
  36946. });
  36947. }
  36948. extendChartView({
  36949. type: 'graph',
  36950. init: function (ecModel, api) {
  36951. var symbolDraw = new SymbolDraw();
  36952. var lineDraw = new LineDraw();
  36953. var group = this.group;
  36954. this._controller = new RoamController(api.getZr());
  36955. this._controllerHost = {target: group};
  36956. group.add(symbolDraw.group);
  36957. group.add(lineDraw.group);
  36958. this._symbolDraw = symbolDraw;
  36959. this._lineDraw = lineDraw;
  36960. this._firstRender = true;
  36961. },
  36962. render: function (seriesModel, ecModel, api) {
  36963. var coordSys = seriesModel.coordinateSystem;
  36964. this._model = seriesModel;
  36965. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  36966. var symbolDraw = this._symbolDraw;
  36967. var lineDraw = this._lineDraw;
  36968. var group = this.group;
  36969. if (coordSys.type === 'view') {
  36970. var groupNewProp = {
  36971. position: coordSys.position,
  36972. scale: coordSys.scale
  36973. };
  36974. if (this._firstRender) {
  36975. group.attr(groupNewProp);
  36976. }
  36977. else {
  36978. updateProps(group, groupNewProp, seriesModel);
  36979. }
  36980. }
  36981. // Fix edge contact point with node
  36982. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  36983. var data = seriesModel.getData();
  36984. symbolDraw.updateData(data);
  36985. var edgeData = seriesModel.getEdgeData();
  36986. lineDraw.updateData(edgeData);
  36987. this._updateNodeAndLinkScale();
  36988. this._updateController(seriesModel, ecModel, api);
  36989. clearTimeout(this._layoutTimeout);
  36990. var forceLayout = seriesModel.forceLayout;
  36991. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  36992. if (forceLayout) {
  36993. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  36994. }
  36995. data.eachItemGraphicEl(function (el, idx) {
  36996. var itemModel = data.getItemModel(idx);
  36997. // Update draggable
  36998. el.off('drag').off('dragend');
  36999. var draggable = data.getItemModel(idx).get('draggable');
  37000. if (draggable) {
  37001. el.on('drag', function () {
  37002. if (forceLayout) {
  37003. forceLayout.warmUp();
  37004. !this._layouting
  37005. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  37006. forceLayout.setFixed(idx);
  37007. // Write position back to layout
  37008. data.setItemLayout(idx, el.position);
  37009. }
  37010. }, this).on('dragend', function () {
  37011. if (forceLayout) {
  37012. forceLayout.setUnfixed(idx);
  37013. }
  37014. }, this);
  37015. }
  37016. el.setDraggable(draggable && forceLayout);
  37017. el.off('mouseover', el.__focusNodeAdjacency);
  37018. el.off('mouseout', el.__unfocusNodeAdjacency);
  37019. if (itemModel.get('focusNodeAdjacency')) {
  37020. el.on('mouseover', el.__focusNodeAdjacency = function () {
  37021. api.dispatchAction({
  37022. type: 'focusNodeAdjacency',
  37023. seriesId: seriesModel.id,
  37024. dataIndex: el.dataIndex
  37025. });
  37026. });
  37027. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  37028. api.dispatchAction({
  37029. type: 'unfocusNodeAdjacency',
  37030. seriesId: seriesModel.id
  37031. });
  37032. });
  37033. }
  37034. }, this);
  37035. data.graph.eachEdge(function (edge) {
  37036. var el = edge.getGraphicEl();
  37037. el.off('mouseover', el.__focusNodeAdjacency);
  37038. el.off('mouseout', el.__unfocusNodeAdjacency);
  37039. if (edge.getModel().get('focusNodeAdjacency')) {
  37040. el.on('mouseover', el.__focusNodeAdjacency = function () {
  37041. api.dispatchAction({
  37042. type: 'focusNodeAdjacency',
  37043. seriesId: seriesModel.id,
  37044. edgeDataIndex: edge.dataIndex
  37045. });
  37046. });
  37047. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  37048. api.dispatchAction({
  37049. type: 'unfocusNodeAdjacency',
  37050. seriesId: seriesModel.id
  37051. });
  37052. });
  37053. }
  37054. });
  37055. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  37056. && seriesModel.get('circular.rotateLabel');
  37057. var cx = data.getLayout('cx');
  37058. var cy = data.getLayout('cy');
  37059. data.eachItemGraphicEl(function (el, idx) {
  37060. var symbolPath = el.getSymbolPath();
  37061. if (circularRotateLabel) {
  37062. var pos = data.getItemLayout(idx);
  37063. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  37064. if (rad < 0) {
  37065. rad = Math.PI * 2 + rad;
  37066. }
  37067. var isLeft = pos[0] < cx;
  37068. if (isLeft) {
  37069. rad = rad - Math.PI;
  37070. }
  37071. var textPosition = isLeft ? 'left' : 'right';
  37072. symbolPath.setStyle({
  37073. textRotation: -rad,
  37074. textPosition: textPosition,
  37075. textOrigin: 'center'
  37076. });
  37077. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  37078. }
  37079. else {
  37080. symbolPath.setStyle({
  37081. textRotation: 0
  37082. });
  37083. }
  37084. });
  37085. this._firstRender = false;
  37086. },
  37087. dispose: function () {
  37088. this._controller && this._controller.dispose();
  37089. this._controllerHost = {};
  37090. },
  37091. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  37092. var data = this._model.getData();
  37093. var graph = data.graph;
  37094. var dataIndex = payload.dataIndex;
  37095. var edgeDataIndex = payload.edgeDataIndex;
  37096. var node = graph.getNodeByIndex(dataIndex);
  37097. var edge = graph.getEdgeByIndex(edgeDataIndex);
  37098. if (!node && !edge) {
  37099. return;
  37100. }
  37101. graph.eachNode(function (node) {
  37102. fadeOutItem(node, nodeOpacityPath, 0.1);
  37103. });
  37104. graph.eachEdge(function (edge) {
  37105. fadeOutItem(edge, lineOpacityPath, 0.1);
  37106. });
  37107. if (node) {
  37108. fadeInItem(node, nodeOpacityPath);
  37109. each$1(node.edges, function (adjacentEdge) {
  37110. if (adjacentEdge.dataIndex < 0) {
  37111. return;
  37112. }
  37113. fadeInItem(adjacentEdge, lineOpacityPath);
  37114. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  37115. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  37116. });
  37117. }
  37118. if (edge) {
  37119. fadeInItem(edge, lineOpacityPath);
  37120. fadeInItem(edge.node1, nodeOpacityPath);
  37121. fadeInItem(edge.node2, nodeOpacityPath);
  37122. }
  37123. },
  37124. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  37125. var graph = this._model.getData().graph;
  37126. graph.eachNode(function (node) {
  37127. fadeOutItem(node, nodeOpacityPath);
  37128. });
  37129. graph.eachEdge(function (edge) {
  37130. fadeOutItem(edge, lineOpacityPath);
  37131. });
  37132. },
  37133. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  37134. var self = this;
  37135. (function step() {
  37136. forceLayout.step(function (stopped) {
  37137. self.updateLayout(self._model);
  37138. (self._layouting = !stopped) && (
  37139. layoutAnimation
  37140. ? (self._layoutTimeout = setTimeout(step, 16))
  37141. : step()
  37142. );
  37143. });
  37144. })();
  37145. },
  37146. _updateController: function (seriesModel, ecModel, api) {
  37147. var controller = this._controller;
  37148. var controllerHost = this._controllerHost;
  37149. var group = this.group;
  37150. controller.setPointerChecker(function (e, x, y) {
  37151. var rect = group.getBoundingRect();
  37152. rect.applyTransform(group.transform);
  37153. return rect.contain(x, y)
  37154. && !onIrrelevantElement(e, api, seriesModel);
  37155. });
  37156. if (seriesModel.coordinateSystem.type !== 'view') {
  37157. controller.disable();
  37158. return;
  37159. }
  37160. controller.enable(seriesModel.get('roam'));
  37161. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  37162. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  37163. controller
  37164. .off('pan')
  37165. .off('zoom')
  37166. .on('pan', function (dx, dy) {
  37167. updateViewOnPan(controllerHost, dx, dy);
  37168. api.dispatchAction({
  37169. seriesId: seriesModel.id,
  37170. type: 'graphRoam',
  37171. dx: dx,
  37172. dy: dy
  37173. });
  37174. })
  37175. .on('zoom', function (zoom, mouseX, mouseY) {
  37176. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  37177. api.dispatchAction({
  37178. seriesId: seriesModel.id,
  37179. type: 'graphRoam',
  37180. zoom: zoom,
  37181. originX: mouseX,
  37182. originY: mouseY
  37183. });
  37184. this._updateNodeAndLinkScale();
  37185. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  37186. this._lineDraw.updateLayout();
  37187. }, this);
  37188. },
  37189. _updateNodeAndLinkScale: function () {
  37190. var seriesModel = this._model;
  37191. var data = seriesModel.getData();
  37192. var nodeScale = this._getNodeGlobalScale(seriesModel);
  37193. var invScale = [nodeScale, nodeScale];
  37194. data.eachItemGraphicEl(function (el, idx) {
  37195. el.attr('scale', invScale);
  37196. });
  37197. },
  37198. _getNodeGlobalScale: function (seriesModel) {
  37199. var coordSys = seriesModel.coordinateSystem;
  37200. if (coordSys.type !== 'view') {
  37201. return 1;
  37202. }
  37203. var nodeScaleRatio = this._nodeScaleRatio;
  37204. var groupScale = coordSys.scale;
  37205. var groupZoom = (groupScale && groupScale[0]) || 1;
  37206. // Scale node when zoom changes
  37207. var roamZoom = coordSys.getZoom();
  37208. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  37209. return nodeScale / groupZoom;
  37210. },
  37211. updateLayout: function (seriesModel) {
  37212. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  37213. this._symbolDraw.updateLayout();
  37214. this._lineDraw.updateLayout();
  37215. },
  37216. remove: function (ecModel, api) {
  37217. this._symbolDraw && this._symbolDraw.remove();
  37218. this._lineDraw && this._lineDraw.remove();
  37219. }
  37220. });
  37221. var actionInfo = {
  37222. type: 'graphRoam',
  37223. event: 'graphRoam',
  37224. update: 'none'
  37225. };
  37226. /**
  37227. * @payload
  37228. * @property {string} name Series name
  37229. * @property {number} [dx]
  37230. * @property {number} [dy]
  37231. * @property {number} [zoom]
  37232. * @property {number} [originX]
  37233. * @property {number} [originY]
  37234. */
  37235. registerAction(actionInfo, function (payload, ecModel) {
  37236. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  37237. var coordSys = seriesModel.coordinateSystem;
  37238. var res = updateCenterAndZoom(coordSys, payload);
  37239. seriesModel.setCenter
  37240. && seriesModel.setCenter(res.center);
  37241. seriesModel.setZoom
  37242. && seriesModel.setZoom(res.zoom);
  37243. });
  37244. });
  37245. /**
  37246. * @payload
  37247. * @property {number} [seriesIndex]
  37248. * @property {string} [seriesId]
  37249. * @property {string} [seriesName]
  37250. * @property {number} [dataIndex]
  37251. */
  37252. registerAction({
  37253. type: 'focusNodeAdjacency',
  37254. event: 'focusNodeAdjacency',
  37255. update: 'series.graph:focusNodeAdjacency'
  37256. }, function () {});
  37257. /**
  37258. * @payload
  37259. * @property {number} [seriesIndex]
  37260. * @property {string} [seriesId]
  37261. * @property {string} [seriesName]
  37262. */
  37263. registerAction({
  37264. type: 'unfocusNodeAdjacency',
  37265. event: 'unfocusNodeAdjacency',
  37266. update: 'series.graph:unfocusNodeAdjacency'
  37267. }, function () {});
  37268. var categoryFilter = function (ecModel) {
  37269. var legendModels = ecModel.findComponents({
  37270. mainType: 'legend'
  37271. });
  37272. if (!legendModels || !legendModels.length) {
  37273. return;
  37274. }
  37275. ecModel.eachSeriesByType('graph', function (graphSeries) {
  37276. var categoriesData = graphSeries.getCategoriesData();
  37277. var graph = graphSeries.getGraph();
  37278. var data = graph.data;
  37279. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  37280. data.filterSelf(function (idx) {
  37281. var model = data.getItemModel(idx);
  37282. var category = model.getShallow('category');
  37283. if (category != null) {
  37284. if (typeof category === 'number') {
  37285. category = categoryNames[category];
  37286. }
  37287. // If in any legend component the status is not selected.
  37288. for (var i = 0; i < legendModels.length; i++) {
  37289. if (!legendModels[i].isSelected(category)) {
  37290. return false;
  37291. }
  37292. }
  37293. }
  37294. return true;
  37295. });
  37296. }, this);
  37297. };
  37298. var categoryVisual = function (ecModel) {
  37299. var paletteScope = {};
  37300. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37301. var categoriesData = seriesModel.getCategoriesData();
  37302. var data = seriesModel.getData();
  37303. var categoryNameIdxMap = {};
  37304. categoriesData.each(function (idx) {
  37305. var name = categoriesData.getName(idx);
  37306. // Add prefix to avoid conflict with Object.prototype.
  37307. categoryNameIdxMap['ec-' + name] = idx;
  37308. var itemModel = categoriesData.getItemModel(idx);
  37309. var color = itemModel.get('itemStyle.normal.color')
  37310. || seriesModel.getColorFromPalette(name, paletteScope);
  37311. categoriesData.setItemVisual(idx, 'color', color);
  37312. });
  37313. // Assign category color to visual
  37314. if (categoriesData.count()) {
  37315. data.each(function (idx) {
  37316. var model = data.getItemModel(idx);
  37317. var category = model.getShallow('category');
  37318. if (category != null) {
  37319. if (typeof category === 'string') {
  37320. category = categoryNameIdxMap['ec-' + category];
  37321. }
  37322. if (!data.getItemVisual(idx, 'color', true)) {
  37323. data.setItemVisual(
  37324. idx, 'color',
  37325. categoriesData.getItemVisual(category, 'color')
  37326. );
  37327. }
  37328. }
  37329. });
  37330. }
  37331. });
  37332. };
  37333. function normalize$1(a) {
  37334. if (!(a instanceof Array)) {
  37335. a = [a, a];
  37336. }
  37337. return a;
  37338. }
  37339. var edgeVisual = function (ecModel) {
  37340. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37341. var graph = seriesModel.getGraph();
  37342. var edgeData = seriesModel.getEdgeData();
  37343. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  37344. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  37345. var colorQuery = 'lineStyle.normal.color'.split('.');
  37346. var opacityQuery = 'lineStyle.normal.opacity'.split('.');
  37347. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  37348. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  37349. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  37350. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  37351. edgeData.setVisual('color', seriesModel.get(colorQuery));
  37352. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  37353. edgeData.each(function (idx) {
  37354. var itemModel = edgeData.getItemModel(idx);
  37355. var edge = graph.getEdgeByIndex(idx);
  37356. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  37357. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  37358. // Edge visual must after node visual
  37359. var color = itemModel.get(colorQuery);
  37360. var opacity = itemModel.get(opacityQuery);
  37361. switch (color) {
  37362. case 'source':
  37363. color = edge.node1.getVisual('color');
  37364. break;
  37365. case 'target':
  37366. color = edge.node2.getVisual('color');
  37367. break;
  37368. }
  37369. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  37370. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  37371. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  37372. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  37373. edge.setVisual('color', color);
  37374. edge.setVisual('opacity', opacity);
  37375. });
  37376. });
  37377. };
  37378. function simpleLayout$1(seriesModel) {
  37379. var coordSys = seriesModel.coordinateSystem;
  37380. if (coordSys && coordSys.type !== 'view') {
  37381. return;
  37382. }
  37383. var graph = seriesModel.getGraph();
  37384. graph.eachNode(function (node) {
  37385. var model = node.getModel();
  37386. node.setLayout([+model.get('x'), +model.get('y')]);
  37387. });
  37388. simpleLayoutEdge(graph);
  37389. }
  37390. function simpleLayoutEdge(graph) {
  37391. graph.eachEdge(function (edge) {
  37392. var curveness = edge.getModel().get('lineStyle.normal.curveness') || 0;
  37393. var p1 = clone$1(edge.node1.getLayout());
  37394. var p2 = clone$1(edge.node2.getLayout());
  37395. var points = [p1, p2];
  37396. if (+curveness) {
  37397. points.push([
  37398. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  37399. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  37400. ]);
  37401. }
  37402. edge.setLayout(points);
  37403. });
  37404. }
  37405. var simpleLayout = function (ecModel, api) {
  37406. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37407. var layout = seriesModel.get('layout');
  37408. var coordSys = seriesModel.coordinateSystem;
  37409. if (coordSys && coordSys.type !== 'view') {
  37410. var data = seriesModel.getData();
  37411. var dimensions = coordSys.dimensions;
  37412. data.each(dimensions, function () {
  37413. var hasValue;
  37414. var args = arguments;
  37415. var value = [];
  37416. for (var i = 0; i < dimensions.length; i++) {
  37417. if (!isNaN(args[i])) {
  37418. hasValue = true;
  37419. }
  37420. value.push(args[i]);
  37421. }
  37422. var idx = args[args.length - 1];
  37423. if (hasValue) {
  37424. data.setItemLayout(idx, coordSys.dataToPoint(value));
  37425. }
  37426. else {
  37427. // Also {Array.<number>}, not undefined to avoid if...else... statement
  37428. data.setItemLayout(idx, [NaN, NaN]);
  37429. }
  37430. });
  37431. simpleLayoutEdge(data.graph);
  37432. }
  37433. else if (!layout || layout === 'none') {
  37434. simpleLayout$1(seriesModel);
  37435. }
  37436. });
  37437. };
  37438. function circularLayout$1(seriesModel) {
  37439. var coordSys = seriesModel.coordinateSystem;
  37440. if (coordSys && coordSys.type !== 'view') {
  37441. return;
  37442. }
  37443. var rect = coordSys.getBoundingRect();
  37444. var nodeData = seriesModel.getData();
  37445. var graph = nodeData.graph;
  37446. var angle = 0;
  37447. var sum = nodeData.getSum('value');
  37448. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  37449. var cx = rect.width / 2 + rect.x;
  37450. var cy = rect.height / 2 + rect.y;
  37451. var r = Math.min(rect.width, rect.height) / 2;
  37452. graph.eachNode(function (node) {
  37453. var value = node.getValue('value');
  37454. angle += unitAngle * (sum ? value : 1) / 2;
  37455. node.setLayout([
  37456. r * Math.cos(angle) + cx,
  37457. r * Math.sin(angle) + cy
  37458. ]);
  37459. angle += unitAngle * (sum ? value : 1) / 2;
  37460. });
  37461. nodeData.setLayout({
  37462. cx: cx,
  37463. cy: cy
  37464. });
  37465. graph.eachEdge(function (edge) {
  37466. var curveness = edge.getModel().get('lineStyle.normal.curveness') || 0;
  37467. var p1 = clone$1(edge.node1.getLayout());
  37468. var p2 = clone$1(edge.node2.getLayout());
  37469. var cp1;
  37470. var x12 = (p1[0] + p2[0]) / 2;
  37471. var y12 = (p1[1] + p2[1]) / 2;
  37472. if (+curveness) {
  37473. curveness *= 3;
  37474. cp1 = [
  37475. cx * curveness + x12 * (1 - curveness),
  37476. cy * curveness + y12 * (1 - curveness)
  37477. ];
  37478. }
  37479. edge.setLayout([p1, p2, cp1]);
  37480. });
  37481. }
  37482. var circularLayout = function (ecModel) {
  37483. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37484. if (seriesModel.get('layout') === 'circular') {
  37485. circularLayout$1(seriesModel);
  37486. }
  37487. });
  37488. };
  37489. var scaleAndAdd$2 = scaleAndAdd;
  37490. // function adjacentNode(n, e) {
  37491. // return e.n1 === n ? e.n2 : e.n1;
  37492. // }
  37493. function forceLayout$1(nodes, edges, opts) {
  37494. var rect = opts.rect;
  37495. var width = rect.width;
  37496. var height = rect.height;
  37497. var center = [rect.x + width / 2, rect.y + height / 2];
  37498. // var scale = opts.scale || 1;
  37499. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  37500. // for (var i = 0; i < edges.length; i++) {
  37501. // var e = edges[i];
  37502. // var n1 = e.n1;
  37503. // var n2 = e.n2;
  37504. // n1.edges = n1.edges || [];
  37505. // n2.edges = n2.edges || [];
  37506. // n1.edges.push(e);
  37507. // n2.edges.push(e);
  37508. // }
  37509. // Init position
  37510. for (var i = 0; i < nodes.length; i++) {
  37511. var n = nodes[i];
  37512. if (!n.p) {
  37513. // Use the position from first adjecent node with defined position
  37514. // Or use a random position
  37515. // From d3
  37516. // if (n.edges) {
  37517. // var j = -1;
  37518. // while (++j < n.edges.length) {
  37519. // var e = n.edges[j];
  37520. // var other = adjacentNode(n, e);
  37521. // if (other.p) {
  37522. // n.p = vec2.clone(other.p);
  37523. // break;
  37524. // }
  37525. // }
  37526. // }
  37527. // if (!n.p) {
  37528. n.p = create(
  37529. width * (Math.random() - 0.5) + center[0],
  37530. height * (Math.random() - 0.5) + center[1]
  37531. );
  37532. // }
  37533. }
  37534. n.pp = clone$1(n.p);
  37535. n.edges = null;
  37536. }
  37537. // Formula in 'Graph Drawing by Force-directed Placement'
  37538. // var k = scale * Math.sqrt(width * height / nodes.length);
  37539. // var k2 = k * k;
  37540. var friction = 0.6;
  37541. return {
  37542. warmUp: function () {
  37543. friction = 0.5;
  37544. },
  37545. setFixed: function (idx) {
  37546. nodes[idx].fixed = true;
  37547. },
  37548. setUnfixed: function (idx) {
  37549. nodes[idx].fixed = false;
  37550. },
  37551. step: function (cb) {
  37552. var v12 = [];
  37553. var nLen = nodes.length;
  37554. for (var i = 0; i < edges.length; i++) {
  37555. var e = edges[i];
  37556. var n1 = e.n1;
  37557. var n2 = e.n2;
  37558. sub(v12, n2.p, n1.p);
  37559. var d = len(v12) - e.d;
  37560. var w = n2.w / (n1.w + n2.w);
  37561. if (isNaN(w)) {
  37562. w = 0;
  37563. }
  37564. normalize(v12, v12);
  37565. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  37566. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  37567. }
  37568. // Gravity
  37569. for (var i = 0; i < nLen; i++) {
  37570. var n = nodes[i];
  37571. if (!n.fixed) {
  37572. sub(v12, center, n.p);
  37573. // var d = vec2.len(v12);
  37574. // vec2.scale(v12, v12, 1 / d);
  37575. // var gravityFactor = gravity;
  37576. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  37577. }
  37578. }
  37579. // Repulsive
  37580. // PENDING
  37581. for (var i = 0; i < nLen; i++) {
  37582. var n1 = nodes[i];
  37583. for (var j = i + 1; j < nLen; j++) {
  37584. var n2 = nodes[j];
  37585. sub(v12, n2.p, n1.p);
  37586. var d = len(v12);
  37587. if (d === 0) {
  37588. // Random repulse
  37589. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  37590. d = 1;
  37591. }
  37592. var repFact = (n1.rep + n2.rep) / d / d;
  37593. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  37594. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  37595. }
  37596. }
  37597. var v = [];
  37598. for (var i = 0; i < nLen; i++) {
  37599. var n = nodes[i];
  37600. if (!n.fixed) {
  37601. sub(v, n.p, n.pp);
  37602. scaleAndAdd$2(n.p, n.p, v, friction);
  37603. copy(n.pp, n.p);
  37604. }
  37605. }
  37606. friction = friction * 0.992;
  37607. cb && cb(nodes, edges, friction < 0.01);
  37608. }
  37609. };
  37610. }
  37611. var forceLayout = function (ecModel) {
  37612. ecModel.eachSeriesByType('graph', function (graphSeries) {
  37613. var coordSys = graphSeries.coordinateSystem;
  37614. if (coordSys && coordSys.type !== 'view') {
  37615. return;
  37616. }
  37617. if (graphSeries.get('layout') === 'force') {
  37618. var preservedPoints = graphSeries.preservedPoints || {};
  37619. var graph = graphSeries.getGraph();
  37620. var nodeData = graph.data;
  37621. var edgeData = graph.edgeData;
  37622. var forceModel = graphSeries.getModel('force');
  37623. var initLayout = forceModel.get('initLayout');
  37624. if (graphSeries.preservedPoints) {
  37625. nodeData.each(function (idx) {
  37626. var id = nodeData.getId(idx);
  37627. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  37628. });
  37629. }
  37630. else if (!initLayout || initLayout === 'none') {
  37631. simpleLayout$1(graphSeries);
  37632. }
  37633. else if (initLayout === 'circular') {
  37634. circularLayout$1(graphSeries);
  37635. }
  37636. var nodeDataExtent = nodeData.getDataExtent('value');
  37637. var edgeDataExtent = edgeData.getDataExtent('value');
  37638. // var edgeDataExtent = edgeData.getDataExtent('value');
  37639. var repulsion = forceModel.get('repulsion');
  37640. var edgeLength = forceModel.get('edgeLength');
  37641. if (!isArray(repulsion)) {
  37642. repulsion = [repulsion, repulsion];
  37643. }
  37644. if (!isArray(edgeLength)) {
  37645. edgeLength = [edgeLength, edgeLength];
  37646. }
  37647. // Larger value has smaller length
  37648. edgeLength = [edgeLength[1], edgeLength[0]];
  37649. var nodes = nodeData.mapArray('value', function (value, idx) {
  37650. var point = nodeData.getItemLayout(idx);
  37651. var rep = linearMap(value, nodeDataExtent, repulsion);
  37652. if (isNaN(rep)) {
  37653. rep = (repulsion[0] + repulsion[1]) / 2;
  37654. }
  37655. return {
  37656. w: rep,
  37657. rep: rep,
  37658. fixed: nodeData.getItemModel(idx).get('fixed'),
  37659. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  37660. };
  37661. });
  37662. var edges = edgeData.mapArray('value', function (value, idx) {
  37663. var edge = graph.getEdgeByIndex(idx);
  37664. var d = linearMap(value, edgeDataExtent, edgeLength);
  37665. if (isNaN(d)) {
  37666. d = (edgeLength[0] + edgeLength[1]) / 2;
  37667. }
  37668. return {
  37669. n1: nodes[edge.node1.dataIndex],
  37670. n2: nodes[edge.node2.dataIndex],
  37671. d: d,
  37672. curveness: edge.getModel().get('lineStyle.normal.curveness') || 0
  37673. };
  37674. });
  37675. var coordSys = graphSeries.coordinateSystem;
  37676. var rect = coordSys.getBoundingRect();
  37677. var forceInstance = forceLayout$1(nodes, edges, {
  37678. rect: rect,
  37679. gravity: forceModel.get('gravity')
  37680. });
  37681. var oldStep = forceInstance.step;
  37682. forceInstance.step = function (cb) {
  37683. for (var i = 0, l = nodes.length; i < l; i++) {
  37684. if (nodes[i].fixed) {
  37685. // Write back to layout instance
  37686. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  37687. }
  37688. }
  37689. oldStep(function (nodes, edges, stopped) {
  37690. for (var i = 0, l = nodes.length; i < l; i++) {
  37691. if (!nodes[i].fixed) {
  37692. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  37693. }
  37694. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  37695. }
  37696. for (var i = 0, l = edges.length; i < l; i++) {
  37697. var e = edges[i];
  37698. var edge = graph.getEdgeByIndex(i);
  37699. var p1 = e.n1.p;
  37700. var p2 = e.n2.p;
  37701. var points = edge.getLayout();
  37702. points = points ? points.slice() : [];
  37703. points[0] = points[0] || [];
  37704. points[1] = points[1] || [];
  37705. copy(points[0], p1);
  37706. copy(points[1], p2);
  37707. if (+e.curveness) {
  37708. points[2] = [
  37709. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  37710. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  37711. ];
  37712. }
  37713. edge.setLayout(points);
  37714. }
  37715. // Update layout
  37716. cb && cb(stopped);
  37717. });
  37718. };
  37719. graphSeries.forceLayout = forceInstance;
  37720. graphSeries.preservedPoints = preservedPoints;
  37721. // Step to get the layout
  37722. forceInstance.step();
  37723. }
  37724. else {
  37725. // Remove prev injected forceLayout instance
  37726. graphSeries.forceLayout = null;
  37727. }
  37728. });
  37729. };
  37730. // FIXME Where to create the simple view coordinate system
  37731. function getViewRect$1(seriesModel, api, aspect) {
  37732. var option = seriesModel.getBoxLayoutParams();
  37733. option.aspect = aspect;
  37734. return getLayoutRect(option, {
  37735. width: api.getWidth(),
  37736. height: api.getHeight()
  37737. });
  37738. }
  37739. var createView = function (ecModel, api) {
  37740. var viewList = [];
  37741. ecModel.eachSeriesByType('graph', function (seriesModel) {
  37742. var coordSysType = seriesModel.get('coordinateSystem');
  37743. if (!coordSysType || coordSysType === 'view') {
  37744. var data = seriesModel.getData();
  37745. var positions = data.mapArray(function (idx) {
  37746. var itemModel = data.getItemModel(idx);
  37747. return [+itemModel.get('x'), +itemModel.get('y')];
  37748. });
  37749. var min = [];
  37750. var max = [];
  37751. fromPoints(positions, min, max);
  37752. // If width or height is 0
  37753. if (max[0] - min[0] === 0) {
  37754. max[0] += 1;
  37755. min[0] -= 1;
  37756. }
  37757. if (max[1] - min[1] === 0) {
  37758. max[1] += 1;
  37759. min[1] -= 1;
  37760. }
  37761. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  37762. // FIXME If get view rect after data processed?
  37763. var viewRect = getViewRect$1(seriesModel, api, aspect);
  37764. // Position may be NaN, use view rect instead
  37765. if (isNaN(aspect)) {
  37766. min = [viewRect.x, viewRect.y];
  37767. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  37768. }
  37769. var bbWidth = max[0] - min[0];
  37770. var bbHeight = max[1] - min[1];
  37771. var viewWidth = viewRect.width;
  37772. var viewHeight = viewRect.height;
  37773. var viewCoordSys = seriesModel.coordinateSystem = new View();
  37774. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  37775. viewCoordSys.setBoundingRect(
  37776. min[0], min[1], bbWidth, bbHeight
  37777. );
  37778. viewCoordSys.setViewRect(
  37779. viewRect.x, viewRect.y, viewWidth, viewHeight
  37780. );
  37781. // Update roam info
  37782. viewCoordSys.setCenter(seriesModel.get('center'));
  37783. viewCoordSys.setZoom(seriesModel.get('zoom'));
  37784. viewList.push(viewCoordSys);
  37785. }
  37786. });
  37787. return viewList;
  37788. };
  37789. registerProcessor(categoryFilter);
  37790. registerVisual(curry(
  37791. visualSymbol, 'graph', 'circle', null
  37792. ));
  37793. registerVisual(categoryVisual);
  37794. registerVisual(edgeVisual);
  37795. registerLayout(simpleLayout);
  37796. registerLayout(circularLayout);
  37797. registerLayout(forceLayout);
  37798. // Graph view coordinate system
  37799. registerCoordinateSystem('graphView', {
  37800. create: createView
  37801. });
  37802. var GaugeSeries = SeriesModel.extend({
  37803. type: 'series.gauge',
  37804. getInitialData: function (option, ecModel) {
  37805. var list = new List(['value'], this);
  37806. var dataOpt = option.data || [];
  37807. if (!isArray(dataOpt)) {
  37808. dataOpt = [dataOpt];
  37809. }
  37810. // Only use the first data item
  37811. list.initData(dataOpt);
  37812. return list;
  37813. },
  37814. defaultOption: {
  37815. zlevel: 0,
  37816. z: 2,
  37817. // 默认全局居中
  37818. center: ['50%', '50%'],
  37819. legendHoverLink: true,
  37820. radius: '75%',
  37821. startAngle: 225,
  37822. endAngle: -45,
  37823. clockwise: true,
  37824. // 最小值
  37825. min: 0,
  37826. // 最大值
  37827. max: 100,
  37828. // 分割段数,默认为10
  37829. splitNumber: 10,
  37830. // 坐标轴线
  37831. axisLine: {
  37832. // 默认显示,属性show控制显示与否
  37833. show: true,
  37834. lineStyle: { // 属性lineStyle控制线条样式
  37835. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  37836. width: 30
  37837. }
  37838. },
  37839. // 分隔线
  37840. splitLine: {
  37841. // 默认显示,属性show控制显示与否
  37842. show: true,
  37843. // 属性length控制线长
  37844. length: 30,
  37845. // 属性lineStyle(详见lineStyle)控制线条样式
  37846. lineStyle: {
  37847. color: '#eee',
  37848. width: 2,
  37849. type: 'solid'
  37850. }
  37851. },
  37852. // 坐标轴小标记
  37853. axisTick: {
  37854. // 属性show控制显示与否,默认不显示
  37855. show: true,
  37856. // 每份split细分多少段
  37857. splitNumber: 5,
  37858. // 属性length控制线长
  37859. length: 8,
  37860. // 属性lineStyle控制线条样式
  37861. lineStyle: {
  37862. color: '#eee',
  37863. width: 1,
  37864. type: 'solid'
  37865. }
  37866. },
  37867. axisLabel: {
  37868. show: true,
  37869. distance: 5,
  37870. // formatter: null,
  37871. color: 'auto'
  37872. },
  37873. pointer: {
  37874. show: true,
  37875. length: '80%',
  37876. width: 8
  37877. },
  37878. itemStyle: {
  37879. normal: {
  37880. color: 'auto'
  37881. }
  37882. },
  37883. title: {
  37884. show: true,
  37885. // x, y,单位px
  37886. offsetCenter: [0, '-40%'],
  37887. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  37888. color: '#333',
  37889. fontSize: 15
  37890. },
  37891. detail: {
  37892. show: true,
  37893. backgroundColor: 'rgba(0,0,0,0)',
  37894. borderWidth: 0,
  37895. borderColor: '#ccc',
  37896. width: 100,
  37897. height: null, // self-adaption
  37898. padding: [5, 10],
  37899. // x, y,单位px
  37900. offsetCenter: [0, '40%'],
  37901. // formatter: null,
  37902. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  37903. color: 'auto',
  37904. fontSize: 30
  37905. }
  37906. }
  37907. });
  37908. var PointerPath = Path.extend({
  37909. type: 'echartsGaugePointer',
  37910. shape: {
  37911. angle: 0,
  37912. width: 10,
  37913. r: 10,
  37914. x: 0,
  37915. y: 0
  37916. },
  37917. buildPath: function (ctx, shape) {
  37918. var mathCos = Math.cos;
  37919. var mathSin = Math.sin;
  37920. var r = shape.r;
  37921. var width = shape.width;
  37922. var angle = shape.angle;
  37923. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  37924. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  37925. angle = shape.angle - Math.PI / 2;
  37926. ctx.moveTo(x, y);
  37927. ctx.lineTo(
  37928. shape.x + mathCos(angle) * width,
  37929. shape.y + mathSin(angle) * width
  37930. );
  37931. ctx.lineTo(
  37932. shape.x + mathCos(shape.angle) * r,
  37933. shape.y + mathSin(shape.angle) * r
  37934. );
  37935. ctx.lineTo(
  37936. shape.x - mathCos(angle) * width,
  37937. shape.y - mathSin(angle) * width
  37938. );
  37939. ctx.lineTo(x, y);
  37940. return;
  37941. }
  37942. });
  37943. function parsePosition(seriesModel, api) {
  37944. var center = seriesModel.get('center');
  37945. var width = api.getWidth();
  37946. var height = api.getHeight();
  37947. var size = Math.min(width, height);
  37948. var cx = parsePercent$1(center[0], api.getWidth());
  37949. var cy = parsePercent$1(center[1], api.getHeight());
  37950. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  37951. return {
  37952. cx: cx,
  37953. cy: cy,
  37954. r: r
  37955. };
  37956. }
  37957. function formatLabel(label, labelFormatter) {
  37958. if (labelFormatter) {
  37959. if (typeof labelFormatter === 'string') {
  37960. label = labelFormatter.replace('{value}', label != null ? label : '');
  37961. }
  37962. else if (typeof labelFormatter === 'function') {
  37963. label = labelFormatter(label);
  37964. }
  37965. }
  37966. return label;
  37967. }
  37968. var PI2$5 = Math.PI * 2;
  37969. var GaugeView = Chart.extend({
  37970. type: 'gauge',
  37971. render: function (seriesModel, ecModel, api) {
  37972. this.group.removeAll();
  37973. var colorList = seriesModel.get('axisLine.lineStyle.color');
  37974. var posInfo = parsePosition(seriesModel, api);
  37975. this._renderMain(
  37976. seriesModel, ecModel, api, colorList, posInfo
  37977. );
  37978. },
  37979. dispose: function () {},
  37980. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  37981. var group = this.group;
  37982. var axisLineModel = seriesModel.getModel('axisLine');
  37983. var lineStyleModel = axisLineModel.getModel('lineStyle');
  37984. var clockwise = seriesModel.get('clockwise');
  37985. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  37986. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  37987. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  37988. var prevEndAngle = startAngle;
  37989. var axisLineWidth = lineStyleModel.get('width');
  37990. for (var i = 0; i < colorList.length; i++) {
  37991. // Clamp
  37992. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  37993. var endAngle = startAngle + angleRangeSpan * percent;
  37994. var sector = new Sector({
  37995. shape: {
  37996. startAngle: prevEndAngle,
  37997. endAngle: endAngle,
  37998. cx: posInfo.cx,
  37999. cy: posInfo.cy,
  38000. clockwise: clockwise,
  38001. r0: posInfo.r - axisLineWidth,
  38002. r: posInfo.r
  38003. },
  38004. silent: true
  38005. });
  38006. sector.setStyle({
  38007. fill: colorList[i][1]
  38008. });
  38009. sector.setStyle(lineStyleModel.getLineStyle(
  38010. // Because we use sector to simulate arc
  38011. // so the properties for stroking are useless
  38012. ['color', 'borderWidth', 'borderColor']
  38013. ));
  38014. group.add(sector);
  38015. prevEndAngle = endAngle;
  38016. }
  38017. var getColor = function (percent) {
  38018. // Less than 0
  38019. if (percent <= 0) {
  38020. return colorList[0][1];
  38021. }
  38022. for (var i = 0; i < colorList.length; i++) {
  38023. if (colorList[i][0] >= percent
  38024. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  38025. ) {
  38026. return colorList[i][1];
  38027. }
  38028. }
  38029. // More than 1
  38030. return colorList[i - 1][1];
  38031. };
  38032. if (!clockwise) {
  38033. var tmp = startAngle;
  38034. startAngle = endAngle;
  38035. endAngle = tmp;
  38036. }
  38037. this._renderTicks(
  38038. seriesModel, ecModel, api, getColor, posInfo,
  38039. startAngle, endAngle, clockwise
  38040. );
  38041. this._renderPointer(
  38042. seriesModel, ecModel, api, getColor, posInfo,
  38043. startAngle, endAngle, clockwise
  38044. );
  38045. this._renderTitle(
  38046. seriesModel, ecModel, api, getColor, posInfo
  38047. );
  38048. this._renderDetail(
  38049. seriesModel, ecModel, api, getColor, posInfo
  38050. );
  38051. },
  38052. _renderTicks: function (
  38053. seriesModel, ecModel, api, getColor, posInfo,
  38054. startAngle, endAngle, clockwise
  38055. ) {
  38056. var group = this.group;
  38057. var cx = posInfo.cx;
  38058. var cy = posInfo.cy;
  38059. var r = posInfo.r;
  38060. var minVal = +seriesModel.get('min');
  38061. var maxVal = +seriesModel.get('max');
  38062. var splitLineModel = seriesModel.getModel('splitLine');
  38063. var tickModel = seriesModel.getModel('axisTick');
  38064. var labelModel = seriesModel.getModel('axisLabel');
  38065. var splitNumber = seriesModel.get('splitNumber');
  38066. var subSplitNumber = tickModel.get('splitNumber');
  38067. var splitLineLen = parsePercent$1(
  38068. splitLineModel.get('length'), r
  38069. );
  38070. var tickLen = parsePercent$1(
  38071. tickModel.get('length'), r
  38072. );
  38073. var angle = startAngle;
  38074. var step = (endAngle - startAngle) / splitNumber;
  38075. var subStep = step / subSplitNumber;
  38076. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  38077. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  38078. for (var i = 0; i <= splitNumber; i++) {
  38079. var unitX = Math.cos(angle);
  38080. var unitY = Math.sin(angle);
  38081. // Split line
  38082. if (splitLineModel.get('show')) {
  38083. var splitLine = new Line({
  38084. shape: {
  38085. x1: unitX * r + cx,
  38086. y1: unitY * r + cy,
  38087. x2: unitX * (r - splitLineLen) + cx,
  38088. y2: unitY * (r - splitLineLen) + cy
  38089. },
  38090. style: splitLineStyle,
  38091. silent: true
  38092. });
  38093. if (splitLineStyle.stroke === 'auto') {
  38094. splitLine.setStyle({
  38095. stroke: getColor(i / splitNumber)
  38096. });
  38097. }
  38098. group.add(splitLine);
  38099. }
  38100. // Label
  38101. if (labelModel.get('show')) {
  38102. var label = formatLabel(
  38103. round(i / splitNumber * (maxVal - minVal) + minVal),
  38104. labelModel.get('formatter')
  38105. );
  38106. var distance = labelModel.get('distance');
  38107. var autoColor = getColor(i / splitNumber);
  38108. group.add(new Text({
  38109. style: setTextStyle({}, labelModel, {
  38110. text: label,
  38111. x: unitX * (r - splitLineLen - distance) + cx,
  38112. y: unitY * (r - splitLineLen - distance) + cy,
  38113. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  38114. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  38115. }, {autoColor: autoColor}),
  38116. silent: true
  38117. }));
  38118. }
  38119. // Axis tick
  38120. if (tickModel.get('show') && i !== splitNumber) {
  38121. for (var j = 0; j <= subSplitNumber; j++) {
  38122. var unitX = Math.cos(angle);
  38123. var unitY = Math.sin(angle);
  38124. var tickLine = new Line({
  38125. shape: {
  38126. x1: unitX * r + cx,
  38127. y1: unitY * r + cy,
  38128. x2: unitX * (r - tickLen) + cx,
  38129. y2: unitY * (r - tickLen) + cy
  38130. },
  38131. silent: true,
  38132. style: tickLineStyle
  38133. });
  38134. if (tickLineStyle.stroke === 'auto') {
  38135. tickLine.setStyle({
  38136. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  38137. });
  38138. }
  38139. group.add(tickLine);
  38140. angle += subStep;
  38141. }
  38142. angle -= subStep;
  38143. }
  38144. else {
  38145. angle += step;
  38146. }
  38147. }
  38148. },
  38149. _renderPointer: function (
  38150. seriesModel, ecModel, api, getColor, posInfo,
  38151. startAngle, endAngle, clockwise
  38152. ) {
  38153. var group = this.group;
  38154. var oldData = this._data;
  38155. if (!seriesModel.get('pointer.show')) {
  38156. // Remove old element
  38157. oldData && oldData.eachItemGraphicEl(function (el) {
  38158. group.remove(el);
  38159. });
  38160. return;
  38161. }
  38162. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  38163. var angleExtent = [startAngle, endAngle];
  38164. var data = seriesModel.getData();
  38165. data.diff(oldData)
  38166. .add(function (idx) {
  38167. var pointer = new PointerPath({
  38168. shape: {
  38169. angle: startAngle
  38170. }
  38171. });
  38172. initProps(pointer, {
  38173. shape: {
  38174. angle: linearMap(data.get('value', idx), valueExtent, angleExtent, true)
  38175. }
  38176. }, seriesModel);
  38177. group.add(pointer);
  38178. data.setItemGraphicEl(idx, pointer);
  38179. })
  38180. .update(function (newIdx, oldIdx) {
  38181. var pointer = oldData.getItemGraphicEl(oldIdx);
  38182. updateProps(pointer, {
  38183. shape: {
  38184. angle: linearMap(data.get('value', newIdx), valueExtent, angleExtent, true)
  38185. }
  38186. }, seriesModel);
  38187. group.add(pointer);
  38188. data.setItemGraphicEl(newIdx, pointer);
  38189. })
  38190. .remove(function (idx) {
  38191. var pointer = oldData.getItemGraphicEl(idx);
  38192. group.remove(pointer);
  38193. })
  38194. .execute();
  38195. data.eachItemGraphicEl(function (pointer, idx) {
  38196. var itemModel = data.getItemModel(idx);
  38197. var pointerModel = itemModel.getModel('pointer');
  38198. pointer.setShape({
  38199. x: posInfo.cx,
  38200. y: posInfo.cy,
  38201. width: parsePercent$1(
  38202. pointerModel.get('width'), posInfo.r
  38203. ),
  38204. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  38205. });
  38206. pointer.useStyle(itemModel.getModel('itemStyle.normal').getItemStyle());
  38207. if (pointer.style.fill === 'auto') {
  38208. pointer.setStyle('fill', getColor(
  38209. linearMap(data.get('value', idx), valueExtent, [0, 1], true)
  38210. ));
  38211. }
  38212. setHoverStyle(
  38213. pointer, itemModel.getModel('itemStyle.emphasis').getItemStyle()
  38214. );
  38215. });
  38216. this._data = data;
  38217. },
  38218. _renderTitle: function (
  38219. seriesModel, ecModel, api, getColor, posInfo
  38220. ) {
  38221. var titleModel = seriesModel.getModel('title');
  38222. if (titleModel.get('show')) {
  38223. var offsetCenter = titleModel.get('offsetCenter');
  38224. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  38225. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  38226. var minVal = +seriesModel.get('min');
  38227. var maxVal = +seriesModel.get('max');
  38228. var value = seriesModel.getData().get('value', 0);
  38229. var autoColor = getColor(
  38230. linearMap(value, [minVal, maxVal], [0, 1], true)
  38231. );
  38232. this.group.add(new Text({
  38233. silent: true,
  38234. style: setTextStyle({}, titleModel, {
  38235. x: x,
  38236. y: y,
  38237. // FIXME First data name ?
  38238. text: seriesModel.getData().getName(0),
  38239. textAlign: 'center',
  38240. textVerticalAlign: 'middle'
  38241. }, {autoColor: autoColor, forceRich: true})
  38242. }));
  38243. }
  38244. },
  38245. _renderDetail: function (
  38246. seriesModel, ecModel, api, getColor, posInfo
  38247. ) {
  38248. var detailModel = seriesModel.getModel('detail');
  38249. var minVal = +seriesModel.get('min');
  38250. var maxVal = +seriesModel.get('max');
  38251. if (detailModel.get('show')) {
  38252. var offsetCenter = detailModel.get('offsetCenter');
  38253. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  38254. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  38255. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  38256. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  38257. var value = seriesModel.getData().get('value', 0);
  38258. var autoColor = getColor(
  38259. linearMap(value, [minVal, maxVal], [0, 1], true)
  38260. );
  38261. this.group.add(new Text({
  38262. silent: true,
  38263. style: setTextStyle({}, detailModel, {
  38264. x: x,
  38265. y: y,
  38266. text: formatLabel(
  38267. // FIXME First data name ?
  38268. value, detailModel.get('formatter')
  38269. ),
  38270. textWidth: isNaN(width) ? null : width,
  38271. textHeight: isNaN(height) ? null : height,
  38272. textAlign: 'center',
  38273. textVerticalAlign: 'middle'
  38274. }, {autoColor: autoColor, forceRich: true})
  38275. }));
  38276. }
  38277. }
  38278. });
  38279. var FunnelSeries = extendSeriesModel({
  38280. type: 'series.funnel',
  38281. init: function (option) {
  38282. FunnelSeries.superApply(this, 'init', arguments);
  38283. // Enable legend selection for each data item
  38284. // Use a function instead of direct access because data reference may changed
  38285. this.legendDataProvider = function () {
  38286. return this.getRawData();
  38287. };
  38288. // Extend labelLine emphasis
  38289. this._defaultLabelLine(option);
  38290. },
  38291. getInitialData: function (option, ecModel) {
  38292. var dimensions = completeDimensions(['value'], option.data);
  38293. var list = new List(dimensions, this);
  38294. list.initData(option.data);
  38295. return list;
  38296. },
  38297. _defaultLabelLine: function (option) {
  38298. // Extend labelLine emphasis
  38299. defaultEmphasis(option.labelLine, ['show']);
  38300. var labelLineNormalOpt = option.labelLine.normal;
  38301. var labelLineEmphasisOpt = option.labelLine.emphasis;
  38302. // Not show label line if `label.normal.show = false`
  38303. labelLineNormalOpt.show = labelLineNormalOpt.show
  38304. && option.label.normal.show;
  38305. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  38306. && option.label.emphasis.show;
  38307. },
  38308. // Overwrite
  38309. getDataParams: function (dataIndex) {
  38310. var data = this.getData();
  38311. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  38312. var sum = data.getSum('value');
  38313. // Percent is 0 if sum is 0
  38314. params.percent = !sum ? 0 : +(data.get('value', dataIndex) / sum * 100).toFixed(2);
  38315. params.$vars.push('percent');
  38316. return params;
  38317. },
  38318. defaultOption: {
  38319. zlevel: 0, // 一级层叠
  38320. z: 2, // 二级层叠
  38321. legendHoverLink: true,
  38322. left: 80,
  38323. top: 60,
  38324. right: 80,
  38325. bottom: 60,
  38326. // width: {totalWidth} - left - right,
  38327. // height: {totalHeight} - top - bottom,
  38328. // 默认取数据最小最大值
  38329. // min: 0,
  38330. // max: 100,
  38331. minSize: '0%',
  38332. maxSize: '100%',
  38333. sort: 'descending', // 'ascending', 'descending'
  38334. gap: 0,
  38335. funnelAlign: 'center',
  38336. label: {
  38337. normal: {
  38338. show: true,
  38339. position: 'outer'
  38340. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38341. },
  38342. emphasis: {
  38343. show: true
  38344. }
  38345. },
  38346. labelLine: {
  38347. normal: {
  38348. show: true,
  38349. length: 20,
  38350. lineStyle: {
  38351. // color: 各异,
  38352. width: 1,
  38353. type: 'solid'
  38354. }
  38355. },
  38356. emphasis: {}
  38357. },
  38358. itemStyle: {
  38359. normal: {
  38360. // color: 各异,
  38361. borderColor: '#fff',
  38362. borderWidth: 1
  38363. },
  38364. emphasis: {
  38365. // color: 各异,
  38366. }
  38367. }
  38368. }
  38369. });
  38370. /**
  38371. * Piece of pie including Sector, Label, LabelLine
  38372. * @constructor
  38373. * @extends {module:zrender/graphic/Group}
  38374. */
  38375. function FunnelPiece(data, idx) {
  38376. Group.call(this);
  38377. var polygon = new Polygon();
  38378. var labelLine = new Polyline();
  38379. var text = new Text();
  38380. this.add(polygon);
  38381. this.add(labelLine);
  38382. this.add(text);
  38383. this.updateData(data, idx, true);
  38384. // Hover to change label and labelLine
  38385. function onEmphasis() {
  38386. labelLine.ignore = labelLine.hoverIgnore;
  38387. text.ignore = text.hoverIgnore;
  38388. }
  38389. function onNormal() {
  38390. labelLine.ignore = labelLine.normalIgnore;
  38391. text.ignore = text.normalIgnore;
  38392. }
  38393. this.on('emphasis', onEmphasis)
  38394. .on('normal', onNormal)
  38395. .on('mouseover', onEmphasis)
  38396. .on('mouseout', onNormal);
  38397. }
  38398. var funnelPieceProto = FunnelPiece.prototype;
  38399. var opacityAccessPath = ['itemStyle', 'normal', 'opacity'];
  38400. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  38401. var polygon = this.childAt(0);
  38402. var seriesModel = data.hostModel;
  38403. var itemModel = data.getItemModel(idx);
  38404. var layout = data.getItemLayout(idx);
  38405. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  38406. opacity = opacity == null ? 1 : opacity;
  38407. // Reset style
  38408. polygon.useStyle({});
  38409. if (firstCreate) {
  38410. polygon.setShape({
  38411. points: layout.points
  38412. });
  38413. polygon.setStyle({ opacity : 0 });
  38414. initProps(polygon, {
  38415. style: {
  38416. opacity: opacity
  38417. }
  38418. }, seriesModel, idx);
  38419. }
  38420. else {
  38421. updateProps(polygon, {
  38422. style: {
  38423. opacity: opacity
  38424. },
  38425. shape: {
  38426. points: layout.points
  38427. }
  38428. }, seriesModel, idx);
  38429. }
  38430. // Update common style
  38431. var itemStyleModel = itemModel.getModel('itemStyle');
  38432. var visualColor = data.getItemVisual(idx, 'color');
  38433. polygon.setStyle(
  38434. defaults(
  38435. {
  38436. lineJoin: 'round',
  38437. fill: visualColor
  38438. },
  38439. itemStyleModel.getModel('normal').getItemStyle(['opacity'])
  38440. )
  38441. );
  38442. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  38443. this._updateLabel(data, idx);
  38444. setHoverStyle(this);
  38445. };
  38446. funnelPieceProto._updateLabel = function (data, idx) {
  38447. var labelLine = this.childAt(1);
  38448. var labelText = this.childAt(2);
  38449. var seriesModel = data.hostModel;
  38450. var itemModel = data.getItemModel(idx);
  38451. var layout = data.getItemLayout(idx);
  38452. var labelLayout = layout.label;
  38453. var visualColor = data.getItemVisual(idx, 'color');
  38454. updateProps(labelLine, {
  38455. shape: {
  38456. points: labelLayout.linePoints || labelLayout.linePoints
  38457. }
  38458. }, seriesModel, idx);
  38459. updateProps(labelText, {
  38460. style: {
  38461. x: labelLayout.x,
  38462. y: labelLayout.y
  38463. }
  38464. }, seriesModel, idx);
  38465. labelText.attr({
  38466. rotation: labelLayout.rotation,
  38467. origin: [labelLayout.x, labelLayout.y],
  38468. z2: 10
  38469. });
  38470. var labelModel = itemModel.getModel('label.normal');
  38471. var labelHoverModel = itemModel.getModel('label.emphasis');
  38472. var labelLineModel = itemModel.getModel('labelLine.normal');
  38473. var labelLineHoverModel = itemModel.getModel('labelLine.emphasis');
  38474. var visualColor = data.getItemVisual(idx, 'color');
  38475. setLabelStyle(
  38476. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  38477. {
  38478. labelFetcher: data.hostModel,
  38479. labelDataIndex: idx,
  38480. defaultText: data.getName(idx),
  38481. autoColor: visualColor,
  38482. useInsideStyle: !!labelLayout.inside
  38483. },
  38484. {
  38485. textAlign: labelLayout.textAlign,
  38486. textVerticalAlign: labelLayout.verticalAlign
  38487. }
  38488. );
  38489. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  38490. labelText.hoverIgnore = !labelHoverModel.get('show');
  38491. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  38492. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  38493. // Default use item visual color
  38494. labelLine.setStyle({
  38495. stroke: visualColor
  38496. });
  38497. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  38498. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  38499. };
  38500. inherits(FunnelPiece, Group);
  38501. var FunnelView = Chart.extend({
  38502. type: 'funnel',
  38503. render: function (seriesModel, ecModel, api) {
  38504. var data = seriesModel.getData();
  38505. var oldData = this._data;
  38506. var group = this.group;
  38507. data.diff(oldData)
  38508. .add(function (idx) {
  38509. var funnelPiece = new FunnelPiece(data, idx);
  38510. data.setItemGraphicEl(idx, funnelPiece);
  38511. group.add(funnelPiece);
  38512. })
  38513. .update(function (newIdx, oldIdx) {
  38514. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38515. piePiece.updateData(data, newIdx);
  38516. group.add(piePiece);
  38517. data.setItemGraphicEl(newIdx, piePiece);
  38518. })
  38519. .remove(function (idx) {
  38520. var piePiece = oldData.getItemGraphicEl(idx);
  38521. group.remove(piePiece);
  38522. })
  38523. .execute();
  38524. this._data = data;
  38525. },
  38526. remove: function () {
  38527. this.group.removeAll();
  38528. this._data = null;
  38529. },
  38530. dispose: function () {}
  38531. });
  38532. function getViewRect$2(seriesModel, api) {
  38533. return getLayoutRect(
  38534. seriesModel.getBoxLayoutParams(), {
  38535. width: api.getWidth(),
  38536. height: api.getHeight()
  38537. }
  38538. );
  38539. }
  38540. function getSortedIndices(data, sort) {
  38541. var valueArr = data.mapArray('value', function (val) {
  38542. return val;
  38543. });
  38544. var indices = [];
  38545. var isAscending = sort === 'ascending';
  38546. for (var i = 0, len = data.count(); i < len; i++) {
  38547. indices[i] = i;
  38548. }
  38549. // Add custom sortable function & none sortable opetion by "options.sort"
  38550. if (typeof sort === 'function') {
  38551. indices.sort(sort);
  38552. } else if (sort !== 'none') {
  38553. indices.sort(function (a, b) {
  38554. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  38555. });
  38556. }
  38557. return indices;
  38558. }
  38559. function labelLayout$1(data) {
  38560. data.each(function (idx) {
  38561. var itemModel = data.getItemModel(idx);
  38562. var labelModel = itemModel.getModel('label.normal');
  38563. var labelPosition = labelModel.get('position');
  38564. var labelLineModel = itemModel.getModel('labelLine.normal');
  38565. var layout = data.getItemLayout(idx);
  38566. var points = layout.points;
  38567. var isLabelInside = labelPosition === 'inner'
  38568. || labelPosition === 'inside' || labelPosition === 'center';
  38569. var textAlign;
  38570. var textX;
  38571. var textY;
  38572. var linePoints;
  38573. if (isLabelInside) {
  38574. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  38575. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  38576. textAlign = 'center';
  38577. linePoints = [
  38578. [textX, textY], [textX, textY]
  38579. ];
  38580. }
  38581. else {
  38582. var x1;
  38583. var y1;
  38584. var x2;
  38585. var labelLineLen = labelLineModel.get('length');
  38586. if (labelPosition === 'left') {
  38587. // Left side
  38588. x1 = (points[3][0] + points[0][0]) / 2;
  38589. y1 = (points[3][1] + points[0][1]) / 2;
  38590. x2 = x1 - labelLineLen;
  38591. textX = x2 - 5;
  38592. textAlign = 'right';
  38593. }
  38594. else {
  38595. // Right side
  38596. x1 = (points[1][0] + points[2][0]) / 2;
  38597. y1 = (points[1][1] + points[2][1]) / 2;
  38598. x2 = x1 + labelLineLen;
  38599. textX = x2 + 5;
  38600. textAlign = 'left';
  38601. }
  38602. var y2 = y1;
  38603. linePoints = [[x1, y1], [x2, y2]];
  38604. textY = y2;
  38605. }
  38606. layout.label = {
  38607. linePoints: linePoints,
  38608. x: textX,
  38609. y: textY,
  38610. verticalAlign: 'middle',
  38611. textAlign: textAlign,
  38612. inside: isLabelInside
  38613. };
  38614. });
  38615. }
  38616. var funnelLayout = function (ecModel, api, payload) {
  38617. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  38618. var data = seriesModel.getData();
  38619. var sort = seriesModel.get('sort');
  38620. var viewRect = getViewRect$2(seriesModel, api);
  38621. var indices = getSortedIndices(data, sort);
  38622. var sizeExtent = [
  38623. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  38624. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  38625. ];
  38626. var dataExtent = data.getDataExtent('value');
  38627. var min = seriesModel.get('min');
  38628. var max = seriesModel.get('max');
  38629. if (min == null) {
  38630. min = Math.min(dataExtent[0], 0);
  38631. }
  38632. if (max == null) {
  38633. max = dataExtent[1];
  38634. }
  38635. var funnelAlign = seriesModel.get('funnelAlign');
  38636. var gap = seriesModel.get('gap');
  38637. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  38638. var y = viewRect.y;
  38639. var getLinePoints = function (idx, offY) {
  38640. // End point index is data.count() and we assign it 0
  38641. var val = data.get('value', idx) || 0;
  38642. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  38643. var x0;
  38644. switch (funnelAlign) {
  38645. case 'left':
  38646. x0 = viewRect.x;
  38647. break;
  38648. case 'center':
  38649. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  38650. break;
  38651. case 'right':
  38652. x0 = viewRect.x + viewRect.width - itemWidth;
  38653. break;
  38654. }
  38655. return [
  38656. [x0, offY],
  38657. [x0 + itemWidth, offY]
  38658. ];
  38659. };
  38660. if (sort === 'ascending') {
  38661. // From bottom to top
  38662. itemHeight = -itemHeight;
  38663. gap = -gap;
  38664. y += viewRect.height;
  38665. indices = indices.reverse();
  38666. }
  38667. for (var i = 0; i < indices.length; i++) {
  38668. var idx = indices[i];
  38669. var nextIdx = indices[i + 1];
  38670. var start = getLinePoints(idx, y);
  38671. var end = getLinePoints(nextIdx, y + itemHeight);
  38672. y += itemHeight + gap;
  38673. data.setItemLayout(idx, {
  38674. points: start.concat(end.slice().reverse())
  38675. });
  38676. }
  38677. labelLayout$1(data);
  38678. });
  38679. };
  38680. registerVisual(curry(dataColor, 'funnel'));
  38681. registerLayout(funnelLayout);
  38682. registerProcessor(curry(dataFilter, 'funnel'));
  38683. var parallelPreprocessor = function (option) {
  38684. createParallelIfNeeded(option);
  38685. mergeAxisOptionFromParallel(option);
  38686. };
  38687. /**
  38688. * Create a parallel coordinate if not exists.
  38689. * @inner
  38690. */
  38691. function createParallelIfNeeded(option) {
  38692. if (option.parallel) {
  38693. return;
  38694. }
  38695. var hasParallelSeries = false;
  38696. each$1(option.series, function (seriesOpt) {
  38697. if (seriesOpt && seriesOpt.type === 'parallel') {
  38698. hasParallelSeries = true;
  38699. }
  38700. });
  38701. if (hasParallelSeries) {
  38702. option.parallel = [{}];
  38703. }
  38704. }
  38705. /**
  38706. * Merge aixs definition from parallel option (if exists) to axis option.
  38707. * @inner
  38708. */
  38709. function mergeAxisOptionFromParallel(option) {
  38710. var axes = normalizeToArray(option.parallelAxis);
  38711. each$1(axes, function (axisOption) {
  38712. if (!isObject(axisOption)) {
  38713. return;
  38714. }
  38715. var parallelIndex = axisOption.parallelIndex || 0;
  38716. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  38717. if (parallelOption && parallelOption.parallelAxisDefault) {
  38718. merge(axisOption, parallelOption.parallelAxisDefault, false);
  38719. }
  38720. });
  38721. }
  38722. /**
  38723. * @constructor module:echarts/coord/parallel/ParallelAxis
  38724. * @extends {module:echarts/coord/Axis}
  38725. * @param {string} dim
  38726. * @param {*} scale
  38727. * @param {Array.<number>} coordExtent
  38728. * @param {string} axisType
  38729. */
  38730. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  38731. Axis.call(this, dim, scale, coordExtent);
  38732. /**
  38733. * Axis type
  38734. * - 'category'
  38735. * - 'value'
  38736. * - 'time'
  38737. * - 'log'
  38738. * @type {string}
  38739. */
  38740. this.type = axisType || 'value';
  38741. /**
  38742. * @type {number}
  38743. * @readOnly
  38744. */
  38745. this.axisIndex = axisIndex;
  38746. };
  38747. ParallelAxis.prototype = {
  38748. constructor: ParallelAxis,
  38749. /**
  38750. * Axis model
  38751. * @param {module:echarts/coord/parallel/AxisModel}
  38752. */
  38753. model: null,
  38754. /**
  38755. * @override
  38756. */
  38757. isHorizontal: function () {
  38758. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  38759. }
  38760. };
  38761. inherits(ParallelAxis, Axis);
  38762. /**
  38763. * Calculate slider move result.
  38764. * Usage:
  38765. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  38766. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  38767. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  38768. *
  38769. * @param {number} delta Move length.
  38770. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  38771. * handleEnds will be modified in this method.
  38772. * @param {Array.<number>} extent handleEnds is restricted by extent.
  38773. * extent[0] should less or equals than extent[1].
  38774. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  38775. * where the input minSpan and maxSpan will not work.
  38776. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  38777. * If not set, handle0 and cross handle1. If set as a non-negative
  38778. * number (including `0`), handles will push each other when reaching
  38779. * the minSpan.
  38780. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  38781. * @return {Array.<number>} The input handleEnds.
  38782. */
  38783. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  38784. // Normalize firstly.
  38785. handleEnds[0] = restrict$1(handleEnds[0], extent);
  38786. handleEnds[1] = restrict$1(handleEnds[1], extent);
  38787. delta = delta || 0;
  38788. var extentSpan = extent[1] - extent[0];
  38789. // Notice maxSpan and minSpan can be null/undefined.
  38790. if (minSpan != null) {
  38791. minSpan = restrict$1(minSpan, [0, extentSpan]);
  38792. }
  38793. if (maxSpan != null) {
  38794. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  38795. }
  38796. if (handleIndex === 'all') {
  38797. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  38798. handleIndex = 0;
  38799. }
  38800. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  38801. handleEnds[handleIndex] += delta;
  38802. // Restrict in extent.
  38803. var extentMinSpan = minSpan || 0;
  38804. var realExtent = extent.slice();
  38805. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  38806. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  38807. // Expand span.
  38808. var currDistSign = getSpanSign(handleEnds, handleIndex);
  38809. if (minSpan != null && (
  38810. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  38811. )) {
  38812. // If minSpan exists, 'cross' is forbinden.
  38813. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  38814. }
  38815. // Shrink span.
  38816. var currDistSign = getSpanSign(handleEnds, handleIndex);
  38817. if (maxSpan != null && currDistSign.span > maxSpan) {
  38818. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  38819. }
  38820. return handleEnds;
  38821. };
  38822. function getSpanSign(handleEnds, handleIndex) {
  38823. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  38824. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  38825. // is at left of handleEnds[1] for non-cross case.
  38826. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  38827. }
  38828. function restrict$1(value, extend) {
  38829. return Math.min(extend[1], Math.max(extend[0], value));
  38830. }
  38831. /**
  38832. * Parallel Coordinates
  38833. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  38834. */
  38835. var each$14 = each$1;
  38836. var mathMin$5 = Math.min;
  38837. var mathMax$5 = Math.max;
  38838. var mathFloor$2 = Math.floor;
  38839. var mathCeil$2 = Math.ceil;
  38840. var round$2 = round;
  38841. var PI$3 = Math.PI;
  38842. function Parallel(parallelModel, ecModel, api) {
  38843. /**
  38844. * key: dimension
  38845. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  38846. * @private
  38847. */
  38848. this._axesMap = createHashMap();
  38849. /**
  38850. * key: dimension
  38851. * value: {position: [], rotation, }
  38852. * @type {Object.<string, Object>}
  38853. * @private
  38854. */
  38855. this._axesLayout = {};
  38856. /**
  38857. * Always follow axis order.
  38858. * @type {Array.<string>}
  38859. * @readOnly
  38860. */
  38861. this.dimensions = parallelModel.dimensions;
  38862. /**
  38863. * @type {module:zrender/core/BoundingRect}
  38864. */
  38865. this._rect;
  38866. /**
  38867. * @type {module:echarts/coord/parallel/ParallelModel}
  38868. */
  38869. this._model = parallelModel;
  38870. this._init(parallelModel, ecModel, api);
  38871. }
  38872. Parallel.prototype = {
  38873. type: 'parallel',
  38874. constructor: Parallel,
  38875. /**
  38876. * Initialize cartesian coordinate systems
  38877. * @private
  38878. */
  38879. _init: function (parallelModel, ecModel, api) {
  38880. var dimensions = parallelModel.dimensions;
  38881. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  38882. each$14(dimensions, function (dim, idx) {
  38883. var axisIndex = parallelAxisIndex[idx];
  38884. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  38885. var axis = this._axesMap.set(dim, new ParallelAxis(
  38886. dim,
  38887. createScaleByModel(axisModel),
  38888. [0, 0],
  38889. axisModel.get('type'),
  38890. axisIndex
  38891. ));
  38892. var isCategory = axis.type === 'category';
  38893. axis.onBand = isCategory && axisModel.get('boundaryGap');
  38894. axis.inverse = axisModel.get('inverse');
  38895. // Injection
  38896. axisModel.axis = axis;
  38897. axis.model = axisModel;
  38898. axis.coordinateSystem = axisModel.coordinateSystem = this;
  38899. }, this);
  38900. },
  38901. /**
  38902. * Update axis scale after data processed
  38903. * @param {module:echarts/model/Global} ecModel
  38904. * @param {module:echarts/ExtensionAPI} api
  38905. */
  38906. update: function (ecModel, api) {
  38907. this._updateAxesFromSeries(this._model, ecModel);
  38908. },
  38909. /**
  38910. * @override
  38911. */
  38912. containPoint: function (point) {
  38913. var layoutInfo = this._makeLayoutInfo();
  38914. var axisBase = layoutInfo.axisBase;
  38915. var layoutBase = layoutInfo.layoutBase;
  38916. var pixelDimIndex = layoutInfo.pixelDimIndex;
  38917. var pAxis = point[1 - pixelDimIndex];
  38918. var pLayout = point[pixelDimIndex];
  38919. return pAxis >= axisBase
  38920. && pAxis <= axisBase + layoutInfo.axisLength
  38921. && pLayout >= layoutBase
  38922. && pLayout <= layoutBase + layoutInfo.layoutLength;
  38923. },
  38924. getModel: function () {
  38925. return this._model;
  38926. },
  38927. /**
  38928. * Update properties from series
  38929. * @private
  38930. */
  38931. _updateAxesFromSeries: function (parallelModel, ecModel) {
  38932. ecModel.eachSeries(function (seriesModel) {
  38933. if (!parallelModel.contains(seriesModel, ecModel)) {
  38934. return;
  38935. }
  38936. var data = seriesModel.getData();
  38937. each$14(this.dimensions, function (dim) {
  38938. var axis = this._axesMap.get(dim);
  38939. axis.scale.unionExtentFromData(data, dim);
  38940. niceScaleExtent(axis.scale, axis.model);
  38941. }, this);
  38942. }, this);
  38943. },
  38944. /**
  38945. * Resize the parallel coordinate system.
  38946. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  38947. * @param {module:echarts/ExtensionAPI} api
  38948. */
  38949. resize: function (parallelModel, api) {
  38950. this._rect = getLayoutRect(
  38951. parallelModel.getBoxLayoutParams(),
  38952. {
  38953. width: api.getWidth(),
  38954. height: api.getHeight()
  38955. }
  38956. );
  38957. this._layoutAxes();
  38958. },
  38959. /**
  38960. * @return {module:zrender/core/BoundingRect}
  38961. */
  38962. getRect: function () {
  38963. return this._rect;
  38964. },
  38965. /**
  38966. * @private
  38967. */
  38968. _makeLayoutInfo: function () {
  38969. var parallelModel = this._model;
  38970. var rect = this._rect;
  38971. var xy = ['x', 'y'];
  38972. var wh = ['width', 'height'];
  38973. var layout = parallelModel.get('layout');
  38974. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  38975. var layoutLength = rect[wh[pixelDimIndex]];
  38976. var layoutExtent = [0, layoutLength];
  38977. var axisCount = this.dimensions.length;
  38978. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  38979. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  38980. var axisExpandable = parallelModel.get('axisExpandable')
  38981. && axisCount > 3
  38982. && axisCount > axisExpandCount
  38983. && axisExpandCount > 1
  38984. && axisExpandWidth > 0
  38985. && layoutLength > 0;
  38986. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  38987. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  38988. // where collapsed axes should be overlapped.
  38989. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  38990. var winSize;
  38991. if (!axisExpandWindow) {
  38992. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  38993. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  38994. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  38995. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  38996. }
  38997. else {
  38998. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  38999. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  39000. }
  39001. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  39002. // Avoid axisCollapseWidth is too small.
  39003. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  39004. // Find the first and last indices > ewin[0] and < ewin[1].
  39005. var winInnerIndices = [
  39006. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  39007. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  39008. ];
  39009. // Pos in ec coordinates.
  39010. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  39011. return {
  39012. layout: layout,
  39013. pixelDimIndex: pixelDimIndex,
  39014. layoutBase: rect[xy[pixelDimIndex]],
  39015. layoutLength: layoutLength,
  39016. axisBase: rect[xy[1 - pixelDimIndex]],
  39017. axisLength: rect[wh[1 - pixelDimIndex]],
  39018. axisExpandable: axisExpandable,
  39019. axisExpandWidth: axisExpandWidth,
  39020. axisCollapseWidth: axisCollapseWidth,
  39021. axisExpandWindow: axisExpandWindow,
  39022. axisCount: axisCount,
  39023. winInnerIndices: winInnerIndices,
  39024. axisExpandWindow0Pos: axisExpandWindow0Pos
  39025. };
  39026. },
  39027. /**
  39028. * @private
  39029. */
  39030. _layoutAxes: function () {
  39031. var rect = this._rect;
  39032. var axes = this._axesMap;
  39033. var dimensions = this.dimensions;
  39034. var layoutInfo = this._makeLayoutInfo();
  39035. var layout = layoutInfo.layout;
  39036. axes.each(function (axis) {
  39037. var axisExtent = [0, layoutInfo.axisLength];
  39038. var idx = axis.inverse ? 1 : 0;
  39039. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  39040. });
  39041. each$14(dimensions, function (dim, idx) {
  39042. var posInfo = (layoutInfo.axisExpandable
  39043. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  39044. )(idx, layoutInfo);
  39045. var positionTable = {
  39046. horizontal: {
  39047. x: posInfo.position,
  39048. y: layoutInfo.axisLength
  39049. },
  39050. vertical: {
  39051. x: 0,
  39052. y: posInfo.position
  39053. }
  39054. };
  39055. var rotationTable = {
  39056. horizontal: PI$3 / 2,
  39057. vertical: 0
  39058. };
  39059. var position = [
  39060. positionTable[layout].x + rect.x,
  39061. positionTable[layout].y + rect.y
  39062. ];
  39063. var rotation = rotationTable[layout];
  39064. var transform = create$1();
  39065. rotate(transform, transform, rotation);
  39066. translate(transform, transform, position);
  39067. // TODO
  39068. // tick等排布信息。
  39069. // TODO
  39070. // 根据axis order 更新 dimensions顺序。
  39071. this._axesLayout[dim] = {
  39072. position: position,
  39073. rotation: rotation,
  39074. transform: transform,
  39075. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  39076. axisLabelShow: posInfo.axisLabelShow,
  39077. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  39078. tickDirection: 1,
  39079. labelDirection: 1,
  39080. labelInterval: axes.get(dim).getLabelInterval()
  39081. };
  39082. }, this);
  39083. },
  39084. /**
  39085. * Get axis by dim.
  39086. * @param {string} dim
  39087. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  39088. */
  39089. getAxis: function (dim) {
  39090. return this._axesMap.get(dim);
  39091. },
  39092. /**
  39093. * Convert a dim value of a single item of series data to Point.
  39094. * @param {*} value
  39095. * @param {string} dim
  39096. * @return {Array}
  39097. */
  39098. dataToPoint: function (value, dim) {
  39099. return this.axisCoordToPoint(
  39100. this._axesMap.get(dim).dataToCoord(value),
  39101. dim
  39102. );
  39103. },
  39104. /**
  39105. * Travel data for one time, get activeState of each data item.
  39106. * @param {module:echarts/data/List} data
  39107. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  39108. * {number} dataIndex
  39109. * @param {Object} context
  39110. */
  39111. eachActiveState: function (data, callback, context) {
  39112. var dimensions = this.dimensions;
  39113. var axesMap = this._axesMap;
  39114. var hasActiveSet = this.hasAxisBrushed();
  39115. for (var i = 0, len = data.count(); i < len; i++) {
  39116. var values = data.getValues(dimensions, i);
  39117. var activeState;
  39118. if (!hasActiveSet) {
  39119. activeState = 'normal';
  39120. }
  39121. else {
  39122. activeState = 'active';
  39123. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  39124. var dimName = dimensions[j];
  39125. var state = axesMap.get(dimName).model.getActiveState(values[j], j);
  39126. if (state === 'inactive') {
  39127. activeState = 'inactive';
  39128. break;
  39129. }
  39130. }
  39131. }
  39132. callback.call(context, activeState, i);
  39133. }
  39134. },
  39135. /**
  39136. * Whether has any activeSet.
  39137. * @return {boolean}
  39138. */
  39139. hasAxisBrushed: function () {
  39140. var dimensions = this.dimensions;
  39141. var axesMap = this._axesMap;
  39142. var hasActiveSet = false;
  39143. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  39144. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  39145. hasActiveSet = true;
  39146. }
  39147. }
  39148. return hasActiveSet;
  39149. },
  39150. /**
  39151. * Convert coords of each axis to Point.
  39152. * Return point. For example: [10, 20]
  39153. * @param {Array.<number>} coords
  39154. * @param {string} dim
  39155. * @return {Array.<number>}
  39156. */
  39157. axisCoordToPoint: function (coord, dim) {
  39158. var axisLayout = this._axesLayout[dim];
  39159. return applyTransform$1([coord, 0], axisLayout.transform);
  39160. },
  39161. /**
  39162. * Get axis layout.
  39163. */
  39164. getAxisLayout: function (dim) {
  39165. return clone(this._axesLayout[dim]);
  39166. },
  39167. /**
  39168. * @param {Array.<number>} point
  39169. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  39170. */
  39171. getSlidedAxisExpandWindow: function (point) {
  39172. var layoutInfo = this._makeLayoutInfo();
  39173. var pixelDimIndex = layoutInfo.pixelDimIndex;
  39174. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  39175. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  39176. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  39177. // Out of the area of coordinate system.
  39178. if (!this.containPoint(point)) {
  39179. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  39180. }
  39181. // Conver the point from global to expand coordinates.
  39182. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  39183. // For dragging operation convenience, the window should not be
  39184. // slided when mouse is the center area of the window.
  39185. var delta;
  39186. var behavior = 'slide';
  39187. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  39188. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  39189. // But consider touch device, jump is necessary.
  39190. var useJump = triggerArea[0] != null;
  39191. if (axisCollapseWidth) {
  39192. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  39193. behavior = 'jump';
  39194. delta = pointCoord - winSize * triggerArea[2];
  39195. }
  39196. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  39197. behavior = 'jump';
  39198. delta = pointCoord - winSize * (1 - triggerArea[2]);
  39199. }
  39200. else {
  39201. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  39202. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  39203. && (delta = 0);
  39204. }
  39205. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  39206. delta
  39207. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  39208. // Avoid nonsense triger on mousemove.
  39209. : (behavior = 'none');
  39210. }
  39211. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  39212. else {
  39213. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  39214. var pos = extent[1] * pointCoord / winSize;
  39215. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  39216. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  39217. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  39218. }
  39219. return {
  39220. axisExpandWindow: axisExpandWindow,
  39221. behavior: behavior
  39222. };
  39223. }
  39224. };
  39225. function restrict(len, extent) {
  39226. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  39227. }
  39228. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  39229. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  39230. return {
  39231. position: step * axisIndex,
  39232. axisNameAvailableWidth: step,
  39233. axisLabelShow: true
  39234. };
  39235. }
  39236. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  39237. var layoutLength = layoutInfo.layoutLength;
  39238. var axisExpandWidth = layoutInfo.axisExpandWidth;
  39239. var axisCount = layoutInfo.axisCount;
  39240. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  39241. var winInnerIndices = layoutInfo.winInnerIndices;
  39242. var position;
  39243. var axisNameAvailableWidth = axisCollapseWidth;
  39244. var axisLabelShow = false;
  39245. var nameTruncateMaxWidth;
  39246. if (axisIndex < winInnerIndices[0]) {
  39247. position = axisIndex * axisCollapseWidth;
  39248. nameTruncateMaxWidth = axisCollapseWidth;
  39249. }
  39250. else if (axisIndex <= winInnerIndices[1]) {
  39251. position = layoutInfo.axisExpandWindow0Pos
  39252. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  39253. axisNameAvailableWidth = axisExpandWidth;
  39254. axisLabelShow = true;
  39255. }
  39256. else {
  39257. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  39258. nameTruncateMaxWidth = axisCollapseWidth;
  39259. }
  39260. return {
  39261. position: position,
  39262. axisNameAvailableWidth: axisNameAvailableWidth,
  39263. axisLabelShow: axisLabelShow,
  39264. nameTruncateMaxWidth: nameTruncateMaxWidth
  39265. };
  39266. }
  39267. /**
  39268. * Parallel coordinate system creater.
  39269. */
  39270. function create$2(ecModel, api) {
  39271. var coordSysList = [];
  39272. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  39273. var coordSys = new Parallel(parallelModel, ecModel, api);
  39274. coordSys.name = 'parallel_' + idx;
  39275. coordSys.resize(parallelModel, api);
  39276. parallelModel.coordinateSystem = coordSys;
  39277. coordSys.model = parallelModel;
  39278. coordSysList.push(coordSys);
  39279. });
  39280. // Inject the coordinateSystems into seriesModel
  39281. ecModel.eachSeries(function (seriesModel) {
  39282. if (seriesModel.get('coordinateSystem') === 'parallel') {
  39283. var parallelModel = ecModel.queryComponents({
  39284. mainType: 'parallel',
  39285. index: seriesModel.get('parallelIndex'),
  39286. id: seriesModel.get('parallelId')
  39287. })[0];
  39288. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  39289. }
  39290. });
  39291. return coordSysList;
  39292. }
  39293. CoordinateSystemManager.register('parallel', {create: create$2});
  39294. var AxisModel$2 = ComponentModel.extend({
  39295. type: 'baseParallelAxis',
  39296. /**
  39297. * @type {module:echarts/coord/parallel/Axis}
  39298. */
  39299. axis: null,
  39300. /**
  39301. * @type {Array.<Array.<number>}
  39302. * @readOnly
  39303. */
  39304. activeIntervals: [],
  39305. /**
  39306. * @return {Object}
  39307. */
  39308. getAreaSelectStyle: function () {
  39309. return makeStyleMapper(
  39310. [
  39311. ['fill', 'color'],
  39312. ['lineWidth', 'borderWidth'],
  39313. ['stroke', 'borderColor'],
  39314. ['width', 'width'],
  39315. ['opacity', 'opacity']
  39316. ]
  39317. )(this.getModel('areaSelectStyle'));
  39318. },
  39319. /**
  39320. * The code of this feature is put on AxisModel but not ParallelAxis,
  39321. * because axisModel can be alive after echarts updating but instance of
  39322. * ParallelAxis having been disposed. this._activeInterval should be kept
  39323. * when action dispatched (i.e. legend click).
  39324. *
  39325. * @param {Array.<Array<number>>} intervals interval.length === 0
  39326. * means set all active.
  39327. * @public
  39328. */
  39329. setActiveIntervals: function (intervals) {
  39330. var activeIntervals = this.activeIntervals = clone(intervals);
  39331. // Normalize
  39332. if (activeIntervals) {
  39333. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  39334. asc(activeIntervals[i]);
  39335. }
  39336. }
  39337. },
  39338. /**
  39339. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  39340. * value can not be input.
  39341. * @return {string} 'normal': no activeIntervals set,
  39342. * 'active',
  39343. * 'inactive'.
  39344. * @public
  39345. */
  39346. getActiveState: function (value) {
  39347. var activeIntervals = this.activeIntervals;
  39348. if (!activeIntervals.length) {
  39349. return 'normal';
  39350. }
  39351. if (value == null) {
  39352. return 'inactive';
  39353. }
  39354. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  39355. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  39356. return 'active';
  39357. }
  39358. }
  39359. return 'inactive';
  39360. }
  39361. });
  39362. var defaultOption$1 = {
  39363. type: 'value',
  39364. /**
  39365. * @type {Array.<number>}
  39366. */
  39367. dim: null, // 0, 1, 2, ...
  39368. // parallelIndex: null,
  39369. areaSelectStyle: {
  39370. width: 20,
  39371. borderWidth: 1,
  39372. borderColor: 'rgba(160,197,232)',
  39373. color: 'rgba(160,197,232)',
  39374. opacity: 0.3
  39375. },
  39376. realtime: true, // Whether realtime update view when select.
  39377. z: 10
  39378. };
  39379. merge(AxisModel$2.prototype, axisModelCommonMixin);
  39380. function getAxisType$1(axisName, option) {
  39381. return option.type || (option.data ? 'category' : 'value');
  39382. }
  39383. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  39384. ComponentModel.extend({
  39385. type: 'parallel',
  39386. dependencies: ['parallelAxis'],
  39387. /**
  39388. * @type {module:echarts/coord/parallel/Parallel}
  39389. */
  39390. coordinateSystem: null,
  39391. /**
  39392. * Each item like: 'dim0', 'dim1', 'dim2', ...
  39393. * @type {Array.<string>}
  39394. * @readOnly
  39395. */
  39396. dimensions: null,
  39397. /**
  39398. * Coresponding to dimensions.
  39399. * @type {Array.<number>}
  39400. * @readOnly
  39401. */
  39402. parallelAxisIndex: null,
  39403. layoutMode: 'box',
  39404. defaultOption: {
  39405. zlevel: 0,
  39406. z: 0,
  39407. left: 80,
  39408. top: 60,
  39409. right: 80,
  39410. bottom: 60,
  39411. // width: {totalWidth} - left - right,
  39412. // height: {totalHeight} - top - bottom,
  39413. layout: 'horizontal', // 'horizontal' or 'vertical'
  39414. // FIXME
  39415. // naming?
  39416. axisExpandable: false,
  39417. axisExpandCenter: null,
  39418. axisExpandCount: 0,
  39419. axisExpandWidth: 50, // FIXME '10%' ?
  39420. axisExpandRate: 17,
  39421. axisExpandDebounce: 50,
  39422. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  39423. // Do not doc to user until necessary.
  39424. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  39425. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  39426. parallelAxisDefault: null
  39427. },
  39428. /**
  39429. * @override
  39430. */
  39431. init: function () {
  39432. ComponentModel.prototype.init.apply(this, arguments);
  39433. this.mergeOption({});
  39434. },
  39435. /**
  39436. * @override
  39437. */
  39438. mergeOption: function (newOption) {
  39439. var thisOption = this.option;
  39440. newOption && merge(thisOption, newOption, true);
  39441. this._initDimensions();
  39442. },
  39443. /**
  39444. * Whether series or axis is in this coordinate system.
  39445. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  39446. * @param {module:echarts/model/Global} ecModel
  39447. */
  39448. contains: function (model, ecModel) {
  39449. var parallelIndex = model.get('parallelIndex');
  39450. return parallelIndex != null
  39451. && ecModel.getComponent('parallel', parallelIndex) === this;
  39452. },
  39453. setAxisExpand: function (opt) {
  39454. each$1(
  39455. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  39456. function (name) {
  39457. if (opt.hasOwnProperty(name)) {
  39458. this.option[name] = opt[name];
  39459. }
  39460. },
  39461. this
  39462. );
  39463. },
  39464. /**
  39465. * @private
  39466. */
  39467. _initDimensions: function () {
  39468. var dimensions = this.dimensions = [];
  39469. var parallelAxisIndex = this.parallelAxisIndex = [];
  39470. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  39471. // Can not use this.contains here, because
  39472. // initialization has not been completed yet.
  39473. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  39474. }, this);
  39475. each$1(axisModels, function (axisModel) {
  39476. dimensions.push('dim' + axisModel.get('dim'));
  39477. parallelAxisIndex.push(axisModel.componentIndex);
  39478. });
  39479. }
  39480. });
  39481. /**
  39482. * @payload
  39483. * @property {string} parallelAxisId
  39484. * @property {Array.<Array.<number>>} intervals
  39485. */
  39486. var actionInfo$1 = {
  39487. type: 'axisAreaSelect',
  39488. event: 'axisAreaSelected',
  39489. update: 'updateVisual'
  39490. };
  39491. registerAction(actionInfo$1, function (payload, ecModel) {
  39492. ecModel.eachComponent(
  39493. {mainType: 'parallelAxis', query: payload},
  39494. function (parallelAxisModel) {
  39495. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  39496. }
  39497. );
  39498. });
  39499. /**
  39500. * @payload
  39501. */
  39502. registerAction('parallelAxisExpand', function (payload, ecModel) {
  39503. ecModel.eachComponent(
  39504. {mainType: 'parallel', query: payload},
  39505. function (parallelModel) {
  39506. parallelModel.setAxisExpand(payload);
  39507. }
  39508. );
  39509. });
  39510. var curry$2 = curry;
  39511. var each$15 = each$1;
  39512. var map$3 = map;
  39513. var mathMin$6 = Math.min;
  39514. var mathMax$6 = Math.max;
  39515. var mathPow$2 = Math.pow;
  39516. var COVER_Z = 10000;
  39517. var UNSELECT_THRESHOLD = 6;
  39518. var MIN_RESIZE_LINE_WIDTH = 6;
  39519. var MUTEX_RESOURCE_KEY = 'globalPan';
  39520. var DIRECTION_MAP = {
  39521. w: [0, 0],
  39522. e: [0, 1],
  39523. n: [1, 0],
  39524. s: [1, 1]
  39525. };
  39526. var CURSOR_MAP = {
  39527. w: 'ew',
  39528. e: 'ew',
  39529. n: 'ns',
  39530. s: 'ns',
  39531. ne: 'nesw',
  39532. sw: 'nesw',
  39533. nw: 'nwse',
  39534. se: 'nwse'
  39535. };
  39536. var DEFAULT_BRUSH_OPT = {
  39537. brushStyle: {
  39538. lineWidth: 2,
  39539. stroke: 'rgba(0,0,0,0.3)',
  39540. fill: 'rgba(0,0,0,0.1)'
  39541. },
  39542. transformable: true,
  39543. brushMode: 'single',
  39544. removeOnClick: false
  39545. };
  39546. var baseUID = 0;
  39547. /**
  39548. * @alias module:echarts/component/helper/BrushController
  39549. * @constructor
  39550. * @mixin {module:zrender/mixin/Eventful}
  39551. * @event module:echarts/component/helper/BrushController#brush
  39552. * params:
  39553. * areas: Array.<Array>, coord relates to container group,
  39554. * If no container specified, to global.
  39555. * opt {
  39556. * isEnd: boolean,
  39557. * removeOnClick: boolean
  39558. * }
  39559. *
  39560. * @param {module:zrender/zrender~ZRender} zr
  39561. */
  39562. function BrushController(zr) {
  39563. if (__DEV__) {
  39564. assert(zr);
  39565. }
  39566. Eventful.call(this);
  39567. /**
  39568. * @type {module:zrender/zrender~ZRender}
  39569. * @private
  39570. */
  39571. this._zr = zr;
  39572. /**
  39573. * @type {module:zrender/container/Group}
  39574. * @readOnly
  39575. */
  39576. this.group = new Group();
  39577. /**
  39578. * Only for drawing (after enabledBrush).
  39579. * 'line', 'rect', 'polygon' or false
  39580. * If passing false/null/undefined, disable brush.
  39581. * If passing 'auto', determined by panel.defaultBrushType
  39582. * @private
  39583. * @type {string}
  39584. */
  39585. this._brushType;
  39586. /**
  39587. * Only for drawing (after enabledBrush).
  39588. *
  39589. * @private
  39590. * @type {Object}
  39591. */
  39592. this._brushOption;
  39593. /**
  39594. * @private
  39595. * @type {Object}
  39596. */
  39597. this._panels;
  39598. /**
  39599. * @private
  39600. * @type {Array.<nubmer>}
  39601. */
  39602. this._track = [];
  39603. /**
  39604. * @private
  39605. * @type {boolean}
  39606. */
  39607. this._dragging;
  39608. /**
  39609. * @private
  39610. * @type {Array}
  39611. */
  39612. this._covers = [];
  39613. /**
  39614. * @private
  39615. * @type {moudule:zrender/container/Group}
  39616. */
  39617. this._creatingCover;
  39618. /**
  39619. * `true` means global panel
  39620. * @private
  39621. * @type {module:zrender/container/Group|boolean}
  39622. */
  39623. this._creatingPanel;
  39624. /**
  39625. * @private
  39626. * @type {boolean}
  39627. */
  39628. this._enableGlobalPan;
  39629. /**
  39630. * @private
  39631. * @type {boolean}
  39632. */
  39633. if (__DEV__) {
  39634. this._mounted;
  39635. }
  39636. /**
  39637. * @private
  39638. * @type {string}
  39639. */
  39640. this._uid = 'brushController_' + baseUID++;
  39641. /**
  39642. * @private
  39643. * @type {Object}
  39644. */
  39645. this._handlers = {};
  39646. each$15(mouseHandlers, function (handler, eventName) {
  39647. this._handlers[eventName] = bind(handler, this);
  39648. }, this);
  39649. }
  39650. BrushController.prototype = {
  39651. constructor: BrushController,
  39652. /**
  39653. * If set to null/undefined/false, select disabled.
  39654. * @param {Object} brushOption
  39655. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  39656. * If passing false/null/undefined, disable brush.
  39657. * If passing 'auto', determined by panel.defaultBrushType.
  39658. * ('auto' can not be used in global panel)
  39659. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  39660. * @param {boolean} [brushOption.transformable=true]
  39661. * @param {boolean} [brushOption.removeOnClick=false]
  39662. * @param {Object} [brushOption.brushStyle]
  39663. * @param {number} [brushOption.brushStyle.width]
  39664. * @param {number} [brushOption.brushStyle.lineWidth]
  39665. * @param {string} [brushOption.brushStyle.stroke]
  39666. * @param {string} [brushOption.brushStyle.fill]
  39667. * @param {number} [brushOption.z]
  39668. */
  39669. enableBrush: function (brushOption) {
  39670. if (__DEV__) {
  39671. assert(this._mounted);
  39672. }
  39673. this._brushType && doDisableBrush(this);
  39674. brushOption.brushType && doEnableBrush(this, brushOption);
  39675. return this;
  39676. },
  39677. /**
  39678. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  39679. * Each items: {
  39680. * panelId, // mandatory.
  39681. * clipPath, // mandatory. function.
  39682. * isTargetByCursor, // mandatory. function.
  39683. * defaultBrushType, // optional, only used when brushType is 'auto'.
  39684. * getLinearBrushOtherExtent, // optional. function.
  39685. * }
  39686. */
  39687. setPanels: function (panelOpts) {
  39688. if (panelOpts && panelOpts.length) {
  39689. var panels = this._panels = {};
  39690. each$1(panelOpts, function (panelOpts) {
  39691. panels[panelOpts.panelId] = clone(panelOpts);
  39692. });
  39693. }
  39694. else {
  39695. this._panels = null;
  39696. }
  39697. return this;
  39698. },
  39699. /**
  39700. * @param {Object} [opt]
  39701. * @return {boolean} [opt.enableGlobalPan=false]
  39702. */
  39703. mount: function (opt) {
  39704. opt = opt || {};
  39705. if (__DEV__) {
  39706. this._mounted = true; // should be at first.
  39707. }
  39708. this._enableGlobalPan = opt.enableGlobalPan;
  39709. var thisGroup = this.group;
  39710. this._zr.add(thisGroup);
  39711. thisGroup.attr({
  39712. position: opt.position || [0, 0],
  39713. rotation: opt.rotation || 0,
  39714. scale: opt.scale || [1, 1]
  39715. });
  39716. this._transform = thisGroup.getLocalTransform();
  39717. return this;
  39718. },
  39719. eachCover: function (cb, context) {
  39720. each$15(this._covers, cb, context);
  39721. },
  39722. /**
  39723. * Update covers.
  39724. * @param {Array.<Object>} brushOptionList Like:
  39725. * [
  39726. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  39727. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  39728. * ...
  39729. * ]
  39730. * `brushType` is required in each cover info. (can not be 'auto')
  39731. * `id` is not mandatory.
  39732. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  39733. * If brushOptionList is null/undefined, all covers removed.
  39734. */
  39735. updateCovers: function (brushOptionList) {
  39736. if (__DEV__) {
  39737. assert(this._mounted);
  39738. }
  39739. brushOptionList = map(brushOptionList, function (brushOption) {
  39740. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  39741. });
  39742. var tmpIdPrefix = '\0-brush-index-';
  39743. var oldCovers = this._covers;
  39744. var newCovers = this._covers = [];
  39745. var controller = this;
  39746. var creatingCover = this._creatingCover;
  39747. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  39748. .add(addOrUpdate)
  39749. .update(addOrUpdate)
  39750. .remove(remove)
  39751. .execute();
  39752. return this;
  39753. function getKey(brushOption, index) {
  39754. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  39755. + '-' + brushOption.brushType;
  39756. }
  39757. function oldGetKey(cover, index) {
  39758. return getKey(cover.__brushOption, index);
  39759. }
  39760. function addOrUpdate(newIndex, oldIndex) {
  39761. var newBrushOption = brushOptionList[newIndex];
  39762. // Consider setOption in event listener of brushSelect,
  39763. // where updating cover when creating should be forbiden.
  39764. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  39765. newCovers[newIndex] = oldCovers[oldIndex];
  39766. }
  39767. else {
  39768. var cover = newCovers[newIndex] = oldIndex != null
  39769. ? (
  39770. oldCovers[oldIndex].__brushOption = newBrushOption,
  39771. oldCovers[oldIndex]
  39772. )
  39773. : endCreating(controller, createCover(controller, newBrushOption));
  39774. updateCoverAfterCreation(controller, cover);
  39775. }
  39776. }
  39777. function remove(oldIndex) {
  39778. if (oldCovers[oldIndex] !== creatingCover) {
  39779. controller.group.remove(oldCovers[oldIndex]);
  39780. }
  39781. }
  39782. },
  39783. unmount: function () {
  39784. if (__DEV__) {
  39785. if (!this._mounted) {
  39786. return;
  39787. }
  39788. }
  39789. this.enableBrush(false);
  39790. // container may 'removeAll' outside.
  39791. clearCovers(this);
  39792. this._zr.remove(this.group);
  39793. if (__DEV__) {
  39794. this._mounted = false; // should be at last.
  39795. }
  39796. return this;
  39797. },
  39798. dispose: function () {
  39799. this.unmount();
  39800. this.off();
  39801. }
  39802. };
  39803. mixin(BrushController, Eventful);
  39804. function doEnableBrush(controller, brushOption) {
  39805. var zr = controller._zr;
  39806. // Consider roam, which takes globalPan too.
  39807. if (!controller._enableGlobalPan) {
  39808. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  39809. }
  39810. each$15(controller._handlers, function (handler, eventName) {
  39811. zr.on(eventName, handler);
  39812. });
  39813. controller._brushType = brushOption.brushType;
  39814. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  39815. }
  39816. function doDisableBrush(controller) {
  39817. var zr = controller._zr;
  39818. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  39819. each$15(controller._handlers, function (handler, eventName) {
  39820. zr.off(eventName, handler);
  39821. });
  39822. controller._brushType = controller._brushOption = null;
  39823. }
  39824. function createCover(controller, brushOption) {
  39825. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  39826. cover.__brushOption = brushOption;
  39827. updateZ$1(cover, brushOption);
  39828. controller.group.add(cover);
  39829. return cover;
  39830. }
  39831. function endCreating(controller, creatingCover) {
  39832. var coverRenderer = getCoverRenderer(creatingCover);
  39833. if (coverRenderer.endCreating) {
  39834. coverRenderer.endCreating(controller, creatingCover);
  39835. updateZ$1(creatingCover, creatingCover.__brushOption);
  39836. }
  39837. return creatingCover;
  39838. }
  39839. function updateCoverShape(controller, cover) {
  39840. var brushOption = cover.__brushOption;
  39841. getCoverRenderer(cover).updateCoverShape(
  39842. controller, cover, brushOption.range, brushOption
  39843. );
  39844. }
  39845. function updateZ$1(cover, brushOption) {
  39846. var z = brushOption.z;
  39847. z == null && (z = COVER_Z);
  39848. cover.traverse(function (el) {
  39849. el.z = z;
  39850. el.z2 = z; // Consider in given container.
  39851. });
  39852. }
  39853. function updateCoverAfterCreation(controller, cover) {
  39854. getCoverRenderer(cover).updateCommon(controller, cover);
  39855. updateCoverShape(controller, cover);
  39856. }
  39857. function getCoverRenderer(cover) {
  39858. return coverRenderers[cover.__brushOption.brushType];
  39859. }
  39860. // return target panel or `true` (means global panel)
  39861. function getPanelByPoint(controller, e, localCursorPoint) {
  39862. var panels = controller._panels;
  39863. if (!panels) {
  39864. return true; // Global panel
  39865. }
  39866. var panel;
  39867. var transform = controller._transform;
  39868. each$15(panels, function (pn) {
  39869. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  39870. });
  39871. return panel;
  39872. }
  39873. // Return a panel or true
  39874. function getPanelByCover(controller, cover) {
  39875. var panels = controller._panels;
  39876. if (!panels) {
  39877. return true; // Global panel
  39878. }
  39879. var panelId = cover.__brushOption.panelId;
  39880. // User may give cover without coord sys info,
  39881. // which is then treated as global panel.
  39882. return panelId != null ? panels[panelId] : true;
  39883. }
  39884. function clearCovers(controller) {
  39885. var covers = controller._covers;
  39886. var originalLength = covers.length;
  39887. each$15(covers, function (cover) {
  39888. controller.group.remove(cover);
  39889. }, controller);
  39890. covers.length = 0;
  39891. return !!originalLength;
  39892. }
  39893. function trigger(controller, opt) {
  39894. var areas = map$3(controller._covers, function (cover) {
  39895. var brushOption = cover.__brushOption;
  39896. var range = clone(brushOption.range);
  39897. return {
  39898. brushType: brushOption.brushType,
  39899. panelId: brushOption.panelId,
  39900. range: range
  39901. };
  39902. });
  39903. controller.trigger('brush', areas, {
  39904. isEnd: !!opt.isEnd,
  39905. removeOnClick: !!opt.removeOnClick
  39906. });
  39907. }
  39908. function shouldShowCover(controller) {
  39909. var track = controller._track;
  39910. if (!track.length) {
  39911. return false;
  39912. }
  39913. var p2 = track[track.length - 1];
  39914. var p1 = track[0];
  39915. var dx = p2[0] - p1[0];
  39916. var dy = p2[1] - p1[1];
  39917. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  39918. return dist > UNSELECT_THRESHOLD;
  39919. }
  39920. function getTrackEnds(track) {
  39921. var tail = track.length - 1;
  39922. tail < 0 && (tail = 0);
  39923. return [track[0], track[tail]];
  39924. }
  39925. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  39926. var cover = new Group();
  39927. cover.add(new Rect({
  39928. name: 'main',
  39929. style: makeStyle(brushOption),
  39930. silent: true,
  39931. draggable: true,
  39932. cursor: 'move',
  39933. drift: curry$2(doDrift, controller, cover, 'nswe'),
  39934. ondragend: curry$2(trigger, controller, {isEnd: true})
  39935. }));
  39936. each$15(
  39937. edgeNames,
  39938. function (name) {
  39939. cover.add(new Rect({
  39940. name: name,
  39941. style: {opacity: 0},
  39942. draggable: true,
  39943. silent: true,
  39944. invisible: true,
  39945. drift: curry$2(doDrift, controller, cover, name),
  39946. ondragend: curry$2(trigger, controller, {isEnd: true})
  39947. }));
  39948. }
  39949. );
  39950. return cover;
  39951. }
  39952. function updateBaseRect(controller, cover, localRange, brushOption) {
  39953. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  39954. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  39955. var x = localRange[0][0];
  39956. var y = localRange[1][0];
  39957. var xa = x - lineWidth / 2;
  39958. var ya = y - lineWidth / 2;
  39959. var x2 = localRange[0][1];
  39960. var y2 = localRange[1][1];
  39961. var x2a = x2 - handleSize + lineWidth / 2;
  39962. var y2a = y2 - handleSize + lineWidth / 2;
  39963. var width = x2 - x;
  39964. var height = y2 - y;
  39965. var widtha = width + lineWidth;
  39966. var heighta = height + lineWidth;
  39967. updateRectShape(controller, cover, 'main', x, y, width, height);
  39968. if (brushOption.transformable) {
  39969. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  39970. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  39971. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  39972. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  39973. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  39974. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  39975. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  39976. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  39977. }
  39978. }
  39979. function updateCommon(controller, cover) {
  39980. var brushOption = cover.__brushOption;
  39981. var transformable = brushOption.transformable;
  39982. var mainEl = cover.childAt(0);
  39983. mainEl.useStyle(makeStyle(brushOption));
  39984. mainEl.attr({
  39985. silent: !transformable,
  39986. cursor: transformable ? 'move' : 'default'
  39987. });
  39988. each$15(
  39989. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  39990. function (name) {
  39991. var el = cover.childOfName(name);
  39992. var globalDir = getGlobalDirection(controller, name);
  39993. el && el.attr({
  39994. silent: !transformable,
  39995. invisible: !transformable,
  39996. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  39997. });
  39998. }
  39999. );
  40000. }
  40001. function updateRectShape(controller, cover, name, x, y, w, h) {
  40002. var el = cover.childOfName(name);
  40003. el && el.setShape(pointsToRect(
  40004. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  40005. ));
  40006. }
  40007. function makeStyle(brushOption) {
  40008. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  40009. }
  40010. function formatRectRange(x, y, x2, y2) {
  40011. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  40012. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  40013. return [
  40014. [min[0], max[0]], // x range
  40015. [min[1], max[1]] // y range
  40016. ];
  40017. }
  40018. function getTransform$1(controller) {
  40019. return getTransform(controller.group);
  40020. }
  40021. function getGlobalDirection(controller, localDirection) {
  40022. if (localDirection.length > 1) {
  40023. localDirection = localDirection.split('');
  40024. var globalDir = [
  40025. getGlobalDirection(controller, localDirection[0]),
  40026. getGlobalDirection(controller, localDirection[1])
  40027. ];
  40028. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  40029. return globalDir.join('');
  40030. }
  40031. else {
  40032. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  40033. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  40034. var globalDir = transformDirection(
  40035. map$$1[localDirection], getTransform$1(controller)
  40036. );
  40037. return inverseMap[globalDir];
  40038. }
  40039. }
  40040. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  40041. var brushOption = cover.__brushOption;
  40042. var rectRange = toRectRange(brushOption.range);
  40043. var localDelta = toLocalDelta(controller, dx, dy);
  40044. each$15(name.split(''), function (namePart) {
  40045. var ind = DIRECTION_MAP[namePart];
  40046. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  40047. });
  40048. brushOption.range = fromRectRange(formatRectRange(
  40049. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  40050. ));
  40051. updateCoverAfterCreation(controller, cover);
  40052. trigger(controller, {isEnd: false});
  40053. }
  40054. function driftPolygon(controller, cover, dx, dy, e) {
  40055. var range = cover.__brushOption.range;
  40056. var localDelta = toLocalDelta(controller, dx, dy);
  40057. each$15(range, function (point) {
  40058. point[0] += localDelta[0];
  40059. point[1] += localDelta[1];
  40060. });
  40061. updateCoverAfterCreation(controller, cover);
  40062. trigger(controller, {isEnd: false});
  40063. }
  40064. function toLocalDelta(controller, dx, dy) {
  40065. var thisGroup = controller.group;
  40066. var localD = thisGroup.transformCoordToLocal(dx, dy);
  40067. var localZero = thisGroup.transformCoordToLocal(0, 0);
  40068. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  40069. }
  40070. function clipByPanel(controller, cover, data) {
  40071. var panel = getPanelByCover(controller, cover);
  40072. return (panel && panel !== true)
  40073. ? panel.clipPath(data, controller._transform)
  40074. : clone(data);
  40075. }
  40076. function pointsToRect(points) {
  40077. var xmin = mathMin$6(points[0][0], points[1][0]);
  40078. var ymin = mathMin$6(points[0][1], points[1][1]);
  40079. var xmax = mathMax$6(points[0][0], points[1][0]);
  40080. var ymax = mathMax$6(points[0][1], points[1][1]);
  40081. return {
  40082. x: xmin,
  40083. y: ymin,
  40084. width: xmax - xmin,
  40085. height: ymax - ymin
  40086. };
  40087. }
  40088. function resetCursor(controller, e, localCursorPoint) {
  40089. // Check active
  40090. if (!controller._brushType) {
  40091. return;
  40092. }
  40093. var zr = controller._zr;
  40094. var covers = controller._covers;
  40095. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  40096. // Check whether in covers.
  40097. if (!controller._dragging) {
  40098. for (var i = 0; i < covers.length; i++) {
  40099. var brushOption = covers[i].__brushOption;
  40100. if (currPanel
  40101. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  40102. && coverRenderers[brushOption.brushType].contain(
  40103. covers[i], localCursorPoint[0], localCursorPoint[1]
  40104. )
  40105. ) {
  40106. // Use cursor style set on cover.
  40107. return;
  40108. }
  40109. }
  40110. }
  40111. currPanel && zr.setCursorStyle('crosshair');
  40112. }
  40113. function preventDefault(e) {
  40114. var rawE = e.event;
  40115. rawE.preventDefault && rawE.preventDefault();
  40116. }
  40117. function mainShapeContain(cover, x, y) {
  40118. return cover.childOfName('main').contain(x, y);
  40119. }
  40120. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  40121. var creatingCover = controller._creatingCover;
  40122. var panel = controller._creatingPanel;
  40123. var thisBrushOption = controller._brushOption;
  40124. var eventParams;
  40125. controller._track.push(localCursorPoint.slice());
  40126. if (shouldShowCover(controller) || creatingCover) {
  40127. if (panel && !creatingCover) {
  40128. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  40129. var brushOption = clone(thisBrushOption);
  40130. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  40131. brushOption.panelId = panel === true ? null : panel.panelId;
  40132. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  40133. controller._covers.push(creatingCover);
  40134. }
  40135. if (creatingCover) {
  40136. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  40137. var coverBrushOption = creatingCover.__brushOption;
  40138. coverBrushOption.range = coverRenderer.getCreatingRange(
  40139. clipByPanel(controller, creatingCover, controller._track)
  40140. );
  40141. if (isEnd) {
  40142. endCreating(controller, creatingCover);
  40143. coverRenderer.updateCommon(controller, creatingCover);
  40144. }
  40145. updateCoverShape(controller, creatingCover);
  40146. eventParams = {isEnd: isEnd};
  40147. }
  40148. }
  40149. else if (
  40150. isEnd
  40151. && thisBrushOption.brushMode === 'single'
  40152. && thisBrushOption.removeOnClick
  40153. ) {
  40154. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  40155. // But a single click do not clear covers, because user may have casual
  40156. // clicks (for example, click on other component and do not expect covers
  40157. // disappear).
  40158. // Only some cover removed, trigger action, but not every click trigger action.
  40159. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  40160. eventParams = {isEnd: isEnd, removeOnClick: true};
  40161. }
  40162. }
  40163. return eventParams;
  40164. }
  40165. function determineBrushType(brushType, panel) {
  40166. if (brushType === 'auto') {
  40167. if (__DEV__) {
  40168. assert(
  40169. panel && panel.defaultBrushType,
  40170. 'MUST have defaultBrushType when brushType is "atuo"'
  40171. );
  40172. }
  40173. return panel.defaultBrushType;
  40174. }
  40175. return brushType;
  40176. }
  40177. var mouseHandlers = {
  40178. mousedown: function (e) {
  40179. if (this._dragging) {
  40180. // In case some browser do not support globalOut,
  40181. // and release mose out side the browser.
  40182. handleDragEnd.call(this, e);
  40183. }
  40184. else if (!e.target || !e.target.draggable) {
  40185. preventDefault(e);
  40186. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40187. this._creatingCover = null;
  40188. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  40189. if (panel) {
  40190. this._dragging = true;
  40191. this._track = [localCursorPoint.slice()];
  40192. }
  40193. }
  40194. },
  40195. mousemove: function (e) {
  40196. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40197. resetCursor(this, e, localCursorPoint);
  40198. if (this._dragging) {
  40199. preventDefault(e);
  40200. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  40201. eventParams && trigger(this, eventParams);
  40202. }
  40203. },
  40204. mouseup: handleDragEnd //,
  40205. // FIXME
  40206. // in tooltip, globalout should not be triggered.
  40207. // globalout: handleDragEnd
  40208. };
  40209. function handleDragEnd(e) {
  40210. if (this._dragging) {
  40211. preventDefault(e);
  40212. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  40213. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  40214. this._dragging = false;
  40215. this._track = [];
  40216. this._creatingCover = null;
  40217. // trigger event shoule be at final, after procedure will be nested.
  40218. eventParams && trigger(this, eventParams);
  40219. }
  40220. }
  40221. /**
  40222. * key: brushType
  40223. * @type {Object}
  40224. */
  40225. var coverRenderers = {
  40226. lineX: getLineRenderer(0),
  40227. lineY: getLineRenderer(1),
  40228. rect: {
  40229. createCover: function (controller, brushOption) {
  40230. return createBaseRectCover(
  40231. curry$2(
  40232. driftRect,
  40233. function (range) {
  40234. return range;
  40235. },
  40236. function (range) {
  40237. return range;
  40238. }
  40239. ),
  40240. controller,
  40241. brushOption,
  40242. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  40243. );
  40244. },
  40245. getCreatingRange: function (localTrack) {
  40246. var ends = getTrackEnds(localTrack);
  40247. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  40248. },
  40249. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40250. updateBaseRect(controller, cover, localRange, brushOption);
  40251. },
  40252. updateCommon: updateCommon,
  40253. contain: mainShapeContain
  40254. },
  40255. polygon: {
  40256. createCover: function (controller, brushOption) {
  40257. var cover = new Group();
  40258. // Do not use graphic.Polygon because graphic.Polyline do not close the
  40259. // border of the shape when drawing, which is a better experience for user.
  40260. cover.add(new Polyline({
  40261. name: 'main',
  40262. style: makeStyle(brushOption),
  40263. silent: true
  40264. }));
  40265. return cover;
  40266. },
  40267. getCreatingRange: function (localTrack) {
  40268. return localTrack;
  40269. },
  40270. endCreating: function (controller, cover) {
  40271. cover.remove(cover.childAt(0));
  40272. // Use graphic.Polygon close the shape.
  40273. cover.add(new Polygon({
  40274. name: 'main',
  40275. draggable: true,
  40276. drift: curry$2(driftPolygon, controller, cover),
  40277. ondragend: curry$2(trigger, controller, {isEnd: true})
  40278. }));
  40279. },
  40280. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40281. cover.childAt(0).setShape({
  40282. points: clipByPanel(controller, cover, localRange)
  40283. });
  40284. },
  40285. updateCommon: updateCommon,
  40286. contain: mainShapeContain
  40287. }
  40288. };
  40289. function getLineRenderer(xyIndex) {
  40290. return {
  40291. createCover: function (controller, brushOption) {
  40292. return createBaseRectCover(
  40293. curry$2(
  40294. driftRect,
  40295. function (range) {
  40296. var rectRange = [range, [0, 100]];
  40297. xyIndex && rectRange.reverse();
  40298. return rectRange;
  40299. },
  40300. function (rectRange) {
  40301. return rectRange[xyIndex];
  40302. }
  40303. ),
  40304. controller,
  40305. brushOption,
  40306. [['w', 'e'], ['n', 's']][xyIndex]
  40307. );
  40308. },
  40309. getCreatingRange: function (localTrack) {
  40310. var ends = getTrackEnds(localTrack);
  40311. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  40312. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  40313. return [min, max];
  40314. },
  40315. updateCoverShape: function (controller, cover, localRange, brushOption) {
  40316. var otherExtent;
  40317. // If brushWidth not specified, fit the panel.
  40318. var panel = getPanelByCover(controller, cover);
  40319. if (panel !== true && panel.getLinearBrushOtherExtent) {
  40320. otherExtent = panel.getLinearBrushOtherExtent(
  40321. xyIndex, controller._transform
  40322. );
  40323. }
  40324. else {
  40325. var zr = controller._zr;
  40326. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  40327. }
  40328. var rectRange = [localRange, otherExtent];
  40329. xyIndex && rectRange.reverse();
  40330. updateBaseRect(controller, cover, rectRange, brushOption);
  40331. },
  40332. updateCommon: updateCommon,
  40333. contain: mainShapeContain
  40334. };
  40335. }
  40336. function makeRectPanelClipPath(rect) {
  40337. rect = normalizeRect(rect);
  40338. return function (localPoints, transform) {
  40339. return clipPointsByRect(localPoints, rect);
  40340. };
  40341. }
  40342. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  40343. rect = normalizeRect(rect);
  40344. return function (xyIndex) {
  40345. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  40346. var brushWidth = idx ? rect.width : rect.height;
  40347. var base = idx ? rect.x : rect.y;
  40348. return [base, base + (brushWidth || 0)];
  40349. };
  40350. }
  40351. function makeRectIsTargetByCursor(rect, api, targetModel) {
  40352. rect = normalizeRect(rect);
  40353. return function (e, localCursorPoint, transform) {
  40354. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  40355. && !onIrrelevantElement(e, api, targetModel);
  40356. };
  40357. }
  40358. // Consider width/height is negative.
  40359. function normalizeRect(rect) {
  40360. return BoundingRect.create(rect);
  40361. }
  40362. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  40363. var AxisView$2 = extendComponentView({
  40364. type: 'parallelAxis',
  40365. /**
  40366. * @override
  40367. */
  40368. init: function (ecModel, api) {
  40369. AxisView$2.superApply(this, 'init', arguments);
  40370. /**
  40371. * @type {module:echarts/component/helper/BrushController}
  40372. */
  40373. (this._brushController = new BrushController(api.getZr()))
  40374. .on('brush', bind(this._onBrush, this));
  40375. },
  40376. /**
  40377. * @override
  40378. */
  40379. render: function (axisModel, ecModel, api, payload) {
  40380. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  40381. return;
  40382. }
  40383. this.axisModel = axisModel;
  40384. this.api = api;
  40385. this.group.removeAll();
  40386. var oldAxisGroup = this._axisGroup;
  40387. this._axisGroup = new Group();
  40388. this.group.add(this._axisGroup);
  40389. if (!axisModel.get('show')) {
  40390. return;
  40391. }
  40392. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  40393. var coordSys = coordSysModel.coordinateSystem;
  40394. var areaSelectStyle = axisModel.getAreaSelectStyle();
  40395. var areaWidth = areaSelectStyle.width;
  40396. var dim = axisModel.axis.dim;
  40397. var axisLayout = coordSys.getAxisLayout(dim);
  40398. var builderOpt = extend(
  40399. {strokeContainThreshold: areaWidth},
  40400. axisLayout
  40401. );
  40402. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  40403. each$1(elementList, axisBuilder.add, axisBuilder);
  40404. this._axisGroup.add(axisBuilder.getGroup());
  40405. this._refreshBrushController(
  40406. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  40407. );
  40408. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  40409. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  40410. },
  40411. /**
  40412. * @override
  40413. */
  40414. updateVisual: function (axisModel, ecModel, api, payload) {
  40415. this._brushController && this._brushController
  40416. .updateCovers(getCoverInfoList(axisModel));
  40417. },
  40418. _refreshBrushController: function (
  40419. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  40420. ) {
  40421. // After filtering, axis may change, select area needs to be update.
  40422. var extent = axisModel.axis.getExtent();
  40423. var extentLen = extent[1] - extent[0];
  40424. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  40425. // width/height might be negative, which will be
  40426. // normalized in BoundingRect.
  40427. var rect = BoundingRect.create({
  40428. x: extent[0],
  40429. y: -areaWidth / 2,
  40430. width: extentLen,
  40431. height: areaWidth
  40432. });
  40433. rect.x -= extra;
  40434. rect.width += 2 * extra;
  40435. this._brushController
  40436. .mount({
  40437. enableGlobalPan: true,
  40438. rotation: builderOpt.rotation,
  40439. position: builderOpt.position
  40440. })
  40441. .setPanels([{
  40442. panelId: 'pl',
  40443. clipPath: makeRectPanelClipPath(rect),
  40444. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  40445. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  40446. }])
  40447. .enableBrush({
  40448. brushType: 'lineX',
  40449. brushStyle: areaSelectStyle,
  40450. removeOnClick: true
  40451. })
  40452. .updateCovers(getCoverInfoList(axisModel));
  40453. },
  40454. _onBrush: function (coverInfoList, opt) {
  40455. // Do not cache these object, because the mey be changed.
  40456. var axisModel = this.axisModel;
  40457. var axis = axisModel.axis;
  40458. var intervals = map(coverInfoList, function (coverInfo) {
  40459. return [
  40460. axis.coordToData(coverInfo.range[0], true),
  40461. axis.coordToData(coverInfo.range[1], true)
  40462. ];
  40463. });
  40464. // If realtime is true, action is not dispatched on drag end, because
  40465. // the drag end emits the same params with the last drag move event,
  40466. // and may have some delay when using touch pad.
  40467. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  40468. this.api.dispatchAction({
  40469. type: 'axisAreaSelect',
  40470. parallelAxisId: axisModel.id,
  40471. intervals: intervals
  40472. });
  40473. }
  40474. },
  40475. /**
  40476. * @override
  40477. */
  40478. dispose: function () {
  40479. this._brushController.dispose();
  40480. }
  40481. });
  40482. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  40483. return payload
  40484. && payload.type === 'axisAreaSelect'
  40485. && ecModel.findComponents(
  40486. {mainType: 'parallelAxis', query: payload}
  40487. )[0] === axisModel;
  40488. }
  40489. function getCoverInfoList(axisModel) {
  40490. var axis = axisModel.axis;
  40491. return map(axisModel.activeIntervals, function (interval) {
  40492. return {
  40493. brushType: 'lineX',
  40494. panelId: 'pl',
  40495. range: [
  40496. axis.dataToCoord(interval[0], true),
  40497. axis.dataToCoord(interval[1], true)
  40498. ]
  40499. };
  40500. });
  40501. }
  40502. function getCoordSysModel(axisModel, ecModel) {
  40503. return ecModel.getComponent(
  40504. 'parallel', axisModel.get('parallelIndex')
  40505. );
  40506. }
  40507. var CLICK_THRESHOLD = 5; // > 4
  40508. // Parallel view
  40509. extendComponentView({
  40510. type: 'parallel',
  40511. render: function (parallelModel, ecModel, api) {
  40512. this._model = parallelModel;
  40513. this._api = api;
  40514. if (!this._handlers) {
  40515. this._handlers = {};
  40516. each$1(handlers, function (handler, eventName) {
  40517. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  40518. }, this);
  40519. }
  40520. createOrUpdate(
  40521. this,
  40522. '_throttledDispatchExpand',
  40523. parallelModel.get('axisExpandRate'),
  40524. 'fixRate'
  40525. );
  40526. },
  40527. dispose: function (ecModel, api) {
  40528. each$1(this._handlers, function (handler, eventName) {
  40529. api.getZr().off(eventName, handler);
  40530. });
  40531. this._handlers = null;
  40532. },
  40533. /**
  40534. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  40535. */
  40536. _throttledDispatchExpand: function (opt) {
  40537. this._dispatchExpand(opt);
  40538. },
  40539. _dispatchExpand: function (opt) {
  40540. opt && this._api.dispatchAction(
  40541. extend({type: 'parallelAxisExpand'}, opt)
  40542. );
  40543. }
  40544. });
  40545. var handlers = {
  40546. mousedown: function (e) {
  40547. if (checkTrigger(this, 'click')) {
  40548. this._mouseDownPoint = [e.offsetX, e.offsetY];
  40549. }
  40550. },
  40551. mouseup: function (e) {
  40552. var mouseDownPoint = this._mouseDownPoint;
  40553. if (checkTrigger(this, 'click') && mouseDownPoint) {
  40554. var point = [e.offsetX, e.offsetY];
  40555. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  40556. + Math.pow(mouseDownPoint[1] - point[1], 2);
  40557. if (dist > CLICK_THRESHOLD) {
  40558. return;
  40559. }
  40560. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  40561. [e.offsetX, e.offsetY]
  40562. );
  40563. result.behavior !== 'none' && this._dispatchExpand({
  40564. axisExpandWindow: result.axisExpandWindow
  40565. });
  40566. }
  40567. this._mouseDownPoint = null;
  40568. },
  40569. mousemove: function (e) {
  40570. // Should do nothing when brushing.
  40571. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  40572. return;
  40573. }
  40574. var model = this._model;
  40575. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  40576. [e.offsetX, e.offsetY]
  40577. );
  40578. var behavior = result.behavior;
  40579. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  40580. this._throttledDispatchExpand(
  40581. behavior === 'none'
  40582. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  40583. : {
  40584. axisExpandWindow: result.axisExpandWindow,
  40585. // Jumping uses animation, and sliding suppresses animation.
  40586. animation: behavior === 'jump' ? null : false
  40587. }
  40588. );
  40589. }
  40590. };
  40591. function checkTrigger(view, triggerOn) {
  40592. var model = view._model;
  40593. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  40594. }
  40595. registerPreprocessor(parallelPreprocessor);
  40596. SeriesModel.extend({
  40597. type: 'series.parallel',
  40598. dependencies: ['parallel'],
  40599. visualColorAccessPath: 'lineStyle.normal.color',
  40600. getInitialData: function (option, ecModel) {
  40601. var parallelModel = ecModel.getComponent(
  40602. 'parallel', this.get('parallelIndex')
  40603. );
  40604. var parallelAxisIndices = parallelModel.parallelAxisIndex;
  40605. var rawData = option.data;
  40606. var modelDims = parallelModel.dimensions;
  40607. var dataDims = generateDataDims(modelDims, rawData);
  40608. var dataDimsInfo = map(dataDims, function (dim, dimIndex) {
  40609. var modelDimsIndex = indexOf(modelDims, dim);
  40610. var axisModel = modelDimsIndex >= 0 && ecModel.getComponent(
  40611. 'parallelAxis', parallelAxisIndices[modelDimsIndex]
  40612. );
  40613. if (axisModel && axisModel.get('type') === 'category') {
  40614. translateCategoryValue(axisModel, dim, rawData);
  40615. return {name: dim, type: 'ordinal'};
  40616. }
  40617. else if (modelDimsIndex < 0) {
  40618. return completeDimensions.guessOrdinal(rawData, dimIndex)
  40619. ? {name: dim, type: 'ordinal'}
  40620. : dim;
  40621. }
  40622. else {
  40623. return dim;
  40624. }
  40625. });
  40626. var list = new List(dataDimsInfo, this);
  40627. list.initData(rawData);
  40628. // Anication is forbiden in progressive data mode.
  40629. if (this.option.progressive) {
  40630. this.option.animation = false;
  40631. }
  40632. return list;
  40633. },
  40634. /**
  40635. * User can get data raw indices on 'axisAreaSelected' event received.
  40636. *
  40637. * @public
  40638. * @param {string} activeState 'active' or 'inactive' or 'normal'
  40639. * @return {Array.<number>} Raw indices
  40640. */
  40641. getRawIndicesByActiveState: function (activeState) {
  40642. var coordSys = this.coordinateSystem;
  40643. var data = this.getData();
  40644. var indices = [];
  40645. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  40646. if (activeState === theActiveState) {
  40647. indices.push(data.getRawIndex(dataIndex));
  40648. }
  40649. });
  40650. return indices;
  40651. },
  40652. defaultOption: {
  40653. zlevel: 0, // 一级层叠
  40654. z: 2, // 二级层叠
  40655. coordinateSystem: 'parallel',
  40656. parallelIndex: 0,
  40657. label: {
  40658. normal: {
  40659. show: false
  40660. },
  40661. emphasis: {
  40662. show: false
  40663. }
  40664. },
  40665. inactiveOpacity: 0.05,
  40666. activeOpacity: 1,
  40667. lineStyle: {
  40668. normal: {
  40669. width: 1,
  40670. opacity: 0.45,
  40671. type: 'solid'
  40672. }
  40673. },
  40674. progressive: false, // 100
  40675. smooth: false,
  40676. animationEasing: 'linear'
  40677. }
  40678. });
  40679. function translateCategoryValue(axisModel, dim, rawData) {
  40680. var axisData = axisModel.get('data');
  40681. var numberDim = convertDimNameToNumber(dim);
  40682. if (axisData && axisData.length) {
  40683. each$1(rawData, function (dataItem) {
  40684. if (!dataItem) {
  40685. return;
  40686. }
  40687. // FIXME
  40688. // time consuming, should use hash?
  40689. var index = indexOf(axisData, dataItem[numberDim]);
  40690. dataItem[numberDim] = index >= 0 ? index : NaN;
  40691. });
  40692. }
  40693. // FIXME
  40694. // 如果没有设置axis data, 应自动算出,或者提示。
  40695. }
  40696. function convertDimNameToNumber(dimName) {
  40697. return +dimName.replace('dim', '');
  40698. }
  40699. function generateDataDims(modelDims, rawData) {
  40700. // parallelModel.dimension should not be regarded as data
  40701. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  40702. // We detect max dim by parallelModel.dimensions and fist
  40703. // item in rawData arbitrarily.
  40704. var maxDimNum = 0;
  40705. each$1(modelDims, function (dimName) {
  40706. var numberDim = convertDimNameToNumber(dimName);
  40707. numberDim > maxDimNum && (maxDimNum = numberDim);
  40708. });
  40709. var firstItem = rawData[0];
  40710. if (firstItem && firstItem.length - 1 > maxDimNum) {
  40711. maxDimNum = firstItem.length - 1;
  40712. }
  40713. var dataDims = [];
  40714. for (var i = 0; i <= maxDimNum; i++) {
  40715. dataDims.push('dim' + i);
  40716. }
  40717. return dataDims;
  40718. }
  40719. var SMOOTH = 0.3;
  40720. var ParallelView = Chart.extend({
  40721. type: 'parallel',
  40722. init: function () {
  40723. /**
  40724. * @type {module:zrender/container/Group}
  40725. * @private
  40726. */
  40727. this._dataGroup = new Group();
  40728. this.group.add(this._dataGroup);
  40729. /**
  40730. * @type {module:echarts/data/List}
  40731. */
  40732. this._data;
  40733. },
  40734. /**
  40735. * @override
  40736. */
  40737. render: function (seriesModel, ecModel, api, payload) {
  40738. this._renderForNormal(seriesModel, payload);
  40739. // this[
  40740. // seriesModel.option.progressive
  40741. // ? '_renderForProgressive'
  40742. // : '_renderForNormal'
  40743. // ](seriesModel);
  40744. },
  40745. dispose: function () {},
  40746. /**
  40747. * @private
  40748. */
  40749. _renderForNormal: function (seriesModel, payload) {
  40750. var dataGroup = this._dataGroup;
  40751. var data = seriesModel.getData();
  40752. var oldData = this._data;
  40753. var coordSys = seriesModel.coordinateSystem;
  40754. var dimensions = coordSys.dimensions;
  40755. var option = seriesModel.option;
  40756. var smooth = option.smooth ? SMOOTH : null;
  40757. // Consider switch between progressive and not.
  40758. // oldData && oldData.__plProgressive && dataGroup.removeAll();
  40759. data.diff(oldData)
  40760. .add(add)
  40761. .update(update)
  40762. .remove(remove)
  40763. .execute();
  40764. // Update style
  40765. updateElCommon(data, smooth);
  40766. // First create
  40767. if (!this._data) {
  40768. var clipPath = createGridClipShape$1(
  40769. coordSys, seriesModel, function () {
  40770. // Callback will be invoked immediately if there is no animation
  40771. setTimeout(function () {
  40772. dataGroup.removeClipPath();
  40773. });
  40774. }
  40775. );
  40776. dataGroup.setClipPath(clipPath);
  40777. }
  40778. this._data = data;
  40779. function add(newDataIndex) {
  40780. addEl(data, dataGroup, newDataIndex, dimensions, coordSys, null, smooth);
  40781. }
  40782. function update(newDataIndex, oldDataIndex) {
  40783. var line = oldData.getItemGraphicEl(oldDataIndex);
  40784. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  40785. data.setItemGraphicEl(newDataIndex, line);
  40786. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  40787. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  40788. }
  40789. function remove(oldDataIndex) {
  40790. var line = oldData.getItemGraphicEl(oldDataIndex);
  40791. dataGroup.remove(line);
  40792. }
  40793. },
  40794. /**
  40795. * @private
  40796. */
  40797. // _renderForProgressive: function (seriesModel) {
  40798. // var dataGroup = this._dataGroup;
  40799. // var data = seriesModel.getData();
  40800. // var oldData = this._data;
  40801. // var coordSys = seriesModel.coordinateSystem;
  40802. // var dimensions = coordSys.dimensions;
  40803. // var option = seriesModel.option;
  40804. // var progressive = option.progressive;
  40805. // var smooth = option.smooth ? SMOOTH : null;
  40806. // // In progressive animation is disabled, so use simple data diff,
  40807. // // which effects performance less.
  40808. // // (Typically performance for data with length 7000+ like:
  40809. // // simpleDiff: 60ms, addEl: 184ms,
  40810. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  40811. // if (simpleDiff(oldData, data, dimensions)) {
  40812. // dataGroup.removeAll();
  40813. // data.each(function (dataIndex) {
  40814. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  40815. // });
  40816. // }
  40817. // updateElCommon(data, progressive, smooth);
  40818. // // Consider switch between progressive and not.
  40819. // data.__plProgressive = true;
  40820. // this._data = data;
  40821. // },
  40822. /**
  40823. * @override
  40824. */
  40825. remove: function () {
  40826. this._dataGroup && this._dataGroup.removeAll();
  40827. this._data = null;
  40828. }
  40829. });
  40830. function createGridClipShape$1(coordSys, seriesModel, cb) {
  40831. var parallelModel = coordSys.model;
  40832. var rect = coordSys.getRect();
  40833. var rectEl = new Rect({
  40834. shape: {
  40835. x: rect.x,
  40836. y: rect.y,
  40837. width: rect.width,
  40838. height: rect.height
  40839. }
  40840. });
  40841. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  40842. rectEl.setShape(dim, 0);
  40843. initProps(rectEl, {
  40844. shape: {
  40845. width: rect.width,
  40846. height: rect.height
  40847. }
  40848. }, seriesModel, cb);
  40849. return rectEl;
  40850. }
  40851. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  40852. var points = [];
  40853. for (var i = 0; i < dimensions.length; i++) {
  40854. var dimName = dimensions[i];
  40855. var value = data.get(dimName, dataIndex);
  40856. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  40857. points.push(coordSys.dataToPoint(value, dimName));
  40858. }
  40859. }
  40860. return points;
  40861. }
  40862. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  40863. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  40864. var line = new Polyline({
  40865. shape: {points: points},
  40866. silent: true,
  40867. z2: 10
  40868. });
  40869. dataGroup.add(line);
  40870. data.setItemGraphicEl(dataIndex, line);
  40871. }
  40872. function updateElCommon(data, smooth) {
  40873. var seriesStyleModel = data.hostModel.getModel('lineStyle.normal');
  40874. var lineStyle = seriesStyleModel.getLineStyle();
  40875. data.eachItemGraphicEl(function (line, dataIndex) {
  40876. if (data.hasItemOption) {
  40877. var itemModel = data.getItemModel(dataIndex);
  40878. var lineStyleModel = itemModel.getModel('lineStyle.normal', seriesStyleModel);
  40879. lineStyle = lineStyleModel.getLineStyle(['color', 'stroke']);
  40880. }
  40881. line.useStyle(extend(lineStyle, {
  40882. fill: null,
  40883. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  40884. stroke: data.getItemVisual(dataIndex, 'color'),
  40885. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  40886. opacity: data.getItemVisual(dataIndex, 'opacity')
  40887. }));
  40888. line.shape.smooth = smooth;
  40889. });
  40890. }
  40891. // function simpleDiff(oldData, newData, dimensions) {
  40892. // var oldLen;
  40893. // if (!oldData
  40894. // || !oldData.__plProgressive
  40895. // || (oldLen = oldData.count()) !== newData.count()
  40896. // ) {
  40897. // return true;
  40898. // }
  40899. // var dimLen = dimensions.length;
  40900. // for (var i = 0; i < oldLen; i++) {
  40901. // for (var j = 0; j < dimLen; j++) {
  40902. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  40903. // return true;
  40904. // }
  40905. // }
  40906. // }
  40907. // return false;
  40908. // }
  40909. // FIXME
  40910. // 公用方法?
  40911. function isEmptyValue(val, axisType) {
  40912. return axisType === 'category'
  40913. ? val == null
  40914. : (val == null || isNaN(val)); // axisType === 'value'
  40915. }
  40916. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  40917. var parallelVisual = function (ecModel) {
  40918. ecModel.eachSeriesByType('parallel', function (seriesModel) {
  40919. var itemStyleModel = seriesModel.getModel('itemStyle.normal');
  40920. var lineStyleModel = seriesModel.getModel('lineStyle.normal');
  40921. var globalColors = ecModel.get('color');
  40922. var color = lineStyleModel.get('color')
  40923. || itemStyleModel.get('color')
  40924. || globalColors[seriesModel.seriesIndex % globalColors.length];
  40925. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  40926. var activeOpacity = seriesModel.get('activeOpacity');
  40927. var lineStyle = seriesModel.getModel('lineStyle.normal').getLineStyle();
  40928. var coordSys = seriesModel.coordinateSystem;
  40929. var data = seriesModel.getData();
  40930. var opacityMap = {
  40931. normal: lineStyle.opacity,
  40932. active: activeOpacity,
  40933. inactive: inactiveOpacity
  40934. };
  40935. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  40936. var itemModel = data.getItemModel(dataIndex);
  40937. var opacity = opacityMap[activeState];
  40938. if (activeState === 'normal') {
  40939. var itemOpacity = itemModel.get(opacityAccessPath$1, true);
  40940. itemOpacity != null && (opacity = itemOpacity);
  40941. }
  40942. data.setItemVisual(dataIndex, 'opacity', opacity);
  40943. });
  40944. data.setVisual('color', color);
  40945. });
  40946. };
  40947. registerVisual(parallelVisual);
  40948. /**
  40949. * @file Get initial data and define sankey view's series model
  40950. * @author Deqing Li(annong035@gmail.com)
  40951. */
  40952. var SankeySeries = SeriesModel.extend({
  40953. type: 'series.sankey',
  40954. layoutInfo: null,
  40955. /**
  40956. * Init a graph data structure from data in option series
  40957. *
  40958. * @param {Object} option the object used to config echarts view
  40959. * @return {module:echarts/data/List} storage initial data
  40960. */
  40961. getInitialData: function (option) {
  40962. var links = option.edges || option.links;
  40963. var nodes = option.data || option.nodes;
  40964. if (nodes && links) {
  40965. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  40966. return graph.data;
  40967. }
  40968. },
  40969. /**
  40970. * Return the graphic data structure
  40971. *
  40972. * @return {module:echarts/data/Graph} graphic data structure
  40973. */
  40974. getGraph: function () {
  40975. return this.getData().graph;
  40976. },
  40977. /**
  40978. * Get edge data of graphic data structure
  40979. *
  40980. * @return {module:echarts/data/List} data structure of list
  40981. */
  40982. getEdgeData: function () {
  40983. return this.getGraph().edgeData;
  40984. },
  40985. /**
  40986. * @override
  40987. */
  40988. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  40989. // dataType === 'node' or empty do not show tooltip by default
  40990. if (dataType === 'edge') {
  40991. var params = this.getDataParams(dataIndex, dataType);
  40992. var rawDataOpt = params.data;
  40993. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  40994. if (params.value) {
  40995. html += ' : ' + params.value;
  40996. }
  40997. return encodeHTML(html);
  40998. }
  40999. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  41000. },
  41001. defaultOption: {
  41002. zlevel: 0,
  41003. z: 2,
  41004. coordinateSystem: 'view',
  41005. layout: null,
  41006. // the position of the whole view
  41007. left: '5%',
  41008. top: '5%',
  41009. right: '20%',
  41010. bottom: '5%',
  41011. // the dx of the node
  41012. nodeWidth: 20,
  41013. // the vertical distance between two nodes
  41014. nodeGap: 8,
  41015. // the number of iterations to change the position of the node
  41016. layoutIterations: 32,
  41017. label: {
  41018. normal: {
  41019. show: true,
  41020. position: 'right',
  41021. color: '#000',
  41022. fontSize: 12
  41023. },
  41024. emphasis: {
  41025. show: true
  41026. }
  41027. },
  41028. itemStyle: {
  41029. normal: {
  41030. borderWidth: 1,
  41031. borderColor: '#333'
  41032. }
  41033. },
  41034. lineStyle: {
  41035. normal: {
  41036. color: '#314656',
  41037. opacity: 0.2,
  41038. curveness: 0.5
  41039. },
  41040. emphasis: {
  41041. opacity: 0.6
  41042. }
  41043. },
  41044. animationEasing: 'linear',
  41045. animationDuration: 1000
  41046. }
  41047. });
  41048. /**
  41049. * @file The file used to draw sankey view
  41050. * @author Deqing Li(annong035@gmail.com)
  41051. */
  41052. var SankeyShape = extendShape({
  41053. shape: {
  41054. x1: 0, y1: 0,
  41055. x2: 0, y2: 0,
  41056. cpx1: 0, cpy1: 0,
  41057. cpx2: 0, cpy2: 0,
  41058. extent: 0
  41059. },
  41060. buildPath: function (ctx, shape) {
  41061. var halfExtent = shape.extent / 2;
  41062. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  41063. ctx.bezierCurveTo(
  41064. shape.cpx1, shape.cpy1 - halfExtent,
  41065. shape.cpx2, shape.cpy2 - halfExtent,
  41066. shape.x2, shape.y2 - halfExtent
  41067. );
  41068. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  41069. ctx.bezierCurveTo(
  41070. shape.cpx2, shape.cpy2 + halfExtent,
  41071. shape.cpx1, shape.cpy1 + halfExtent,
  41072. shape.x1, shape.y1 + halfExtent
  41073. );
  41074. ctx.closePath();
  41075. }
  41076. });
  41077. extendChartView({
  41078. type: 'sankey',
  41079. /**
  41080. * @private
  41081. * @type {module:echarts/chart/sankey/SankeySeries}
  41082. */
  41083. _model: null,
  41084. render: function (seriesModel, ecModel, api) {
  41085. var graph = seriesModel.getGraph();
  41086. var group = this.group;
  41087. var layoutInfo = seriesModel.layoutInfo;
  41088. var nodeData = seriesModel.getData();
  41089. var edgeData = seriesModel.getData('edge');
  41090. this._model = seriesModel;
  41091. group.removeAll();
  41092. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  41093. // generate a bezire Curve for each edge
  41094. graph.eachEdge(function (edge) {
  41095. var curve = new SankeyShape();
  41096. curve.dataIndex = edge.dataIndex;
  41097. curve.seriesIndex = seriesModel.seriesIndex;
  41098. curve.dataType = 'edge';
  41099. var lineStyleModel = edge.getModel('lineStyle.normal');
  41100. var curvature = lineStyleModel.get('curveness');
  41101. var n1Layout = edge.node1.getLayout();
  41102. var n2Layout = edge.node2.getLayout();
  41103. var edgeLayout = edge.getLayout();
  41104. curve.shape.extent = Math.max(1, edgeLayout.dy);
  41105. var x1 = n1Layout.x + n1Layout.dx;
  41106. var y1 = n1Layout.y + edgeLayout.sy + edgeLayout.dy / 2;
  41107. var x2 = n2Layout.x;
  41108. var y2 = n2Layout.y + edgeLayout.ty + edgeLayout.dy / 2;
  41109. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  41110. var cpy1 = y1;
  41111. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  41112. var cpy2 = y2;
  41113. curve.setShape({
  41114. x1: x1,
  41115. y1: y1,
  41116. x2: x2,
  41117. y2: y2,
  41118. cpx1: cpx1,
  41119. cpy1: cpy1,
  41120. cpx2: cpx2,
  41121. cpy2: cpy2
  41122. });
  41123. curve.setStyle(lineStyleModel.getItemStyle());
  41124. // Special color, use source node color or target node color
  41125. switch (curve.style.fill) {
  41126. case 'source':
  41127. curve.style.fill = edge.node1.getVisual('color');
  41128. break;
  41129. case 'target':
  41130. curve.style.fill = edge.node2.getVisual('color');
  41131. break;
  41132. }
  41133. setHoverStyle(curve, edge.getModel('lineStyle.emphasis').getItemStyle());
  41134. group.add(curve);
  41135. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  41136. });
  41137. // generate a rect for each node
  41138. graph.eachNode(function (node) {
  41139. var layout = node.getLayout();
  41140. var itemModel = node.getModel();
  41141. var labelModel = itemModel.getModel('label.normal');
  41142. var labelHoverModel = itemModel.getModel('label.emphasis');
  41143. var rect = new Rect({
  41144. shape: {
  41145. x: layout.x,
  41146. y: layout.y,
  41147. width: node.getLayout().dx,
  41148. height: node.getLayout().dy
  41149. },
  41150. style: itemModel.getModel('itemStyle.normal').getItemStyle()
  41151. });
  41152. var hoverStyle = node.getModel('itemStyle.emphasis').getItemStyle();
  41153. setLabelStyle(
  41154. rect.style, hoverStyle, labelModel, labelHoverModel,
  41155. {
  41156. labelFetcher: seriesModel,
  41157. labelDataIndex: node.dataIndex,
  41158. defaultText: node.id,
  41159. isRectText: true
  41160. }
  41161. );
  41162. rect.setStyle('fill', node.getVisual('color'));
  41163. setHoverStyle(rect, hoverStyle);
  41164. group.add(rect);
  41165. nodeData.setItemGraphicEl(node.dataIndex, rect);
  41166. rect.dataType = 'node';
  41167. });
  41168. if (!this._data && seriesModel.get('animation')) {
  41169. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  41170. group.removeClipPath();
  41171. }));
  41172. }
  41173. this._data = seriesModel.getData();
  41174. },
  41175. dispose: function () {}
  41176. });
  41177. // add animation to the view
  41178. function createGridClipShape$2(rect, seriesModel, cb) {
  41179. var rectEl = new Rect({
  41180. shape: {
  41181. x: rect.x - 10,
  41182. y: rect.y - 10,
  41183. width: 0,
  41184. height: rect.height + 20
  41185. }
  41186. });
  41187. initProps(rectEl, {
  41188. shape: {
  41189. width: rect.width + 20,
  41190. height: rect.height + 20
  41191. }
  41192. }, seriesModel, cb);
  41193. return rectEl;
  41194. }
  41195. /**
  41196. * nest helper used to group by the array.
  41197. * can specified the keys and sort the keys.
  41198. */
  41199. function nest() {
  41200. var keysFunction = [];
  41201. var sortKeysFunction = [];
  41202. /**
  41203. * map an Array into the mapObject.
  41204. * @param {Array} array
  41205. * @param {number} depth
  41206. */
  41207. function map$$1(array, depth) {
  41208. if (depth >= keysFunction.length) {
  41209. return array;
  41210. }
  41211. var i = -1;
  41212. var n = array.length;
  41213. var keyFunction = keysFunction[depth++];
  41214. var mapObject = {};
  41215. var valuesByKey = {};
  41216. while (++i < n) {
  41217. var keyValue = keyFunction(array[i]);
  41218. var values = valuesByKey[keyValue];
  41219. if (values) {
  41220. values.push(array[i]);
  41221. }
  41222. else {
  41223. valuesByKey[keyValue] = [array[i]];
  41224. }
  41225. }
  41226. each$1(valuesByKey, function (value, key) {
  41227. mapObject[key] = map$$1(value, depth);
  41228. });
  41229. return mapObject;
  41230. }
  41231. /**
  41232. * transform the Map Object to multidimensional Array
  41233. * @param {Object} map
  41234. * @param {number} depth
  41235. */
  41236. function entriesMap(mapObject, depth) {
  41237. if (depth >= keysFunction.length) {
  41238. return mapObject;
  41239. }
  41240. var array = [];
  41241. var sortKeyFunction = sortKeysFunction[depth++];
  41242. each$1(mapObject, function (value, key) {
  41243. array.push({
  41244. key: key, values: entriesMap(value, depth)
  41245. });
  41246. });
  41247. if (sortKeyFunction) {
  41248. return array.sort(function (a, b) {
  41249. return sortKeyFunction(a.key, b.key);
  41250. });
  41251. }
  41252. else {
  41253. return array;
  41254. }
  41255. }
  41256. return {
  41257. /**
  41258. * specified the key to groupby the arrays.
  41259. * users can specified one more keys.
  41260. * @param {Function} d
  41261. */
  41262. key: function (d) {
  41263. keysFunction.push(d);
  41264. return this;
  41265. },
  41266. /**
  41267. * specified the comparator to sort the keys
  41268. * @param {Function} order
  41269. */
  41270. sortKeys: function (order) {
  41271. sortKeysFunction[keysFunction.length - 1] = order;
  41272. return this;
  41273. },
  41274. /**
  41275. * the array to be grouped by.
  41276. * @param {Array} array
  41277. */
  41278. entries: function (array) {
  41279. return entriesMap(map$$1(array, 0), 0);
  41280. }
  41281. };
  41282. }
  41283. /**
  41284. * @file The layout algorithm of sankey view
  41285. * @author Deqing Li(annong035@gmail.com)
  41286. */
  41287. var sankeyLayout = function (ecModel, api, payload) {
  41288. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  41289. var nodeWidth = seriesModel.get('nodeWidth');
  41290. var nodeGap = seriesModel.get('nodeGap');
  41291. var layoutInfo = getViewRect$3(seriesModel, api);
  41292. seriesModel.layoutInfo = layoutInfo;
  41293. var width = layoutInfo.width;
  41294. var height = layoutInfo.height;
  41295. var graph = seriesModel.getGraph();
  41296. var nodes = graph.nodes;
  41297. var edges = graph.edges;
  41298. computeNodeValues(nodes);
  41299. var filteredNodes = filter(nodes, function (node) {
  41300. return node.getLayout().value === 0;
  41301. });
  41302. var iterations = filteredNodes.length !== 0
  41303. ? 0 : seriesModel.get('layoutIterations');
  41304. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  41305. });
  41306. };
  41307. /**
  41308. * Get the layout position of the whole view
  41309. *
  41310. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  41311. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  41312. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  41313. */
  41314. function getViewRect$3(seriesModel, api) {
  41315. return getLayoutRect(
  41316. seriesModel.getBoxLayoutParams(), {
  41317. width: api.getWidth(),
  41318. height: api.getHeight()
  41319. }
  41320. );
  41321. }
  41322. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  41323. computeNodeBreadths(nodes, nodeWidth, width);
  41324. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  41325. computeEdgeDepths(nodes);
  41326. }
  41327. /**
  41328. * Compute the value of each node by summing the associated edge's value
  41329. *
  41330. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41331. */
  41332. function computeNodeValues(nodes) {
  41333. each$1(nodes, function (node) {
  41334. var value1 = sum(node.outEdges, getEdgeValue);
  41335. var value2 = sum(node.inEdges, getEdgeValue);
  41336. var value = Math.max(value1, value2);
  41337. node.setLayout({value: value}, true);
  41338. });
  41339. }
  41340. /**
  41341. * Compute the x-position for each node
  41342. *
  41343. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41344. * @param {number} nodeWidth the dx of the node
  41345. * @param {number} width the whole width of the area to draw the view
  41346. */
  41347. function computeNodeBreadths(nodes, nodeWidth, width) {
  41348. var remainNodes = nodes;
  41349. var nextNode = null;
  41350. var x = 0;
  41351. var kx = 0;
  41352. while (remainNodes.length) {
  41353. nextNode = [];
  41354. for (var i = 0, len = remainNodes.length; i < len; i++) {
  41355. var node = remainNodes[i];
  41356. node.setLayout({x: x}, true);
  41357. node.setLayout({dx: nodeWidth}, true);
  41358. for (var j = 0, lenj = node.outEdges.length; j < lenj; j++) {
  41359. nextNode.push(node.outEdges[j].node2);
  41360. }
  41361. }
  41362. remainNodes = nextNode;
  41363. ++x;
  41364. }
  41365. moveSinksRight(nodes, x);
  41366. kx = (width - nodeWidth) / (x - 1);
  41367. scaleNodeBreadths(nodes, kx);
  41368. }
  41369. /**
  41370. * All the node without outEgdes are assigned maximum x-position and
  41371. * be aligned in the last column.
  41372. *
  41373. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41374. * @param {number} x value (x-1) use to assign to node without outEdges
  41375. * as x-position
  41376. */
  41377. function moveSinksRight(nodes, x) {
  41378. each$1(nodes, function (node) {
  41379. if (!node.outEdges.length) {
  41380. node.setLayout({x: x - 1}, true);
  41381. }
  41382. });
  41383. }
  41384. /**
  41385. * Scale node x-position to the width
  41386. *
  41387. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41388. * @param {number} kx multiple used to scale nodes
  41389. */
  41390. function scaleNodeBreadths(nodes, kx) {
  41391. each$1(nodes, function (node) {
  41392. var nodeX = node.getLayout().x * kx;
  41393. node.setLayout({x: nodeX}, true);
  41394. });
  41395. }
  41396. /**
  41397. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  41398. *
  41399. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41400. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  41401. * @param {number} height the whole height of the area to draw the view
  41402. * @param {number} nodeGap the vertical distance between two nodes
  41403. * in the same column.
  41404. * @param {number} iterations the number of iterations for the algorithm
  41405. */
  41406. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  41407. var nodesByBreadth = nest()
  41408. .key(function (d) {
  41409. return d.getLayout().x;
  41410. })
  41411. .sortKeys(ascending)
  41412. .entries(nodes)
  41413. .map(function (d) {
  41414. return d.values;
  41415. });
  41416. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  41417. resolveCollisions(nodesByBreadth, nodeGap, height);
  41418. for (var alpha = 1; iterations > 0; iterations--) {
  41419. // 0.99 is a experience parameter, ensure that each iterations of
  41420. // changes as small as possible.
  41421. alpha *= 0.99;
  41422. relaxRightToLeft(nodesByBreadth, alpha);
  41423. resolveCollisions(nodesByBreadth, nodeGap, height);
  41424. relaxLeftToRight(nodesByBreadth, alpha);
  41425. resolveCollisions(nodesByBreadth, nodeGap, height);
  41426. }
  41427. }
  41428. /**
  41429. * Compute the original y-position for each node
  41430. *
  41431. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41432. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41433. * group by the array of all sankey nodes based on the nodes x-position.
  41434. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  41435. * @param {number} height the whole height of the area to draw the view
  41436. * @param {number} nodeGap the vertical distance between two nodes
  41437. */
  41438. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  41439. var kyArray = [];
  41440. each$1(nodesByBreadth, function (nodes) {
  41441. var n = nodes.length;
  41442. var sum = 0;
  41443. each$1(nodes, function (node) {
  41444. sum += node.getLayout().value;
  41445. });
  41446. var ky = (height - (n - 1) * nodeGap) / sum;
  41447. kyArray.push(ky);
  41448. });
  41449. kyArray.sort(function (a, b) {
  41450. return a - b;
  41451. });
  41452. var ky0 = kyArray[0];
  41453. each$1(nodesByBreadth, function (nodes) {
  41454. each$1(nodes, function (node, i) {
  41455. node.setLayout({y: i}, true);
  41456. var nodeDy = node.getLayout().value * ky0;
  41457. node.setLayout({dy: nodeDy}, true);
  41458. });
  41459. });
  41460. each$1(edges, function (edge) {
  41461. var edgeDy = +edge.getValue() * ky0;
  41462. edge.setLayout({dy: edgeDy}, true);
  41463. });
  41464. }
  41465. /**
  41466. * Resolve the collision of initialized depth (y-position)
  41467. *
  41468. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41469. * group by the array of all sankey nodes based on the nodes x-position.
  41470. * @param {number} nodeGap the vertical distance between two nodes
  41471. * @param {number} height the whole height of the area to draw the view
  41472. */
  41473. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  41474. each$1(nodesByBreadth, function (nodes) {
  41475. var node;
  41476. var dy;
  41477. var y0 = 0;
  41478. var n = nodes.length;
  41479. var i;
  41480. nodes.sort(ascendingDepth);
  41481. for (i = 0; i < n; i++) {
  41482. node = nodes[i];
  41483. dy = y0 - node.getLayout().y;
  41484. if (dy > 0) {
  41485. var nodeY = node.getLayout().y + dy;
  41486. node.setLayout({y: nodeY}, true);
  41487. }
  41488. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  41489. }
  41490. // if the bottommost node goes outside the bounds, push it back up
  41491. dy = y0 - nodeGap - height;
  41492. if (dy > 0) {
  41493. var nodeY = node.getLayout().y - dy;
  41494. node.setLayout({y: nodeY}, true);
  41495. y0 = node.getLayout().y;
  41496. for (i = n - 2; i >= 0; --i) {
  41497. node = nodes[i];
  41498. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  41499. if (dy > 0) {
  41500. nodeY = node.getLayout().y - dy;
  41501. node.setLayout({y: nodeY}, true);
  41502. }
  41503. y0 = node.getLayout().y;
  41504. }
  41505. }
  41506. });
  41507. }
  41508. /**
  41509. * Change the y-position of the nodes, except most the right side nodes
  41510. *
  41511. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41512. * group by the array of all sankey nodes based on the node x-position.
  41513. * @param {number} alpha parameter used to adjust the nodes y-position
  41514. */
  41515. function relaxRightToLeft(nodesByBreadth, alpha) {
  41516. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  41517. each$1(nodes, function (node) {
  41518. if (node.outEdges.length) {
  41519. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  41520. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  41521. node.setLayout({y: nodeY}, true);
  41522. }
  41523. });
  41524. });
  41525. }
  41526. function weightedTarget(edge) {
  41527. return center$1(edge.node2) * edge.getValue();
  41528. }
  41529. /**
  41530. * Change the y-position of the nodes, except most the left side nodes
  41531. *
  41532. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  41533. * group by the array of all sankey nodes based on the node x-position.
  41534. * @param {number} alpha parameter used to adjust the nodes y-position
  41535. */
  41536. function relaxLeftToRight(nodesByBreadth, alpha) {
  41537. each$1(nodesByBreadth, function (nodes) {
  41538. each$1(nodes, function (node) {
  41539. if (node.inEdges.length) {
  41540. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  41541. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  41542. node.setLayout({y: nodeY}, true);
  41543. }
  41544. });
  41545. });
  41546. }
  41547. function weightedSource(edge) {
  41548. return center$1(edge.node1) * edge.getValue();
  41549. }
  41550. /**
  41551. * Compute the depth(y-position) of each edge
  41552. *
  41553. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  41554. */
  41555. function computeEdgeDepths(nodes) {
  41556. each$1(nodes, function (node) {
  41557. node.outEdges.sort(ascendingTargetDepth);
  41558. node.inEdges.sort(ascendingSourceDepth);
  41559. });
  41560. each$1(nodes, function (node) {
  41561. var sy = 0;
  41562. var ty = 0;
  41563. each$1(node.outEdges, function (edge) {
  41564. edge.setLayout({sy: sy}, true);
  41565. sy += edge.getLayout().dy;
  41566. });
  41567. each$1(node.inEdges, function (edge) {
  41568. edge.setLayout({ty: ty}, true);
  41569. ty += edge.getLayout().dy;
  41570. });
  41571. });
  41572. }
  41573. function ascendingTargetDepth(a, b) {
  41574. return a.node2.getLayout().y - b.node2.getLayout().y;
  41575. }
  41576. function ascendingSourceDepth(a, b) {
  41577. return a.node1.getLayout().y - b.node1.getLayout().y;
  41578. }
  41579. function sum(array, f) {
  41580. var sum = 0;
  41581. var len = array.length;
  41582. var i = -1;
  41583. while (++i < len) {
  41584. var value = +f.call(array, array[i], i);
  41585. if (!isNaN(value)) {
  41586. sum += value;
  41587. }
  41588. }
  41589. return sum;
  41590. }
  41591. function center$1(node) {
  41592. return node.getLayout().y + node.getLayout().dy / 2;
  41593. }
  41594. function ascendingDepth(a, b) {
  41595. return a.getLayout().y - b.getLayout().y;
  41596. }
  41597. function ascending(a, b) {
  41598. return a < b ? -1 : a > b ? 1 : a === b ? 0 : NaN;
  41599. }
  41600. function getEdgeValue(edge) {
  41601. return edge.getValue();
  41602. }
  41603. /**
  41604. * @file Visual encoding for sankey view
  41605. * @author Deqing Li(annong035@gmail.com)
  41606. */
  41607. var sankeyVisual = function (ecModel, payload) {
  41608. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  41609. var graph = seriesModel.getGraph();
  41610. var nodes = graph.nodes;
  41611. nodes.sort(function (a, b) {
  41612. return a.getLayout().value - b.getLayout().value;
  41613. });
  41614. var minValue = nodes[0].getLayout().value;
  41615. var maxValue = nodes[nodes.length - 1].getLayout().value;
  41616. each$1(nodes, function (node) {
  41617. var mapping = new VisualMapping({
  41618. type: 'color',
  41619. mappingMethod: 'linear',
  41620. dataExtent: [minValue, maxValue],
  41621. visual: seriesModel.get('color')
  41622. });
  41623. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  41624. node.setVisual('color', mapValueToColor);
  41625. // If set itemStyle.normal.color
  41626. var itemModel = node.getModel();
  41627. var customColor = itemModel.get('itemStyle.normal.color');
  41628. if (customColor != null) {
  41629. node.setVisual('color', customColor);
  41630. }
  41631. });
  41632. });
  41633. };
  41634. registerLayout(sankeyLayout);
  41635. registerVisual(sankeyVisual);
  41636. /**
  41637. * @module echarts/chart/helper/Symbol
  41638. */
  41639. var WhiskerPath = Path.extend({
  41640. type: 'whiskerInBox',
  41641. shape: {},
  41642. buildPath: function (ctx, shape) {
  41643. for (var i in shape) {
  41644. if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
  41645. var pts = shape[i];
  41646. ctx.moveTo(pts[0][0], pts[0][1]);
  41647. ctx.lineTo(pts[1][0], pts[1][1]);
  41648. }
  41649. }
  41650. }
  41651. });
  41652. /**
  41653. * @constructor
  41654. * @alias {module:echarts/chart/helper/WhiskerBox}
  41655. * @param {module:echarts/data/List} data
  41656. * @param {number} idx
  41657. * @param {Function} styleUpdater
  41658. * @param {boolean} isInit
  41659. * @extends {module:zrender/graphic/Group}
  41660. */
  41661. function WhiskerBox(data, idx, styleUpdater, isInit) {
  41662. Group.call(this);
  41663. /**
  41664. * @type {number}
  41665. * @readOnly
  41666. */
  41667. this.bodyIndex;
  41668. /**
  41669. * @type {number}
  41670. * @readOnly
  41671. */
  41672. this.whiskerIndex;
  41673. /**
  41674. * @type {Function}
  41675. */
  41676. this.styleUpdater = styleUpdater;
  41677. this._createContent(data, idx, isInit);
  41678. this.updateData(data, idx, isInit);
  41679. /**
  41680. * Last series model.
  41681. * @type {module:echarts/model/Series}
  41682. */
  41683. this._seriesModel;
  41684. }
  41685. var whiskerBoxProto = WhiskerBox.prototype;
  41686. whiskerBoxProto._createContent = function (data, idx, isInit) {
  41687. var itemLayout = data.getItemLayout(idx);
  41688. var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
  41689. var count = 0;
  41690. // Whisker element.
  41691. this.add(new Polygon({
  41692. shape: {
  41693. points: isInit
  41694. ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
  41695. : itemLayout.bodyEnds
  41696. },
  41697. style: {strokeNoScale: true},
  41698. z2: 100
  41699. }));
  41700. this.bodyIndex = count++;
  41701. // Box element.
  41702. var whiskerEnds = map(itemLayout.whiskerEnds, function (ends) {
  41703. return isInit ? transInit(ends, constDim, itemLayout) : ends;
  41704. });
  41705. this.add(new WhiskerPath({
  41706. shape: makeWhiskerEndsShape(whiskerEnds),
  41707. style: {strokeNoScale: true},
  41708. z2: 100
  41709. }));
  41710. this.whiskerIndex = count++;
  41711. };
  41712. function transInit(points, dim, itemLayout) {
  41713. return map(points, function (point) {
  41714. point = point.slice();
  41715. point[dim] = itemLayout.initBaseline;
  41716. return point;
  41717. });
  41718. }
  41719. function makeWhiskerEndsShape(whiskerEnds) {
  41720. // zr animation only support 2-dim array.
  41721. var shape = {};
  41722. each$1(whiskerEnds, function (ends, i) {
  41723. shape['ends' + i] = ends;
  41724. });
  41725. return shape;
  41726. }
  41727. /**
  41728. * Update symbol properties
  41729. * @param {module:echarts/data/List} data
  41730. * @param {number} idx
  41731. */
  41732. whiskerBoxProto.updateData = function (data, idx, isInit) {
  41733. var seriesModel = this._seriesModel = data.hostModel;
  41734. var itemLayout = data.getItemLayout(idx);
  41735. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  41736. // this.childAt(this.bodyIndex).stopAnimation(true);
  41737. // this.childAt(this.whiskerIndex).stopAnimation(true);
  41738. updateMethod(
  41739. this.childAt(this.bodyIndex),
  41740. {shape: {points: itemLayout.bodyEnds}},
  41741. seriesModel, idx
  41742. );
  41743. updateMethod(
  41744. this.childAt(this.whiskerIndex),
  41745. {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
  41746. seriesModel, idx
  41747. );
  41748. this.styleUpdater.call(null, this, data, idx);
  41749. };
  41750. inherits(WhiskerBox, Group);
  41751. /**
  41752. * @constructor
  41753. * @alias module:echarts/chart/helper/WhiskerBoxDraw
  41754. */
  41755. function WhiskerBoxDraw(styleUpdater) {
  41756. this.group = new Group();
  41757. this.styleUpdater = styleUpdater;
  41758. }
  41759. var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;
  41760. /**
  41761. * Update symbols draw by new data
  41762. * @param {module:echarts/data/List} data
  41763. */
  41764. whiskerBoxDrawProto.updateData = function (data) {
  41765. var group = this.group;
  41766. var oldData = this._data;
  41767. var styleUpdater = this.styleUpdater;
  41768. data.diff(oldData)
  41769. .add(function (newIdx) {
  41770. if (data.hasValue(newIdx)) {
  41771. var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
  41772. data.setItemGraphicEl(newIdx, symbolEl);
  41773. group.add(symbolEl);
  41774. }
  41775. })
  41776. .update(function (newIdx, oldIdx) {
  41777. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  41778. // Empty data
  41779. if (!data.hasValue(newIdx)) {
  41780. group.remove(symbolEl);
  41781. return;
  41782. }
  41783. if (!symbolEl) {
  41784. symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
  41785. }
  41786. else {
  41787. symbolEl.updateData(data, newIdx);
  41788. }
  41789. // Add back
  41790. group.add(symbolEl);
  41791. data.setItemGraphicEl(newIdx, symbolEl);
  41792. })
  41793. .remove(function (oldIdx) {
  41794. var el = oldData.getItemGraphicEl(oldIdx);
  41795. el && group.remove(el);
  41796. })
  41797. .execute();
  41798. this._data = data;
  41799. };
  41800. /**
  41801. * Remove symbols.
  41802. * @param {module:echarts/data/List} data
  41803. */
  41804. whiskerBoxDrawProto.remove = function () {
  41805. var group = this.group;
  41806. var data = this._data;
  41807. this._data = null;
  41808. data && data.eachItemGraphicEl(function (el) {
  41809. el && group.remove(el);
  41810. });
  41811. };
  41812. var seriesModelMixin = {
  41813. /**
  41814. * @private
  41815. * @type {string}
  41816. */
  41817. _baseAxisDim: null,
  41818. /**
  41819. * @override
  41820. */
  41821. getInitialData: function (option, ecModel) {
  41822. // When both types of xAxis and yAxis are 'value', layout is
  41823. // needed to be specified by user. Otherwise, layout can be
  41824. // judged by which axis is category.
  41825. var categories;
  41826. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  41827. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  41828. var xAxisType = xAxisModel.get('type');
  41829. var yAxisType = yAxisModel.get('type');
  41830. var addOrdinal;
  41831. // FIXME
  41832. // 考虑时间轴
  41833. if (xAxisType === 'category') {
  41834. option.layout = 'horizontal';
  41835. categories = xAxisModel.getCategories();
  41836. addOrdinal = true;
  41837. }
  41838. else if (yAxisType === 'category') {
  41839. option.layout = 'vertical';
  41840. categories = yAxisModel.getCategories();
  41841. addOrdinal = true;
  41842. }
  41843. else {
  41844. option.layout = option.layout || 'horizontal';
  41845. }
  41846. var coordDims = ['x', 'y'];
  41847. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  41848. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  41849. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  41850. var data = option.data;
  41851. addOrdinal && each$1(data, function (item, index) {
  41852. if (item.value && isArray(item.value)) {
  41853. item.value.unshift(index);
  41854. } else {
  41855. isArray(item) && item.unshift(index);
  41856. }
  41857. });
  41858. var defaultValueDimensions = this.defaultValueDimensions;
  41859. var dimensions = [{
  41860. name: baseAxisDim,
  41861. otherDims: {
  41862. tooltip: false
  41863. },
  41864. dimsDef: ['base']
  41865. }, {
  41866. name: otherAxisDim,
  41867. dimsDef: defaultValueDimensions.slice()
  41868. }];
  41869. dimensions = completeDimensions(dimensions, data, {
  41870. encodeDef: this.get('encode'),
  41871. dimsDef: this.get('dimensions'),
  41872. // Consider empty data entry.
  41873. dimCount: defaultValueDimensions.length + 1
  41874. });
  41875. var list = new List(dimensions, this);
  41876. list.initData(data, categories ? categories.slice() : null);
  41877. return list;
  41878. },
  41879. /**
  41880. * If horizontal, base axis is x, otherwise y.
  41881. * @override
  41882. */
  41883. getBaseAxis: function () {
  41884. var dim = this._baseAxisDim;
  41885. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  41886. }
  41887. };
  41888. var viewMixin = {
  41889. init: function () {
  41890. /**
  41891. * Old data.
  41892. * @private
  41893. * @type {module:echarts/chart/helper/WhiskerBoxDraw}
  41894. */
  41895. var whiskerBoxDraw = this._whiskerBoxDraw = new WhiskerBoxDraw(
  41896. this.getStyleUpdater()
  41897. );
  41898. this.group.add(whiskerBoxDraw.group);
  41899. },
  41900. render: function (seriesModel, ecModel, api) {
  41901. this._whiskerBoxDraw.updateData(seriesModel.getData());
  41902. },
  41903. remove: function (ecModel) {
  41904. this._whiskerBoxDraw.remove();
  41905. }
  41906. };
  41907. var BoxplotSeries = SeriesModel.extend({
  41908. type: 'series.boxplot',
  41909. dependencies: ['xAxis', 'yAxis', 'grid'],
  41910. // TODO
  41911. // box width represents group size, so dimension should have 'size'.
  41912. /**
  41913. * @see <https://en.wikipedia.org/wiki/Box_plot>
  41914. * The meanings of 'min' and 'max' depend on user,
  41915. * and echarts do not need to know it.
  41916. * @readOnly
  41917. */
  41918. defaultValueDimensions: ['min', 'Q1', 'median', 'Q3', 'max'],
  41919. /**
  41920. * @type {Array.<string>}
  41921. * @readOnly
  41922. */
  41923. dimensions: null,
  41924. /**
  41925. * @override
  41926. */
  41927. defaultOption: {
  41928. zlevel: 0, // 一级层叠
  41929. z: 2, // 二级层叠
  41930. coordinateSystem: 'cartesian2d',
  41931. legendHoverLink: true,
  41932. hoverAnimation: true,
  41933. // xAxisIndex: 0,
  41934. // yAxisIndex: 0,
  41935. layout: null, // 'horizontal' or 'vertical'
  41936. boxWidth: [7, 50], // [min, max] can be percent of band width.
  41937. itemStyle: {
  41938. normal: {
  41939. color: '#fff',
  41940. borderWidth: 1
  41941. },
  41942. emphasis: {
  41943. borderWidth: 2,
  41944. shadowBlur: 5,
  41945. shadowOffsetX: 2,
  41946. shadowOffsetY: 2,
  41947. shadowColor: 'rgba(0,0,0,0.4)'
  41948. }
  41949. },
  41950. animationEasing: 'elasticOut',
  41951. animationDuration: 800
  41952. }
  41953. });
  41954. mixin(BoxplotSeries, seriesModelMixin, true);
  41955. var BoxplotView = Chart.extend({
  41956. type: 'boxplot',
  41957. getStyleUpdater: function () {
  41958. return updateStyle$1;
  41959. },
  41960. dispose: noop
  41961. });
  41962. mixin(BoxplotView, viewMixin, true);
  41963. // Update common properties
  41964. var normalStyleAccessPath$1 = ['itemStyle', 'normal'];
  41965. var emphasisStyleAccessPath$1 = ['itemStyle', 'emphasis'];
  41966. function updateStyle$1(itemGroup, data, idx) {
  41967. var itemModel = data.getItemModel(idx);
  41968. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$1);
  41969. var borderColor = data.getItemVisual(idx, 'color');
  41970. // Exclude borderColor.
  41971. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  41972. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  41973. whiskerEl.style.set(itemStyle);
  41974. whiskerEl.style.stroke = borderColor;
  41975. whiskerEl.dirty();
  41976. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  41977. bodyEl.style.set(itemStyle);
  41978. bodyEl.style.stroke = borderColor;
  41979. bodyEl.dirty();
  41980. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$1).getItemStyle();
  41981. setHoverStyle(itemGroup, hoverStyle);
  41982. }
  41983. var borderColorQuery = ['itemStyle', 'normal', 'borderColor'];
  41984. var boxplotVisual = function (ecModel, api) {
  41985. var globalColors = ecModel.get('color');
  41986. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  41987. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  41988. var data = seriesModel.getData();
  41989. data.setVisual({
  41990. legendSymbol: 'roundRect',
  41991. // Use name 'color' but not 'borderColor' for legend usage and
  41992. // visual coding from other component like dataRange.
  41993. color: seriesModel.get(borderColorQuery) || defaulColor
  41994. });
  41995. // Only visible series has each data be visual encoded
  41996. if (!ecModel.isSeriesFiltered(seriesModel)) {
  41997. data.each(function (idx) {
  41998. var itemModel = data.getItemModel(idx);
  41999. data.setItemVisual(
  42000. idx,
  42001. {color: itemModel.get(borderColorQuery, true)}
  42002. );
  42003. });
  42004. }
  42005. });
  42006. };
  42007. var each$16 = each$1;
  42008. var boxplotLayout = function (ecModel) {
  42009. var groupResult = groupSeriesByAxis(ecModel);
  42010. each$16(groupResult, function (groupItem) {
  42011. var seriesModels = groupItem.seriesModels;
  42012. if (!seriesModels.length) {
  42013. return;
  42014. }
  42015. calculateBase(groupItem);
  42016. each$16(seriesModels, function (seriesModel, idx) {
  42017. layoutSingleSeries(
  42018. seriesModel,
  42019. groupItem.boxOffsetList[idx],
  42020. groupItem.boxWidthList[idx]
  42021. );
  42022. });
  42023. });
  42024. };
  42025. /**
  42026. * Group series by axis.
  42027. */
  42028. function groupSeriesByAxis(ecModel) {
  42029. var result = [];
  42030. var axisList = [];
  42031. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  42032. var baseAxis = seriesModel.getBaseAxis();
  42033. var idx = indexOf(axisList, baseAxis);
  42034. if (idx < 0) {
  42035. idx = axisList.length;
  42036. axisList[idx] = baseAxis;
  42037. result[idx] = {axis: baseAxis, seriesModels: []};
  42038. }
  42039. result[idx].seriesModels.push(seriesModel);
  42040. });
  42041. return result;
  42042. }
  42043. /**
  42044. * Calculate offset and box width for each series.
  42045. */
  42046. function calculateBase(groupItem) {
  42047. var extent;
  42048. var baseAxis = groupItem.axis;
  42049. var seriesModels = groupItem.seriesModels;
  42050. var seriesCount = seriesModels.length;
  42051. var boxWidthList = groupItem.boxWidthList = [];
  42052. var boxOffsetList = groupItem.boxOffsetList = [];
  42053. var boundList = [];
  42054. var bandWidth;
  42055. if (baseAxis.type === 'category') {
  42056. bandWidth = baseAxis.getBandWidth();
  42057. }
  42058. else {
  42059. var maxDataCount = 0;
  42060. each$16(seriesModels, function (seriesModel) {
  42061. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  42062. });
  42063. extent = baseAxis.getExtent(),
  42064. Math.abs(extent[1] - extent[0]) / maxDataCount;
  42065. }
  42066. each$16(seriesModels, function (seriesModel) {
  42067. var boxWidthBound = seriesModel.get('boxWidth');
  42068. if (!isArray(boxWidthBound)) {
  42069. boxWidthBound = [boxWidthBound, boxWidthBound];
  42070. }
  42071. boundList.push([
  42072. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  42073. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  42074. ]);
  42075. });
  42076. var availableWidth = bandWidth * 0.8 - 2;
  42077. var boxGap = availableWidth / seriesCount * 0.3;
  42078. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  42079. var base = boxWidth / 2 - availableWidth / 2;
  42080. each$16(seriesModels, function (seriesModel, idx) {
  42081. boxOffsetList.push(base);
  42082. base += boxGap + boxWidth;
  42083. boxWidthList.push(
  42084. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  42085. );
  42086. });
  42087. }
  42088. /**
  42089. * Calculate points location for each series.
  42090. */
  42091. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  42092. var coordSys = seriesModel.coordinateSystem;
  42093. var data = seriesModel.getData();
  42094. var halfWidth = boxWidth / 2;
  42095. var chartLayout = seriesModel.get('layout');
  42096. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  42097. var constDim = 1 - variableDim;
  42098. var coordDims = ['x', 'y'];
  42099. var vDims = [];
  42100. var cDim;
  42101. each$1(data.dimensions, function (dimName) {
  42102. var dimInfo = data.getDimensionInfo(dimName);
  42103. var coordDim = dimInfo.coordDim;
  42104. if (coordDim === coordDims[constDim]) {
  42105. vDims.push(dimName);
  42106. }
  42107. else if (coordDim === coordDims[variableDim]) {
  42108. cDim = dimName;
  42109. }
  42110. });
  42111. if (cDim == null || vDims.length < 5) {
  42112. return;
  42113. }
  42114. data.each([cDim].concat(vDims), function () {
  42115. var args = arguments;
  42116. var axisDimVal = args[0];
  42117. var idx = args[vDims.length + 1];
  42118. var median = getPoint(args[3]);
  42119. var end1 = getPoint(args[1]);
  42120. var end5 = getPoint(args[5]);
  42121. var whiskerEnds = [
  42122. [end1, getPoint(args[2])],
  42123. [end5, getPoint(args[4])]
  42124. ];
  42125. layEndLine(end1);
  42126. layEndLine(end5);
  42127. layEndLine(median);
  42128. var bodyEnds = [];
  42129. addBodyEnd(whiskerEnds[0][1], 0);
  42130. addBodyEnd(whiskerEnds[1][1], 1);
  42131. data.setItemLayout(idx, {
  42132. chartLayout: chartLayout,
  42133. initBaseline: median[constDim],
  42134. median: median,
  42135. bodyEnds: bodyEnds,
  42136. whiskerEnds: whiskerEnds
  42137. });
  42138. function getPoint(val) {
  42139. var p = [];
  42140. p[variableDim] = axisDimVal;
  42141. p[constDim] = val;
  42142. var point;
  42143. if (isNaN(axisDimVal) || isNaN(val)) {
  42144. point = [NaN, NaN];
  42145. }
  42146. else {
  42147. point = coordSys.dataToPoint(p);
  42148. point[variableDim] += offset;
  42149. }
  42150. return point;
  42151. }
  42152. function addBodyEnd(point, start) {
  42153. var point1 = point.slice();
  42154. var point2 = point.slice();
  42155. point1[variableDim] += halfWidth;
  42156. point2[variableDim] -= halfWidth;
  42157. start
  42158. ? bodyEnds.push(point1, point2)
  42159. : bodyEnds.push(point2, point1);
  42160. }
  42161. function layEndLine(endCenter) {
  42162. var line = [endCenter.slice(), endCenter.slice()];
  42163. line[0][variableDim] -= halfWidth;
  42164. line[1][variableDim] += halfWidth;
  42165. whiskerEnds.push(line);
  42166. }
  42167. });
  42168. }
  42169. registerVisual(boxplotVisual);
  42170. registerLayout(boxplotLayout);
  42171. var CandlestickSeries = SeriesModel.extend({
  42172. type: 'series.candlestick',
  42173. dependencies: ['xAxis', 'yAxis', 'grid'],
  42174. /**
  42175. * @readOnly
  42176. */
  42177. defaultValueDimensions: ['open', 'close', 'lowest', 'highest'],
  42178. /**
  42179. * @type {Array.<string>}
  42180. * @readOnly
  42181. */
  42182. dimensions: null,
  42183. /**
  42184. * @override
  42185. */
  42186. defaultOption: {
  42187. zlevel: 0, // 一级层叠
  42188. z: 2, // 二级层叠
  42189. coordinateSystem: 'cartesian2d',
  42190. legendHoverLink: true,
  42191. hoverAnimation: true,
  42192. // xAxisIndex: 0,
  42193. // yAxisIndex: 0,
  42194. layout: null, // 'horizontal' or 'vertical'
  42195. itemStyle: {
  42196. normal: {
  42197. color: '#c23531', // 阳线 positive
  42198. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  42199. borderWidth: 1,
  42200. // FIXME
  42201. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  42202. borderColor: '#c23531',
  42203. borderColor0: '#314656'
  42204. },
  42205. emphasis: {
  42206. borderWidth: 2
  42207. }
  42208. },
  42209. barMaxWidth: null,
  42210. barMinWidth: null,
  42211. barWidth: null,
  42212. animationUpdate: false,
  42213. animationEasing: 'linear',
  42214. animationDuration: 300
  42215. },
  42216. /**
  42217. * Get dimension for shadow in dataZoom
  42218. * @return {string} dimension name
  42219. */
  42220. getShadowDim: function () {
  42221. return 'open';
  42222. },
  42223. brushSelector: function (dataIndex, data, selectors) {
  42224. var itemLayout = data.getItemLayout(dataIndex);
  42225. return selectors.rect(itemLayout.brushRect);
  42226. }
  42227. });
  42228. mixin(CandlestickSeries, seriesModelMixin, true);
  42229. var CandlestickView = Chart.extend({
  42230. type: 'candlestick',
  42231. getStyleUpdater: function () {
  42232. return updateStyle$2;
  42233. },
  42234. dispose: noop
  42235. });
  42236. mixin(CandlestickView, viewMixin, true);
  42237. // Update common properties
  42238. var normalStyleAccessPath$2 = ['itemStyle', 'normal'];
  42239. var emphasisStyleAccessPath$2 = ['itemStyle', 'emphasis'];
  42240. function updateStyle$2(itemGroup, data, idx) {
  42241. var itemModel = data.getItemModel(idx);
  42242. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$2);
  42243. var color = data.getItemVisual(idx, 'color');
  42244. var borderColor = data.getItemVisual(idx, 'borderColor') || color;
  42245. // Color must be excluded.
  42246. // Because symbol provide setColor individually to set fill and stroke
  42247. var itemStyle = normalItemStyleModel.getItemStyle(
  42248. ['color', 'color0', 'borderColor', 'borderColor0']
  42249. );
  42250. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  42251. whiskerEl.useStyle(itemStyle);
  42252. whiskerEl.style.stroke = borderColor;
  42253. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  42254. bodyEl.useStyle(itemStyle);
  42255. bodyEl.style.fill = color;
  42256. bodyEl.style.stroke = borderColor;
  42257. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$2).getItemStyle();
  42258. setHoverStyle(itemGroup, hoverStyle);
  42259. }
  42260. var preprocessor = function (option) {
  42261. if (!option || !isArray(option.series)) {
  42262. return;
  42263. }
  42264. // Translate 'k' to 'candlestick'.
  42265. each$1(option.series, function (seriesItem) {
  42266. if (isObject(seriesItem) && seriesItem.type === 'k') {
  42267. seriesItem.type = 'candlestick';
  42268. }
  42269. });
  42270. };
  42271. var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
  42272. var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
  42273. var positiveColorQuery = ['itemStyle', 'normal', 'color'];
  42274. var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
  42275. var candlestickVisual = function (ecModel, api) {
  42276. ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
  42277. var data = seriesModel.getData();
  42278. data.setVisual({
  42279. legendSymbol: 'roundRect'
  42280. });
  42281. // Only visible series has each data be visual encoded
  42282. if (!ecModel.isSeriesFiltered(seriesModel)) {
  42283. data.each(function (idx) {
  42284. var itemModel = data.getItemModel(idx);
  42285. var sign = data.getItemLayout(idx).sign;
  42286. data.setItemVisual(
  42287. idx,
  42288. {
  42289. color: itemModel.get(
  42290. sign > 0 ? positiveColorQuery : negativeColorQuery
  42291. ),
  42292. borderColor: itemModel.get(
  42293. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  42294. )
  42295. }
  42296. );
  42297. });
  42298. }
  42299. });
  42300. };
  42301. var retrieve2$1 = retrieve2;
  42302. var candlestickLayout = function (ecModel) {
  42303. ecModel.eachSeriesByType('candlestick', function (seriesModel) {
  42304. var coordSys = seriesModel.coordinateSystem;
  42305. var data = seriesModel.getData();
  42306. var candleWidth = calculateCandleWidth(seriesModel, data);
  42307. var chartLayout = seriesModel.get('layout');
  42308. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  42309. var constDim = 1 - variableDim;
  42310. var coordDims = ['x', 'y'];
  42311. var vDims = [];
  42312. var cDim;
  42313. each$1(data.dimensions, function (dimName) {
  42314. var dimInfo = data.getDimensionInfo(dimName);
  42315. var coordDim = dimInfo.coordDim;
  42316. if (coordDim === coordDims[constDim]) {
  42317. vDims.push(dimName);
  42318. }
  42319. else if (coordDim === coordDims[variableDim]) {
  42320. cDim = dimName;
  42321. }
  42322. });
  42323. if (cDim == null || vDims.length < 4) {
  42324. return;
  42325. }
  42326. var dataIndex = 0;
  42327. data.each([cDim].concat(vDims), function () {
  42328. var args = arguments;
  42329. var axisDimVal = args[0];
  42330. var idx = args[vDims.length + 1];
  42331. var openVal = args[1];
  42332. var closeVal = args[2];
  42333. var lowestVal = args[3];
  42334. var highestVal = args[4];
  42335. var ocLow = Math.min(openVal, closeVal);
  42336. var ocHigh = Math.max(openVal, closeVal);
  42337. var ocLowPoint = getPoint(ocLow);
  42338. var ocHighPoint = getPoint(ocHigh);
  42339. var lowestPoint = getPoint(lowestVal);
  42340. var highestPoint = getPoint(highestVal);
  42341. var whiskerEnds = [
  42342. [
  42343. subPixelOptimizePoint(highestPoint),
  42344. subPixelOptimizePoint(ocHighPoint)
  42345. ],
  42346. [
  42347. subPixelOptimizePoint(lowestPoint),
  42348. subPixelOptimizePoint(ocLowPoint)
  42349. ]
  42350. ];
  42351. var bodyEnds = [];
  42352. addBodyEnd(ocHighPoint, 0);
  42353. addBodyEnd(ocLowPoint, 1);
  42354. var sign;
  42355. if (openVal > closeVal) {
  42356. sign = -1;
  42357. }
  42358. else if (openVal < closeVal) {
  42359. sign = 1;
  42360. }
  42361. else {
  42362. // If close === open, compare with close of last record
  42363. if (dataIndex > 0) {
  42364. sign = data.getItemModel(dataIndex - 1).get()[2]
  42365. <= closeVal
  42366. ? 1
  42367. : -1;
  42368. }
  42369. else {
  42370. // No record of previous, set to be positive
  42371. sign = 1;
  42372. }
  42373. }
  42374. data.setItemLayout(idx, {
  42375. chartLayout: chartLayout,
  42376. sign: sign,
  42377. initBaseline: openVal > closeVal
  42378. ? ocHighPoint[constDim] : ocLowPoint[constDim], // open point.
  42379. bodyEnds: bodyEnds,
  42380. whiskerEnds: whiskerEnds,
  42381. brushRect: makeBrushRect()
  42382. });
  42383. ++dataIndex;
  42384. function getPoint(val) {
  42385. var p = [];
  42386. p[variableDim] = axisDimVal;
  42387. p[constDim] = val;
  42388. return (isNaN(axisDimVal) || isNaN(val))
  42389. ? [NaN, NaN]
  42390. : coordSys.dataToPoint(p);
  42391. }
  42392. function addBodyEnd(point, start) {
  42393. var point1 = point.slice();
  42394. var point2 = point.slice();
  42395. point1[variableDim] = subPixelOptimize(
  42396. point1[variableDim] + candleWidth / 2, 1, false
  42397. );
  42398. point2[variableDim] = subPixelOptimize(
  42399. point2[variableDim] - candleWidth / 2, 1, true
  42400. );
  42401. start
  42402. ? bodyEnds.push(point1, point2)
  42403. : bodyEnds.push(point2, point1);
  42404. }
  42405. function makeBrushRect() {
  42406. var pmin = getPoint(Math.min(openVal, closeVal, lowestVal, highestVal));
  42407. var pmax = getPoint(Math.max(openVal, closeVal, lowestVal, highestVal));
  42408. pmin[variableDim] -= candleWidth / 2;
  42409. pmax[variableDim] -= candleWidth / 2;
  42410. return {
  42411. x: pmin[0],
  42412. y: pmin[1],
  42413. width: constDim ? candleWidth : pmax[0] - pmin[0],
  42414. height: constDim ? pmax[1] - pmin[1] : candleWidth
  42415. };
  42416. }
  42417. function subPixelOptimizePoint(point) {
  42418. point[variableDim] = subPixelOptimize(point[variableDim], 1);
  42419. return point;
  42420. }
  42421. }, true);
  42422. });
  42423. };
  42424. function calculateCandleWidth(seriesModel, data) {
  42425. var baseAxis = seriesModel.getBaseAxis();
  42426. var extent;
  42427. var bandWidth = baseAxis.type === 'category'
  42428. ? baseAxis.getBandWidth()
  42429. : (
  42430. extent = baseAxis.getExtent(),
  42431. Math.abs(extent[1] - extent[0]) / data.count()
  42432. );
  42433. var barMaxWidth = parsePercent$1(
  42434. retrieve2$1(seriesModel.get('barMaxWidth'), bandWidth),
  42435. bandWidth
  42436. );
  42437. var barMinWidth = parsePercent$1(
  42438. retrieve2$1(seriesModel.get('barMinWidth'), 1),
  42439. bandWidth
  42440. );
  42441. var barWidth = seriesModel.get('barWidth');
  42442. return barWidth != null
  42443. ? parsePercent$1(barWidth, bandWidth)
  42444. // Put max outer to ensure bar visible in spite of overlap.
  42445. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  42446. }
  42447. registerPreprocessor(preprocessor);
  42448. registerVisual(candlestickVisual);
  42449. registerLayout(candlestickLayout);
  42450. SeriesModel.extend({
  42451. type: 'series.effectScatter',
  42452. dependencies: ['grid', 'polar'],
  42453. getInitialData: function (option, ecModel) {
  42454. var list = createListFromArray(option.data, this, ecModel);
  42455. return list;
  42456. },
  42457. brushSelector: 'point',
  42458. defaultOption: {
  42459. coordinateSystem: 'cartesian2d',
  42460. zlevel: 0,
  42461. z: 2,
  42462. legendHoverLink: true,
  42463. effectType: 'ripple',
  42464. progressive: 0,
  42465. // When to show the effect, option: 'render'|'emphasis'
  42466. showEffectOn: 'render',
  42467. // Ripple effect config
  42468. rippleEffect: {
  42469. period: 4,
  42470. // Scale of ripple
  42471. scale: 2.5,
  42472. // Brush type can be fill or stroke
  42473. brushType: 'fill'
  42474. },
  42475. // Cartesian coordinate system
  42476. // xAxisIndex: 0,
  42477. // yAxisIndex: 0,
  42478. // Polar coordinate system
  42479. // polarIndex: 0,
  42480. // Geo coordinate system
  42481. // geoIndex: 0,
  42482. // symbol: null, // 图形类型
  42483. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  42484. // symbolRotate: null, // 图形旋转控制
  42485. // large: false,
  42486. // Available when large is true
  42487. // largeThreshold: 2000,
  42488. // itemStyle: {
  42489. // normal: {
  42490. // opacity: 1
  42491. // }
  42492. // }
  42493. }
  42494. });
  42495. /**
  42496. * Symbol with ripple effect
  42497. * @module echarts/chart/helper/EffectSymbol
  42498. */
  42499. var EFFECT_RIPPLE_NUMBER = 3;
  42500. function normalizeSymbolSize$1(symbolSize) {
  42501. if (!isArray(symbolSize)) {
  42502. symbolSize = [+symbolSize, +symbolSize];
  42503. }
  42504. return symbolSize;
  42505. }
  42506. function updateRipplePath(rippleGroup, effectCfg) {
  42507. rippleGroup.eachChild(function (ripplePath) {
  42508. ripplePath.attr({
  42509. z: effectCfg.z,
  42510. zlevel: effectCfg.zlevel,
  42511. style: {
  42512. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  42513. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  42514. }
  42515. });
  42516. });
  42517. }
  42518. /**
  42519. * @constructor
  42520. * @param {module:echarts/data/List} data
  42521. * @param {number} idx
  42522. * @extends {module:zrender/graphic/Group}
  42523. */
  42524. function EffectSymbol(data, idx) {
  42525. Group.call(this);
  42526. var symbol = new SymbolClz$1(data, idx);
  42527. var rippleGroup = new Group();
  42528. this.add(symbol);
  42529. this.add(rippleGroup);
  42530. rippleGroup.beforeUpdate = function () {
  42531. this.attr(symbol.getScale());
  42532. };
  42533. this.updateData(data, idx);
  42534. }
  42535. var effectSymbolProto = EffectSymbol.prototype;
  42536. effectSymbolProto.stopEffectAnimation = function () {
  42537. this.childAt(1).removeAll();
  42538. };
  42539. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  42540. var symbolType = effectCfg.symbolType;
  42541. var color = effectCfg.color;
  42542. var rippleGroup = this.childAt(1);
  42543. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  42544. // var ripplePath = createSymbol(
  42545. // symbolType, -0.5, -0.5, 1, 1, color
  42546. // );
  42547. // If width/height are set too small (e.g., set to 1) on ios10
  42548. // and macOS Sierra, a circle stroke become a rect, no matter what
  42549. // the scale is set. So we set width/height as 2. See #4136.
  42550. var ripplePath = createSymbol(
  42551. symbolType, -1, -1, 2, 2, color
  42552. );
  42553. ripplePath.attr({
  42554. style: {
  42555. strokeNoScale: true
  42556. },
  42557. z2: 99,
  42558. silent: true,
  42559. scale: [0.5, 0.5]
  42560. });
  42561. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  42562. // TODO Configurable effectCfg.period
  42563. ripplePath.animate('', true)
  42564. .when(effectCfg.period, {
  42565. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  42566. })
  42567. .delay(delay)
  42568. .start();
  42569. ripplePath.animateStyle(true)
  42570. .when(effectCfg.period, {
  42571. opacity: 0
  42572. })
  42573. .delay(delay)
  42574. .start();
  42575. rippleGroup.add(ripplePath);
  42576. }
  42577. updateRipplePath(rippleGroup, effectCfg);
  42578. };
  42579. /**
  42580. * Update effect symbol
  42581. */
  42582. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  42583. var oldEffectCfg = this._effectCfg;
  42584. var rippleGroup = this.childAt(1);
  42585. // Must reinitialize effect if following configuration changed
  42586. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  42587. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  42588. var propName = DIFFICULT_PROPS[i];
  42589. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  42590. this.stopEffectAnimation();
  42591. this.startEffectAnimation(effectCfg);
  42592. return;
  42593. }
  42594. }
  42595. updateRipplePath(rippleGroup, effectCfg);
  42596. };
  42597. /**
  42598. * Highlight symbol
  42599. */
  42600. effectSymbolProto.highlight = function () {
  42601. this.trigger('emphasis');
  42602. };
  42603. /**
  42604. * Downplay symbol
  42605. */
  42606. effectSymbolProto.downplay = function () {
  42607. this.trigger('normal');
  42608. };
  42609. /**
  42610. * Update symbol properties
  42611. * @param {module:echarts/data/List} data
  42612. * @param {number} idx
  42613. */
  42614. effectSymbolProto.updateData = function (data, idx) {
  42615. var seriesModel = data.hostModel;
  42616. this.childAt(0).updateData(data, idx);
  42617. var rippleGroup = this.childAt(1);
  42618. var itemModel = data.getItemModel(idx);
  42619. var symbolType = data.getItemVisual(idx, 'symbol');
  42620. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  42621. var color = data.getItemVisual(idx, 'color');
  42622. rippleGroup.attr('scale', symbolSize);
  42623. rippleGroup.traverse(function (ripplePath) {
  42624. ripplePath.attr({
  42625. fill: color
  42626. });
  42627. });
  42628. var symbolOffset = itemModel.getShallow('symbolOffset');
  42629. if (symbolOffset) {
  42630. var pos = rippleGroup.position;
  42631. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  42632. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  42633. }
  42634. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  42635. var effectCfg = {};
  42636. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  42637. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  42638. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  42639. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  42640. effectCfg.effectOffset = idx / data.count();
  42641. effectCfg.z = itemModel.getShallow('z') || 0;
  42642. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  42643. effectCfg.symbolType = symbolType;
  42644. effectCfg.color = color;
  42645. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  42646. if (effectCfg.showEffectOn === 'render') {
  42647. this._effectCfg
  42648. ? this.updateEffectAnimation(effectCfg)
  42649. : this.startEffectAnimation(effectCfg);
  42650. this._effectCfg = effectCfg;
  42651. }
  42652. else {
  42653. // Not keep old effect config
  42654. this._effectCfg = null;
  42655. this.stopEffectAnimation();
  42656. var symbol = this.childAt(0);
  42657. var onEmphasis = function () {
  42658. symbol.highlight();
  42659. if (effectCfg.showEffectOn !== 'render') {
  42660. this.startEffectAnimation(effectCfg);
  42661. }
  42662. };
  42663. var onNormal = function () {
  42664. symbol.downplay();
  42665. if (effectCfg.showEffectOn !== 'render') {
  42666. this.stopEffectAnimation();
  42667. }
  42668. };
  42669. this.on('mouseover', onEmphasis, this)
  42670. .on('mouseout', onNormal, this)
  42671. .on('emphasis', onEmphasis, this)
  42672. .on('normal', onNormal, this);
  42673. }
  42674. this._effectCfg = effectCfg;
  42675. };
  42676. effectSymbolProto.fadeOut = function (cb) {
  42677. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  42678. cb && cb();
  42679. };
  42680. inherits(EffectSymbol, Group);
  42681. extendChartView({
  42682. type: 'effectScatter',
  42683. init: function () {
  42684. this._symbolDraw = new SymbolDraw(EffectSymbol);
  42685. },
  42686. render: function (seriesModel, ecModel, api) {
  42687. var data = seriesModel.getData();
  42688. var effectSymbolDraw = this._symbolDraw;
  42689. effectSymbolDraw.updateData(data);
  42690. this.group.add(effectSymbolDraw.group);
  42691. },
  42692. updateLayout: function () {
  42693. this._symbolDraw.updateLayout();
  42694. },
  42695. remove: function (ecModel, api) {
  42696. this._symbolDraw && this._symbolDraw.remove(api);
  42697. },
  42698. dispose: function () {}
  42699. });
  42700. registerVisual(curry(
  42701. visualSymbol, 'effectScatter', 'circle', null
  42702. ));
  42703. registerLayout(curry(
  42704. layoutPoints, 'effectScatter'
  42705. ));
  42706. // Convert [ [{coord: []}, {coord: []}] ]
  42707. // to [ { coords: [[]] } ]
  42708. function preprocessOption(seriesOpt) {
  42709. var data = seriesOpt.data;
  42710. if (data && data[0] && data[0][0] && data[0][0].coord) {
  42711. if (__DEV__) {
  42712. console.warn('Lines data configuration has been changed to'
  42713. + ' { coords:[[1,2],[2,3]] }');
  42714. }
  42715. seriesOpt.data = map(data, function (itemOpt) {
  42716. var coords = [
  42717. itemOpt[0].coord, itemOpt[1].coord
  42718. ];
  42719. var target = {
  42720. coords: coords
  42721. };
  42722. if (itemOpt[0].name) {
  42723. target.fromName = itemOpt[0].name;
  42724. }
  42725. if (itemOpt[1].name) {
  42726. target.toName = itemOpt[1].name;
  42727. }
  42728. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  42729. });
  42730. }
  42731. }
  42732. var LinesSeries = SeriesModel.extend({
  42733. type: 'series.lines',
  42734. dependencies: ['grid', 'polar'],
  42735. visualColorAccessPath: 'lineStyle.normal.color',
  42736. init: function (option) {
  42737. // Not using preprocessor because mergeOption may not have series.type
  42738. preprocessOption(option);
  42739. LinesSeries.superApply(this, 'init', arguments);
  42740. },
  42741. mergeOption: function (option) {
  42742. preprocessOption(option);
  42743. LinesSeries.superApply(this, 'mergeOption', arguments);
  42744. },
  42745. getInitialData: function (option, ecModel) {
  42746. if (__DEV__) {
  42747. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  42748. if (!CoordSys) {
  42749. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  42750. }
  42751. }
  42752. var lineData = new List(['value'], this);
  42753. lineData.hasItemOption = false;
  42754. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  42755. // dataItem is simply coords
  42756. if (dataItem instanceof Array) {
  42757. return NaN;
  42758. }
  42759. else {
  42760. lineData.hasItemOption = true;
  42761. var value = dataItem.value;
  42762. if (value != null) {
  42763. return value instanceof Array ? value[dimIndex] : value;
  42764. }
  42765. }
  42766. });
  42767. return lineData;
  42768. },
  42769. formatTooltip: function (dataIndex) {
  42770. var data = this.getData();
  42771. var itemModel = data.getItemModel(dataIndex);
  42772. var name = itemModel.get('name');
  42773. if (name) {
  42774. return name;
  42775. }
  42776. var fromName = itemModel.get('fromName');
  42777. var toName = itemModel.get('toName');
  42778. var html = [];
  42779. fromName != null && html.push(fromName);
  42780. toName != null && html.push(toName);
  42781. return encodeHTML(html.join(' > '));
  42782. },
  42783. defaultOption: {
  42784. coordinateSystem: 'geo',
  42785. zlevel: 0,
  42786. z: 2,
  42787. legendHoverLink: true,
  42788. hoverAnimation: true,
  42789. // Cartesian coordinate system
  42790. xAxisIndex: 0,
  42791. yAxisIndex: 0,
  42792. symbol: ['none', 'none'],
  42793. symbolSize: [10, 10],
  42794. // Geo coordinate system
  42795. geoIndex: 0,
  42796. effect: {
  42797. show: false,
  42798. period: 4,
  42799. // Animation delay. support callback
  42800. // delay: 0,
  42801. // If move with constant speed px/sec
  42802. // period will be ignored if this property is > 0,
  42803. constantSpeed: 0,
  42804. symbol: 'circle',
  42805. symbolSize: 3,
  42806. loop: true,
  42807. // Length of trail, 0 - 1
  42808. trailLength: 0.2
  42809. // Same with lineStyle.normal.color
  42810. // color
  42811. },
  42812. large: false,
  42813. // Available when large is true
  42814. largeThreshold: 2000,
  42815. // If lines are polyline
  42816. // polyline not support curveness, label, animation
  42817. polyline: false,
  42818. label: {
  42819. normal: {
  42820. show: false,
  42821. position: 'end'
  42822. // distance: 5,
  42823. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  42824. }
  42825. },
  42826. lineStyle: {
  42827. normal: {
  42828. opacity: 0.5
  42829. }
  42830. }
  42831. }
  42832. });
  42833. /**
  42834. * Provide effect for line
  42835. * @module echarts/chart/helper/EffectLine
  42836. */
  42837. /**
  42838. * @constructor
  42839. * @extends {module:zrender/graphic/Group}
  42840. * @alias {module:echarts/chart/helper/Line}
  42841. */
  42842. function EffectLine(lineData, idx, seriesScope) {
  42843. Group.call(this);
  42844. this.add(this.createLine(lineData, idx, seriesScope));
  42845. this._updateEffectSymbol(lineData, idx);
  42846. }
  42847. var effectLineProto = EffectLine.prototype;
  42848. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  42849. return new Line$1(lineData, idx, seriesScope);
  42850. };
  42851. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  42852. var itemModel = lineData.getItemModel(idx);
  42853. var effectModel = itemModel.getModel('effect');
  42854. var size = effectModel.get('symbolSize');
  42855. var symbolType = effectModel.get('symbol');
  42856. if (!isArray(size)) {
  42857. size = [size, size];
  42858. }
  42859. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  42860. var symbol = this.childAt(1);
  42861. if (this._symbolType !== symbolType) {
  42862. // Remove previous
  42863. this.remove(symbol);
  42864. symbol = createSymbol(
  42865. symbolType, -0.5, -0.5, 1, 1, color
  42866. );
  42867. symbol.z2 = 100;
  42868. symbol.culling = true;
  42869. this.add(symbol);
  42870. }
  42871. // Symbol may be removed if loop is false
  42872. if (!symbol) {
  42873. return;
  42874. }
  42875. // Shadow color is same with color in default
  42876. symbol.setStyle('shadowColor', color);
  42877. symbol.setStyle(effectModel.getItemStyle(['color']));
  42878. symbol.attr('scale', size);
  42879. symbol.setColor(color);
  42880. symbol.attr('scale', size);
  42881. this._symbolType = symbolType;
  42882. this._updateEffectAnimation(lineData, effectModel, idx);
  42883. };
  42884. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  42885. var symbol = this.childAt(1);
  42886. if (!symbol) {
  42887. return;
  42888. }
  42889. var self = this;
  42890. var points = lineData.getItemLayout(idx);
  42891. var period = effectModel.get('period') * 1000;
  42892. var loop = effectModel.get('loop');
  42893. var constantSpeed = effectModel.get('constantSpeed');
  42894. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  42895. return idx / lineData.count() * period / 3;
  42896. });
  42897. var isDelayFunc = typeof delayExpr === 'function';
  42898. // Ignore when updating
  42899. symbol.ignore = true;
  42900. this.updateAnimationPoints(symbol, points);
  42901. if (constantSpeed > 0) {
  42902. period = this.getLineLength(symbol) / constantSpeed * 1000;
  42903. }
  42904. if (period !== this._period || loop !== this._loop) {
  42905. symbol.stopAnimation();
  42906. var delay = delayExpr;
  42907. if (isDelayFunc) {
  42908. delay = delayExpr(idx);
  42909. }
  42910. if (symbol.__t > 0) {
  42911. delay = -period * symbol.__t;
  42912. }
  42913. symbol.__t = 0;
  42914. var animator = symbol.animate('', loop)
  42915. .when(period, {
  42916. __t: 1
  42917. })
  42918. .delay(delay)
  42919. .during(function () {
  42920. self.updateSymbolPosition(symbol);
  42921. });
  42922. if (!loop) {
  42923. animator.done(function () {
  42924. self.remove(symbol);
  42925. });
  42926. }
  42927. animator.start();
  42928. }
  42929. this._period = period;
  42930. this._loop = loop;
  42931. };
  42932. effectLineProto.getLineLength = function (symbol) {
  42933. // Not so accurate
  42934. return (dist(symbol.__p1, symbol.__cp1)
  42935. + dist(symbol.__cp1, symbol.__p2));
  42936. };
  42937. effectLineProto.updateAnimationPoints = function (symbol, points) {
  42938. symbol.__p1 = points[0];
  42939. symbol.__p2 = points[1];
  42940. symbol.__cp1 = points[2] || [
  42941. (points[0][0] + points[1][0]) / 2,
  42942. (points[0][1] + points[1][1]) / 2
  42943. ];
  42944. };
  42945. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  42946. this.childAt(0).updateData(lineData, idx, seriesScope);
  42947. this._updateEffectSymbol(lineData, idx);
  42948. };
  42949. effectLineProto.updateSymbolPosition = function (symbol) {
  42950. var p1 = symbol.__p1;
  42951. var p2 = symbol.__p2;
  42952. var cp1 = symbol.__cp1;
  42953. var t = symbol.__t;
  42954. var pos = symbol.position;
  42955. var quadraticAt$$1 = quadraticAt;
  42956. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  42957. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  42958. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  42959. // Tangent
  42960. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  42961. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  42962. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  42963. symbol.ignore = false;
  42964. };
  42965. effectLineProto.updateLayout = function (lineData, idx) {
  42966. this.childAt(0).updateLayout(lineData, idx);
  42967. var effectModel = lineData.getItemModel(idx).getModel('effect');
  42968. this._updateEffectAnimation(lineData, effectModel, idx);
  42969. };
  42970. inherits(EffectLine, Group);
  42971. /**
  42972. * @module echarts/chart/helper/Line
  42973. */
  42974. /**
  42975. * @constructor
  42976. * @extends {module:zrender/graphic/Group}
  42977. * @alias {module:echarts/chart/helper/Polyline}
  42978. */
  42979. function Polyline$2(lineData, idx, seriesScope) {
  42980. Group.call(this);
  42981. this._createPolyline(lineData, idx, seriesScope);
  42982. }
  42983. var polylineProto = Polyline$2.prototype;
  42984. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  42985. // var seriesModel = lineData.hostModel;
  42986. var points = lineData.getItemLayout(idx);
  42987. var line = new Polyline({
  42988. shape: {
  42989. points: points
  42990. }
  42991. });
  42992. this.add(line);
  42993. this._updateCommonStl(lineData, idx, seriesScope);
  42994. };
  42995. polylineProto.updateData = function (lineData, idx, seriesScope) {
  42996. var seriesModel = lineData.hostModel;
  42997. var line = this.childAt(0);
  42998. var target = {
  42999. shape: {
  43000. points: lineData.getItemLayout(idx)
  43001. }
  43002. };
  43003. updateProps(line, target, seriesModel, idx);
  43004. this._updateCommonStl(lineData, idx, seriesScope);
  43005. };
  43006. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  43007. var line = this.childAt(0);
  43008. var itemModel = lineData.getItemModel(idx);
  43009. var visualColor = lineData.getItemVisual(idx, 'color');
  43010. var lineStyle = seriesScope && seriesScope.lineStyle;
  43011. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  43012. if (!seriesScope || lineData.hasItemOption) {
  43013. lineStyle = itemModel.getModel('lineStyle.normal').getLineStyle();
  43014. hoverLineStyle = itemModel.getModel('lineStyle.emphasis').getLineStyle();
  43015. }
  43016. line.useStyle(defaults(
  43017. {
  43018. strokeNoScale: true,
  43019. fill: 'none',
  43020. stroke: visualColor
  43021. },
  43022. lineStyle
  43023. ));
  43024. line.hoverStyle = hoverLineStyle;
  43025. setHoverStyle(this);
  43026. };
  43027. polylineProto.updateLayout = function (lineData, idx) {
  43028. var polyline = this.childAt(0);
  43029. polyline.setShape('points', lineData.getItemLayout(idx));
  43030. };
  43031. inherits(Polyline$2, Group);
  43032. /**
  43033. * Provide effect for line
  43034. * @module echarts/chart/helper/EffectLine
  43035. */
  43036. /**
  43037. * @constructor
  43038. * @extends {module:echarts/chart/helper/EffectLine}
  43039. * @alias {module:echarts/chart/helper/Polyline}
  43040. */
  43041. function EffectPolyline(lineData, idx, seriesScope) {
  43042. EffectLine.call(this, lineData, idx, seriesScope);
  43043. this._lastFrame = 0;
  43044. this._lastFramePercent = 0;
  43045. }
  43046. var effectPolylineProto = EffectPolyline.prototype;
  43047. // Overwrite
  43048. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  43049. return new Polyline$2(lineData, idx, seriesScope);
  43050. };
  43051. // Overwrite
  43052. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  43053. this._points = points;
  43054. var accLenArr = [0];
  43055. var len$$1 = 0;
  43056. for (var i = 1; i < points.length; i++) {
  43057. var p1 = points[i - 1];
  43058. var p2 = points[i];
  43059. len$$1 += dist(p1, p2);
  43060. accLenArr.push(len$$1);
  43061. }
  43062. if (len$$1 === 0) {
  43063. return;
  43064. }
  43065. for (var i = 0; i < accLenArr.length; i++) {
  43066. accLenArr[i] /= len$$1;
  43067. }
  43068. this._offsets = accLenArr;
  43069. this._length = len$$1;
  43070. };
  43071. // Overwrite
  43072. effectPolylineProto.getLineLength = function (symbol) {
  43073. return this._length;
  43074. };
  43075. // Overwrite
  43076. effectPolylineProto.updateSymbolPosition = function (symbol) {
  43077. var t = symbol.__t;
  43078. var points = this._points;
  43079. var offsets = this._offsets;
  43080. var len$$1 = points.length;
  43081. if (!offsets) {
  43082. // Has length 0
  43083. return;
  43084. }
  43085. var lastFrame = this._lastFrame;
  43086. var frame;
  43087. if (t < this._lastFramePercent) {
  43088. // Start from the next frame
  43089. // PENDING start from lastFrame ?
  43090. var start = Math.min(lastFrame + 1, len$$1 - 1);
  43091. for (frame = start; frame >= 0; frame--) {
  43092. if (offsets[frame] <= t) {
  43093. break;
  43094. }
  43095. }
  43096. // PENDING really need to do this ?
  43097. frame = Math.min(frame, len$$1 - 2);
  43098. }
  43099. else {
  43100. for (var frame = lastFrame; frame < len$$1; frame++) {
  43101. if (offsets[frame] > t) {
  43102. break;
  43103. }
  43104. }
  43105. frame = Math.min(frame - 1, len$$1 - 2);
  43106. }
  43107. lerp(
  43108. symbol.position, points[frame], points[frame + 1],
  43109. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  43110. );
  43111. var tx = points[frame + 1][0] - points[frame][0];
  43112. var ty = points[frame + 1][1] - points[frame][1];
  43113. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  43114. this._lastFrame = frame;
  43115. this._lastFramePercent = t;
  43116. symbol.ignore = false;
  43117. };
  43118. inherits(EffectPolyline, EffectLine);
  43119. // TODO Batch by color
  43120. var LargeLineShape = extendShape({
  43121. shape: {
  43122. polyline: false,
  43123. segs: []
  43124. },
  43125. buildPath: function (path, shape) {
  43126. var segs = shape.segs;
  43127. var isPolyline = shape.polyline;
  43128. for (var i = 0; i < segs.length; i++) {
  43129. var seg = segs[i];
  43130. if (isPolyline) {
  43131. path.moveTo(seg[0][0], seg[0][1]);
  43132. for (var j = 1; j < seg.length; j++) {
  43133. path.lineTo(seg[j][0], seg[j][1]);
  43134. }
  43135. }
  43136. else {
  43137. path.moveTo(seg[0][0], seg[0][1]);
  43138. if (seg.length > 2) {
  43139. path.quadraticCurveTo(seg[2][0], seg[2][1], seg[1][0], seg[1][1]);
  43140. }
  43141. else {
  43142. path.lineTo(seg[1][0], seg[1][1]);
  43143. }
  43144. }
  43145. }
  43146. },
  43147. findDataIndex: function (x, y) {
  43148. var shape = this.shape;
  43149. var segs = shape.segs;
  43150. var isPolyline = shape.polyline;
  43151. var lineWidth = Math.max(this.style.lineWidth, 1);
  43152. // Not consider transform
  43153. for (var i = 0; i < segs.length; i++) {
  43154. var seg = segs[i];
  43155. if (isPolyline) {
  43156. for (var j = 1; j < seg.length; j++) {
  43157. if (containStroke$1(
  43158. seg[j - 1][0], seg[j - 1][1], seg[j][0], seg[j][1], lineWidth, x, y
  43159. )) {
  43160. return i;
  43161. }
  43162. }
  43163. }
  43164. else {
  43165. if (seg.length > 2) {
  43166. if (containStroke$3(
  43167. seg[0][0], seg[0][1], seg[2][0], seg[2][1], seg[1][0], seg[1][1], lineWidth, x, y
  43168. )) {
  43169. return i;
  43170. }
  43171. }
  43172. else {
  43173. if (containStroke$1(
  43174. seg[0][0], seg[0][1], seg[1][0], seg[1][1], lineWidth, x, y
  43175. )) {
  43176. return i;
  43177. }
  43178. }
  43179. }
  43180. }
  43181. return -1;
  43182. }
  43183. });
  43184. function LargeLineDraw() {
  43185. this.group = new Group();
  43186. this._lineEl = new LargeLineShape();
  43187. }
  43188. var largeLineProto = LargeLineDraw.prototype;
  43189. /**
  43190. * Update symbols draw by new data
  43191. * @param {module:echarts/data/List} data
  43192. */
  43193. largeLineProto.updateData = function (data) {
  43194. this.group.removeAll();
  43195. var lineEl = this._lineEl;
  43196. var seriesModel = data.hostModel;
  43197. lineEl.setShape({
  43198. segs: data.mapArray(data.getItemLayout),
  43199. polyline: seriesModel.get('polyline')
  43200. });
  43201. lineEl.useStyle(
  43202. seriesModel.getModel('lineStyle.normal').getLineStyle()
  43203. );
  43204. var visualColor = data.getVisual('color');
  43205. if (visualColor) {
  43206. lineEl.setStyle('stroke', visualColor);
  43207. }
  43208. lineEl.setStyle('fill');
  43209. // Enable tooltip
  43210. // PENDING May have performance issue when path is extremely large
  43211. lineEl.seriesIndex = seriesModel.seriesIndex;
  43212. lineEl.on('mousemove', function (e) {
  43213. lineEl.dataIndex = null;
  43214. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  43215. if (dataIndex > 0) {
  43216. // Provide dataIndex for tooltip
  43217. lineEl.dataIndex = dataIndex;
  43218. }
  43219. });
  43220. // Add back
  43221. this.group.add(lineEl);
  43222. };
  43223. largeLineProto.updateLayout = function (seriesModel) {
  43224. var data = seriesModel.getData();
  43225. this._lineEl.setShape({
  43226. segs: data.mapArray(data.getItemLayout)
  43227. });
  43228. };
  43229. largeLineProto.remove = function () {
  43230. this.group.removeAll();
  43231. };
  43232. extendChartView({
  43233. type: 'lines',
  43234. init: function () {},
  43235. render: function (seriesModel, ecModel, api) {
  43236. var data = seriesModel.getData();
  43237. var lineDraw = this._lineDraw;
  43238. var hasEffect = seriesModel.get('effect.show');
  43239. var isPolyline = seriesModel.get('polyline');
  43240. var isLarge = seriesModel.get('large') && data.count() >= seriesModel.get('largeThreshold');
  43241. if (__DEV__) {
  43242. if (hasEffect && isLarge) {
  43243. console.warn('Large lines not support effect');
  43244. }
  43245. }
  43246. if (hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLarge !== this._isLarge) {
  43247. if (lineDraw) {
  43248. lineDraw.remove();
  43249. }
  43250. lineDraw = this._lineDraw = isLarge
  43251. ? new LargeLineDraw()
  43252. : new LineDraw(
  43253. isPolyline
  43254. ? (hasEffect ? EffectPolyline : Polyline$2)
  43255. : (hasEffect ? EffectLine : Line$1)
  43256. );
  43257. this._hasEffet = hasEffect;
  43258. this._isPolyline = isPolyline;
  43259. this._isLarge = isLarge;
  43260. }
  43261. var zlevel = seriesModel.get('zlevel');
  43262. var trailLength = seriesModel.get('effect.trailLength');
  43263. var zr = api.getZr();
  43264. // Avoid the drag cause ghost shadow
  43265. // FIXME Better way ?
  43266. // SVG doesn't support
  43267. var isSvg = zr.painter.getType() === 'svg';
  43268. if (!isSvg) {
  43269. zr.painter.getLayer(zlevel).clear(true);
  43270. }
  43271. // Config layer with motion blur
  43272. if (this._lastZlevel != null && !isSvg) {
  43273. zr.configLayer(this._lastZlevel, {
  43274. motionBlur: false
  43275. });
  43276. }
  43277. if (hasEffect && trailLength) {
  43278. if (__DEV__) {
  43279. var notInIndividual = false;
  43280. ecModel.eachSeries(function (otherSeriesModel) {
  43281. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  43282. notInIndividual = true;
  43283. }
  43284. });
  43285. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  43286. }
  43287. if (!isSvg) {
  43288. zr.configLayer(zlevel, {
  43289. motionBlur: true,
  43290. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  43291. });
  43292. }
  43293. }
  43294. this.group.add(lineDraw.group);
  43295. lineDraw.updateData(data);
  43296. this._lastZlevel = zlevel;
  43297. },
  43298. updateLayout: function (seriesModel, ecModel, api) {
  43299. this._lineDraw.updateLayout(seriesModel);
  43300. // Not use motion when dragging or zooming
  43301. var zr = api.getZr();
  43302. var isSvg = zr.painter.getType() === 'svg';
  43303. if (!isSvg) {
  43304. zr.painter.getLayer(this._lastZlevel).clear(true);
  43305. }
  43306. },
  43307. remove: function (ecModel, api) {
  43308. this._lineDraw && this._lineDraw.remove(api, true);
  43309. // Clear motion when lineDraw is removed
  43310. var zr = api.getZr();
  43311. var isSvg = zr.painter.getType() === 'svg';
  43312. if (!isSvg) {
  43313. zr.painter.getLayer(this._lastZlevel).clear(true);
  43314. }
  43315. },
  43316. dispose: function () {}
  43317. });
  43318. var linesLayout = function (ecModel) {
  43319. ecModel.eachSeriesByType('lines', function (seriesModel) {
  43320. var coordSys = seriesModel.coordinateSystem;
  43321. var lineData = seriesModel.getData();
  43322. // FIXME Use data dimensions ?
  43323. lineData.each(function (idx) {
  43324. var itemModel = lineData.getItemModel(idx);
  43325. var coords = (itemModel.option instanceof Array) ?
  43326. itemModel.option : itemModel.get('coords');
  43327. if (__DEV__) {
  43328. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  43329. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  43330. }
  43331. }
  43332. var pts = [];
  43333. if (seriesModel.get('polyline')) {
  43334. for (var i = 0; i < coords.length; i++) {
  43335. pts.push(coordSys.dataToPoint(coords[i]));
  43336. }
  43337. }
  43338. else {
  43339. pts[0] = coordSys.dataToPoint(coords[0]);
  43340. pts[1] = coordSys.dataToPoint(coords[1]);
  43341. var curveness = itemModel.get('lineStyle.normal.curveness');
  43342. if (+curveness) {
  43343. pts[2] = [
  43344. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  43345. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  43346. ];
  43347. }
  43348. }
  43349. lineData.setItemLayout(idx, pts);
  43350. });
  43351. });
  43352. };
  43353. function normalize$2(a) {
  43354. if (!(a instanceof Array)) {
  43355. a = [a, a];
  43356. }
  43357. return a;
  43358. }
  43359. var linesVisual = function (ecModel) {
  43360. ecModel.eachSeriesByType('lines', function (seriesModel) {
  43361. var data = seriesModel.getData();
  43362. var symbolType = normalize$2(seriesModel.get('symbol'));
  43363. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  43364. var opacityQuery = 'lineStyle.normal.opacity'.split('.');
  43365. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  43366. data.setVisual('toSymbol', symbolType && symbolType[1]);
  43367. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  43368. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  43369. data.setVisual('opacity', seriesModel.get(opacityQuery));
  43370. data.each(function (idx) {
  43371. var itemModel = data.getItemModel(idx);
  43372. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  43373. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  43374. var opacity = itemModel.get(opacityQuery);
  43375. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  43376. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  43377. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  43378. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  43379. data.setItemVisual(idx, 'opacity', opacity);
  43380. });
  43381. });
  43382. };
  43383. registerLayout(linesLayout);
  43384. registerVisual(linesVisual);
  43385. SeriesModel.extend({
  43386. type: 'series.heatmap',
  43387. getInitialData: function (option, ecModel) {
  43388. return createListFromArray(option.data, this, ecModel);
  43389. },
  43390. defaultOption: {
  43391. // Cartesian2D or geo
  43392. coordinateSystem: 'cartesian2d',
  43393. zlevel: 0,
  43394. z: 2,
  43395. // Cartesian coordinate system
  43396. // xAxisIndex: 0,
  43397. // yAxisIndex: 0,
  43398. // Geo coordinate system
  43399. geoIndex: 0,
  43400. blurSize: 30,
  43401. pointSize: 20,
  43402. maxOpacity: 1,
  43403. minOpacity: 0
  43404. }
  43405. });
  43406. /**
  43407. * @file defines echarts Heatmap Chart
  43408. * @author Ovilia (me@zhangwenli.com)
  43409. * Inspired by https://github.com/mourner/simpleheat
  43410. *
  43411. * @module
  43412. */
  43413. var GRADIENT_LEVELS = 256;
  43414. /**
  43415. * Heatmap Chart
  43416. *
  43417. * @class
  43418. */
  43419. function Heatmap() {
  43420. var canvas = createCanvas();
  43421. this.canvas = canvas;
  43422. this.blurSize = 30;
  43423. this.pointSize = 20;
  43424. this.maxOpacity = 1;
  43425. this.minOpacity = 0;
  43426. this._gradientPixels = {};
  43427. }
  43428. Heatmap.prototype = {
  43429. /**
  43430. * Renders Heatmap and returns the rendered canvas
  43431. * @param {Array} data array of data, each has x, y, value
  43432. * @param {number} width canvas width
  43433. * @param {number} height canvas height
  43434. */
  43435. update: function(data, width, height, normalize, colorFunc, isInRange) {
  43436. var brush = this._getBrush();
  43437. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  43438. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  43439. var r = this.pointSize + this.blurSize;
  43440. var canvas = this.canvas;
  43441. var ctx = canvas.getContext('2d');
  43442. var len = data.length;
  43443. canvas.width = width;
  43444. canvas.height = height;
  43445. for (var i = 0; i < len; ++i) {
  43446. var p = data[i];
  43447. var x = p[0];
  43448. var y = p[1];
  43449. var value = p[2];
  43450. // calculate alpha using value
  43451. var alpha = normalize(value);
  43452. // draw with the circle brush with alpha
  43453. ctx.globalAlpha = alpha;
  43454. ctx.drawImage(brush, x - r, y - r);
  43455. }
  43456. if (!canvas.width || !canvas.height) {
  43457. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  43458. // 'CanvasRenderingContext2D': The source height is 0."
  43459. return canvas;
  43460. }
  43461. // colorize the canvas using alpha value and set with gradient
  43462. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  43463. var pixels = imageData.data;
  43464. var offset = 0;
  43465. var pixelLen = pixels.length;
  43466. var minOpacity = this.minOpacity;
  43467. var maxOpacity = this.maxOpacity;
  43468. var diffOpacity = maxOpacity - minOpacity;
  43469. while(offset < pixelLen) {
  43470. var alpha = pixels[offset + 3] / 256;
  43471. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  43472. // Simple optimize to ignore the empty data
  43473. if (alpha > 0) {
  43474. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  43475. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  43476. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  43477. pixels[offset++] = gradient[gradientOffset];
  43478. pixels[offset++] = gradient[gradientOffset + 1];
  43479. pixels[offset++] = gradient[gradientOffset + 2];
  43480. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  43481. }
  43482. else {
  43483. offset += 4;
  43484. }
  43485. }
  43486. ctx.putImageData(imageData, 0, 0);
  43487. return canvas;
  43488. },
  43489. /**
  43490. * get canvas of a black circle brush used for canvas to draw later
  43491. * @private
  43492. * @returns {Object} circle brush canvas
  43493. */
  43494. _getBrush: function() {
  43495. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  43496. // set brush size
  43497. var r = this.pointSize + this.blurSize;
  43498. var d = r * 2;
  43499. brushCanvas.width = d;
  43500. brushCanvas.height = d;
  43501. var ctx = brushCanvas.getContext('2d');
  43502. ctx.clearRect(0, 0, d, d);
  43503. // in order to render shadow without the distinct circle,
  43504. // draw the distinct circle in an invisible place,
  43505. // and use shadowOffset to draw shadow in the center of the canvas
  43506. ctx.shadowOffsetX = d;
  43507. ctx.shadowBlur = this.blurSize;
  43508. // draw the shadow in black, and use alpha and shadow blur to generate
  43509. // color in color map
  43510. ctx.shadowColor = '#000';
  43511. // draw circle in the left to the canvas
  43512. ctx.beginPath();
  43513. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  43514. ctx.closePath();
  43515. ctx.fill();
  43516. return brushCanvas;
  43517. },
  43518. /**
  43519. * get gradient color map
  43520. * @private
  43521. */
  43522. _getGradient: function (data, colorFunc, state) {
  43523. var gradientPixels = this._gradientPixels;
  43524. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  43525. var color = [0, 0, 0, 0];
  43526. var off = 0;
  43527. for (var i = 0; i < 256; i++) {
  43528. colorFunc[state](i / 255, true, color);
  43529. pixelsSingleState[off++] = color[0];
  43530. pixelsSingleState[off++] = color[1];
  43531. pixelsSingleState[off++] = color[2];
  43532. pixelsSingleState[off++] = color[3];
  43533. }
  43534. return pixelsSingleState;
  43535. }
  43536. };
  43537. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  43538. var dataSpan = dataExtent[1] - dataExtent[0];
  43539. pieceList = map(pieceList, function (piece) {
  43540. return {
  43541. interval: [
  43542. (piece.interval[0] - dataExtent[0]) / dataSpan,
  43543. (piece.interval[1] - dataExtent[0]) / dataSpan
  43544. ]
  43545. };
  43546. });
  43547. var len = pieceList.length;
  43548. var lastIndex = 0;
  43549. return function (val) {
  43550. // Try to find in the location of the last found
  43551. for (var i = lastIndex; i < len; i++) {
  43552. var interval = pieceList[i].interval;
  43553. if (interval[0] <= val && val <= interval[1]) {
  43554. lastIndex = i;
  43555. break;
  43556. }
  43557. }
  43558. if (i === len) { // Not found, back interation
  43559. for (var i = lastIndex - 1; i >= 0; i--) {
  43560. var interval = pieceList[i].interval;
  43561. if (interval[0] <= val && val <= interval[1]) {
  43562. lastIndex = i;
  43563. break;
  43564. }
  43565. }
  43566. }
  43567. return i >= 0 && i < len && selected[i];
  43568. };
  43569. }
  43570. function getIsInContinuousRange(dataExtent, range) {
  43571. var dataSpan = dataExtent[1] - dataExtent[0];
  43572. range = [
  43573. (range[0] - dataExtent[0]) / dataSpan,
  43574. (range[1] - dataExtent[0]) / dataSpan
  43575. ];
  43576. return function (val) {
  43577. return val >= range[0] && val <= range[1];
  43578. };
  43579. }
  43580. function isGeoCoordSys(coordSys) {
  43581. var dimensions = coordSys.dimensions;
  43582. // Not use coorSys.type === 'geo' because coordSys maybe extended
  43583. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  43584. }
  43585. extendChartView({
  43586. type: 'heatmap',
  43587. render: function (seriesModel, ecModel, api) {
  43588. var visualMapOfThisSeries;
  43589. ecModel.eachComponent('visualMap', function (visualMap) {
  43590. visualMap.eachTargetSeries(function (targetSeries) {
  43591. if (targetSeries === seriesModel) {
  43592. visualMapOfThisSeries = visualMap;
  43593. }
  43594. });
  43595. });
  43596. if (__DEV__) {
  43597. if (!visualMapOfThisSeries) {
  43598. throw new Error('Heatmap must use with visualMap');
  43599. }
  43600. }
  43601. this.group.removeAll();
  43602. var coordSys = seriesModel.coordinateSystem;
  43603. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  43604. this._renderOnCartesianAndCalendar(coordSys, seriesModel, api);
  43605. }
  43606. else if (isGeoCoordSys(coordSys)) {
  43607. this._renderOnGeo(
  43608. coordSys, seriesModel, visualMapOfThisSeries, api
  43609. );
  43610. }
  43611. },
  43612. dispose: function () {},
  43613. _renderOnCartesianAndCalendar: function (coordSys, seriesModel, api) {
  43614. if (coordSys.type === 'cartesian2d') {
  43615. var xAxis = coordSys.getAxis('x');
  43616. var yAxis = coordSys.getAxis('y');
  43617. if (__DEV__) {
  43618. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  43619. throw new Error('Heatmap on cartesian must have two category axes');
  43620. }
  43621. if (!(xAxis.onBand && yAxis.onBand)) {
  43622. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  43623. }
  43624. }
  43625. var width = xAxis.getBandWidth();
  43626. var height = yAxis.getBandWidth();
  43627. }
  43628. var group = this.group;
  43629. var data = seriesModel.getData();
  43630. var itemStyleQuery = 'itemStyle.normal';
  43631. var hoverItemStyleQuery = 'itemStyle.emphasis';
  43632. var labelQuery = 'label.normal';
  43633. var hoverLabelQuery = 'label.emphasis';
  43634. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  43635. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  43636. var labelModel = seriesModel.getModel('label.normal');
  43637. var hoverLabelModel = seriesModel.getModel('label.emphasis');
  43638. var coordSysType = coordSys.type;
  43639. var dataDims = coordSysType === 'cartesian2d'
  43640. ? [
  43641. seriesModel.coordDimToDataDim('x')[0],
  43642. seriesModel.coordDimToDataDim('y')[0],
  43643. seriesModel.coordDimToDataDim('value')[0]
  43644. ]
  43645. : [
  43646. seriesModel.coordDimToDataDim('time')[0],
  43647. seriesModel.coordDimToDataDim('value')[0]
  43648. ];
  43649. data.each(function (idx) {
  43650. var rect;
  43651. if (coordSysType === 'cartesian2d') {
  43652. // Ignore empty data
  43653. if (isNaN(data.get(dataDims[2], idx))) {
  43654. return;
  43655. }
  43656. var point = coordSys.dataToPoint([
  43657. data.get(dataDims[0], idx),
  43658. data.get(dataDims[1], idx)
  43659. ]);
  43660. rect = new Rect({
  43661. shape: {
  43662. x: point[0] - width / 2,
  43663. y: point[1] - height / 2,
  43664. width: width,
  43665. height: height
  43666. },
  43667. style: {
  43668. fill: data.getItemVisual(idx, 'color'),
  43669. opacity: data.getItemVisual(idx, 'opacity')
  43670. }
  43671. });
  43672. }
  43673. else {
  43674. // Ignore empty data
  43675. if (isNaN(data.get(dataDims[1], idx))) {
  43676. return;
  43677. }
  43678. rect = new Rect({
  43679. z2: 1,
  43680. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  43681. style: {
  43682. fill: data.getItemVisual(idx, 'color'),
  43683. opacity: data.getItemVisual(idx, 'opacity')
  43684. }
  43685. });
  43686. }
  43687. var itemModel = data.getItemModel(idx);
  43688. // Optimization for large datset
  43689. if (data.hasItemOption) {
  43690. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  43691. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  43692. labelModel = itemModel.getModel(labelQuery);
  43693. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  43694. }
  43695. var rawValue = seriesModel.getRawValue(idx);
  43696. var defaultText = '-';
  43697. if (rawValue && rawValue[2] != null) {
  43698. defaultText = rawValue[2];
  43699. }
  43700. setLabelStyle(
  43701. style, hoverStl, labelModel, hoverLabelModel,
  43702. {
  43703. labelFetcher: seriesModel,
  43704. labelDataIndex: idx,
  43705. defaultText: defaultText,
  43706. isRectText: true
  43707. }
  43708. );
  43709. rect.setStyle(style);
  43710. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  43711. group.add(rect);
  43712. data.setItemGraphicEl(idx, rect);
  43713. });
  43714. },
  43715. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  43716. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  43717. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  43718. // if (!visualMapping) {
  43719. // throw new Error('Data range must have color visuals');
  43720. // }
  43721. var data = seriesModel.getData();
  43722. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  43723. hmLayer.blurSize = seriesModel.get('blurSize');
  43724. hmLayer.pointSize = seriesModel.get('pointSize');
  43725. hmLayer.minOpacity = seriesModel.get('minOpacity');
  43726. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  43727. var rect = geo.getViewRect().clone();
  43728. var roamTransform = geo.getRoamTransform().transform;
  43729. rect.applyTransform(roamTransform);
  43730. // Clamp on viewport
  43731. var x = Math.max(rect.x, 0);
  43732. var y = Math.max(rect.y, 0);
  43733. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  43734. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  43735. var width = x2 - x;
  43736. var height = y2 - y;
  43737. var points = data.mapArray(['lng', 'lat', 'value'], function (lng, lat, value) {
  43738. var pt = geo.dataToPoint([lng, lat]);
  43739. pt[0] -= x;
  43740. pt[1] -= y;
  43741. pt.push(value);
  43742. return pt;
  43743. });
  43744. var dataExtent = visualMapModel.getExtent();
  43745. var isInRange = visualMapModel.type === 'visualMap.continuous'
  43746. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  43747. : getIsInPiecewiseRange(
  43748. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  43749. );
  43750. hmLayer.update(
  43751. points, width, height,
  43752. inRangeVisuals.color.getNormalizer(),
  43753. {
  43754. inRange: inRangeVisuals.color.getColorMapper(),
  43755. outOfRange: outOfRangeVisuals.color.getColorMapper()
  43756. },
  43757. isInRange
  43758. );
  43759. var img = new ZImage({
  43760. style: {
  43761. width: width,
  43762. height: height,
  43763. x: x,
  43764. y: y,
  43765. image: hmLayer.canvas
  43766. },
  43767. silent: true
  43768. });
  43769. this.group.add(img);
  43770. }
  43771. });
  43772. var PictorialBarSeries = BaseBarSeries.extend({
  43773. type: 'series.pictorialBar',
  43774. dependencies: ['grid'],
  43775. defaultOption: {
  43776. symbol: 'circle', // Customized bar shape
  43777. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  43778. symbolRotate: null,
  43779. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  43780. symbolOffset: null,
  43781. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  43782. // Auto margin by defualt.
  43783. symbolRepeat: false, // false/null/undefined, means no repeat.
  43784. // Can be true, means auto calculate repeat times and cut by data.
  43785. // Can be a number, specifies repeat times, and do not cut by data.
  43786. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  43787. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  43788. symbolClip: false,
  43789. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  43790. symbolPatternSize: 400, // 400 * 400 px
  43791. barGap: '-100%', // In most case, overlap is needed.
  43792. // z can be set in data item, which is z2 actually.
  43793. // Disable progressive
  43794. progressive: 0,
  43795. hoverAnimation: false // Open only when needed.
  43796. },
  43797. getInitialData: function (option) {
  43798. // Disable stack.
  43799. option.stack = null;
  43800. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  43801. }
  43802. });
  43803. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'normal', 'borderWidth'];
  43804. // index: +isHorizontal
  43805. var LAYOUT_ATTRS = [
  43806. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  43807. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  43808. ];
  43809. var pathForLineWidth = new Circle();
  43810. var BarView$1 = extendChartView({
  43811. type: 'pictorialBar',
  43812. render: function (seriesModel, ecModel, api) {
  43813. var group = this.group;
  43814. var data = seriesModel.getData();
  43815. var oldData = this._data;
  43816. var cartesian = seriesModel.coordinateSystem;
  43817. var baseAxis = cartesian.getBaseAxis();
  43818. var isHorizontal = !!baseAxis.isHorizontal();
  43819. var coordSysRect = cartesian.grid.getRect();
  43820. var opt = {
  43821. ecSize: {width: api.getWidth(), height: api.getHeight()},
  43822. seriesModel: seriesModel,
  43823. coordSys: cartesian,
  43824. coordSysExtent: [
  43825. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  43826. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  43827. ],
  43828. isHorizontal: isHorizontal,
  43829. valueDim: LAYOUT_ATTRS[+isHorizontal],
  43830. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  43831. };
  43832. data.diff(oldData)
  43833. .add(function (dataIndex) {
  43834. if (!data.hasValue(dataIndex)) {
  43835. return;
  43836. }
  43837. var itemModel = getItemModel(data, dataIndex);
  43838. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  43839. var bar = createBar(data, opt, symbolMeta);
  43840. data.setItemGraphicEl(dataIndex, bar);
  43841. group.add(bar);
  43842. updateCommon$1(bar, opt, symbolMeta);
  43843. })
  43844. .update(function (newIndex, oldIndex) {
  43845. var bar = oldData.getItemGraphicEl(oldIndex);
  43846. if (!data.hasValue(newIndex)) {
  43847. group.remove(bar);
  43848. return;
  43849. }
  43850. var itemModel = getItemModel(data, newIndex);
  43851. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  43852. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  43853. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  43854. group.remove(bar);
  43855. data.setItemGraphicEl(newIndex, null);
  43856. bar = null;
  43857. }
  43858. if (bar) {
  43859. updateBar(bar, opt, symbolMeta);
  43860. }
  43861. else {
  43862. bar = createBar(data, opt, symbolMeta, true);
  43863. }
  43864. data.setItemGraphicEl(newIndex, bar);
  43865. bar.__pictorialSymbolMeta = symbolMeta;
  43866. // Add back
  43867. group.add(bar);
  43868. updateCommon$1(bar, opt, symbolMeta);
  43869. })
  43870. .remove(function (dataIndex) {
  43871. var bar = oldData.getItemGraphicEl(dataIndex);
  43872. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  43873. })
  43874. .execute();
  43875. this._data = data;
  43876. return this.group;
  43877. },
  43878. dispose: noop,
  43879. remove: function (ecModel, api) {
  43880. var group = this.group;
  43881. var data = this._data;
  43882. if (ecModel.get('animation')) {
  43883. if (data) {
  43884. data.eachItemGraphicEl(function (bar) {
  43885. removeBar(data, bar.dataIndex, ecModel, bar);
  43886. });
  43887. }
  43888. }
  43889. else {
  43890. group.removeAll();
  43891. }
  43892. }
  43893. });
  43894. // Set or calculate default value about symbol, and calculate layout info.
  43895. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  43896. var layout = data.getItemLayout(dataIndex);
  43897. var symbolRepeat = itemModel.get('symbolRepeat');
  43898. var symbolClip = itemModel.get('symbolClip');
  43899. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  43900. var symbolRotate = itemModel.get('symbolRotate');
  43901. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  43902. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  43903. var isAnimationEnabled = itemModel.isAnimationEnabled();
  43904. var symbolMeta = {
  43905. dataIndex: dataIndex,
  43906. layout: layout,
  43907. itemModel: itemModel,
  43908. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  43909. color: data.getItemVisual(dataIndex, 'color'),
  43910. symbolClip: symbolClip,
  43911. symbolRepeat: symbolRepeat,
  43912. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  43913. symbolPatternSize: symbolPatternSize,
  43914. rotation: rotation,
  43915. animationModel: isAnimationEnabled ? itemModel : null,
  43916. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  43917. z2: itemModel.getShallow('z', true) || 0
  43918. };
  43919. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  43920. prepareSymbolSize(
  43921. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  43922. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  43923. );
  43924. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  43925. var symbolSize = symbolMeta.symbolSize;
  43926. var symbolOffset = itemModel.get('symbolOffset');
  43927. if (isArray(symbolOffset)) {
  43928. symbolOffset = [
  43929. parsePercent$1(symbolOffset[0], symbolSize[0]),
  43930. parsePercent$1(symbolOffset[1], symbolSize[1])
  43931. ];
  43932. }
  43933. prepareLayoutInfo(
  43934. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  43935. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  43936. opt, symbolMeta
  43937. );
  43938. return symbolMeta;
  43939. }
  43940. // bar length can be negative.
  43941. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  43942. var valueDim = opt.valueDim;
  43943. var symbolBoundingData = itemModel.get('symbolBoundingData');
  43944. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  43945. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  43946. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  43947. var boundingLength;
  43948. if (isArray(symbolBoundingData)) {
  43949. var symbolBoundingExtent = [
  43950. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  43951. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  43952. ];
  43953. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  43954. boundingLength = symbolBoundingExtent[pxSignIdx];
  43955. }
  43956. else if (symbolBoundingData != null) {
  43957. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  43958. }
  43959. else if (symbolRepeat) {
  43960. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  43961. }
  43962. else {
  43963. boundingLength = layout[valueDim.wh];
  43964. }
  43965. output.boundingLength = boundingLength;
  43966. if (symbolRepeat) {
  43967. output.repeatCutLength = layout[valueDim.wh];
  43968. }
  43969. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  43970. }
  43971. function convertToCoordOnAxis(axis, value) {
  43972. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  43973. }
  43974. // Support ['100%', '100%']
  43975. function prepareSymbolSize(
  43976. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  43977. pxSign, symbolPatternSize, opt, output
  43978. ) {
  43979. var valueDim = opt.valueDim;
  43980. var categoryDim = opt.categoryDim;
  43981. var categorySize = Math.abs(layout[categoryDim.wh]);
  43982. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  43983. if (isArray(symbolSize)) {
  43984. symbolSize = symbolSize.slice();
  43985. }
  43986. else {
  43987. if (symbolSize == null) {
  43988. symbolSize = '100%';
  43989. }
  43990. symbolSize = [symbolSize, symbolSize];
  43991. }
  43992. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  43993. // to complicated to calculate real percent value if considering scaled lineWidth.
  43994. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  43995. // which can be tolerated in pictorial chart.
  43996. symbolSize[categoryDim.index] = parsePercent$1(
  43997. symbolSize[categoryDim.index],
  43998. categorySize
  43999. );
  44000. symbolSize[valueDim.index] = parsePercent$1(
  44001. symbolSize[valueDim.index],
  44002. symbolRepeat ? categorySize : Math.abs(boundingLength)
  44003. );
  44004. output.symbolSize = symbolSize;
  44005. // If x or y is less than zero, show reversed shape.
  44006. var symbolScale = output.symbolScale = [
  44007. symbolSize[0] / symbolPatternSize,
  44008. symbolSize[1] / symbolPatternSize
  44009. ];
  44010. // Follow convention, 'right' and 'top' is the normal scale.
  44011. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  44012. }
  44013. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  44014. // In symbols are drawn with scale, so do not need to care about the case that width
  44015. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  44016. // be calculated.
  44017. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  44018. if (valueLineWidth) {
  44019. pathForLineWidth.attr({
  44020. scale: symbolScale.slice(),
  44021. rotation: rotation
  44022. });
  44023. pathForLineWidth.updateTransform();
  44024. valueLineWidth /= pathForLineWidth.getLineScale();
  44025. valueLineWidth *= symbolScale[opt.valueDim.index];
  44026. }
  44027. output.valueLineWidth = valueLineWidth;
  44028. }
  44029. function prepareLayoutInfo(
  44030. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  44031. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  44032. ) {
  44033. var categoryDim = opt.categoryDim;
  44034. var valueDim = opt.valueDim;
  44035. var pxSign = output.pxSign;
  44036. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  44037. var pathLen = unitLength;
  44038. // Note: rotation will not effect the layout of symbols, because user may
  44039. // want symbols to rotate on its center, which should not be translated
  44040. // when rotating.
  44041. if (symbolRepeat) {
  44042. var absBoundingLength = Math.abs(boundingLength);
  44043. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  44044. var hasEndGap = false;
  44045. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  44046. hasEndGap = true;
  44047. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  44048. }
  44049. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  44050. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  44051. // When symbol margin is less than 0, margin at both ends will be subtracted
  44052. // to ensure that all of the symbols will not be overflow the given area.
  44053. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  44054. // Both final repeatTimes and final symbolMargin area calculated based on
  44055. // boundingLength.
  44056. var repeatSpecified = isNumeric(symbolRepeat);
  44057. var repeatTimes = repeatSpecified
  44058. ? symbolRepeat
  44059. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  44060. // Adjust calculate margin, to ensure each symbol is displayed
  44061. // entirely in the given layout area.
  44062. var mDiff = absBoundingLength - repeatTimes * unitLength;
  44063. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  44064. uLenWithMargin = unitLength + symbolMargin * 2;
  44065. endFix = hasEndGap ? 0 : symbolMargin * 2;
  44066. // Update repeatTimes when not all symbol will be shown.
  44067. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  44068. repeatTimes = repeatCutLength
  44069. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  44070. : 0;
  44071. }
  44072. pathLen = repeatTimes * uLenWithMargin - endFix;
  44073. output.repeatTimes = repeatTimes;
  44074. output.symbolMargin = symbolMargin;
  44075. }
  44076. var sizeFix = pxSign * (pathLen / 2);
  44077. var pathPosition = output.pathPosition = [];
  44078. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  44079. pathPosition[valueDim.index] = symbolPosition === 'start'
  44080. ? sizeFix
  44081. : symbolPosition === 'end'
  44082. ? boundingLength - sizeFix
  44083. : boundingLength / 2; // 'center'
  44084. if (symbolOffset) {
  44085. pathPosition[0] += symbolOffset[0];
  44086. pathPosition[1] += symbolOffset[1];
  44087. }
  44088. var bundlePosition = output.bundlePosition = [];
  44089. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  44090. bundlePosition[valueDim.index] = layout[valueDim.xy];
  44091. var barRectShape = output.barRectShape = extend({}, layout);
  44092. barRectShape[valueDim.wh] = pxSign * Math.max(
  44093. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  44094. );
  44095. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  44096. var clipShape = output.clipShape = {};
  44097. // Consider that symbol may be overflow layout rect.
  44098. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  44099. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  44100. clipShape[valueDim.xy] = 0;
  44101. clipShape[valueDim.wh] = layout[valueDim.wh];
  44102. }
  44103. function createPath(symbolMeta) {
  44104. var symbolPatternSize = symbolMeta.symbolPatternSize;
  44105. var path = createSymbol(
  44106. // Consider texture img, make a big size.
  44107. symbolMeta.symbolType,
  44108. -symbolPatternSize / 2,
  44109. -symbolPatternSize / 2,
  44110. symbolPatternSize,
  44111. symbolPatternSize,
  44112. symbolMeta.color
  44113. );
  44114. path.attr({
  44115. culling: true
  44116. });
  44117. path.type !== 'image' && path.setStyle({
  44118. strokeNoScale: true
  44119. });
  44120. return path;
  44121. }
  44122. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  44123. var bundle = bar.__pictorialBundle;
  44124. var symbolSize = symbolMeta.symbolSize;
  44125. var valueLineWidth = symbolMeta.valueLineWidth;
  44126. var pathPosition = symbolMeta.pathPosition;
  44127. var valueDim = opt.valueDim;
  44128. var repeatTimes = symbolMeta.repeatTimes || 0;
  44129. var index = 0;
  44130. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  44131. eachPath(bar, function (path) {
  44132. path.__pictorialAnimationIndex = index;
  44133. path.__pictorialRepeatTimes = repeatTimes;
  44134. if (index < repeatTimes) {
  44135. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  44136. }
  44137. else {
  44138. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  44139. bundle.remove(path);
  44140. });
  44141. }
  44142. updateHoverAnimation(path, symbolMeta);
  44143. index++;
  44144. });
  44145. for (; index < repeatTimes; index++) {
  44146. var path = createPath(symbolMeta);
  44147. path.__pictorialAnimationIndex = index;
  44148. path.__pictorialRepeatTimes = repeatTimes;
  44149. bundle.add(path);
  44150. var target = makeTarget(index);
  44151. updateAttr(
  44152. path,
  44153. {
  44154. position: target.position,
  44155. scale: [0, 0]
  44156. },
  44157. {
  44158. scale: target.scale,
  44159. rotation: target.rotation
  44160. },
  44161. symbolMeta,
  44162. isUpdate
  44163. );
  44164. // FIXME
  44165. // If all emphasis/normal through action.
  44166. path
  44167. .on('mouseover', onMouseOver)
  44168. .on('mouseout', onMouseOut);
  44169. updateHoverAnimation(path, symbolMeta);
  44170. }
  44171. function makeTarget(index) {
  44172. var position = pathPosition.slice();
  44173. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  44174. // Otherwise: i = index;
  44175. var pxSign = symbolMeta.pxSign;
  44176. var i = index;
  44177. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  44178. i = repeatTimes - 1 - index;
  44179. }
  44180. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  44181. return {
  44182. position: position,
  44183. scale: symbolMeta.symbolScale.slice(),
  44184. rotation: symbolMeta.rotation
  44185. };
  44186. }
  44187. function onMouseOver() {
  44188. eachPath(bar, function (path) {
  44189. path.trigger('emphasis');
  44190. });
  44191. }
  44192. function onMouseOut() {
  44193. eachPath(bar, function (path) {
  44194. path.trigger('normal');
  44195. });
  44196. }
  44197. }
  44198. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  44199. var bundle = bar.__pictorialBundle;
  44200. var mainPath = bar.__pictorialMainPath;
  44201. if (!mainPath) {
  44202. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  44203. bundle.add(mainPath);
  44204. updateAttr(
  44205. mainPath,
  44206. {
  44207. position: symbolMeta.pathPosition.slice(),
  44208. scale: [0, 0],
  44209. rotation: symbolMeta.rotation
  44210. },
  44211. {
  44212. scale: symbolMeta.symbolScale.slice()
  44213. },
  44214. symbolMeta,
  44215. isUpdate
  44216. );
  44217. mainPath
  44218. .on('mouseover', onMouseOver)
  44219. .on('mouseout', onMouseOut);
  44220. }
  44221. else {
  44222. updateAttr(
  44223. mainPath,
  44224. null,
  44225. {
  44226. position: symbolMeta.pathPosition.slice(),
  44227. scale: symbolMeta.symbolScale.slice(),
  44228. rotation: symbolMeta.rotation
  44229. },
  44230. symbolMeta,
  44231. isUpdate
  44232. );
  44233. }
  44234. updateHoverAnimation(mainPath, symbolMeta);
  44235. function onMouseOver() {
  44236. this.trigger('emphasis');
  44237. }
  44238. function onMouseOut() {
  44239. this.trigger('normal');
  44240. }
  44241. }
  44242. // bar rect is used for label.
  44243. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  44244. var rectShape = extend({}, symbolMeta.barRectShape);
  44245. var barRect = bar.__pictorialBarRect;
  44246. if (!barRect) {
  44247. barRect = bar.__pictorialBarRect = new Rect({
  44248. z2: 2,
  44249. shape: rectShape,
  44250. silent: true,
  44251. style: {
  44252. stroke: 'transparent',
  44253. fill: 'transparent',
  44254. lineWidth: 0
  44255. }
  44256. });
  44257. bar.add(barRect);
  44258. }
  44259. else {
  44260. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  44261. }
  44262. }
  44263. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  44264. // If not clip, symbol will be remove and rebuilt.
  44265. if (symbolMeta.symbolClip) {
  44266. var clipPath = bar.__pictorialClipPath;
  44267. var clipShape = extend({}, symbolMeta.clipShape);
  44268. var valueDim = opt.valueDim;
  44269. var animationModel = symbolMeta.animationModel;
  44270. var dataIndex = symbolMeta.dataIndex;
  44271. if (clipPath) {
  44272. updateProps(
  44273. clipPath, {shape: clipShape}, animationModel, dataIndex
  44274. );
  44275. }
  44276. else {
  44277. clipShape[valueDim.wh] = 0;
  44278. clipPath = new Rect({shape: clipShape});
  44279. bar.__pictorialBundle.setClipPath(clipPath);
  44280. bar.__pictorialClipPath = clipPath;
  44281. var target = {};
  44282. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  44283. graphic[isUpdate ? 'updateProps' : 'initProps'](
  44284. clipPath, {shape: target}, animationModel, dataIndex
  44285. );
  44286. }
  44287. }
  44288. }
  44289. function getItemModel(data, dataIndex) {
  44290. var itemModel = data.getItemModel(dataIndex);
  44291. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  44292. itemModel.isAnimationEnabled = isAnimationEnabled;
  44293. return itemModel;
  44294. }
  44295. function getAnimationDelayParams(path) {
  44296. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  44297. return {
  44298. index: path.__pictorialAnimationIndex,
  44299. count: path.__pictorialRepeatTimes
  44300. };
  44301. }
  44302. function isAnimationEnabled() {
  44303. // `animation` prop can be set on itemModel in pictorial bar chart.
  44304. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  44305. }
  44306. function updateHoverAnimation(path, symbolMeta) {
  44307. path.off('emphasis').off('normal');
  44308. var scale = symbolMeta.symbolScale.slice();
  44309. symbolMeta.hoverAnimation && path
  44310. .on('emphasis', function() {
  44311. this.animateTo({
  44312. scale: [scale[0] * 1.1, scale[1] * 1.1]
  44313. }, 400, 'elasticOut');
  44314. })
  44315. .on('normal', function() {
  44316. this.animateTo({
  44317. scale: scale.slice()
  44318. }, 400, 'elasticOut');
  44319. });
  44320. }
  44321. function createBar(data, opt, symbolMeta, isUpdate) {
  44322. // bar is the main element for each data.
  44323. var bar = new Group();
  44324. // bundle is used for location and clip.
  44325. var bundle = new Group();
  44326. bar.add(bundle);
  44327. bar.__pictorialBundle = bundle;
  44328. bundle.attr('position', symbolMeta.bundlePosition.slice());
  44329. if (symbolMeta.symbolRepeat) {
  44330. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  44331. }
  44332. else {
  44333. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  44334. }
  44335. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  44336. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  44337. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  44338. bar.__pictorialSymbolMeta = symbolMeta;
  44339. return bar;
  44340. }
  44341. function updateBar(bar, opt, symbolMeta) {
  44342. var animationModel = symbolMeta.animationModel;
  44343. var dataIndex = symbolMeta.dataIndex;
  44344. var bundle = bar.__pictorialBundle;
  44345. updateProps(
  44346. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  44347. );
  44348. if (symbolMeta.symbolRepeat) {
  44349. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  44350. }
  44351. else {
  44352. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  44353. }
  44354. createOrUpdateBarRect(bar, symbolMeta, true);
  44355. createOrUpdateClip(bar, opt, symbolMeta, true);
  44356. }
  44357. function removeBar(data, dataIndex, animationModel, bar) {
  44358. // Not show text when animating
  44359. var labelRect = bar.__pictorialBarRect;
  44360. labelRect && (labelRect.style.text = null);
  44361. var pathes = [];
  44362. eachPath(bar, function (path) {
  44363. pathes.push(path);
  44364. });
  44365. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  44366. // I do not find proper remove animation for clip yet.
  44367. bar.__pictorialClipPath && (animationModel = null);
  44368. each$1(pathes, function (path) {
  44369. updateProps(
  44370. path, {scale: [0, 0]}, animationModel, dataIndex,
  44371. function () {
  44372. bar.parent && bar.parent.remove(bar);
  44373. }
  44374. );
  44375. });
  44376. data.setItemGraphicEl(dataIndex, null);
  44377. }
  44378. function getShapeStr(data, symbolMeta) {
  44379. return [
  44380. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  44381. !!symbolMeta.symbolRepeat,
  44382. !!symbolMeta.symbolClip
  44383. ].join(':');
  44384. }
  44385. function eachPath(bar, cb, context) {
  44386. // Do not use Group#eachChild, because it do not support remove.
  44387. each$1(bar.__pictorialBundle.children(), function (el) {
  44388. el !== bar.__pictorialBarRect && cb.call(context, el);
  44389. });
  44390. }
  44391. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  44392. immediateAttrs && el.attr(immediateAttrs);
  44393. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  44394. if (symbolMeta.symbolClip && !isUpdate) {
  44395. animationAttrs && el.attr(animationAttrs);
  44396. }
  44397. else {
  44398. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  44399. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  44400. );
  44401. }
  44402. }
  44403. function updateCommon$1(bar, opt, symbolMeta) {
  44404. var color = symbolMeta.color;
  44405. var dataIndex = symbolMeta.dataIndex;
  44406. var itemModel = symbolMeta.itemModel;
  44407. // Color must be excluded.
  44408. // Because symbol provide setColor individually to set fill and stroke
  44409. var normalStyle = itemModel.getModel('itemStyle.normal').getItemStyle(['color']);
  44410. var hoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  44411. var cursorStyle = itemModel.getShallow('cursor');
  44412. eachPath(bar, function (path) {
  44413. // PENDING setColor should be before setStyle!!!
  44414. path.setColor(color);
  44415. path.setStyle(defaults(
  44416. {
  44417. fill: color,
  44418. opacity: symbolMeta.opacity
  44419. },
  44420. normalStyle
  44421. ));
  44422. setHoverStyle(path, hoverStyle);
  44423. cursorStyle && (path.cursor = cursorStyle);
  44424. path.z2 = symbolMeta.z2;
  44425. });
  44426. var barRectHoverStyle = {};
  44427. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  44428. var barRect = bar.__pictorialBarRect;
  44429. setLabel(
  44430. barRect.style, barRectHoverStyle, itemModel,
  44431. color, opt.seriesModel, dataIndex, barPositionOutside
  44432. );
  44433. setHoverStyle(barRect, barRectHoverStyle);
  44434. }
  44435. function toIntTimes(times) {
  44436. var roundedTimes = Math.round(times);
  44437. // Escapse accurate error
  44438. return Math.abs(times - roundedTimes) < 1e-4
  44439. ? roundedTimes
  44440. : Math.ceil(times);
  44441. }
  44442. // In case developer forget to include grid component
  44443. registerLayout(curry(
  44444. barLayoutGrid, 'pictorialBar'
  44445. ));
  44446. registerVisual(curry(
  44447. visualSymbol, 'pictorialBar', 'roundRect', null
  44448. ));
  44449. /**
  44450. * @constructor module:echarts/coord/single/SingleAxis
  44451. * @extends {module:echarts/coord/Axis}
  44452. * @param {string} dim
  44453. * @param {*} scale
  44454. * @param {Array.<number>} coordExtent
  44455. * @param {string} axisType
  44456. * @param {string} position
  44457. */
  44458. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  44459. Axis.call(this, dim, scale, coordExtent);
  44460. /**
  44461. * Axis type
  44462. * - 'category'
  44463. * - 'value'
  44464. * - 'time'
  44465. * - 'log'
  44466. * @type {string}
  44467. */
  44468. this.type = axisType || 'value';
  44469. /**
  44470. * Axis position
  44471. * - 'top'
  44472. * - 'bottom'
  44473. * - 'left'
  44474. * - 'right'
  44475. * @type {string}
  44476. */
  44477. this.position = position || 'bottom';
  44478. /**
  44479. * Axis orient
  44480. * - 'horizontal'
  44481. * - 'vertical'
  44482. * @type {[type]}
  44483. */
  44484. this.orient = null;
  44485. /**
  44486. * @type {number}
  44487. */
  44488. this._labelInterval = null;
  44489. };
  44490. SingleAxis.prototype = {
  44491. constructor: SingleAxis,
  44492. /**
  44493. * Axis model
  44494. * @type {module:echarts/coord/single/AxisModel}
  44495. */
  44496. model: null,
  44497. /**
  44498. * Judge the orient of the axis.
  44499. * @return {boolean}
  44500. */
  44501. isHorizontal: function () {
  44502. var position = this.position;
  44503. return position === 'top' || position === 'bottom';
  44504. },
  44505. /**
  44506. * @override
  44507. */
  44508. pointToData: function (point, clamp) {
  44509. return this.coordinateSystem.pointToData(point, clamp)[0];
  44510. },
  44511. /**
  44512. * Convert the local coord(processed by dataToCoord())
  44513. * to global coord(concrete pixel coord).
  44514. * designated by module:echarts/coord/single/Single.
  44515. * @type {Function}
  44516. */
  44517. toGlobalCoord: null,
  44518. /**
  44519. * Convert the global coord to local coord.
  44520. * designated by module:echarts/coord/single/Single.
  44521. * @type {Function}
  44522. */
  44523. toLocalCoord: null
  44524. };
  44525. inherits(SingleAxis, Axis);
  44526. /**
  44527. * Single coordinates system.
  44528. */
  44529. /**
  44530. * Create a single coordinates system.
  44531. *
  44532. * @param {module:echarts/coord/single/AxisModel} axisModel
  44533. * @param {module:echarts/model/Global} ecModel
  44534. * @param {module:echarts/ExtensionAPI} api
  44535. */
  44536. function Single(axisModel, ecModel, api) {
  44537. /**
  44538. * @type {string}
  44539. * @readOnly
  44540. */
  44541. this.dimension = 'single';
  44542. /**
  44543. * Add it just for draw tooltip.
  44544. *
  44545. * @type {Array.<string>}
  44546. * @readOnly
  44547. */
  44548. this.dimensions = ['single'];
  44549. /**
  44550. * @private
  44551. * @type {module:echarts/coord/single/SingleAxis}.
  44552. */
  44553. this._axis = null;
  44554. /**
  44555. * @private
  44556. * @type {module:zrender/core/BoundingRect}
  44557. */
  44558. this._rect;
  44559. this._init(axisModel, ecModel, api);
  44560. /**
  44561. * @type {module:echarts/coord/single/AxisModel}
  44562. */
  44563. this.model = axisModel;
  44564. }
  44565. Single.prototype = {
  44566. type: 'singleAxis',
  44567. axisPointerEnabled: true,
  44568. constructor: Single,
  44569. /**
  44570. * Initialize single coordinate system.
  44571. *
  44572. * @param {module:echarts/coord/single/AxisModel} axisModel
  44573. * @param {module:echarts/model/Global} ecModel
  44574. * @param {module:echarts/ExtensionAPI} api
  44575. * @private
  44576. */
  44577. _init: function (axisModel, ecModel, api) {
  44578. var dim = this.dimension;
  44579. var axis = new SingleAxis(
  44580. dim,
  44581. createScaleByModel(axisModel),
  44582. [0, 0],
  44583. axisModel.get('type'),
  44584. axisModel.get('position')
  44585. );
  44586. var isCategory = axis.type === 'category';
  44587. axis.onBand = isCategory && axisModel.get('boundaryGap');
  44588. axis.inverse = axisModel.get('inverse');
  44589. axis.orient = axisModel.get('orient');
  44590. axisModel.axis = axis;
  44591. axis.model = axisModel;
  44592. axis.coordinateSystem = this;
  44593. this._axis = axis;
  44594. },
  44595. /**
  44596. * Update axis scale after data processed
  44597. * @param {module:echarts/model/Global} ecModel
  44598. * @param {module:echarts/ExtensionAPI} api
  44599. */
  44600. update: function (ecModel, api) {
  44601. ecModel.eachSeries(function (seriesModel) {
  44602. if (seriesModel.coordinateSystem === this) {
  44603. var data = seriesModel.getData();
  44604. var dim = this.dimension;
  44605. this._axis.scale.unionExtentFromData(
  44606. data, seriesModel.coordDimToDataDim(dim)
  44607. );
  44608. niceScaleExtent(this._axis.scale, this._axis.model);
  44609. }
  44610. }, this);
  44611. },
  44612. /**
  44613. * Resize the single coordinate system.
  44614. *
  44615. * @param {module:echarts/coord/single/AxisModel} axisModel
  44616. * @param {module:echarts/ExtensionAPI} api
  44617. */
  44618. resize: function (axisModel, api) {
  44619. this._rect = getLayoutRect(
  44620. {
  44621. left: axisModel.get('left'),
  44622. top: axisModel.get('top'),
  44623. right: axisModel.get('right'),
  44624. bottom: axisModel.get('bottom'),
  44625. width: axisModel.get('width'),
  44626. height: axisModel.get('height')
  44627. },
  44628. {
  44629. width: api.getWidth(),
  44630. height: api.getHeight()
  44631. }
  44632. );
  44633. this._adjustAxis();
  44634. },
  44635. /**
  44636. * @return {module:zrender/core/BoundingRect}
  44637. */
  44638. getRect: function () {
  44639. return this._rect;
  44640. },
  44641. /**
  44642. * @private
  44643. */
  44644. _adjustAxis: function () {
  44645. var rect = this._rect;
  44646. var axis = this._axis;
  44647. var isHorizontal = axis.isHorizontal();
  44648. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  44649. var idx = axis.reverse ? 1 : 0;
  44650. axis.setExtent(extent[idx], extent[1 - idx]);
  44651. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  44652. },
  44653. /**
  44654. * @param {module:echarts/coord/single/SingleAxis} axis
  44655. * @param {number} coordBase
  44656. */
  44657. _updateAxisTransform: function (axis, coordBase) {
  44658. var axisExtent = axis.getExtent();
  44659. var extentSum = axisExtent[0] + axisExtent[1];
  44660. var isHorizontal = axis.isHorizontal();
  44661. axis.toGlobalCoord = isHorizontal
  44662. ? function (coord) {
  44663. return coord + coordBase;
  44664. }
  44665. : function (coord) {
  44666. return extentSum - coord + coordBase;
  44667. };
  44668. axis.toLocalCoord = isHorizontal
  44669. ? function (coord) {
  44670. return coord - coordBase;
  44671. }
  44672. : function (coord) {
  44673. return extentSum - coord + coordBase;
  44674. };
  44675. },
  44676. /**
  44677. * Get axis.
  44678. *
  44679. * @return {module:echarts/coord/single/SingleAxis}
  44680. */
  44681. getAxis: function () {
  44682. return this._axis;
  44683. },
  44684. /**
  44685. * Get axis, add it just for draw tooltip.
  44686. *
  44687. * @return {[type]} [description]
  44688. */
  44689. getBaseAxis: function () {
  44690. return this._axis;
  44691. },
  44692. /**
  44693. * @return {Array.<module:echarts/coord/Axis>}
  44694. */
  44695. getAxes: function () {
  44696. return [this._axis];
  44697. },
  44698. /**
  44699. * @return {Object} {baseAxes: [], otherAxes: []}
  44700. */
  44701. getTooltipAxes: function () {
  44702. return {baseAxes: [this.getAxis()]};
  44703. },
  44704. /**
  44705. * If contain point.
  44706. *
  44707. * @param {Array.<number>} point
  44708. * @return {boolean}
  44709. */
  44710. containPoint: function (point) {
  44711. var rect = this.getRect();
  44712. var axis = this.getAxis();
  44713. var orient = axis.orient;
  44714. if (orient === 'horizontal') {
  44715. return axis.contain(axis.toLocalCoord(point[0]))
  44716. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  44717. }
  44718. else {
  44719. return axis.contain(axis.toLocalCoord(point[1]))
  44720. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  44721. }
  44722. },
  44723. /**
  44724. * @param {Array.<number>} point
  44725. * @return {Array.<number>}
  44726. */
  44727. pointToData: function (point) {
  44728. var axis = this.getAxis();
  44729. return [axis.coordToData(axis.toLocalCoord(
  44730. point[axis.orient === 'horizontal' ? 0 : 1]
  44731. ))];
  44732. },
  44733. /**
  44734. * Convert the series data to concrete point.
  44735. *
  44736. * @param {number|Array.<number>} val
  44737. * @return {Array.<number>}
  44738. */
  44739. dataToPoint: function (val) {
  44740. var axis = this.getAxis();
  44741. var rect = this.getRect();
  44742. var pt = [];
  44743. var idx = axis.orient === 'horizontal' ? 0 : 1;
  44744. if (val instanceof Array) {
  44745. val = val[0];
  44746. }
  44747. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  44748. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  44749. return pt;
  44750. }
  44751. };
  44752. /**
  44753. * Single coordinate system creator.
  44754. */
  44755. /**
  44756. * Create single coordinate system and inject it into seriesModel.
  44757. *
  44758. * @param {module:echarts/model/Global} ecModel
  44759. * @param {module:echarts/ExtensionAPI} api
  44760. * @return {Array.<module:echarts/coord/single/Single>}
  44761. */
  44762. function create$3(ecModel, api) {
  44763. var singles = [];
  44764. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  44765. var single = new Single(axisModel, ecModel, api);
  44766. single.name = 'single_' + idx;
  44767. single.resize(axisModel, api);
  44768. axisModel.coordinateSystem = single;
  44769. singles.push(single);
  44770. });
  44771. ecModel.eachSeries(function (seriesModel) {
  44772. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  44773. var singleAxisModel = ecModel.queryComponents({
  44774. mainType: 'singleAxis',
  44775. index: seriesModel.get('singleAxisIndex'),
  44776. id: seriesModel.get('singleAxisId')
  44777. })[0];
  44778. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  44779. }
  44780. });
  44781. return singles;
  44782. }
  44783. CoordinateSystemManager.register('single', {
  44784. create: create$3,
  44785. dimensions: Single.prototype.dimensions
  44786. });
  44787. /**
  44788. * @param {Object} opt {labelInside}
  44789. * @return {Object} {
  44790. * position, rotation, labelDirection, labelOffset,
  44791. * tickDirection, labelRotate, labelInterval, z2
  44792. * }
  44793. */
  44794. function layout$1 (axisModel, opt) {
  44795. opt = opt || {};
  44796. var single = axisModel.coordinateSystem;
  44797. var axis = axisModel.axis;
  44798. var layout = {};
  44799. var axisPosition = axis.position;
  44800. var orient = axis.orient;
  44801. var rect = single.getRect();
  44802. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  44803. var positionMap = {
  44804. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  44805. vertical: {left: rectBound[0], right: rectBound[1]}
  44806. };
  44807. layout.position = [
  44808. orient === 'vertical'
  44809. ? positionMap.vertical[axisPosition]
  44810. : rectBound[0],
  44811. orient === 'horizontal'
  44812. ? positionMap.horizontal[axisPosition]
  44813. : rectBound[3]
  44814. ];
  44815. var r = {horizontal: 0, vertical: 1};
  44816. layout.rotation = Math.PI / 2 * r[orient];
  44817. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  44818. layout.labelDirection = layout.tickDirection
  44819. = layout.nameDirection
  44820. = directionMap[axisPosition];
  44821. if (axisModel.get('axisTick.inside')) {
  44822. layout.tickDirection = -layout.tickDirection;
  44823. }
  44824. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  44825. layout.labelDirection = -layout.labelDirection;
  44826. }
  44827. var labelRotation = opt.rotate;
  44828. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  44829. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  44830. layout.labelInterval = axis.getLabelInterval();
  44831. layout.z2 = 1;
  44832. return layout;
  44833. }
  44834. var getInterval$2 = AxisBuilder.getInterval;
  44835. var ifIgnoreOnTick$2 = AxisBuilder.ifIgnoreOnTick;
  44836. var axisBuilderAttrs$2 = [
  44837. 'axisLine', 'axisTickLabel', 'axisName'
  44838. ];
  44839. var selfBuilderAttr = 'splitLine';
  44840. var SingleAxisView = AxisView.extend({
  44841. type: 'singleAxis',
  44842. axisPointerClass: 'SingleAxisPointer',
  44843. render: function (axisModel, ecModel, api, payload) {
  44844. var group = this.group;
  44845. group.removeAll();
  44846. var layout = layout$1(axisModel);
  44847. var axisBuilder = new AxisBuilder(axisModel, layout);
  44848. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  44849. group.add(axisBuilder.getGroup());
  44850. if (axisModel.get(selfBuilderAttr + '.show')) {
  44851. this['_' + selfBuilderAttr](axisModel, layout.labelInterval);
  44852. }
  44853. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  44854. },
  44855. _splitLine: function(axisModel, labelInterval) {
  44856. var axis = axisModel.axis;
  44857. if (axis.scale.isBlank()) {
  44858. return;
  44859. }
  44860. var splitLineModel = axisModel.getModel('splitLine');
  44861. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44862. var lineWidth = lineStyleModel.get('width');
  44863. var lineColors = lineStyleModel.get('color');
  44864. var lineInterval = getInterval$2(splitLineModel, labelInterval);
  44865. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  44866. var gridRect = axisModel.coordinateSystem.getRect();
  44867. var isHorizontal = axis.isHorizontal();
  44868. var splitLines = [];
  44869. var lineCount = 0;
  44870. var ticksCoords = axis.getTicksCoords();
  44871. var p1 = [];
  44872. var p2 = [];
  44873. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  44874. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  44875. for (var i = 0; i < ticksCoords.length; ++i) {
  44876. if (ifIgnoreOnTick$2(
  44877. axis, i, lineInterval, ticksCoords.length,
  44878. showMinLabel, showMaxLabel
  44879. )) {
  44880. continue;
  44881. }
  44882. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  44883. if (isHorizontal) {
  44884. p1[0] = tickCoord;
  44885. p1[1] = gridRect.y;
  44886. p2[0] = tickCoord;
  44887. p2[1] = gridRect.y + gridRect.height;
  44888. }
  44889. else {
  44890. p1[0] = gridRect.x;
  44891. p1[1] = tickCoord;
  44892. p2[0] = gridRect.x + gridRect.width;
  44893. p2[1] = tickCoord;
  44894. }
  44895. var colorIndex = (lineCount++) % lineColors.length;
  44896. splitLines[colorIndex] = splitLines[colorIndex] || [];
  44897. splitLines[colorIndex].push(new Line(
  44898. subPixelOptimizeLine({
  44899. shape: {
  44900. x1: p1[0],
  44901. y1: p1[1],
  44902. x2: p2[0],
  44903. y2: p2[1]
  44904. },
  44905. style: {
  44906. lineWidth: lineWidth
  44907. },
  44908. silent: true
  44909. })));
  44910. }
  44911. for (var i = 0; i < splitLines.length; ++i) {
  44912. this.group.add(mergePath(splitLines[i], {
  44913. style: {
  44914. stroke: lineColors[i % lineColors.length],
  44915. lineDash: lineStyleModel.getLineDash(lineWidth),
  44916. lineWidth: lineWidth
  44917. },
  44918. silent: true
  44919. }));
  44920. }
  44921. }
  44922. });
  44923. var AxisModel$4 = ComponentModel.extend({
  44924. type: 'singleAxis',
  44925. layoutMode: 'box',
  44926. /**
  44927. * @type {module:echarts/coord/single/SingleAxis}
  44928. */
  44929. axis: null,
  44930. /**
  44931. * @type {module:echarts/coord/single/Single}
  44932. */
  44933. coordinateSystem: null,
  44934. /**
  44935. * @override
  44936. */
  44937. getCoordSysModel: function () {
  44938. return this;
  44939. }
  44940. });
  44941. var defaultOption$2 = {
  44942. left: '5%',
  44943. top: '5%',
  44944. right: '5%',
  44945. bottom: '5%',
  44946. type: 'value',
  44947. position: 'bottom',
  44948. orient: 'horizontal',
  44949. axisLine: {
  44950. show: true,
  44951. lineStyle: {
  44952. width: 2,
  44953. type: 'solid'
  44954. }
  44955. },
  44956. // Single coordinate system and single axis is the,
  44957. // which is used as the parent tooltip model.
  44958. // same model, so we set default tooltip show as true.
  44959. tooltip: {
  44960. show: true
  44961. },
  44962. axisTick: {
  44963. show: true,
  44964. length: 6,
  44965. lineStyle: {
  44966. width: 2
  44967. }
  44968. },
  44969. axisLabel: {
  44970. show: true,
  44971. interval: 'auto'
  44972. },
  44973. splitLine: {
  44974. show: true,
  44975. lineStyle: {
  44976. type: 'dashed',
  44977. opacity: 0.2
  44978. }
  44979. }
  44980. };
  44981. function getAxisType$2(axisName, option) {
  44982. return option.type || (option.data ? 'category' : 'value');
  44983. }
  44984. merge(AxisModel$4.prototype, axisModelCommonMixin);
  44985. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  44986. /**
  44987. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  44988. * @param {module:echarts/model/Global} ecModel
  44989. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  44990. */
  44991. var findPointFromSeries = function (finder, ecModel) {
  44992. var point = [];
  44993. var seriesIndex = finder.seriesIndex;
  44994. var seriesModel;
  44995. if (seriesIndex == null || !(
  44996. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  44997. )) {
  44998. return {point: []};
  44999. }
  45000. var data = seriesModel.getData();
  45001. var dataIndex = queryDataIndex(data, finder);
  45002. if (dataIndex == null || isArray(dataIndex)) {
  45003. return {point: []};
  45004. }
  45005. var el = data.getItemGraphicEl(dataIndex);
  45006. var coordSys = seriesModel.coordinateSystem;
  45007. if (seriesModel.getTooltipPosition) {
  45008. point = seriesModel.getTooltipPosition(dataIndex) || [];
  45009. }
  45010. else if (coordSys && coordSys.dataToPoint) {
  45011. point = coordSys.dataToPoint(
  45012. data.getValues(
  45013. map(coordSys.dimensions, function (dim) {
  45014. return seriesModel.coordDimToDataDim(dim)[0];
  45015. }), dataIndex, true
  45016. )
  45017. ) || [];
  45018. }
  45019. else if (el) {
  45020. // Use graphic bounding rect
  45021. var rect = el.getBoundingRect().clone();
  45022. rect.applyTransform(el.transform);
  45023. point = [
  45024. rect.x + rect.width / 2,
  45025. rect.y + rect.height / 2
  45026. ];
  45027. }
  45028. return {point: point, el: el};
  45029. };
  45030. var each$17 = each$1;
  45031. var curry$3 = curry;
  45032. var get$2 = makeGetter();
  45033. /**
  45034. * Basic logic: check all axis, if they do not demand show/highlight,
  45035. * then hide/downplay them.
  45036. *
  45037. * @param {Object} coordSysAxesInfo
  45038. * @param {Object} payload
  45039. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  45040. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  45041. * trigger axisPointer and tooltip.
  45042. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  45043. * trigger axisPointer and tooltip.
  45044. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  45045. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  45046. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  45047. * [{
  45048. * axisDim: 'x'|'y'|'angle'|...,
  45049. * axisIndex: ...,
  45050. * value: ...
  45051. * }, ...]
  45052. * @param {Function} [payload.dispatchAction]
  45053. * @param {Object} [payload.tooltipOption]
  45054. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  45055. * which can be specified in dispatchAction
  45056. * @param {module:echarts/model/Global} ecModel
  45057. * @param {module:echarts/ExtensionAPI} api
  45058. * @return {Object} content of event obj for echarts.connect.
  45059. */
  45060. var axisTrigger = function (payload, ecModel, api) {
  45061. var currTrigger = payload.currTrigger;
  45062. var point = [payload.x, payload.y];
  45063. var finder = payload;
  45064. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  45065. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  45066. // Pending
  45067. // See #6121. But we are not able to reproduce it yet.
  45068. if (!coordSysAxesInfo) {
  45069. return;
  45070. }
  45071. if (illegalPoint(point)) {
  45072. // Used in the default behavior of `connection`: use the sample seriesIndex
  45073. // and dataIndex. And also used in the tooltipView trigger.
  45074. point = findPointFromSeries({
  45075. seriesIndex: finder.seriesIndex,
  45076. // Do not use dataIndexInside from other ec instance.
  45077. // FIXME: auto detect it?
  45078. dataIndex: finder.dataIndex
  45079. }, ecModel).point;
  45080. }
  45081. var isIllegalPoint = illegalPoint(point);
  45082. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  45083. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  45084. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  45085. // and dataIndex.
  45086. var inputAxesInfo = finder.axesInfo;
  45087. var axesInfo = coordSysAxesInfo.axesInfo;
  45088. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  45089. var outputFinder = {};
  45090. var showValueMap = {};
  45091. var dataByCoordSys = {list: [], map: {}};
  45092. var updaters = {
  45093. showPointer: curry$3(showPointer, showValueMap),
  45094. showTooltip: curry$3(showTooltip, dataByCoordSys)
  45095. };
  45096. // Process for triggered axes.
  45097. each$17(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  45098. // If a point given, it must be contained by the coordinate system.
  45099. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  45100. each$17(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  45101. var axis = axisInfo.axis;
  45102. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  45103. // If no inputAxesInfo, no axis is restricted.
  45104. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  45105. var val = inputAxisInfo && inputAxisInfo.value;
  45106. if (val == null && !isIllegalPoint) {
  45107. val = axis.pointToData(point);
  45108. }
  45109. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  45110. }
  45111. });
  45112. });
  45113. // Process for linked axes.
  45114. var linkTriggers = {};
  45115. each$17(axesInfo, function (tarAxisInfo, tarKey) {
  45116. var linkGroup = tarAxisInfo.linkGroup;
  45117. // If axis has been triggered in the previous stage, it should not be triggered by link.
  45118. if (linkGroup && !showValueMap[tarKey]) {
  45119. each$17(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  45120. var srcValItem = showValueMap[srcKey];
  45121. // If srcValItem exist, source axis is triggered, so link to target axis.
  45122. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  45123. var val = srcValItem.value;
  45124. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  45125. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  45126. )));
  45127. linkTriggers[tarAxisInfo.key] = val;
  45128. }
  45129. });
  45130. }
  45131. });
  45132. each$17(linkTriggers, function (val, tarKey) {
  45133. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  45134. });
  45135. updateModelActually(showValueMap, axesInfo, outputFinder);
  45136. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  45137. dispatchHighDownActually(axesInfo, dispatchAction, api);
  45138. return outputFinder;
  45139. };
  45140. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  45141. var axis = axisInfo.axis;
  45142. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  45143. return;
  45144. }
  45145. if (!axisInfo.involveSeries) {
  45146. updaters.showPointer(axisInfo, newValue);
  45147. return;
  45148. }
  45149. // Heavy calculation. So put it after axis.containData checking.
  45150. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  45151. var payloadBatch = payloadInfo.payloadBatch;
  45152. var snapToValue = payloadInfo.snapToValue;
  45153. // Fill content of event obj for echarts.connect.
  45154. // By defualt use the first involved series data as a sample to connect.
  45155. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  45156. extend(outputFinder, payloadBatch[0]);
  45157. }
  45158. // If no linkSource input, this process is for collecting link
  45159. // target, where snap should not be accepted.
  45160. if (!dontSnap && axisInfo.snap) {
  45161. if (axis.containData(snapToValue) && snapToValue != null) {
  45162. newValue = snapToValue;
  45163. }
  45164. }
  45165. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  45166. // Tooltip should always be snapToValue, otherwise there will be
  45167. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  45168. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  45169. }
  45170. function buildPayloadsBySeries(value, axisInfo) {
  45171. var axis = axisInfo.axis;
  45172. var dim = axis.dim;
  45173. var snapToValue = value;
  45174. var payloadBatch = [];
  45175. var minDist = Number.MAX_VALUE;
  45176. var minDiff = -1;
  45177. each$17(axisInfo.seriesModels, function (series, idx) {
  45178. var dataDim = series.coordDimToDataDim(dim);
  45179. var seriesNestestValue;
  45180. var dataIndices;
  45181. if (series.getAxisTooltipData) {
  45182. var result = series.getAxisTooltipData(dataDim, value, axis);
  45183. dataIndices = result.dataIndices;
  45184. seriesNestestValue = result.nestestValue;
  45185. }
  45186. else {
  45187. dataIndices = series.getData().indicesOfNearest(
  45188. dataDim[0],
  45189. value,
  45190. // Add a threshold to avoid find the wrong dataIndex
  45191. // when data length is not same.
  45192. false, axis.type === 'category' ? 0.5 : null
  45193. );
  45194. if (!dataIndices.length) {
  45195. return;
  45196. }
  45197. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  45198. }
  45199. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  45200. return;
  45201. }
  45202. var diff = value - seriesNestestValue;
  45203. var dist = Math.abs(diff);
  45204. // Consider category case
  45205. if (dist <= minDist) {
  45206. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  45207. minDist = dist;
  45208. minDiff = diff;
  45209. snapToValue = seriesNestestValue;
  45210. payloadBatch.length = 0;
  45211. }
  45212. each$17(dataIndices, function (dataIndex) {
  45213. payloadBatch.push({
  45214. seriesIndex: series.seriesIndex,
  45215. dataIndexInside: dataIndex,
  45216. dataIndex: series.getData().getRawIndex(dataIndex)
  45217. });
  45218. });
  45219. }
  45220. });
  45221. return {
  45222. payloadBatch: payloadBatch,
  45223. snapToValue: snapToValue
  45224. };
  45225. }
  45226. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  45227. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  45228. }
  45229. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  45230. var payloadBatch = payloadInfo.payloadBatch;
  45231. var axis = axisInfo.axis;
  45232. var axisModel = axis.model;
  45233. var axisPointerModel = axisInfo.axisPointerModel;
  45234. // If no data, do not create anything in dataByCoordSys,
  45235. // whose length will be used to judge whether dispatch action.
  45236. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  45237. return;
  45238. }
  45239. var coordSysModel = axisInfo.coordSys.model;
  45240. var coordSysKey = makeKey(coordSysModel);
  45241. var coordSysItem = dataByCoordSys.map[coordSysKey];
  45242. if (!coordSysItem) {
  45243. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  45244. coordSysId: coordSysModel.id,
  45245. coordSysIndex: coordSysModel.componentIndex,
  45246. coordSysType: coordSysModel.type,
  45247. coordSysMainType: coordSysModel.mainType,
  45248. dataByAxis: []
  45249. };
  45250. dataByCoordSys.list.push(coordSysItem);
  45251. }
  45252. coordSysItem.dataByAxis.push({
  45253. axisDim: axis.dim,
  45254. axisIndex: axisModel.componentIndex,
  45255. axisType: axisModel.type,
  45256. axisId: axisModel.id,
  45257. value: value,
  45258. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  45259. // depends that all models have been updated. So it should not be performed
  45260. // here. Considering axisPointerModel used here is volatile, which is hard
  45261. // to be retrieve in TooltipView, we prepare parameters here.
  45262. valueLabelOpt: {
  45263. precision: axisPointerModel.get('label.precision'),
  45264. formatter: axisPointerModel.get('label.formatter')
  45265. },
  45266. seriesDataIndices: payloadBatch.slice()
  45267. });
  45268. }
  45269. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  45270. var outputAxesInfo = outputFinder.axesInfo = [];
  45271. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  45272. each$17(axesInfo, function (axisInfo, key) {
  45273. var option = axisInfo.axisPointerModel.option;
  45274. var valItem = showValueMap[key];
  45275. if (valItem) {
  45276. !axisInfo.useHandle && (option.status = 'show');
  45277. option.value = valItem.value;
  45278. // For label formatter param and highlight.
  45279. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  45280. }
  45281. // When always show (e.g., handle used), remain
  45282. // original value and status.
  45283. else {
  45284. // If hide, value still need to be set, consider
  45285. // click legend to toggle axis blank.
  45286. !axisInfo.useHandle && (option.status = 'hide');
  45287. }
  45288. // If status is 'hide', should be no info in payload.
  45289. option.status === 'show' && outputAxesInfo.push({
  45290. axisDim: axisInfo.axis.dim,
  45291. axisIndex: axisInfo.axis.model.componentIndex,
  45292. value: option.value
  45293. });
  45294. });
  45295. }
  45296. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  45297. // Basic logic: If no showTip required, hideTip will be dispatched.
  45298. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  45299. dispatchAction({type: 'hideTip'});
  45300. return;
  45301. }
  45302. // In most case only one axis (or event one series is used). It is
  45303. // convinient to fetch payload.seriesIndex and payload.dataIndex
  45304. // dirtectly. So put the first seriesIndex and dataIndex of the first
  45305. // axis on the payload.
  45306. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  45307. dispatchAction({
  45308. type: 'showTip',
  45309. escapeConnect: true,
  45310. x: point[0],
  45311. y: point[1],
  45312. tooltipOption: payload.tooltipOption,
  45313. position: payload.position,
  45314. dataIndexInside: sampleItem.dataIndexInside,
  45315. dataIndex: sampleItem.dataIndex,
  45316. seriesIndex: sampleItem.seriesIndex,
  45317. dataByCoordSys: dataByCoordSys.list
  45318. });
  45319. }
  45320. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  45321. // FIXME
  45322. // highlight status modification shoule be a stage of main process?
  45323. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  45324. var zr = api.getZr();
  45325. var highDownKey = 'axisPointerLastHighlights';
  45326. var lastHighlights = get$2(zr)[highDownKey] || {};
  45327. var newHighlights = get$2(zr)[highDownKey] = {};
  45328. // Update highlight/downplay status according to axisPointer model.
  45329. // Build hash map and remove duplicate incidentally.
  45330. each$17(axesInfo, function (axisInfo, key) {
  45331. var option = axisInfo.axisPointerModel.option;
  45332. option.status === 'show' && each$17(option.seriesDataIndices, function (batchItem) {
  45333. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  45334. newHighlights[key] = batchItem;
  45335. });
  45336. });
  45337. // Diff.
  45338. var toHighlight = [];
  45339. var toDownplay = [];
  45340. each$1(lastHighlights, function (batchItem, key) {
  45341. !newHighlights[key] && toDownplay.push(batchItem);
  45342. });
  45343. each$1(newHighlights, function (batchItem, key) {
  45344. !lastHighlights[key] && toHighlight.push(batchItem);
  45345. });
  45346. toDownplay.length && api.dispatchAction({
  45347. type: 'downplay', escapeConnect: true, batch: toDownplay
  45348. });
  45349. toHighlight.length && api.dispatchAction({
  45350. type: 'highlight', escapeConnect: true, batch: toHighlight
  45351. });
  45352. }
  45353. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  45354. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  45355. var inputAxisInfo = inputAxesInfo[i];
  45356. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  45357. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  45358. ) {
  45359. return inputAxisInfo;
  45360. }
  45361. }
  45362. }
  45363. function makeMapperParam(axisInfo) {
  45364. var axisModel = axisInfo.axis.model;
  45365. var item = {};
  45366. var dim = item.axisDim = axisInfo.axis.dim;
  45367. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  45368. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  45369. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  45370. return item;
  45371. }
  45372. function illegalPoint(point) {
  45373. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  45374. }
  45375. var AxisPointerModel = extendComponentModel({
  45376. type: 'axisPointer',
  45377. coordSysAxesInfo: null,
  45378. defaultOption: {
  45379. // 'auto' means that show when triggered by tooltip or handle.
  45380. show: 'auto',
  45381. // 'click' | 'mousemove' | 'none'
  45382. triggerOn: null, // set default in AxisPonterView.js
  45383. zlevel: 0,
  45384. z: 50,
  45385. type: 'line',
  45386. // axispointer triggered by tootip determine snap automatically,
  45387. // see `modelHelper`.
  45388. snap: false,
  45389. triggerTooltip: true,
  45390. value: null,
  45391. status: null, // Init value depends on whether handle is used.
  45392. // [group0, group1, ...]
  45393. // Each group can be: {
  45394. // mapper: function () {},
  45395. // singleTooltip: 'multiple', // 'multiple' or 'single'
  45396. // xAxisId: ...,
  45397. // yAxisName: ...,
  45398. // angleAxisIndex: ...
  45399. // }
  45400. // mapper: can be ignored.
  45401. // input: {axisInfo, value}
  45402. // output: {axisInfo, value}
  45403. link: [],
  45404. // Do not set 'auto' here, otherwise global animation: false
  45405. // will not effect at this axispointer.
  45406. animation: null,
  45407. animationDurationUpdate: 200,
  45408. lineStyle: {
  45409. color: '#aaa',
  45410. width: 1,
  45411. type: 'solid'
  45412. },
  45413. shadowStyle: {
  45414. color: 'rgba(150,150,150,0.3)'
  45415. },
  45416. label: {
  45417. show: true,
  45418. formatter: null, // string | Function
  45419. precision: 'auto', // Or a number like 0, 1, 2 ...
  45420. margin: 3,
  45421. color: '#fff',
  45422. padding: [5, 7, 5, 7],
  45423. backgroundColor: 'auto', // default: axis line color
  45424. borderColor: null,
  45425. borderWidth: 0,
  45426. shadowBlur: 3,
  45427. shadowColor: '#aaa'
  45428. // Considering applicability, common style should
  45429. // better not have shadowOffset.
  45430. // shadowOffsetX: 0,
  45431. // shadowOffsetY: 2
  45432. },
  45433. handle: {
  45434. show: false,
  45435. 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
  45436. size: 45,
  45437. // handle margin is from symbol center to axis, which is stable when circular move.
  45438. margin: 50,
  45439. // color: '#1b8bbd'
  45440. // color: '#2f4554'
  45441. color: '#333',
  45442. shadowBlur: 3,
  45443. shadowColor: '#aaa',
  45444. shadowOffsetX: 0,
  45445. shadowOffsetY: 2,
  45446. // For mobile performance
  45447. throttle: 40
  45448. }
  45449. }
  45450. });
  45451. var get$3 = makeGetter();
  45452. var each$18 = each$1;
  45453. /**
  45454. * @param {string} key
  45455. * @param {module:echarts/ExtensionAPI} api
  45456. * @param {Function} handler
  45457. * param: {string} currTrigger
  45458. * param: {Array.<number>} point
  45459. */
  45460. function register(key, api, handler) {
  45461. if (env$1.node) {
  45462. return;
  45463. }
  45464. var zr = api.getZr();
  45465. get$3(zr).records || (get$3(zr).records = {});
  45466. initGlobalListeners(zr, api);
  45467. var record = get$3(zr).records[key] || (get$3(zr).records[key] = {});
  45468. record.handler = handler;
  45469. }
  45470. function initGlobalListeners(zr, api) {
  45471. if (get$3(zr).initialized) {
  45472. return;
  45473. }
  45474. get$3(zr).initialized = true;
  45475. useHandler('click', curry(doEnter, 'click'));
  45476. useHandler('mousemove', curry(doEnter, 'mousemove'));
  45477. // useHandler('mouseout', onLeave);
  45478. useHandler('globalout', onLeave);
  45479. function useHandler(eventType, cb) {
  45480. zr.on(eventType, function (e) {
  45481. var dis = makeDispatchAction(api);
  45482. each$18(get$3(zr).records, function (record) {
  45483. record && cb(record, e, dis.dispatchAction);
  45484. });
  45485. dispatchTooltipFinally(dis.pendings, api);
  45486. });
  45487. }
  45488. }
  45489. function dispatchTooltipFinally(pendings, api) {
  45490. var showLen = pendings.showTip.length;
  45491. var hideLen = pendings.hideTip.length;
  45492. var actuallyPayload;
  45493. if (showLen) {
  45494. actuallyPayload = pendings.showTip[showLen - 1];
  45495. }
  45496. else if (hideLen) {
  45497. actuallyPayload = pendings.hideTip[hideLen - 1];
  45498. }
  45499. if (actuallyPayload) {
  45500. actuallyPayload.dispatchAction = null;
  45501. api.dispatchAction(actuallyPayload);
  45502. }
  45503. }
  45504. function onLeave(record, e, dispatchAction) {
  45505. record.handler('leave', null, dispatchAction);
  45506. }
  45507. function doEnter(currTrigger, record, e, dispatchAction) {
  45508. record.handler(currTrigger, e, dispatchAction);
  45509. }
  45510. function makeDispatchAction(api) {
  45511. var pendings = {
  45512. showTip: [],
  45513. hideTip: []
  45514. };
  45515. // FIXME
  45516. // better approach?
  45517. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  45518. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  45519. // So we have to add "final stage" to merge those dispatched actions.
  45520. var dispatchAction = function (payload) {
  45521. var pendingList = pendings[payload.type];
  45522. if (pendingList) {
  45523. pendingList.push(payload);
  45524. }
  45525. else {
  45526. payload.dispatchAction = dispatchAction;
  45527. api.dispatchAction(payload);
  45528. }
  45529. };
  45530. return {
  45531. dispatchAction: dispatchAction,
  45532. pendings: pendings
  45533. };
  45534. }
  45535. /**
  45536. * @param {string} key
  45537. * @param {module:echarts/ExtensionAPI} api
  45538. */
  45539. function unregister(key, api) {
  45540. if (env$1.node) {
  45541. return;
  45542. }
  45543. var zr = api.getZr();
  45544. var record = (get$3(zr).records || {})[key];
  45545. if (record) {
  45546. get$3(zr).records[key] = null;
  45547. }
  45548. }
  45549. var AxisPointerView = extendComponentView({
  45550. type: 'axisPointer',
  45551. render: function (globalAxisPointerModel, ecModel, api) {
  45552. var globalTooltipModel = ecModel.getComponent('tooltip');
  45553. var triggerOn = globalAxisPointerModel.get('triggerOn')
  45554. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  45555. // Register global listener in AxisPointerView to enable
  45556. // AxisPointerView to be independent to Tooltip.
  45557. register(
  45558. 'axisPointer',
  45559. api,
  45560. function (currTrigger, e, dispatchAction) {
  45561. // If 'none', it is not controlled by mouse totally.
  45562. if (triggerOn !== 'none'
  45563. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  45564. ) {
  45565. dispatchAction({
  45566. type: 'updateAxisPointer',
  45567. currTrigger: currTrigger,
  45568. x: e && e.offsetX,
  45569. y: e && e.offsetY
  45570. });
  45571. }
  45572. }
  45573. );
  45574. },
  45575. /**
  45576. * @override
  45577. */
  45578. remove: function (ecModel, api) {
  45579. unregister(api.getZr(), 'axisPointer');
  45580. AxisPointerView.superApply(this._model, 'remove', arguments);
  45581. },
  45582. /**
  45583. * @override
  45584. */
  45585. dispose: function (ecModel, api) {
  45586. unregister('axisPointer', api);
  45587. AxisPointerView.superApply(this._model, 'dispose', arguments);
  45588. }
  45589. });
  45590. var get$4 = makeGetter();
  45591. var clone$3 = clone;
  45592. var bind$2 = bind;
  45593. /**
  45594. * Base axis pointer class in 2D.
  45595. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  45596. */
  45597. function BaseAxisPointer () {
  45598. }
  45599. BaseAxisPointer.prototype = {
  45600. /**
  45601. * @private
  45602. */
  45603. _group: null,
  45604. /**
  45605. * @private
  45606. */
  45607. _lastGraphicKey: null,
  45608. /**
  45609. * @private
  45610. */
  45611. _handle: null,
  45612. /**
  45613. * @private
  45614. */
  45615. _dragging: false,
  45616. /**
  45617. * @private
  45618. */
  45619. _lastValue: null,
  45620. /**
  45621. * @private
  45622. */
  45623. _lastStatus: null,
  45624. /**
  45625. * @private
  45626. */
  45627. _payloadInfo: null,
  45628. /**
  45629. * In px, arbitrary value. Do not set too small,
  45630. * no animation is ok for most cases.
  45631. * @protected
  45632. */
  45633. animationThreshold: 15,
  45634. /**
  45635. * @implement
  45636. */
  45637. render: function (axisModel, axisPointerModel, api, forceRender) {
  45638. var value = axisPointerModel.get('value');
  45639. var status = axisPointerModel.get('status');
  45640. // Bind them to `this`, not in closure, otherwise they will not
  45641. // be replaced when user calling setOption in not merge mode.
  45642. this._axisModel = axisModel;
  45643. this._axisPointerModel = axisPointerModel;
  45644. this._api = api;
  45645. // Optimize: `render` will be called repeatly during mouse move.
  45646. // So it is power consuming if performing `render` each time,
  45647. // especially on mobile device.
  45648. if (!forceRender
  45649. && this._lastValue === value
  45650. && this._lastStatus === status
  45651. ) {
  45652. return;
  45653. }
  45654. this._lastValue = value;
  45655. this._lastStatus = status;
  45656. var group = this._group;
  45657. var handle = this._handle;
  45658. if (!status || status === 'hide') {
  45659. // Do not clear here, for animation better.
  45660. group && group.hide();
  45661. handle && handle.hide();
  45662. return;
  45663. }
  45664. group && group.show();
  45665. handle && handle.show();
  45666. // Otherwise status is 'show'
  45667. var elOption = {};
  45668. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  45669. // Enable change axis pointer type.
  45670. var graphicKey = elOption.graphicKey;
  45671. if (graphicKey !== this._lastGraphicKey) {
  45672. this.clear(api);
  45673. }
  45674. this._lastGraphicKey = graphicKey;
  45675. var moveAnimation = this._moveAnimation =
  45676. this.determineAnimation(axisModel, axisPointerModel);
  45677. if (!group) {
  45678. group = this._group = new Group();
  45679. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  45680. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  45681. api.getZr().add(group);
  45682. }
  45683. else {
  45684. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  45685. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  45686. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  45687. }
  45688. updateMandatoryProps(group, axisPointerModel, true);
  45689. this._renderHandle(value);
  45690. },
  45691. /**
  45692. * @implement
  45693. */
  45694. remove: function (api) {
  45695. this.clear(api);
  45696. },
  45697. /**
  45698. * @implement
  45699. */
  45700. dispose: function (api) {
  45701. this.clear(api);
  45702. },
  45703. /**
  45704. * @protected
  45705. */
  45706. determineAnimation: function (axisModel, axisPointerModel) {
  45707. var animation = axisPointerModel.get('animation');
  45708. var axis = axisModel.axis;
  45709. var isCategoryAxis = axis.type === 'category';
  45710. var useSnap = axisPointerModel.get('snap');
  45711. // Value axis without snap always do not snap.
  45712. if (!useSnap && !isCategoryAxis) {
  45713. return false;
  45714. }
  45715. if (animation === 'auto' || animation == null) {
  45716. var animationThreshold = this.animationThreshold;
  45717. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  45718. return true;
  45719. }
  45720. // It is important to auto animation when snap used. Consider if there is
  45721. // a dataZoom, animation will be disabled when too many points exist, while
  45722. // it will be enabled for better visual effect when little points exist.
  45723. if (useSnap) {
  45724. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  45725. var axisExtent = axis.getExtent();
  45726. // Approximate band width
  45727. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  45728. }
  45729. return false;
  45730. }
  45731. return animation === true;
  45732. },
  45733. /**
  45734. * add {pointer, label, graphicKey} to elOption
  45735. * @protected
  45736. */
  45737. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  45738. // Shoule be implemenented by sub-class.
  45739. },
  45740. /**
  45741. * @protected
  45742. */
  45743. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  45744. var pointerOption = elOption.pointer;
  45745. if (pointerOption) {
  45746. var pointerEl = get$4(group).pointerEl = new graphic[pointerOption.type](
  45747. clone$3(elOption.pointer)
  45748. );
  45749. group.add(pointerEl);
  45750. }
  45751. },
  45752. /**
  45753. * @protected
  45754. */
  45755. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  45756. if (elOption.label) {
  45757. var labelEl = get$4(group).labelEl = new Rect(
  45758. clone$3(elOption.label)
  45759. );
  45760. group.add(labelEl);
  45761. updateLabelShowHide(labelEl, axisPointerModel);
  45762. }
  45763. },
  45764. /**
  45765. * @protected
  45766. */
  45767. updatePointerEl: function (group, elOption, updateProps$$1) {
  45768. var pointerEl = get$4(group).pointerEl;
  45769. if (pointerEl) {
  45770. pointerEl.setStyle(elOption.pointer.style);
  45771. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  45772. }
  45773. },
  45774. /**
  45775. * @protected
  45776. */
  45777. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  45778. var labelEl = get$4(group).labelEl;
  45779. if (labelEl) {
  45780. labelEl.setStyle(elOption.label.style);
  45781. updateProps$$1(labelEl, {
  45782. // Consider text length change in vertical axis, animation should
  45783. // be used on shape, otherwise the effect will be weird.
  45784. shape: elOption.label.shape,
  45785. position: elOption.label.position
  45786. });
  45787. updateLabelShowHide(labelEl, axisPointerModel);
  45788. }
  45789. },
  45790. /**
  45791. * @private
  45792. */
  45793. _renderHandle: function (value) {
  45794. if (this._dragging || !this.updateHandleTransform) {
  45795. return;
  45796. }
  45797. var axisPointerModel = this._axisPointerModel;
  45798. var zr = this._api.getZr();
  45799. var handle = this._handle;
  45800. var handleModel = axisPointerModel.getModel('handle');
  45801. var status = axisPointerModel.get('status');
  45802. if (!handleModel.get('show') || !status || status === 'hide') {
  45803. handle && zr.remove(handle);
  45804. this._handle = null;
  45805. return;
  45806. }
  45807. var isInit;
  45808. if (!this._handle) {
  45809. isInit = true;
  45810. handle = this._handle = createIcon(
  45811. handleModel.get('icon'),
  45812. {
  45813. cursor: 'move',
  45814. draggable: true,
  45815. onmousemove: function (e) {
  45816. // Fot mobile devicem, prevent screen slider on the button.
  45817. stop(e.event);
  45818. },
  45819. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  45820. drift: bind$2(this._onHandleDragMove, this),
  45821. ondragend: bind$2(this._onHandleDragEnd, this)
  45822. }
  45823. );
  45824. zr.add(handle);
  45825. }
  45826. updateMandatoryProps(handle, axisPointerModel, false);
  45827. // update style
  45828. var includeStyles = [
  45829. 'color', 'borderColor', 'borderWidth', 'opacity',
  45830. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  45831. ];
  45832. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  45833. // update position
  45834. var handleSize = handleModel.get('size');
  45835. if (!isArray(handleSize)) {
  45836. handleSize = [handleSize, handleSize];
  45837. }
  45838. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  45839. createOrUpdate(
  45840. this,
  45841. '_doDispatchAxisPointer',
  45842. handleModel.get('throttle') || 0,
  45843. 'fixRate'
  45844. );
  45845. this._moveHandleToValue(value, isInit);
  45846. },
  45847. /**
  45848. * @private
  45849. */
  45850. _moveHandleToValue: function (value, isInit) {
  45851. updateProps$1(
  45852. this._axisPointerModel,
  45853. !isInit && this._moveAnimation,
  45854. this._handle,
  45855. getHandleTransProps(this.getHandleTransform(
  45856. value, this._axisModel, this._axisPointerModel
  45857. ))
  45858. );
  45859. },
  45860. /**
  45861. * @private
  45862. */
  45863. _onHandleDragMove: function (dx, dy) {
  45864. var handle = this._handle;
  45865. if (!handle) {
  45866. return;
  45867. }
  45868. this._dragging = true;
  45869. // Persistent for throttle.
  45870. var trans = this.updateHandleTransform(
  45871. getHandleTransProps(handle),
  45872. [dx, dy],
  45873. this._axisModel,
  45874. this._axisPointerModel
  45875. );
  45876. this._payloadInfo = trans;
  45877. handle.stopAnimation();
  45878. handle.attr(getHandleTransProps(trans));
  45879. get$4(handle).lastProp = null;
  45880. this._doDispatchAxisPointer();
  45881. },
  45882. /**
  45883. * Throttled method.
  45884. * @private
  45885. */
  45886. _doDispatchAxisPointer: function () {
  45887. var handle = this._handle;
  45888. if (!handle) {
  45889. return;
  45890. }
  45891. var payloadInfo = this._payloadInfo;
  45892. var axisModel = this._axisModel;
  45893. this._api.dispatchAction({
  45894. type: 'updateAxisPointer',
  45895. x: payloadInfo.cursorPoint[0],
  45896. y: payloadInfo.cursorPoint[1],
  45897. tooltipOption: payloadInfo.tooltipOption,
  45898. axesInfo: [{
  45899. axisDim: axisModel.axis.dim,
  45900. axisIndex: axisModel.componentIndex
  45901. }]
  45902. });
  45903. },
  45904. /**
  45905. * @private
  45906. */
  45907. _onHandleDragEnd: function (moveAnimation) {
  45908. this._dragging = false;
  45909. var handle = this._handle;
  45910. if (!handle) {
  45911. return;
  45912. }
  45913. var value = this._axisPointerModel.get('value');
  45914. // Consider snap or categroy axis, handle may be not consistent with
  45915. // axisPointer. So move handle to align the exact value position when
  45916. // drag ended.
  45917. this._moveHandleToValue(value);
  45918. // For the effect: tooltip will be shown when finger holding on handle
  45919. // button, and will be hidden after finger left handle button.
  45920. this._api.dispatchAction({
  45921. type: 'hideTip'
  45922. });
  45923. },
  45924. /**
  45925. * Should be implemenented by sub-class if support `handle`.
  45926. * @protected
  45927. * @param {number} value
  45928. * @param {module:echarts/model/Model} axisModel
  45929. * @param {module:echarts/model/Model} axisPointerModel
  45930. * @return {Object} {position: [x, y], rotation: 0}
  45931. */
  45932. getHandleTransform: null,
  45933. /**
  45934. * * Should be implemenented by sub-class if support `handle`.
  45935. * @protected
  45936. * @param {Object} transform {position, rotation}
  45937. * @param {Array.<number>} delta [dx, dy]
  45938. * @param {module:echarts/model/Model} axisModel
  45939. * @param {module:echarts/model/Model} axisPointerModel
  45940. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  45941. */
  45942. updateHandleTransform: null,
  45943. /**
  45944. * @private
  45945. */
  45946. clear: function (api) {
  45947. this._lastValue = null;
  45948. this._lastStatus = null;
  45949. var zr = api.getZr();
  45950. var group = this._group;
  45951. var handle = this._handle;
  45952. if (zr && group) {
  45953. this._lastGraphicKey = null;
  45954. group && zr.remove(group);
  45955. handle && zr.remove(handle);
  45956. this._group = null;
  45957. this._handle = null;
  45958. this._payloadInfo = null;
  45959. }
  45960. },
  45961. /**
  45962. * @protected
  45963. */
  45964. doClear: function () {
  45965. // Implemented by sub-class if necessary.
  45966. },
  45967. /**
  45968. * @protected
  45969. * @param {Array.<number>} xy
  45970. * @param {Array.<number>} wh
  45971. * @param {number} [xDimIndex=0] or 1
  45972. */
  45973. buildLabel: function (xy, wh, xDimIndex) {
  45974. xDimIndex = xDimIndex || 0;
  45975. return {
  45976. x: xy[xDimIndex],
  45977. y: xy[1 - xDimIndex],
  45978. width: wh[xDimIndex],
  45979. height: wh[1 - xDimIndex]
  45980. };
  45981. }
  45982. };
  45983. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  45984. function updateProps$1(animationModel, moveAnimation, el, props) {
  45985. // Animation optimize.
  45986. if (!propsEqual(get$4(el).lastProp, props)) {
  45987. get$4(el).lastProp = props;
  45988. moveAnimation
  45989. ? updateProps(el, props, animationModel)
  45990. : (el.stopAnimation(), el.attr(props));
  45991. }
  45992. }
  45993. function propsEqual(lastProps, newProps) {
  45994. if (isObject(lastProps) && isObject(newProps)) {
  45995. var equals = true;
  45996. each$1(newProps, function (item, key) {
  45997. equals = equals && propsEqual(lastProps[key], item);
  45998. });
  45999. return !!equals;
  46000. }
  46001. else {
  46002. return lastProps === newProps;
  46003. }
  46004. }
  46005. function updateLabelShowHide(labelEl, axisPointerModel) {
  46006. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  46007. }
  46008. function getHandleTransProps(trans) {
  46009. return {
  46010. position: trans.position.slice(),
  46011. rotation: trans.rotation || 0
  46012. };
  46013. }
  46014. function updateMandatoryProps(group, axisPointerModel, silent) {
  46015. var z = axisPointerModel.get('z');
  46016. var zlevel = axisPointerModel.get('zlevel');
  46017. group && group.traverse(function (el) {
  46018. if (el.type !== 'group') {
  46019. z != null && (el.z = z);
  46020. zlevel != null && (el.zlevel = zlevel);
  46021. el.silent = silent;
  46022. }
  46023. });
  46024. }
  46025. enableClassExtend(BaseAxisPointer);
  46026. /**
  46027. * @param {module:echarts/model/Model} axisPointerModel
  46028. */
  46029. function buildElStyle(axisPointerModel) {
  46030. var axisPointerType = axisPointerModel.get('type');
  46031. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  46032. var style;
  46033. if (axisPointerType === 'line') {
  46034. style = styleModel.getLineStyle();
  46035. style.fill = null;
  46036. }
  46037. else if (axisPointerType === 'shadow') {
  46038. style = styleModel.getAreaStyle();
  46039. style.stroke = null;
  46040. }
  46041. return style;
  46042. }
  46043. /**
  46044. * @param {Function} labelPos {align, verticalAlign, position}
  46045. */
  46046. function buildLabelElOption(
  46047. elOption, axisModel, axisPointerModel, api, labelPos
  46048. ) {
  46049. var value = axisPointerModel.get('value');
  46050. var text = getValueLabel(
  46051. value, axisModel.axis, axisModel.ecModel,
  46052. axisPointerModel.get('seriesDataIndices'),
  46053. {
  46054. precision: axisPointerModel.get('label.precision'),
  46055. formatter: axisPointerModel.get('label.formatter')
  46056. }
  46057. );
  46058. var labelModel = axisPointerModel.getModel('label');
  46059. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  46060. var font = labelModel.getFont();
  46061. var textRect = getBoundingRect(text, font);
  46062. var position = labelPos.position;
  46063. var width = textRect.width + paddings[1] + paddings[3];
  46064. var height = textRect.height + paddings[0] + paddings[2];
  46065. // Adjust by align.
  46066. var align = labelPos.align;
  46067. align === 'right' && (position[0] -= width);
  46068. align === 'center' && (position[0] -= width / 2);
  46069. var verticalAlign = labelPos.verticalAlign;
  46070. verticalAlign === 'bottom' && (position[1] -= height);
  46071. verticalAlign === 'middle' && (position[1] -= height / 2);
  46072. // Not overflow ec container
  46073. confineInContainer(position, width, height, api);
  46074. var bgColor = labelModel.get('backgroundColor');
  46075. if (!bgColor || bgColor === 'auto') {
  46076. bgColor = axisModel.get('axisLine.lineStyle.color');
  46077. }
  46078. elOption.label = {
  46079. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  46080. position: position.slice(),
  46081. // TODO: rich
  46082. style: {
  46083. text: text,
  46084. textFont: font,
  46085. textFill: labelModel.getTextColor(),
  46086. textPosition: 'inside',
  46087. fill: bgColor,
  46088. stroke: labelModel.get('borderColor') || 'transparent',
  46089. lineWidth: labelModel.get('borderWidth') || 0,
  46090. shadowBlur: labelModel.get('shadowBlur'),
  46091. shadowColor: labelModel.get('shadowColor'),
  46092. shadowOffsetX: labelModel.get('shadowOffsetX'),
  46093. shadowOffsetY: labelModel.get('shadowOffsetY')
  46094. },
  46095. // Lable should be over axisPointer.
  46096. z2: 10
  46097. };
  46098. }
  46099. // Do not overflow ec container
  46100. function confineInContainer(position, width, height, api) {
  46101. var viewWidth = api.getWidth();
  46102. var viewHeight = api.getHeight();
  46103. position[0] = Math.min(position[0] + width, viewWidth) - width;
  46104. position[1] = Math.min(position[1] + height, viewHeight) - height;
  46105. position[0] = Math.max(position[0], 0);
  46106. position[1] = Math.max(position[1], 0);
  46107. }
  46108. /**
  46109. * @param {number} value
  46110. * @param {module:echarts/coord/Axis} axis
  46111. * @param {module:echarts/model/Global} ecModel
  46112. * @param {Object} opt
  46113. * @param {Array.<Object>} seriesDataIndices
  46114. * @param {number|string} opt.precision 'auto' or a number
  46115. * @param {string|Function} opt.formatter label formatter
  46116. */
  46117. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  46118. var text = axis.scale.getLabel(
  46119. // If `precision` is set, width can be fixed (like '12.00500'), which
  46120. // helps to debounce when when moving label.
  46121. value, {precision: opt.precision}
  46122. );
  46123. var formatter = opt.formatter;
  46124. if (formatter) {
  46125. var params = {
  46126. value: getAxisRawValue(axis, value),
  46127. seriesData: []
  46128. };
  46129. each$1(seriesDataIndices, function (idxItem) {
  46130. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  46131. var dataIndex = idxItem.dataIndexInside;
  46132. var dataParams = series && series.getDataParams(dataIndex);
  46133. dataParams && params.seriesData.push(dataParams);
  46134. });
  46135. if (isString(formatter)) {
  46136. text = formatter.replace('{value}', text);
  46137. }
  46138. else if (isFunction(formatter)) {
  46139. text = formatter(params);
  46140. }
  46141. }
  46142. return text;
  46143. }
  46144. /**
  46145. * @param {module:echarts/coord/Axis} axis
  46146. * @param {number} value
  46147. * @param {Object} layoutInfo {
  46148. * rotation, position, labelOffset, labelDirection, labelMargin
  46149. * }
  46150. */
  46151. function getTransformedPosition (axis, value, layoutInfo) {
  46152. var transform = create$1();
  46153. rotate(transform, transform, layoutInfo.rotation);
  46154. translate(transform, transform, layoutInfo.position);
  46155. return applyTransform$1([
  46156. axis.dataToCoord(value),
  46157. (layoutInfo.labelOffset || 0)
  46158. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  46159. ], transform);
  46160. }
  46161. function buildCartesianSingleLabelElOption(
  46162. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46163. ) {
  46164. var textLayout = AxisBuilder.innerTextLayout(
  46165. layoutInfo.rotation, 0, layoutInfo.labelDirection
  46166. );
  46167. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  46168. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  46169. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46170. align: textLayout.textAlign,
  46171. verticalAlign: textLayout.textVerticalAlign
  46172. });
  46173. }
  46174. /**
  46175. * @param {Array.<number>} p1
  46176. * @param {Array.<number>} p2
  46177. * @param {number} [xDimIndex=0] or 1
  46178. */
  46179. function makeLineShape(p1, p2, xDimIndex) {
  46180. xDimIndex = xDimIndex || 0;
  46181. return {
  46182. x1: p1[xDimIndex],
  46183. y1: p1[1 - xDimIndex],
  46184. x2: p2[xDimIndex],
  46185. y2: p2[1 - xDimIndex]
  46186. };
  46187. }
  46188. /**
  46189. * @param {Array.<number>} xy
  46190. * @param {Array.<number>} wh
  46191. * @param {number} [xDimIndex=0] or 1
  46192. */
  46193. function makeRectShape(xy, wh, xDimIndex) {
  46194. xDimIndex = xDimIndex || 0;
  46195. return {
  46196. x: xy[xDimIndex],
  46197. y: xy[1 - xDimIndex],
  46198. width: wh[xDimIndex],
  46199. height: wh[1 - xDimIndex]
  46200. };
  46201. }
  46202. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  46203. return {
  46204. cx: cx,
  46205. cy: cy,
  46206. r0: r0,
  46207. r: r,
  46208. startAngle: startAngle,
  46209. endAngle: endAngle,
  46210. clockwise: true
  46211. };
  46212. }
  46213. var CartesianAxisPointer = BaseAxisPointer.extend({
  46214. /**
  46215. * @override
  46216. */
  46217. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  46218. var axis = axisModel.axis;
  46219. var grid = axis.grid;
  46220. var axisPointerType = axisPointerModel.get('type');
  46221. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  46222. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  46223. if (axisPointerType && axisPointerType !== 'none') {
  46224. var elStyle = buildElStyle(axisPointerModel);
  46225. var pointerOption = pointerShapeBuilder[axisPointerType](
  46226. axis, pixelValue, otherExtent, elStyle
  46227. );
  46228. pointerOption.style = elStyle;
  46229. elOption.graphicKey = pointerOption.type;
  46230. elOption.pointer = pointerOption;
  46231. }
  46232. var layoutInfo = layout(grid.model, axisModel);
  46233. buildCartesianSingleLabelElOption(
  46234. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46235. );
  46236. },
  46237. /**
  46238. * @override
  46239. */
  46240. getHandleTransform: function (value, axisModel, axisPointerModel) {
  46241. var layoutInfo = layout(axisModel.axis.grid.model, axisModel, {
  46242. labelInside: false
  46243. });
  46244. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  46245. return {
  46246. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46247. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  46248. };
  46249. },
  46250. /**
  46251. * @override
  46252. */
  46253. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  46254. var axis = axisModel.axis;
  46255. var grid = axis.grid;
  46256. var axisExtent = axis.getGlobalExtent(true);
  46257. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  46258. var dimIndex = axis.dim === 'x' ? 0 : 1;
  46259. var currPosition = transform.position;
  46260. currPosition[dimIndex] += delta[dimIndex];
  46261. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  46262. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  46263. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  46264. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  46265. cursorPoint[dimIndex] = currPosition[dimIndex];
  46266. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  46267. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  46268. return {
  46269. position: currPosition,
  46270. rotation: transform.rotation,
  46271. cursorPoint: cursorPoint,
  46272. tooltipOption: tooltipOptions[dimIndex]
  46273. };
  46274. }
  46275. });
  46276. function getCartesian(grid, axis) {
  46277. var opt = {};
  46278. opt[axis.dim + 'AxisIndex'] = axis.index;
  46279. return grid.getCartesian(opt);
  46280. }
  46281. var pointerShapeBuilder = {
  46282. line: function (axis, pixelValue, otherExtent, elStyle) {
  46283. var targetShape = makeLineShape(
  46284. [pixelValue, otherExtent[0]],
  46285. [pixelValue, otherExtent[1]],
  46286. getAxisDimIndex(axis)
  46287. );
  46288. subPixelOptimizeLine({
  46289. shape: targetShape,
  46290. style: elStyle
  46291. });
  46292. return {
  46293. type: 'Line',
  46294. shape: targetShape
  46295. };
  46296. },
  46297. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  46298. var bandWidth = axis.getBandWidth();
  46299. var span = otherExtent[1] - otherExtent[0];
  46300. return {
  46301. type: 'Rect',
  46302. shape: makeRectShape(
  46303. [pixelValue - bandWidth / 2, otherExtent[0]],
  46304. [bandWidth, span],
  46305. getAxisDimIndex(axis)
  46306. )
  46307. };
  46308. }
  46309. };
  46310. function getAxisDimIndex(axis) {
  46311. return axis.dim === 'x' ? 0 : 1;
  46312. }
  46313. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  46314. // CartesianAxisPointer is not supposed to be required here. But consider
  46315. // echarts.simple.js and online build tooltip, which only require gridSimple,
  46316. // CartesianAxisPointer should be able to required somewhere.
  46317. registerPreprocessor(function (option) {
  46318. // Always has a global axisPointerModel for default setting.
  46319. if (option) {
  46320. (!option.axisPointer || option.axisPointer.length === 0)
  46321. && (option.axisPointer = {});
  46322. var link = option.axisPointer.link;
  46323. // Normalize to array to avoid object mergin. But if link
  46324. // is not set, remain null/undefined, otherwise it will
  46325. // override existent link setting.
  46326. if (link && !isArray(link)) {
  46327. option.axisPointer.link = [link];
  46328. }
  46329. }
  46330. });
  46331. // This process should proformed after coordinate systems created
  46332. // and series data processed. So put it on statistic processing stage.
  46333. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  46334. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  46335. // allAxesInfo should be updated when setOption performed.
  46336. ecModel.getComponent('axisPointer').coordSysAxesInfo
  46337. = collect(ecModel, api);
  46338. });
  46339. // Broadcast to all views.
  46340. registerAction({
  46341. type: 'updateAxisPointer',
  46342. event: 'updateAxisPointer',
  46343. update: ':updateAxisPointer'
  46344. }, axisTrigger);
  46345. var XY = ['x', 'y'];
  46346. var WH = ['width', 'height'];
  46347. var SingleAxisPointer = BaseAxisPointer.extend({
  46348. /**
  46349. * @override
  46350. */
  46351. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  46352. var axis = axisModel.axis;
  46353. var coordSys = axis.coordinateSystem;
  46354. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  46355. var pixelValue = coordSys.dataToPoint(value)[0];
  46356. var axisPointerType = axisPointerModel.get('type');
  46357. if (axisPointerType && axisPointerType !== 'none') {
  46358. var elStyle = buildElStyle(axisPointerModel);
  46359. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  46360. axis, pixelValue, otherExtent, elStyle
  46361. );
  46362. pointerOption.style = elStyle;
  46363. elOption.graphicKey = pointerOption.type;
  46364. elOption.pointer = pointerOption;
  46365. }
  46366. var layoutInfo = layout$1(axisModel);
  46367. buildCartesianSingleLabelElOption(
  46368. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  46369. );
  46370. },
  46371. /**
  46372. * @override
  46373. */
  46374. getHandleTransform: function (value, axisModel, axisPointerModel) {
  46375. var layoutInfo = layout$1(axisModel, {labelInside: false});
  46376. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  46377. return {
  46378. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  46379. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  46380. };
  46381. },
  46382. /**
  46383. * @override
  46384. */
  46385. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  46386. var axis = axisModel.axis;
  46387. var coordSys = axis.coordinateSystem;
  46388. var dimIndex = getPointDimIndex(axis);
  46389. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  46390. var currPosition = transform.position;
  46391. currPosition[dimIndex] += delta[dimIndex];
  46392. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  46393. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  46394. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  46395. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  46396. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  46397. cursorPoint[dimIndex] = currPosition[dimIndex];
  46398. return {
  46399. position: currPosition,
  46400. rotation: transform.rotation,
  46401. cursorPoint: cursorPoint,
  46402. tooltipOption: {
  46403. verticalAlign: 'middle'
  46404. }
  46405. };
  46406. }
  46407. });
  46408. var pointerShapeBuilder$1 = {
  46409. line: function (axis, pixelValue, otherExtent, elStyle) {
  46410. var targetShape = makeLineShape(
  46411. [pixelValue, otherExtent[0]],
  46412. [pixelValue, otherExtent[1]],
  46413. getPointDimIndex(axis)
  46414. );
  46415. subPixelOptimizeLine({
  46416. shape: targetShape,
  46417. style: elStyle
  46418. });
  46419. return {
  46420. type: 'Line',
  46421. shape: targetShape
  46422. };
  46423. },
  46424. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  46425. var bandWidth = axis.getBandWidth();
  46426. var span = otherExtent[1] - otherExtent[0];
  46427. return {
  46428. type: 'Rect',
  46429. shape: makeRectShape(
  46430. [pixelValue - bandWidth / 2, otherExtent[0]],
  46431. [bandWidth, span],
  46432. getPointDimIndex(axis)
  46433. )
  46434. };
  46435. }
  46436. };
  46437. function getPointDimIndex(axis) {
  46438. return axis.isHorizontal() ? 0 : 1;
  46439. }
  46440. function getGlobalExtent(coordSys, dimIndex) {
  46441. var rect = coordSys.getRect();
  46442. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  46443. }
  46444. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  46445. extendComponentView({
  46446. type: 'single'
  46447. });
  46448. /**
  46449. * @file Define the themeRiver view's series model
  46450. * @author Deqing Li(annong035@gmail.com)
  46451. */
  46452. var DATA_NAME_INDEX = 2;
  46453. var ThemeRiverSeries = SeriesModel.extend({
  46454. type: 'series.themeRiver',
  46455. dependencies: ['singleAxis'],
  46456. /**
  46457. * @readOnly
  46458. * @type {module:zrender/core/util#HashMap}
  46459. */
  46460. nameMap: null,
  46461. /**
  46462. * @override
  46463. */
  46464. init: function (option) {
  46465. ThemeRiverSeries.superApply(this, 'init', arguments);
  46466. // Put this function here is for the sake of consistency of code style.
  46467. // Enable legend selection for each data item
  46468. // Use a function instead of direct access because data reference may changed
  46469. this.legendDataProvider = function () {
  46470. return this.getRawData();
  46471. };
  46472. },
  46473. /**
  46474. * If there is no value of a certain point in the time for some event,set it value to 0.
  46475. *
  46476. * @param {Array} data initial data in the option
  46477. * @return {Array}
  46478. */
  46479. fixData: function (data) {
  46480. var rawDataLength = data.length;
  46481. // grouped data by name
  46482. var dataByName = nest()
  46483. .key(function (dataItem) {
  46484. return dataItem[2];
  46485. })
  46486. .entries(data);
  46487. // data group in each layer
  46488. var layData = map(dataByName, function (d) {
  46489. return {
  46490. name: d.key,
  46491. dataList: d.values
  46492. };
  46493. });
  46494. var layerNum = layData.length;
  46495. var largestLayer = -1;
  46496. var index = -1;
  46497. for (var i = 0; i < layerNum; ++i) {
  46498. var len = layData[i].dataList.length;
  46499. if (len > largestLayer) {
  46500. largestLayer = len;
  46501. index = i;
  46502. }
  46503. }
  46504. for (var k = 0; k < layerNum; ++k) {
  46505. if (k === index) {
  46506. continue;
  46507. }
  46508. var name = layData[k].name;
  46509. for (var j = 0; j < largestLayer; ++j) {
  46510. var timeValue = layData[index].dataList[j][0];
  46511. var length = layData[k].dataList.length;
  46512. var keyIndex = -1;
  46513. for (var l = 0; l < length; ++l) {
  46514. var value = layData[k].dataList[l][0];
  46515. if (value === timeValue) {
  46516. keyIndex = l;
  46517. break;
  46518. }
  46519. }
  46520. if (keyIndex === -1) {
  46521. data[rawDataLength] = [];
  46522. data[rawDataLength][0] = timeValue;
  46523. data[rawDataLength][1] = 0;
  46524. data[rawDataLength][2] = name;
  46525. rawDataLength++;
  46526. }
  46527. }
  46528. }
  46529. return data;
  46530. },
  46531. /**
  46532. * @override
  46533. * @param {Object} option the initial option that user gived
  46534. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  46535. * @return {module:echarts/data/List}
  46536. */
  46537. getInitialData: function (option, ecModel) {
  46538. var dimensions = [];
  46539. var singleAxisModel = ecModel.queryComponents({
  46540. mainType: 'singleAxis',
  46541. index: this.get('singleAxisIndex'),
  46542. id: this.get('singleAxisId')
  46543. })[0];
  46544. var axisType = singleAxisModel.get('type');
  46545. dimensions = [
  46546. {
  46547. name: 'time',
  46548. // FIXME common?
  46549. type: axisType === 'category'
  46550. ? 'ordinal'
  46551. : axisType === 'time'
  46552. ? 'time'
  46553. : 'float'
  46554. },
  46555. {
  46556. name: 'value',
  46557. type: 'float'
  46558. },
  46559. {
  46560. name: 'name',
  46561. type: 'ordinal'
  46562. }
  46563. ];
  46564. // filter the data item with the value of label is undefined
  46565. var filterData = filter(option.data, function (dataItem) {
  46566. return dataItem[2] !== undefined;
  46567. });
  46568. var data = this.fixData(filterData || []);
  46569. var nameList = [];
  46570. var nameMap = this.nameMap = createHashMap();
  46571. var count = 0;
  46572. for (var i = 0; i < data.length; ++i) {
  46573. nameList.push(data[i][DATA_NAME_INDEX]);
  46574. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  46575. nameMap.set(data[i][DATA_NAME_INDEX], count);
  46576. count++;
  46577. }
  46578. }
  46579. dimensions = completeDimensions(dimensions, data);
  46580. var list = new List(dimensions, this);
  46581. list.initData(data, nameList);
  46582. return list;
  46583. },
  46584. /**
  46585. * Used by single coordinate
  46586. *
  46587. * @param {string} axisDim the dimension for single coordinate
  46588. * @return {Array.<string> } specified dimensions on the axis.
  46589. */
  46590. coordDimToDataDim: function (axisDim) {
  46591. return ['time'];
  46592. },
  46593. /**
  46594. * The raw data is divided into multiple layers and each layer
  46595. * has same name.
  46596. *
  46597. * @return {Array.<Array.<number>>}
  46598. */
  46599. getLayerSeries: function () {
  46600. var data = this.getData();
  46601. var lenCount = data.count();
  46602. var indexArr = [];
  46603. for (var i = 0; i < lenCount; ++i) {
  46604. indexArr[i] = i;
  46605. }
  46606. // data group by name
  46607. var dataByName = nest()
  46608. .key(function (index) {
  46609. return data.get('name', index);
  46610. })
  46611. .entries(indexArr);
  46612. var layerSeries = map(dataByName, function (d) {
  46613. return {
  46614. name: d.key,
  46615. indices: d.values
  46616. };
  46617. });
  46618. for (var j = 0; j < layerSeries.length; ++j) {
  46619. layerSeries[j].indices.sort(comparer);
  46620. }
  46621. function comparer(index1, index2) {
  46622. return data.get('time', index1) - data.get('time', index2);
  46623. }
  46624. return layerSeries;
  46625. },
  46626. /**
  46627. * Get data indices for show tooltip content
  46628. *
  46629. * @param {Array.<string>|string} dim single coordinate dimension
  46630. * @param {number} value axis value
  46631. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  46632. * the themeRiver.
  46633. * @return {Object} {dataIndices, nestestValue}
  46634. */
  46635. getAxisTooltipData: function (dim, value, baseAxis) {
  46636. if (!isArray(dim)) {
  46637. dim = dim ? [dim] : [];
  46638. }
  46639. var data = this.getData();
  46640. var layerSeries = this.getLayerSeries();
  46641. var indices = [];
  46642. var layerNum = layerSeries.length;
  46643. var nestestValue;
  46644. for (var i = 0; i < layerNum; ++i) {
  46645. var minDist = Number.MAX_VALUE;
  46646. var nearestIdx = -1;
  46647. var pointNum = layerSeries[i].indices.length;
  46648. for (var j = 0; j < pointNum; ++j) {
  46649. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  46650. var dist = Math.abs(theValue - value);
  46651. if (dist <= minDist) {
  46652. nestestValue = theValue;
  46653. minDist = dist;
  46654. nearestIdx = layerSeries[i].indices[j];
  46655. }
  46656. }
  46657. indices.push(nearestIdx);
  46658. }
  46659. return {dataIndices: indices, nestestValue: nestestValue};
  46660. },
  46661. /**
  46662. * @override
  46663. * @param {number} dataIndex index of data
  46664. */
  46665. formatTooltip: function (dataIndex) {
  46666. var data = this.getData();
  46667. var htmlName = data.get('name', dataIndex);
  46668. var htmlValue = data.get('value', dataIndex);
  46669. if (isNaN(htmlValue) || htmlValue == null) {
  46670. htmlValue = '-';
  46671. }
  46672. return encodeHTML(htmlName + ' : ' + htmlValue);
  46673. },
  46674. defaultOption: {
  46675. zlevel: 0,
  46676. z: 2,
  46677. coordinateSystem: 'singleAxis',
  46678. // gap in axis's orthogonal orientation
  46679. boundaryGap: ['10%', '10%'],
  46680. // legendHoverLink: true,
  46681. singleAxisIndex: 0,
  46682. animationEasing: 'linear',
  46683. label: {
  46684. normal: {
  46685. margin: 4,
  46686. textAlign: 'right',
  46687. show: true,
  46688. position: 'left',
  46689. color: '#000',
  46690. fontSize: 11
  46691. },
  46692. emphasis: {
  46693. show: true
  46694. }
  46695. }
  46696. }
  46697. });
  46698. /**
  46699. * @file The file used to draw themeRiver view
  46700. * @author Deqing Li(annong035@gmail.com)
  46701. */
  46702. extendChartView({
  46703. type: 'themeRiver',
  46704. init: function () {
  46705. this._layers = [];
  46706. },
  46707. render: function (seriesModel, ecModel, api) {
  46708. var data = seriesModel.getData();
  46709. var group = this.group;
  46710. var layerSeries = seriesModel.getLayerSeries();
  46711. var layoutInfo = data.getLayout('layoutInfo');
  46712. var rect = layoutInfo.rect;
  46713. var boundaryGap = layoutInfo.boundaryGap;
  46714. group.attr('position', [0, rect.y + boundaryGap[0]]);
  46715. function keyGetter(item) {
  46716. return item.name;
  46717. }
  46718. var dataDiffer = new DataDiffer(
  46719. this._layersSeries || [], layerSeries,
  46720. keyGetter, keyGetter
  46721. );
  46722. var newLayersGroups = {};
  46723. dataDiffer
  46724. .add(bind(process, this, 'add'))
  46725. .update(bind(process, this, 'update'))
  46726. .remove(bind(process, this, 'remove'))
  46727. .execute();
  46728. function process(status, idx, oldIdx) {
  46729. var oldLayersGroups = this._layers;
  46730. if (status === 'remove') {
  46731. group.remove(oldLayersGroups[idx]);
  46732. return;
  46733. }
  46734. var points0 = [];
  46735. var points1 = [];
  46736. var color;
  46737. var indices = layerSeries[idx].indices;
  46738. for (var j = 0; j < indices.length; j++) {
  46739. var layout = data.getItemLayout(indices[j]);
  46740. var x = layout.x;
  46741. var y0 = layout.y0;
  46742. var y = layout.y;
  46743. points0.push([x, y0]);
  46744. points1.push([x, y0 + y]);
  46745. color = data.getItemVisual(indices[j], 'color');
  46746. }
  46747. var polygon;
  46748. var text;
  46749. var textLayout = data.getItemLayout(indices[0]);
  46750. var itemModel = data.getItemModel(indices[j - 1]);
  46751. var labelModel = itemModel.getModel('label.normal');
  46752. var margin = labelModel.get('margin');
  46753. if (status === 'add') {
  46754. var layerGroup = newLayersGroups[idx] = new Group();
  46755. polygon = new Polygon$1({
  46756. shape: {
  46757. points: points0,
  46758. stackedOnPoints: points1,
  46759. smooth: 0.4,
  46760. stackedOnSmooth: 0.4,
  46761. smoothConstraint: false
  46762. },
  46763. z2: 0
  46764. });
  46765. text = new Text({
  46766. style: {
  46767. x: textLayout.x - margin,
  46768. y: textLayout.y0 + textLayout.y / 2
  46769. }
  46770. });
  46771. layerGroup.add(polygon);
  46772. layerGroup.add(text);
  46773. group.add(layerGroup);
  46774. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  46775. polygon.removeClipPath();
  46776. }));
  46777. }
  46778. else {
  46779. var layerGroup = oldLayersGroups[oldIdx];
  46780. polygon = layerGroup.childAt(0);
  46781. text = layerGroup.childAt(1);
  46782. group.add(layerGroup);
  46783. newLayersGroups[idx] = layerGroup;
  46784. updateProps(polygon, {
  46785. shape: {
  46786. points: points0,
  46787. stackedOnPoints: points1
  46788. }
  46789. }, seriesModel);
  46790. updateProps(text, {
  46791. style: {
  46792. x: textLayout.x - margin,
  46793. y: textLayout.y0 + textLayout.y / 2
  46794. }
  46795. }, seriesModel);
  46796. }
  46797. var hoverItemStyleModel = itemModel.getModel('itemStyle.emphasis');
  46798. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  46799. setTextStyle(text.style, labelModel, {
  46800. text: labelModel.get('show')
  46801. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  46802. || data.getName(indices[j - 1])
  46803. : null,
  46804. textVerticalAlign: 'middle'
  46805. });
  46806. polygon.setStyle(extend({
  46807. fill: color
  46808. }, itemStyleModel.getItemStyle(['color'])));
  46809. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  46810. }
  46811. this._layersSeries = layerSeries;
  46812. this._layers = newLayersGroups;
  46813. },
  46814. dispose: function () {}
  46815. });
  46816. // add animation to the view
  46817. function createGridClipShape$3(rect, seriesModel, cb) {
  46818. var rectEl = new Rect({
  46819. shape: {
  46820. x: rect.x - 10,
  46821. y: rect.y - 10,
  46822. width: 0,
  46823. height: rect.height + 20
  46824. }
  46825. });
  46826. initProps(rectEl, {
  46827. shape: {
  46828. width: rect.width + 20,
  46829. height: rect.height + 20
  46830. }
  46831. }, seriesModel, cb);
  46832. return rectEl;
  46833. }
  46834. /**
  46835. * @file Using layout algorithm transform the raw data to layout information.
  46836. * @author Deqing Li(annong035@gmail.com)
  46837. */
  46838. var themeRiverLayout = function (ecModel, api) {
  46839. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  46840. var data = seriesModel.getData();
  46841. var single = seriesModel.coordinateSystem;
  46842. var layoutInfo = {};
  46843. // use the axis boundingRect for view
  46844. var rect = single.getRect();
  46845. layoutInfo.rect = rect;
  46846. var boundaryGap = seriesModel.get('boundaryGap');
  46847. var axis = single.getAxis();
  46848. layoutInfo.boundaryGap = boundaryGap;
  46849. if (axis.orient === 'horizontal') {
  46850. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  46851. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  46852. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  46853. themeRiverLayout$1(data, seriesModel, height);
  46854. }
  46855. else {
  46856. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  46857. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  46858. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  46859. themeRiverLayout$1(data, seriesModel, width);
  46860. }
  46861. data.setLayout('layoutInfo', layoutInfo);
  46862. });
  46863. };
  46864. /**
  46865. * The layout information about themeriver
  46866. *
  46867. * @param {module:echarts/data/List} data data in the series
  46868. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  46869. * @param {number} height value used to compute every series height
  46870. */
  46871. function themeRiverLayout$1(data, seriesModel, height) {
  46872. if (!data.count()) {
  46873. return;
  46874. }
  46875. var coordSys = seriesModel.coordinateSystem;
  46876. // the data in each layer are organized into a series.
  46877. var layerSeries = seriesModel.getLayerSeries();
  46878. // the points in each layer.
  46879. var layerPoints = map(layerSeries, function (singleLayer) {
  46880. return map(singleLayer.indices, function (idx) {
  46881. var pt = coordSys.dataToPoint(data.get('time', idx));
  46882. pt[1] = data.get('value', idx);
  46883. return pt;
  46884. });
  46885. });
  46886. var base = computeBaseline(layerPoints);
  46887. var baseLine = base.y0;
  46888. var ky = height / base.max;
  46889. // set layout information for each item.
  46890. var n = layerSeries.length;
  46891. var m = layerSeries[0].indices.length;
  46892. var baseY0;
  46893. for (var j = 0; j < m; ++j) {
  46894. baseY0 = baseLine[j] * ky;
  46895. data.setItemLayout(layerSeries[0].indices[j], {
  46896. layerIndex: 0,
  46897. x: layerPoints[0][j][0],
  46898. y0: baseY0,
  46899. y: layerPoints[0][j][1] * ky
  46900. });
  46901. for (var i = 1; i < n; ++i) {
  46902. baseY0 += layerPoints[i - 1][j][1] * ky;
  46903. data.setItemLayout(layerSeries[i].indices[j], {
  46904. layerIndex: i,
  46905. x: layerPoints[i][j][0],
  46906. y0: baseY0,
  46907. y: layerPoints[i][j][1] * ky
  46908. });
  46909. }
  46910. }
  46911. }
  46912. /**
  46913. * Compute the baseLine of the rawdata
  46914. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  46915. *
  46916. * @param {Array.<Array>} data the points in each layer
  46917. * @return {Object}
  46918. */
  46919. function computeBaseline(data) {
  46920. var layerNum = data.length;
  46921. var pointNum = data[0].length;
  46922. var sums = [];
  46923. var y0 = [];
  46924. var max = 0;
  46925. var temp;
  46926. var base = {};
  46927. for (var i = 0; i < pointNum; ++i) {
  46928. for (var j = 0, temp = 0; j < layerNum; ++j) {
  46929. temp += data[j][i][1];
  46930. }
  46931. if (temp > max) {
  46932. max = temp;
  46933. }
  46934. sums.push(temp);
  46935. }
  46936. for (var k = 0; k < pointNum; ++k) {
  46937. y0[k] = (max - sums[k]) / 2;
  46938. }
  46939. max = 0;
  46940. for (var l = 0; l < pointNum; ++l) {
  46941. var sum = sums[l] + y0[l];
  46942. if (sum > max) {
  46943. max = sum;
  46944. }
  46945. }
  46946. base.y0 = y0;
  46947. base.max = max;
  46948. return base;
  46949. }
  46950. /**
  46951. * @file Visual encoding for themeRiver view
  46952. * @author Deqing Li(annong035@gmail.com)
  46953. */
  46954. var themeRiverVisual = function (ecModel) {
  46955. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  46956. var data = seriesModel.getData();
  46957. var rawData = seriesModel.getRawData();
  46958. var colorList = seriesModel.get('color');
  46959. var idxMap = createHashMap();
  46960. data.each(function (idx) {
  46961. idxMap.set(data.getRawIndex(idx), idx);
  46962. });
  46963. rawData.each(function (rawIndex) {
  46964. var name = rawData.getName(rawIndex);
  46965. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  46966. rawData.setItemVisual(rawIndex, 'color', color);
  46967. var idx = idxMap.get(rawIndex);
  46968. if (idx != null) {
  46969. data.setItemVisual(idx, 'color', color);
  46970. }
  46971. });
  46972. });
  46973. };
  46974. registerLayout(themeRiverLayout);
  46975. registerVisual(themeRiverVisual);
  46976. registerProcessor(curry(dataFilter, 'themeRiver'));
  46977. function dataToCoordSize(dataSize, dataItem) {
  46978. // dataItem is necessary in log axis.
  46979. dataItem = dataItem || [0, 0];
  46980. return map(['x', 'y'], function (dim, dimIdx) {
  46981. var axis = this.getAxis(dim);
  46982. var val = dataItem[dimIdx];
  46983. var halfSize = dataSize[dimIdx] / 2;
  46984. return axis.type === 'category'
  46985. ? axis.getBandWidth()
  46986. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  46987. }, this);
  46988. }
  46989. var prepareCartesian2d = function (coordSys) {
  46990. var rect = coordSys.grid.getRect();
  46991. return {
  46992. coordSys: {
  46993. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  46994. type: 'cartesian2d',
  46995. x: rect.x,
  46996. y: rect.y,
  46997. width: rect.width,
  46998. height: rect.height
  46999. },
  47000. api: {
  47001. coord: bind(coordSys.dataToPoint, coordSys),
  47002. size: bind(dataToCoordSize, coordSys)
  47003. }
  47004. };
  47005. };
  47006. function dataToCoordSize$1(dataSize, dataItem) {
  47007. dataItem = dataItem || [0, 0];
  47008. return map([0, 1], function (dimIdx) {
  47009. var val = dataItem[dimIdx];
  47010. var halfSize = dataSize[dimIdx] / 2;
  47011. var p1 = [];
  47012. var p2 = [];
  47013. p1[dimIdx] = val - halfSize;
  47014. p2[dimIdx] = val + halfSize;
  47015. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  47016. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  47017. }, this);
  47018. }
  47019. var prepareGeo = function (coordSys) {
  47020. var rect = coordSys.getBoundingRect();
  47021. return {
  47022. coordSys: {
  47023. type: 'geo',
  47024. x: rect.x,
  47025. y: rect.y,
  47026. width: rect.width,
  47027. height: rect.height
  47028. },
  47029. api: {
  47030. coord: bind(coordSys.dataToPoint, coordSys),
  47031. size: bind(dataToCoordSize$1, coordSys)
  47032. }
  47033. };
  47034. };
  47035. function dataToCoordSize$2(dataSize, dataItem) {
  47036. // dataItem is necessary in log axis.
  47037. var axis = this.getAxis();
  47038. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  47039. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  47040. return axis.type === 'category'
  47041. ? axis.getBandWidth()
  47042. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  47043. }
  47044. var prepareSingleAxis = function (coordSys) {
  47045. var rect = coordSys.getRect();
  47046. return {
  47047. coordSys: {
  47048. type: 'singleAxis',
  47049. x: rect.x,
  47050. y: rect.y,
  47051. width: rect.width,
  47052. height: rect.height
  47053. },
  47054. api: {
  47055. coord: bind(coordSys.dataToPoint, coordSys),
  47056. size: bind(dataToCoordSize$2, coordSys)
  47057. }
  47058. };
  47059. };
  47060. function dataToCoordSize$3(dataSize, dataItem) {
  47061. // dataItem is necessary in log axis.
  47062. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  47063. var axis = this['get' + dim + 'Axis']();
  47064. var val = dataItem[dimIdx];
  47065. var halfSize = dataSize[dimIdx] / 2;
  47066. var method = 'dataTo' + dim;
  47067. var result = axis.type === 'category'
  47068. ? axis.getBandWidth()
  47069. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  47070. if (dim === 'Angle') {
  47071. result = result * Math.PI / 180;
  47072. }
  47073. return result;
  47074. }, this);
  47075. }
  47076. var preparePolar = function (coordSys) {
  47077. var radiusAxis = coordSys.getRadiusAxis();
  47078. var angleAxis = coordSys.getAngleAxis();
  47079. var radius = radiusAxis.getExtent();
  47080. radius[0] > radius[1] && radius.reverse();
  47081. return {
  47082. coordSys: {
  47083. type: 'polar',
  47084. cx: coordSys.cx,
  47085. cy: coordSys.cy,
  47086. r: radius[1],
  47087. r0: radius[0]
  47088. },
  47089. api: {
  47090. coord: bind(function (data) {
  47091. var radius = radiusAxis.dataToRadius(data[0]);
  47092. var angle = angleAxis.dataToAngle(data[1]);
  47093. var coord = coordSys.coordToPoint([radius, angle]);
  47094. coord.push(radius, angle * Math.PI / 180);
  47095. return coord;
  47096. }),
  47097. size: bind(dataToCoordSize$3, coordSys)
  47098. }
  47099. };
  47100. };
  47101. var prepareCalendar = function (coordSys) {
  47102. var rect = coordSys.getRect();
  47103. var rangeInfo = coordSys.getRangeInfo();
  47104. return {
  47105. coordSys: {
  47106. type: 'calendar',
  47107. x: rect.x,
  47108. y: rect.y,
  47109. width: rect.width,
  47110. height: rect.height,
  47111. cellWidth: coordSys.getCellWidth(),
  47112. cellHeight: coordSys.getCellHeight(),
  47113. rangeInfo: {
  47114. start: rangeInfo.start,
  47115. end: rangeInfo.end,
  47116. weeks: rangeInfo.weeks,
  47117. dayCount: rangeInfo.allDay
  47118. }
  47119. },
  47120. api: {
  47121. coord: bind(coordSys.dataToPoint, coordSys)
  47122. }
  47123. };
  47124. };
  47125. var ITEM_STYLE_NORMAL_PATH = ['itemStyle', 'normal'];
  47126. var ITEM_STYLE_EMPHASIS_PATH = ['itemStyle', 'emphasis'];
  47127. var LABEL_NORMAL = ['label', 'normal'];
  47128. var LABEL_EMPHASIS = ['label', 'emphasis'];
  47129. // Use prefix to avoid index to be the same as el.name,
  47130. // which will cause weird udpate animation.
  47131. var GROUP_DIFF_PREFIX = 'e\0\0';
  47132. /**
  47133. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  47134. * of each coordinate systems are not required by each coordinate systems directly, but
  47135. * required by the module `custom`.
  47136. *
  47137. * prepareInfoForCustomSeries {Function}: optional
  47138. * @return {Object} {coordSys: {...}, api: {
  47139. * coord: function (data, clamp) {}, // return point in global.
  47140. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  47141. * }}
  47142. */
  47143. var prepareCustoms = {
  47144. cartesian2d: prepareCartesian2d,
  47145. geo: prepareGeo,
  47146. singleAxis: prepareSingleAxis,
  47147. polar: preparePolar,
  47148. calendar: prepareCalendar
  47149. };
  47150. // ------
  47151. // Model
  47152. // ------
  47153. extendSeriesModel({
  47154. type: 'series.custom',
  47155. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  47156. defaultOption: {
  47157. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  47158. zlevel: 0,
  47159. z: 2,
  47160. legendHoverLink: true
  47161. // Cartesian coordinate system
  47162. // xAxisIndex: 0,
  47163. // yAxisIndex: 0,
  47164. // Polar coordinate system
  47165. // polarIndex: 0,
  47166. // Geo coordinate system
  47167. // geoIndex: 0,
  47168. // label: {}
  47169. // itemStyle: {}
  47170. },
  47171. getInitialData: function (option, ecModel) {
  47172. return createListFromArray(option.data, this, ecModel);
  47173. }
  47174. });
  47175. // -----
  47176. // View
  47177. // -----
  47178. extendChartView({
  47179. type: 'custom',
  47180. /**
  47181. * @private
  47182. * @type {module:echarts/data/List}
  47183. */
  47184. _data: null,
  47185. /**
  47186. * @override
  47187. */
  47188. render: function (customSeries, ecModel, api) {
  47189. var oldData = this._data;
  47190. var data = customSeries.getData();
  47191. var group = this.group;
  47192. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  47193. data.diff(oldData)
  47194. .add(function (newIdx) {
  47195. data.hasValue(newIdx) && createOrUpdate$1(
  47196. null, newIdx, renderItem(newIdx), customSeries, group, data
  47197. );
  47198. })
  47199. .update(function (newIdx, oldIdx) {
  47200. var el = oldData.getItemGraphicEl(oldIdx);
  47201. data.hasValue(newIdx)
  47202. ? createOrUpdate$1(
  47203. el, newIdx, renderItem(newIdx), customSeries, group, data
  47204. )
  47205. : (el && group.remove(el));
  47206. })
  47207. .remove(function (oldIdx) {
  47208. var el = oldData.getItemGraphicEl(oldIdx);
  47209. el && group.remove(el);
  47210. })
  47211. .execute();
  47212. this._data = data;
  47213. },
  47214. /**
  47215. * @override
  47216. */
  47217. dispose: noop
  47218. });
  47219. function createEl(elOption) {
  47220. var graphicType = elOption.type;
  47221. var el;
  47222. if (graphicType === 'path') {
  47223. var shape = elOption.shape;
  47224. el = makePath(
  47225. shape.pathData,
  47226. null,
  47227. {
  47228. x: shape.x || 0,
  47229. y: shape.y || 0,
  47230. width: shape.width || 0,
  47231. height: shape.height || 0
  47232. },
  47233. 'center'
  47234. );
  47235. el.__customPathData = elOption.pathData;
  47236. }
  47237. else if (graphicType === 'image') {
  47238. el = new ZImage({
  47239. });
  47240. el.__customImagePath = elOption.style.image;
  47241. }
  47242. else if (graphicType === 'text') {
  47243. el = new Text({
  47244. });
  47245. el.__customText = elOption.style.text;
  47246. }
  47247. else {
  47248. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  47249. if (__DEV__) {
  47250. assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
  47251. }
  47252. el = new Clz();
  47253. }
  47254. el.__customGraphicType = graphicType;
  47255. el.name = elOption.name;
  47256. return el;
  47257. }
  47258. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  47259. var targetProps = {};
  47260. var elOptionStyle = elOption.style || {};
  47261. elOption.shape && (targetProps.shape = clone(elOption.shape));
  47262. elOption.position && (targetProps.position = elOption.position.slice());
  47263. elOption.scale && (targetProps.scale = elOption.scale.slice());
  47264. elOption.origin && (targetProps.origin = elOption.origin.slice());
  47265. elOption.rotation && (targetProps.rotation = elOption.rotation);
  47266. if (el.type === 'image' && elOption.style) {
  47267. var targetStyle = targetProps.style = {};
  47268. each$1(['x', 'y', 'width', 'height'], function (prop) {
  47269. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  47270. });
  47271. }
  47272. if (el.type === 'text' && elOption.style) {
  47273. var targetStyle = targetProps.style = {};
  47274. each$1(['x', 'y'], function (prop) {
  47275. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  47276. });
  47277. // Compatible with previous: both support
  47278. // textFill and fill, textStroke and stroke in 'text' element.
  47279. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  47280. elOptionStyle.textFill = elOptionStyle.fill
  47281. );
  47282. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  47283. elOptionStyle.textStroke = elOptionStyle.stroke
  47284. );
  47285. }
  47286. if (el.type !== 'group') {
  47287. el.useStyle(elOptionStyle);
  47288. // Init animation.
  47289. if (isInit) {
  47290. el.style.opacity = 0;
  47291. var targetOpacity = elOptionStyle.opacity;
  47292. targetOpacity == null && (targetOpacity = 1);
  47293. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  47294. }
  47295. }
  47296. if (isInit) {
  47297. el.attr(targetProps);
  47298. }
  47299. else {
  47300. updateProps(el, targetProps, animatableModel, dataIndex);
  47301. }
  47302. // z2 must not be null/undefined, otherwise sort error may occur.
  47303. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  47304. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  47305. }
  47306. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  47307. if (elOptionStyle[prop] != null && !isInit) {
  47308. targetStyle[prop] = elOptionStyle[prop];
  47309. elOptionStyle[prop] = oldElStyle[prop];
  47310. }
  47311. }
  47312. function makeRenderItem(customSeries, data, ecModel, api) {
  47313. var renderItem = customSeries.get('renderItem');
  47314. var coordSys = customSeries.coordinateSystem;
  47315. var prepareResult = {};
  47316. if (coordSys) {
  47317. if (__DEV__) {
  47318. assert(renderItem, 'series.render is required.');
  47319. assert(
  47320. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  47321. 'This coordSys does not support custom series.'
  47322. );
  47323. }
  47324. prepareResult = coordSys.prepareCustoms
  47325. ? coordSys.prepareCustoms()
  47326. : prepareCustoms[coordSys.type](coordSys);
  47327. }
  47328. var userAPI = defaults({
  47329. getWidth: api.getWidth,
  47330. getHeight: api.getHeight,
  47331. getZr: api.getZr,
  47332. getDevicePixelRatio: api.getDevicePixelRatio,
  47333. value: value,
  47334. style: style,
  47335. styleEmphasis: styleEmphasis,
  47336. visual: visual,
  47337. barLayout: barLayout,
  47338. currentSeriesIndices: currentSeriesIndices,
  47339. font: font
  47340. }, prepareResult.api || {});
  47341. var userParams = {
  47342. context: {},
  47343. seriesId: customSeries.id,
  47344. seriesName: customSeries.name,
  47345. seriesIndex: customSeries.seriesIndex,
  47346. coordSys: prepareResult.coordSys,
  47347. dataInsideLength: data.count(),
  47348. encode: wrapEncodeDef(customSeries.getData())
  47349. };
  47350. // Do not support call `api` asynchronously without dataIndexInside input.
  47351. var currDataIndexInside;
  47352. var currDirty = true;
  47353. var currItemModel;
  47354. var currLabelNormalModel;
  47355. var currLabelEmphasisModel;
  47356. var currLabelValueDim;
  47357. var currVisualColor;
  47358. return function (dataIndexInside) {
  47359. currDataIndexInside = dataIndexInside;
  47360. currDirty = true;
  47361. return renderItem && renderItem(
  47362. defaults({
  47363. dataIndexInside: dataIndexInside,
  47364. dataIndex: data.getRawIndex(dataIndexInside)
  47365. }, userParams),
  47366. userAPI
  47367. ) || {};
  47368. };
  47369. // Do not update cache until api called.
  47370. function updateCache(dataIndexInside) {
  47371. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47372. if (currDirty) {
  47373. currItemModel = data.getItemModel(dataIndexInside);
  47374. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  47375. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  47376. currLabelValueDim = findLabelValueDim(data);
  47377. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  47378. currDirty = false;
  47379. }
  47380. }
  47381. /**
  47382. * @public
  47383. * @param {number|string} dim
  47384. * @param {number} [dataIndexInside=currDataIndexInside]
  47385. * @return {number|string} value
  47386. */
  47387. function value(dim, dataIndexInside) {
  47388. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47389. return data.get(data.getDimension(dim || 0), dataIndexInside);
  47390. }
  47391. /**
  47392. * By default, `visual` is applied to style (to support visualMap).
  47393. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  47394. * it can be implemented as:
  47395. * `api.style({stroke: api.visual('color'), fill: null})`;
  47396. * @public
  47397. * @param {Object} [extra]
  47398. * @param {number} [dataIndexInside=currDataIndexInside]
  47399. */
  47400. function style(extra, dataIndexInside) {
  47401. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47402. updateCache(dataIndexInside);
  47403. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  47404. currVisualColor != null && (itemStyle.fill = currVisualColor);
  47405. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  47406. opacity != null && (itemStyle.opacity = opacity);
  47407. if (currLabelValueDim != null) {
  47408. setTextStyle(itemStyle, currLabelNormalModel, null, {
  47409. autoColor: currVisualColor,
  47410. isRectText: true
  47411. });
  47412. itemStyle.text = currLabelNormalModel.getShallow('show')
  47413. ? retrieve2(
  47414. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  47415. data.get(currLabelValueDim, dataIndexInside)
  47416. )
  47417. : null;
  47418. }
  47419. extra && extend(itemStyle, extra);
  47420. return itemStyle;
  47421. }
  47422. /**
  47423. * @public
  47424. * @param {Object} [extra]
  47425. * @param {number} [dataIndexInside=currDataIndexInside]
  47426. */
  47427. function styleEmphasis(extra, dataIndexInside) {
  47428. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47429. updateCache(dataIndexInside);
  47430. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  47431. if (currLabelValueDim != null) {
  47432. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  47433. isRectText: true
  47434. }, true);
  47435. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  47436. ? retrieve3(
  47437. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  47438. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  47439. data.get(currLabelValueDim, dataIndexInside)
  47440. )
  47441. : null;
  47442. }
  47443. extra && extend(itemStyle, extra);
  47444. return itemStyle;
  47445. }
  47446. /**
  47447. * @public
  47448. * @param {string} visualType
  47449. * @param {number} [dataIndexInside=currDataIndexInside]
  47450. */
  47451. function visual(visualType, dataIndexInside) {
  47452. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  47453. return data.getItemVisual(dataIndexInside, visualType);
  47454. }
  47455. /**
  47456. * @public
  47457. * @param {number} opt.count Positive interger.
  47458. * @param {number} [opt.barWidth]
  47459. * @param {number} [opt.barMaxWidth]
  47460. * @param {number} [opt.barGap]
  47461. * @param {number} [opt.barCategoryGap]
  47462. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  47463. */
  47464. function barLayout(opt) {
  47465. if (coordSys.getBaseAxis) {
  47466. var baseAxis = coordSys.getBaseAxis();
  47467. return barLayoutGrid.getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  47468. }
  47469. }
  47470. /**
  47471. * @public
  47472. * @return {Array.<number>}
  47473. */
  47474. function currentSeriesIndices() {
  47475. return ecModel.getCurrentSeriesIndices();
  47476. }
  47477. /**
  47478. * @public
  47479. * @param {Object} opt
  47480. * @param {string} [opt.fontStyle]
  47481. * @param {number} [opt.fontWeight]
  47482. * @param {number} [opt.fontSize]
  47483. * @param {string} [opt.fontFamily]
  47484. * @return {string} font string
  47485. */
  47486. function font(opt) {
  47487. return getFont(opt, ecModel);
  47488. }
  47489. }
  47490. function wrapEncodeDef(data) {
  47491. var encodeDef = {};
  47492. each$1(data.dimensions, function (dimName, dataDimIndex) {
  47493. var dimInfo = data.getDimensionInfo(dimName);
  47494. if (!dimInfo.isExtraCoord) {
  47495. var coordDim = dimInfo.coordDim;
  47496. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  47497. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  47498. }
  47499. });
  47500. return encodeDef;
  47501. }
  47502. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  47503. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  47504. el && data.setItemGraphicEl(dataIndex, el);
  47505. }
  47506. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  47507. var elOptionType = elOption.type;
  47508. if (el
  47509. && elOptionType !== el.__customGraphicType
  47510. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  47511. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  47512. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  47513. ) {
  47514. group.remove(el);
  47515. el = null;
  47516. }
  47517. // `elOption.type` is undefined when `renderItem` returns nothing.
  47518. if (elOptionType == null) {
  47519. return;
  47520. }
  47521. var isInit = !el;
  47522. !el && (el = createEl(elOption));
  47523. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  47524. if (elOptionType === 'group') {
  47525. var oldChildren = el.children() || [];
  47526. var newChildren = elOption.children || [];
  47527. if (elOption.diffChildrenByName) {
  47528. // lower performance.
  47529. diffGroupChildren({
  47530. oldChildren: oldChildren,
  47531. newChildren: newChildren,
  47532. dataIndex: dataIndex,
  47533. animatableModel: animatableModel,
  47534. group: el,
  47535. data: data
  47536. });
  47537. }
  47538. else {
  47539. // better performance.
  47540. var index = 0;
  47541. for (; index < newChildren.length; index++) {
  47542. doCreateOrUpdate(
  47543. el.childAt(index),
  47544. dataIndex,
  47545. newChildren[index],
  47546. animatableModel,
  47547. el,
  47548. data
  47549. );
  47550. }
  47551. for (; index < oldChildren.length; index++) {
  47552. oldChildren[index] && el.remove(oldChildren[index]);
  47553. }
  47554. }
  47555. }
  47556. group.add(el);
  47557. return el;
  47558. }
  47559. function diffGroupChildren(context) {
  47560. (new DataDiffer(
  47561. context.oldChildren,
  47562. context.newChildren,
  47563. getKey,
  47564. getKey,
  47565. context
  47566. ))
  47567. .add(processAddUpdate)
  47568. .update(processAddUpdate)
  47569. .remove(processRemove)
  47570. .execute();
  47571. }
  47572. function getKey(item, idx) {
  47573. var name = item && item.name;
  47574. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  47575. }
  47576. function processAddUpdate(newIndex, oldIndex) {
  47577. var context = this.context;
  47578. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  47579. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  47580. doCreateOrUpdate(
  47581. child,
  47582. context.dataIndex,
  47583. childOption,
  47584. context.animatableModel,
  47585. context.group,
  47586. context.data
  47587. );
  47588. }
  47589. function processRemove(oldIndex) {
  47590. var context = this.context;
  47591. var child = context.oldChildren[oldIndex];
  47592. child && context.group.remove(child);
  47593. }
  47594. // -------------
  47595. // Preprocessor
  47596. // -------------
  47597. registerPreprocessor(function (option) {
  47598. var graphicOption = option.graphic;
  47599. // Convert
  47600. // {graphic: [{left: 10, type: 'circle'}, ...]}
  47601. // or
  47602. // {graphic: {left: 10, type: 'circle'}}
  47603. // to
  47604. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  47605. if (isArray(graphicOption)) {
  47606. if (!graphicOption[0] || !graphicOption[0].elements) {
  47607. option.graphic = [{elements: graphicOption}];
  47608. }
  47609. else {
  47610. // Only one graphic instance can be instantiated. (We dont
  47611. // want that too many views are created in echarts._viewMap)
  47612. option.graphic = [option.graphic[0]];
  47613. }
  47614. }
  47615. else if (graphicOption && !graphicOption.elements) {
  47616. option.graphic = [{elements: [graphicOption]}];
  47617. }
  47618. });
  47619. // ------
  47620. // Model
  47621. // ------
  47622. var GraphicModel = extendComponentModel({
  47623. type: 'graphic',
  47624. defaultOption: {
  47625. // Extra properties for each elements:
  47626. //
  47627. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  47628. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  47629. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  47630. // This mechanism is useful when you want to position a group/element
  47631. // against the right side or the center of this container.
  47632. //
  47633. // width/height: (can only be pixel value, default 0)
  47634. // Only be used to specify contianer(group) size, if needed. And
  47635. // can not be percentage value (like '33%'). See the reason in the
  47636. // layout algorithm below.
  47637. //
  47638. // bounding: (enum: 'all' (default) | 'raw')
  47639. // Specify how to calculate boundingRect when locating.
  47640. // 'all': Get uioned and transformed boundingRect
  47641. // from both itself and its descendants.
  47642. // This mode simplies confining a group of elements in the bounding
  47643. // of their ancester container (e.g., using 'right: 0').
  47644. // 'raw': Only use the boundingRect of itself and before transformed.
  47645. // This mode is similar to css behavior, which is useful when you
  47646. // want an element to be able to overflow its container. (Consider
  47647. // a rotated circle needs to be located in a corner.)
  47648. // Note: elements is always behind its ancestors in this elements array.
  47649. elements: [],
  47650. parentId: null
  47651. },
  47652. /**
  47653. * Save el options for the sake of the performance (only update modified graphics).
  47654. * The order is the same as those in option. (ancesters -> descendants)
  47655. *
  47656. * @private
  47657. * @type {Array.<Object>}
  47658. */
  47659. _elOptionsToUpdate: null,
  47660. /**
  47661. * @override
  47662. */
  47663. mergeOption: function (option) {
  47664. // Prevent default merge to elements
  47665. var elements = this.option.elements;
  47666. this.option.elements = null;
  47667. GraphicModel.superApply(this, 'mergeOption', arguments);
  47668. this.option.elements = elements;
  47669. },
  47670. /**
  47671. * @override
  47672. */
  47673. optionUpdated: function (newOption, isInit) {
  47674. var thisOption = this.option;
  47675. var newList = (isInit ? thisOption : newOption).elements;
  47676. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  47677. var flattenedList = [];
  47678. this._flatten(newList, flattenedList);
  47679. var mappingResult = mappingToExists(existList, flattenedList);
  47680. makeIdAndName(mappingResult);
  47681. // Clear elOptionsToUpdate
  47682. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  47683. each$1(mappingResult, function (resultItem, index) {
  47684. var newElOption = resultItem.option;
  47685. if (__DEV__) {
  47686. assert(
  47687. isObject(newElOption) || resultItem.exist,
  47688. 'Empty graphic option definition'
  47689. );
  47690. }
  47691. if (!newElOption) {
  47692. return;
  47693. }
  47694. elOptionsToUpdate.push(newElOption);
  47695. setKeyInfoToNewElOption(resultItem, newElOption);
  47696. mergeNewElOptionToExist(existList, index, newElOption);
  47697. setLayoutInfoToExist(existList[index], newElOption);
  47698. }, this);
  47699. // Clean
  47700. for (var i = existList.length - 1; i >= 0; i--) {
  47701. if (existList[i] == null) {
  47702. existList.splice(i, 1);
  47703. }
  47704. else {
  47705. // $action should be volatile, otherwise option gotten from
  47706. // `getOption` will contain unexpected $action.
  47707. delete existList[i].$action;
  47708. }
  47709. }
  47710. },
  47711. /**
  47712. * Convert
  47713. * [{
  47714. * type: 'group',
  47715. * id: 'xx',
  47716. * children: [{type: 'circle'}, {type: 'polygon'}]
  47717. * }]
  47718. * to
  47719. * [
  47720. * {type: 'group', id: 'xx'},
  47721. * {type: 'circle', parentId: 'xx'},
  47722. * {type: 'polygon', parentId: 'xx'}
  47723. * ]
  47724. *
  47725. * @private
  47726. * @param {Array.<Object>} optionList option list
  47727. * @param {Array.<Object>} result result of flatten
  47728. * @param {Object} parentOption parent option
  47729. */
  47730. _flatten: function (optionList, result, parentOption) {
  47731. each$1(optionList, function (option) {
  47732. if (!option) {
  47733. return;
  47734. }
  47735. if (parentOption) {
  47736. option.parentOption = parentOption;
  47737. }
  47738. result.push(option);
  47739. var children = option.children;
  47740. if (option.type === 'group' && children) {
  47741. this._flatten(children, result, option);
  47742. }
  47743. // Deleting for JSON output, and for not affecting group creation.
  47744. delete option.children;
  47745. }, this);
  47746. },
  47747. // FIXME
  47748. // Pass to view using payload? setOption has a payload?
  47749. useElOptionsToUpdate: function () {
  47750. var els = this._elOptionsToUpdate;
  47751. // Clear to avoid render duplicately when zooming.
  47752. this._elOptionsToUpdate = null;
  47753. return els;
  47754. }
  47755. });
  47756. // -----
  47757. // View
  47758. // -----
  47759. extendComponentView({
  47760. type: 'graphic',
  47761. /**
  47762. * @override
  47763. */
  47764. init: function (ecModel, api) {
  47765. /**
  47766. * @private
  47767. * @type {module:zrender/core/util.HashMap}
  47768. */
  47769. this._elMap = createHashMap();
  47770. /**
  47771. * @private
  47772. * @type {module:echarts/graphic/GraphicModel}
  47773. */
  47774. this._lastGraphicModel;
  47775. },
  47776. /**
  47777. * @override
  47778. */
  47779. render: function (graphicModel, ecModel, api) {
  47780. // Having leveraged between use cases and algorithm complexity, a very
  47781. // simple layout mechanism is used:
  47782. // The size(width/height) can be determined by itself or its parent (not
  47783. // implemented yet), but can not by its children. (Top-down travel)
  47784. // The location(x/y) can be determined by the bounding rect of itself
  47785. // (can including its descendants or not) and the size of its parent.
  47786. // (Bottom-up travel)
  47787. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  47788. // view will be reused.
  47789. if (graphicModel !== this._lastGraphicModel) {
  47790. this._clear();
  47791. }
  47792. this._lastGraphicModel = graphicModel;
  47793. this._updateElements(graphicModel, api);
  47794. this._relocate(graphicModel, api);
  47795. },
  47796. /**
  47797. * Update graphic elements.
  47798. *
  47799. * @private
  47800. * @param {Object} graphicModel graphic model
  47801. * @param {module:echarts/ExtensionAPI} api extension API
  47802. */
  47803. _updateElements: function (graphicModel, api) {
  47804. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  47805. if (!elOptionsToUpdate) {
  47806. return;
  47807. }
  47808. var elMap = this._elMap;
  47809. var rootGroup = this.group;
  47810. // Top-down tranverse to assign graphic settings to each elements.
  47811. each$1(elOptionsToUpdate, function (elOption) {
  47812. var $action = elOption.$action;
  47813. var id = elOption.id;
  47814. var existEl = elMap.get(id);
  47815. var parentId = elOption.parentId;
  47816. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  47817. if (elOption.type === 'text') {
  47818. var elOptionStyle = elOption.style;
  47819. // In top/bottom mode, textVerticalAlign should not be used, which cause
  47820. // inaccurately locating.
  47821. if (elOption.hv && elOption.hv[1]) {
  47822. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  47823. }
  47824. // Compatible with previous setting: both support fill and textFill,
  47825. // stroke and textStroke.
  47826. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  47827. elOptionStyle.textFill = elOptionStyle.fill
  47828. );
  47829. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  47830. elOptionStyle.textStroke = elOptionStyle.stroke
  47831. );
  47832. }
  47833. // Remove unnecessary props to avoid potential problems.
  47834. var elOptionCleaned = getCleanedElOption(elOption);
  47835. // For simple, do not support parent change, otherwise reorder is needed.
  47836. if (__DEV__) {
  47837. existEl && assert(
  47838. targetElParent === existEl.parent,
  47839. 'Changing parent is not supported.'
  47840. );
  47841. }
  47842. if (!$action || $action === 'merge') {
  47843. existEl
  47844. ? existEl.attr(elOptionCleaned)
  47845. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  47846. }
  47847. else if ($action === 'replace') {
  47848. removeEl(existEl, elMap);
  47849. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  47850. }
  47851. else if ($action === 'remove') {
  47852. removeEl(existEl, elMap);
  47853. }
  47854. var el = elMap.get(id);
  47855. if (el) {
  47856. el.__ecGraphicWidth = elOption.width;
  47857. el.__ecGraphicHeight = elOption.height;
  47858. }
  47859. });
  47860. },
  47861. /**
  47862. * Locate graphic elements.
  47863. *
  47864. * @private
  47865. * @param {Object} graphicModel graphic model
  47866. * @param {module:echarts/ExtensionAPI} api extension API
  47867. */
  47868. _relocate: function (graphicModel, api) {
  47869. var elOptions = graphicModel.option.elements;
  47870. var rootGroup = this.group;
  47871. var elMap = this._elMap;
  47872. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  47873. for (var i = elOptions.length - 1; i >= 0; i--) {
  47874. var elOption = elOptions[i];
  47875. var el = elMap.get(elOption.id);
  47876. if (!el) {
  47877. continue;
  47878. }
  47879. var parentEl = el.parent;
  47880. var containerInfo = parentEl === rootGroup
  47881. ? {
  47882. width: api.getWidth(),
  47883. height: api.getHeight()
  47884. }
  47885. : { // Like 'position:absolut' in css, default 0.
  47886. width: parentEl.__ecGraphicWidth || 0,
  47887. height: parentEl.__ecGraphicHeight || 0
  47888. };
  47889. positionElement(
  47890. el, elOption, containerInfo, null,
  47891. {hv: elOption.hv, boundingMode: elOption.bounding}
  47892. );
  47893. }
  47894. },
  47895. /**
  47896. * Clear all elements.
  47897. *
  47898. * @private
  47899. */
  47900. _clear: function () {
  47901. var elMap = this._elMap;
  47902. elMap.each(function (el) {
  47903. removeEl(el, elMap);
  47904. });
  47905. this._elMap = createHashMap();
  47906. },
  47907. /**
  47908. * @override
  47909. */
  47910. dispose: function () {
  47911. this._clear();
  47912. }
  47913. });
  47914. function createEl$1(id, targetElParent, elOption, elMap) {
  47915. var graphicType = elOption.type;
  47916. if (__DEV__) {
  47917. assert(graphicType, 'graphic type MUST be set');
  47918. }
  47919. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  47920. if (__DEV__) {
  47921. assert(Clz, 'graphic type can not be found');
  47922. }
  47923. var el = new Clz(elOption);
  47924. targetElParent.add(el);
  47925. elMap.set(id, el);
  47926. el.__ecGraphicId = id;
  47927. }
  47928. function removeEl(existEl, elMap) {
  47929. var existElParent = existEl && existEl.parent;
  47930. if (existElParent) {
  47931. existEl.type === 'group' && existEl.traverse(function (el) {
  47932. removeEl(el, elMap);
  47933. });
  47934. elMap.removeKey(existEl.__ecGraphicId);
  47935. existElParent.remove(existEl);
  47936. }
  47937. }
  47938. // Remove unnecessary props to avoid potential problems.
  47939. function getCleanedElOption(elOption) {
  47940. elOption = extend({}, elOption);
  47941. each$1(
  47942. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  47943. function (name) {
  47944. delete elOption[name];
  47945. }
  47946. );
  47947. return elOption;
  47948. }
  47949. function isSetLoc(obj, props) {
  47950. var isSet;
  47951. each$1(props, function (prop) {
  47952. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  47953. });
  47954. return isSet;
  47955. }
  47956. function setKeyInfoToNewElOption(resultItem, newElOption) {
  47957. var existElOption = resultItem.exist;
  47958. // Set id and type after id assigned.
  47959. newElOption.id = resultItem.keyInfo.id;
  47960. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  47961. // Set parent id if not specified
  47962. if (newElOption.parentId == null) {
  47963. var newElParentOption = newElOption.parentOption;
  47964. if (newElParentOption) {
  47965. newElOption.parentId = newElParentOption.id;
  47966. }
  47967. else if (existElOption) {
  47968. newElOption.parentId = existElOption.parentId;
  47969. }
  47970. }
  47971. // Clear
  47972. newElOption.parentOption = null;
  47973. }
  47974. function mergeNewElOptionToExist(existList, index, newElOption) {
  47975. // Update existing options, for `getOption` feature.
  47976. var newElOptCopy = extend({}, newElOption);
  47977. var existElOption = existList[index];
  47978. var $action = newElOption.$action || 'merge';
  47979. if ($action === 'merge') {
  47980. if (existElOption) {
  47981. if (__DEV__) {
  47982. var newType = newElOption.type;
  47983. assert(
  47984. !newType || existElOption.type === newType,
  47985. 'Please set $action: "replace" to change `type`'
  47986. );
  47987. }
  47988. // We can ensure that newElOptCopy and existElOption are not
  47989. // the same object, so `merge` will not change newElOptCopy.
  47990. merge(existElOption, newElOptCopy, true);
  47991. // Rigid body, use ignoreSize.
  47992. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  47993. // Will be used in render.
  47994. copyLayoutParams(newElOption, existElOption);
  47995. }
  47996. else {
  47997. existList[index] = newElOptCopy;
  47998. }
  47999. }
  48000. else if ($action === 'replace') {
  48001. existList[index] = newElOptCopy;
  48002. }
  48003. else if ($action === 'remove') {
  48004. // null will be cleaned later.
  48005. existElOption && (existList[index] = null);
  48006. }
  48007. }
  48008. function setLayoutInfoToExist(existItem, newElOption) {
  48009. if (!existItem) {
  48010. return;
  48011. }
  48012. existItem.hv = newElOption.hv = [
  48013. // Rigid body, dont care `width`.
  48014. isSetLoc(newElOption, ['left', 'right']),
  48015. // Rigid body, dont care `height`.
  48016. isSetLoc(newElOption, ['top', 'bottom'])
  48017. ];
  48018. // Give default group size. Otherwise layout error may occur.
  48019. if (existItem.type === 'group') {
  48020. existItem.width == null && (existItem.width = newElOption.width = 0);
  48021. existItem.height == null && (existItem.height = newElOption.height = 0);
  48022. }
  48023. }
  48024. var LegendModel = extendComponentModel({
  48025. type: 'legend.plain',
  48026. dependencies: ['series'],
  48027. layoutMode: {
  48028. type: 'box',
  48029. // legend.width/height are maxWidth/maxHeight actually,
  48030. // whereas realy width/height is calculated by its content.
  48031. // (Setting {left: 10, right: 10} does not make sense).
  48032. // So consider the case:
  48033. // `setOption({legend: {left: 10});`
  48034. // then `setOption({legend: {right: 10});`
  48035. // The previous `left` should be cleared by setting `ignoreSize`.
  48036. ignoreSize: true
  48037. },
  48038. init: function (option, parentModel, ecModel) {
  48039. this.mergeDefaultAndTheme(option, ecModel);
  48040. option.selected = option.selected || {};
  48041. },
  48042. mergeOption: function (option) {
  48043. LegendModel.superCall(this, 'mergeOption', option);
  48044. },
  48045. optionUpdated: function () {
  48046. this._updateData(this.ecModel);
  48047. var legendData = this._data;
  48048. // If selectedMode is single, try to select one
  48049. if (legendData[0] && this.get('selectedMode') === 'single') {
  48050. var hasSelected = false;
  48051. // If has any selected in option.selected
  48052. for (var i = 0; i < legendData.length; i++) {
  48053. var name = legendData[i].get('name');
  48054. if (this.isSelected(name)) {
  48055. // Force to unselect others
  48056. this.select(name);
  48057. hasSelected = true;
  48058. break;
  48059. }
  48060. }
  48061. // Try select the first if selectedMode is single
  48062. !hasSelected && this.select(legendData[0].get('name'));
  48063. }
  48064. },
  48065. _updateData: function (ecModel) {
  48066. var legendData = map(this.get('data') || [], function (dataItem) {
  48067. // Can be string or number
  48068. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  48069. dataItem = {
  48070. name: dataItem
  48071. };
  48072. }
  48073. return new Model(dataItem, this, this.ecModel);
  48074. }, this);
  48075. this._data = legendData;
  48076. var availableNames = map(ecModel.getSeries(), function (series) {
  48077. return series.name;
  48078. });
  48079. ecModel.eachSeries(function (seriesModel) {
  48080. if (seriesModel.legendDataProvider) {
  48081. var data = seriesModel.legendDataProvider();
  48082. availableNames = availableNames.concat(data.mapArray(data.getName));
  48083. }
  48084. });
  48085. /**
  48086. * @type {Array.<string>}
  48087. * @private
  48088. */
  48089. this._availableNames = availableNames;
  48090. },
  48091. /**
  48092. * @return {Array.<module:echarts/model/Model>}
  48093. */
  48094. getData: function () {
  48095. return this._data;
  48096. },
  48097. /**
  48098. * @param {string} name
  48099. */
  48100. select: function (name) {
  48101. var selected = this.option.selected;
  48102. var selectedMode = this.get('selectedMode');
  48103. if (selectedMode === 'single') {
  48104. var data = this._data;
  48105. each$1(data, function (dataItem) {
  48106. selected[dataItem.get('name')] = false;
  48107. });
  48108. }
  48109. selected[name] = true;
  48110. },
  48111. /**
  48112. * @param {string} name
  48113. */
  48114. unSelect: function (name) {
  48115. if (this.get('selectedMode') !== 'single') {
  48116. this.option.selected[name] = false;
  48117. }
  48118. },
  48119. /**
  48120. * @param {string} name
  48121. */
  48122. toggleSelected: function (name) {
  48123. var selected = this.option.selected;
  48124. // Default is true
  48125. if (!selected.hasOwnProperty(name)) {
  48126. selected[name] = true;
  48127. }
  48128. this[selected[name] ? 'unSelect' : 'select'](name);
  48129. },
  48130. /**
  48131. * @param {string} name
  48132. */
  48133. isSelected: function (name) {
  48134. var selected = this.option.selected;
  48135. return !(selected.hasOwnProperty(name) && !selected[name])
  48136. && indexOf(this._availableNames, name) >= 0;
  48137. },
  48138. defaultOption: {
  48139. // 一级层叠
  48140. zlevel: 0,
  48141. // 二级层叠
  48142. z: 4,
  48143. show: true,
  48144. // 布局方式,默认为水平布局,可选为:
  48145. // 'horizontal' | 'vertical'
  48146. orient: 'horizontal',
  48147. left: 'center',
  48148. // right: 'center',
  48149. top: 0,
  48150. // bottom: null,
  48151. // 水平对齐
  48152. // 'auto' | 'left' | 'right'
  48153. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  48154. align: 'auto',
  48155. backgroundColor: 'rgba(0,0,0,0)',
  48156. // 图例边框颜色
  48157. borderColor: '#ccc',
  48158. borderRadius: 0,
  48159. // 图例边框线宽,单位px,默认为0(无边框)
  48160. borderWidth: 0,
  48161. // 图例内边距,单位px,默认各方向内边距为5,
  48162. // 接受数组分别设定上右下左边距,同css
  48163. padding: 5,
  48164. // 各个item之间的间隔,单位px,默认为10,
  48165. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  48166. itemGap: 10,
  48167. // 图例图形宽度
  48168. itemWidth: 25,
  48169. // 图例图形高度
  48170. itemHeight: 14,
  48171. // 图例关闭时候的颜色
  48172. inactiveColor: '#ccc',
  48173. textStyle: {
  48174. // 图例文字颜色
  48175. color: '#333'
  48176. },
  48177. // formatter: '',
  48178. // 选择模式,默认开启图例开关
  48179. selectedMode: true,
  48180. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  48181. // selected: null,
  48182. // 图例内容(详见legend.data,数组中每一项代表一个item
  48183. // data: [],
  48184. // Tooltip 相关配置
  48185. tooltip: {
  48186. show: false
  48187. }
  48188. }
  48189. });
  48190. function legendSelectActionHandler(methodName, payload, ecModel) {
  48191. var selectedMap = {};
  48192. var isToggleSelect = methodName === 'toggleSelected';
  48193. var isSelected;
  48194. // Update all legend components
  48195. ecModel.eachComponent('legend', function (legendModel) {
  48196. if (isToggleSelect && isSelected != null) {
  48197. // Force other legend has same selected status
  48198. // Or the first is toggled to true and other are toggled to false
  48199. // In the case one legend has some item unSelected in option. And if other legend
  48200. // doesn't has the item, they will assume it is selected.
  48201. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  48202. }
  48203. else {
  48204. legendModel[methodName](payload.name);
  48205. isSelected = legendModel.isSelected(payload.name);
  48206. }
  48207. var legendData = legendModel.getData();
  48208. each$1(legendData, function (model) {
  48209. var name = model.get('name');
  48210. // Wrap element
  48211. if (name === '\n' || name === '') {
  48212. return;
  48213. }
  48214. var isItemSelected = legendModel.isSelected(name);
  48215. if (selectedMap.hasOwnProperty(name)) {
  48216. // Unselected if any legend is unselected
  48217. selectedMap[name] = selectedMap[name] && isItemSelected;
  48218. }
  48219. else {
  48220. selectedMap[name] = isItemSelected;
  48221. }
  48222. });
  48223. });
  48224. // Return the event explicitly
  48225. return {
  48226. name: payload.name,
  48227. selected: selectedMap
  48228. };
  48229. }
  48230. /**
  48231. * @event legendToggleSelect
  48232. * @type {Object}
  48233. * @property {string} type 'legendToggleSelect'
  48234. * @property {string} [from]
  48235. * @property {string} name Series name or data item name
  48236. */
  48237. registerAction(
  48238. 'legendToggleSelect', 'legendselectchanged',
  48239. curry(legendSelectActionHandler, 'toggleSelected')
  48240. );
  48241. /**
  48242. * @event legendSelect
  48243. * @type {Object}
  48244. * @property {string} type 'legendSelect'
  48245. * @property {string} name Series name or data item name
  48246. */
  48247. registerAction(
  48248. 'legendSelect', 'legendselected',
  48249. curry(legendSelectActionHandler, 'select')
  48250. );
  48251. /**
  48252. * @event legendUnSelect
  48253. * @type {Object}
  48254. * @property {string} type 'legendUnSelect'
  48255. * @property {string} name Series name or data item name
  48256. */
  48257. registerAction(
  48258. 'legendUnSelect', 'legendunselected',
  48259. curry(legendSelectActionHandler, 'unSelect')
  48260. );
  48261. /**
  48262. * Layout list like component.
  48263. * It will box layout each items in group of component and then position the whole group in the viewport
  48264. * @param {module:zrender/group/Group} group
  48265. * @param {module:echarts/model/Component} componentModel
  48266. * @param {module:echarts/ExtensionAPI}
  48267. */
  48268. function layout$2(group, componentModel, api) {
  48269. var boxLayoutParams = componentModel.getBoxLayoutParams();
  48270. var padding = componentModel.get('padding');
  48271. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  48272. var rect = getLayoutRect(
  48273. boxLayoutParams,
  48274. viewportSize,
  48275. padding
  48276. );
  48277. box(
  48278. componentModel.get('orient'),
  48279. group,
  48280. componentModel.get('itemGap'),
  48281. rect.width,
  48282. rect.height
  48283. );
  48284. positionElement(
  48285. group,
  48286. boxLayoutParams,
  48287. viewportSize,
  48288. padding
  48289. );
  48290. }
  48291. function makeBackground(rect, componentModel) {
  48292. var padding = normalizeCssArray$1(
  48293. componentModel.get('padding')
  48294. );
  48295. var style = componentModel.getItemStyle(['color', 'opacity']);
  48296. style.fill = componentModel.get('backgroundColor');
  48297. var rect = new Rect({
  48298. shape: {
  48299. x: rect.x - padding[3],
  48300. y: rect.y - padding[0],
  48301. width: rect.width + padding[1] + padding[3],
  48302. height: rect.height + padding[0] + padding[2],
  48303. r: componentModel.get('borderRadius')
  48304. },
  48305. style: style,
  48306. silent: true,
  48307. z2: -1
  48308. });
  48309. // FIXME
  48310. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  48311. // and background rect when setting like `left: 0`, `top: 0`.
  48312. // graphic.subPixelOptimizeRect(rect);
  48313. return rect;
  48314. }
  48315. var curry$4 = curry;
  48316. var each$19 = each$1;
  48317. var Group$3 = Group;
  48318. var LegendView = extendComponentView({
  48319. type: 'legend.plain',
  48320. newlineDisabled: false,
  48321. /**
  48322. * @override
  48323. */
  48324. init: function () {
  48325. /**
  48326. * @private
  48327. * @type {module:zrender/container/Group}
  48328. */
  48329. this.group.add(this._contentGroup = new Group$3());
  48330. /**
  48331. * @private
  48332. * @type {module:zrender/Element}
  48333. */
  48334. this._backgroundEl;
  48335. },
  48336. /**
  48337. * @protected
  48338. */
  48339. getContentGroup: function () {
  48340. return this._contentGroup;
  48341. },
  48342. /**
  48343. * @override
  48344. */
  48345. render: function (legendModel, ecModel, api) {
  48346. this.resetInner();
  48347. if (!legendModel.get('show', true)) {
  48348. return;
  48349. }
  48350. var itemAlign = legendModel.get('align');
  48351. if (!itemAlign || itemAlign === 'auto') {
  48352. itemAlign = (
  48353. legendModel.get('left') === 'right'
  48354. && legendModel.get('orient') === 'vertical'
  48355. ) ? 'right' : 'left';
  48356. }
  48357. this.renderInner(itemAlign, legendModel, ecModel, api);
  48358. // Perform layout.
  48359. var positionInfo = legendModel.getBoxLayoutParams();
  48360. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  48361. var padding = legendModel.get('padding');
  48362. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  48363. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  48364. // Place mainGroup, based on the calculated `mainRect`.
  48365. var layoutRect = getLayoutRect(
  48366. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  48367. viewportSize,
  48368. padding
  48369. );
  48370. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  48371. // Render background after group is layout.
  48372. this.group.add(
  48373. this._backgroundEl = makeBackground(mainRect, legendModel)
  48374. );
  48375. },
  48376. /**
  48377. * @protected
  48378. */
  48379. resetInner: function () {
  48380. this.getContentGroup().removeAll();
  48381. this._backgroundEl && this.group.remove(this._backgroundEl);
  48382. },
  48383. /**
  48384. * @protected
  48385. */
  48386. renderInner: function (itemAlign, legendModel, ecModel, api) {
  48387. var contentGroup = this.getContentGroup();
  48388. var legendDrawnMap = createHashMap();
  48389. var selectMode = legendModel.get('selectedMode');
  48390. each$19(legendModel.getData(), function (itemModel, dataIndex) {
  48391. var name = itemModel.get('name');
  48392. // Use empty string or \n as a newline string
  48393. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  48394. contentGroup.add(new Group$3({
  48395. newline: true
  48396. }));
  48397. return;
  48398. }
  48399. var seriesModel = ecModel.getSeriesByName(name)[0];
  48400. if (legendDrawnMap.get(name)) {
  48401. // Have been drawed
  48402. return;
  48403. }
  48404. // Series legend
  48405. if (seriesModel) {
  48406. var data = seriesModel.getData();
  48407. var color = data.getVisual('color');
  48408. // If color is a callback function
  48409. if (typeof color === 'function') {
  48410. // Use the first data
  48411. color = color(seriesModel.getDataParams(0));
  48412. }
  48413. // Using rect symbol defaultly
  48414. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  48415. var symbolType = data.getVisual('symbol');
  48416. var itemGroup = this._createItem(
  48417. name, dataIndex, itemModel, legendModel,
  48418. legendSymbolType, symbolType,
  48419. itemAlign, color,
  48420. selectMode
  48421. );
  48422. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  48423. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api))
  48424. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api));
  48425. legendDrawnMap.set(name, true);
  48426. }
  48427. else {
  48428. // Data legend of pie, funnel
  48429. ecModel.eachRawSeries(function (seriesModel) {
  48430. // In case multiple series has same data name
  48431. if (legendDrawnMap.get(name)) {
  48432. return;
  48433. }
  48434. if (seriesModel.legendDataProvider) {
  48435. var data = seriesModel.legendDataProvider();
  48436. var idx = data.indexOfName(name);
  48437. if (idx < 0) {
  48438. return;
  48439. }
  48440. var color = data.getItemVisual(idx, 'color');
  48441. var legendSymbolType = 'roundRect';
  48442. var itemGroup = this._createItem(
  48443. name, dataIndex, itemModel, legendModel,
  48444. legendSymbolType, null,
  48445. itemAlign, color,
  48446. selectMode
  48447. );
  48448. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  48449. // FIXME Should not specify the series name
  48450. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api))
  48451. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api));
  48452. legendDrawnMap.set(name, true);
  48453. }
  48454. }, this);
  48455. }
  48456. if (__DEV__) {
  48457. if (!legendDrawnMap.get(name)) {
  48458. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  48459. }
  48460. }
  48461. }, this);
  48462. },
  48463. _createItem: function (
  48464. name, dataIndex, itemModel, legendModel,
  48465. legendSymbolType, symbolType,
  48466. itemAlign, color, selectMode
  48467. ) {
  48468. var itemWidth = legendModel.get('itemWidth');
  48469. var itemHeight = legendModel.get('itemHeight');
  48470. var inactiveColor = legendModel.get('inactiveColor');
  48471. var isSelected = legendModel.isSelected(name);
  48472. var itemGroup = new Group$3();
  48473. var textStyleModel = itemModel.getModel('textStyle');
  48474. var itemIcon = itemModel.get('icon');
  48475. var tooltipModel = itemModel.getModel('tooltip');
  48476. var legendGlobalTooltipModel = tooltipModel.parentModel;
  48477. // Use user given icon first
  48478. legendSymbolType = itemIcon || legendSymbolType;
  48479. itemGroup.add(createSymbol(
  48480. legendSymbolType,
  48481. 0,
  48482. 0,
  48483. itemWidth,
  48484. itemHeight,
  48485. isSelected ? color : inactiveColor,
  48486. true
  48487. ));
  48488. // Compose symbols
  48489. // PENDING
  48490. if (!itemIcon && symbolType
  48491. // At least show one symbol, can't be all none
  48492. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  48493. ) {
  48494. var size = itemHeight * 0.8;
  48495. if (symbolType === 'none') {
  48496. symbolType = 'circle';
  48497. }
  48498. // Put symbol in the center
  48499. itemGroup.add(createSymbol(
  48500. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  48501. isSelected ? color : inactiveColor
  48502. ));
  48503. }
  48504. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  48505. var textAlign = itemAlign;
  48506. var formatter = legendModel.get('formatter');
  48507. var content = name;
  48508. if (typeof formatter === 'string' && formatter) {
  48509. content = formatter.replace('{name}', name != null ? name : '');
  48510. }
  48511. else if (typeof formatter === 'function') {
  48512. content = formatter(name);
  48513. }
  48514. itemGroup.add(new Text({
  48515. style: setTextStyle({}, textStyleModel, {
  48516. text: content,
  48517. x: textX,
  48518. y: itemHeight / 2,
  48519. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  48520. textAlign: textAlign,
  48521. textVerticalAlign: 'middle'
  48522. })
  48523. }));
  48524. // Add a invisible rect to increase the area of mouse hover
  48525. var hitRect = new Rect({
  48526. shape: itemGroup.getBoundingRect(),
  48527. invisible: true,
  48528. tooltip: tooltipModel.get('show') ? extend({
  48529. content: name,
  48530. // Defaul formatter
  48531. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  48532. return name;
  48533. },
  48534. formatterParams: {
  48535. componentType: 'legend',
  48536. legendIndex: legendModel.componentIndex,
  48537. name: name,
  48538. $vars: ['name']
  48539. }
  48540. }, tooltipModel.option) : null
  48541. });
  48542. itemGroup.add(hitRect);
  48543. itemGroup.eachChild(function (child) {
  48544. child.silent = true;
  48545. });
  48546. hitRect.silent = !selectMode;
  48547. this.getContentGroup().add(itemGroup);
  48548. setHoverStyle(itemGroup);
  48549. itemGroup.__legendDataIndex = dataIndex;
  48550. return itemGroup;
  48551. },
  48552. /**
  48553. * @protected
  48554. */
  48555. layoutInner: function (legendModel, itemAlign, maxSize) {
  48556. var contentGroup = this.getContentGroup();
  48557. // Place items in contentGroup.
  48558. box(
  48559. legendModel.get('orient'),
  48560. contentGroup,
  48561. legendModel.get('itemGap'),
  48562. maxSize.width,
  48563. maxSize.height
  48564. );
  48565. var contentRect = contentGroup.getBoundingRect();
  48566. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  48567. return this.group.getBoundingRect();
  48568. }
  48569. });
  48570. function dispatchSelectAction(name, api) {
  48571. api.dispatchAction({
  48572. type: 'legendToggleSelect',
  48573. name: name
  48574. });
  48575. }
  48576. function dispatchHighlightAction(seriesModel, dataName, api) {
  48577. // If element hover will move to a hoverLayer.
  48578. var el = api.getZr().storage.getDisplayList()[0];
  48579. if (!(el && el.useHoverLayer)) {
  48580. seriesModel.get('legendHoverLink') && api.dispatchAction({
  48581. type: 'highlight',
  48582. seriesName: seriesModel.name,
  48583. name: dataName
  48584. });
  48585. }
  48586. }
  48587. function dispatchDownplayAction(seriesModel, dataName, api) {
  48588. // If element hover will move to a hoverLayer.
  48589. var el = api.getZr().storage.getDisplayList()[0];
  48590. if (!(el && el.useHoverLayer)) {
  48591. seriesModel.get('legendHoverLink') && api.dispatchAction({
  48592. type: 'downplay',
  48593. seriesName: seriesModel.name,
  48594. name: dataName
  48595. });
  48596. }
  48597. }
  48598. var legendFilter = function (ecModel) {
  48599. var legendModels = ecModel.findComponents({
  48600. mainType: 'legend'
  48601. });
  48602. if (legendModels && legendModels.length) {
  48603. ecModel.filterSeries(function (series) {
  48604. // If in any legend component the status is not selected.
  48605. // Because in legend series is assumed selected when it is not in the legend data.
  48606. for (var i = 0; i < legendModels.length; i++) {
  48607. if (!legendModels[i].isSelected(series.name)) {
  48608. return false;
  48609. }
  48610. }
  48611. return true;
  48612. });
  48613. }
  48614. };
  48615. // Do not contain scrollable legend, for sake of file size.
  48616. // Series Filter
  48617. registerProcessor(legendFilter);
  48618. ComponentModel.registerSubTypeDefaulter('legend', function () {
  48619. // Default 'plain' when no type specified.
  48620. return 'plain';
  48621. });
  48622. var ScrollableLegendModel = LegendModel.extend({
  48623. type: 'legend.scroll',
  48624. /**
  48625. * @param {number} scrollDataIndex
  48626. */
  48627. setScrollDataIndex: function (scrollDataIndex) {
  48628. this.option.scrollDataIndex = scrollDataIndex;
  48629. },
  48630. defaultOption: {
  48631. scrollDataIndex: 0,
  48632. pageButtonItemGap: 5,
  48633. pageButtonGap: null,
  48634. pageButtonPosition: 'end', // 'start' or 'end'
  48635. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  48636. pageIcons: {
  48637. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  48638. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  48639. },
  48640. pageIconColor: '#2f4554',
  48641. pageIconInactiveColor: '#aaa',
  48642. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  48643. pageTextStyle: {
  48644. color: '#333'
  48645. },
  48646. animationDurationUpdate: 800
  48647. },
  48648. /**
  48649. * @override
  48650. */
  48651. init: function (option, parentModel, ecModel, extraOpt) {
  48652. var inputPositionParams = getLayoutParams(option);
  48653. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  48654. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  48655. },
  48656. /**
  48657. * @override
  48658. */
  48659. mergeOption: function (option, extraOpt) {
  48660. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  48661. mergeAndNormalizeLayoutParams(this, this.option, option);
  48662. },
  48663. getOrient: function () {
  48664. return this.get('orient') === 'vertical'
  48665. ? {index: 1, name: 'vertical'}
  48666. : {index: 0, name: 'horizontal'};
  48667. }
  48668. });
  48669. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  48670. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  48671. var orient = legendModel.getOrient();
  48672. var ignoreSize = [1, 1];
  48673. ignoreSize[orient.index] = 0;
  48674. mergeLayoutParam(target, raw, {
  48675. type: 'box', ignoreSize: ignoreSize
  48676. });
  48677. }
  48678. /**
  48679. * Separate legend and scrollable legend to reduce package size.
  48680. */
  48681. var Group$4 = Group;
  48682. var WH$1 = ['width', 'height'];
  48683. var XY$1 = ['x', 'y'];
  48684. var ScrollableLegendView = LegendView.extend({
  48685. type: 'legend.scroll',
  48686. newlineDisabled: true,
  48687. init: function () {
  48688. ScrollableLegendView.superCall(this, 'init');
  48689. /**
  48690. * @private
  48691. * @type {number} For `scroll`.
  48692. */
  48693. this._currentIndex = 0;
  48694. /**
  48695. * @private
  48696. * @type {module:zrender/container/Group}
  48697. */
  48698. this.group.add(this._containerGroup = new Group$4());
  48699. this._containerGroup.add(this.getContentGroup());
  48700. /**
  48701. * @private
  48702. * @type {module:zrender/container/Group}
  48703. */
  48704. this.group.add(this._controllerGroup = new Group$4());
  48705. /**
  48706. *
  48707. * @private
  48708. */
  48709. this._showController;
  48710. },
  48711. /**
  48712. * @override
  48713. */
  48714. resetInner: function () {
  48715. ScrollableLegendView.superCall(this, 'resetInner');
  48716. this._controllerGroup.removeAll();
  48717. this._containerGroup.removeClipPath();
  48718. this._containerGroup.__rectSize = null;
  48719. },
  48720. /**
  48721. * @override
  48722. */
  48723. renderInner: function (itemAlign, legendModel, ecModel, api) {
  48724. var me = this;
  48725. // Render content items.
  48726. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  48727. var controllerGroup = this._controllerGroup;
  48728. var pageIconSize = legendModel.get('pageIconSize', true);
  48729. if (!isArray(pageIconSize)) {
  48730. pageIconSize = [pageIconSize, pageIconSize];
  48731. }
  48732. createPageButton('pagePrev', 0);
  48733. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  48734. controllerGroup.add(new Text({
  48735. name: 'pageText',
  48736. style: {
  48737. textFill: pageTextStyleModel.getTextColor(),
  48738. font: pageTextStyleModel.getFont(),
  48739. textVerticalAlign: 'middle',
  48740. textAlign: 'center'
  48741. },
  48742. silent: true
  48743. }));
  48744. createPageButton('pageNext', 1);
  48745. function createPageButton(name, iconIdx) {
  48746. var pageDataIndexName = name + 'DataIndex';
  48747. var icon = createIcon(
  48748. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  48749. {
  48750. // Buttons will be created in each render, so we do not need
  48751. // to worry about avoiding using legendModel kept in scope.
  48752. onclick: bind(
  48753. me._pageGo, me, pageDataIndexName, legendModel, api
  48754. )
  48755. },
  48756. {
  48757. x: -pageIconSize[0] / 2,
  48758. y: -pageIconSize[1] / 2,
  48759. width: pageIconSize[0],
  48760. height: pageIconSize[1]
  48761. }
  48762. );
  48763. icon.name = name;
  48764. controllerGroup.add(icon);
  48765. }
  48766. },
  48767. /**
  48768. * @override
  48769. */
  48770. layoutInner: function (legendModel, itemAlign, maxSize) {
  48771. var contentGroup = this.getContentGroup();
  48772. var containerGroup = this._containerGroup;
  48773. var controllerGroup = this._controllerGroup;
  48774. var orientIdx = legendModel.getOrient().index;
  48775. var wh = WH$1[orientIdx];
  48776. var hw = WH$1[1 - orientIdx];
  48777. var yx = XY$1[1 - orientIdx];
  48778. // Place items in contentGroup.
  48779. box(
  48780. legendModel.get('orient'),
  48781. contentGroup,
  48782. legendModel.get('itemGap'),
  48783. !orientIdx ? null : maxSize.width,
  48784. orientIdx ? null : maxSize.height
  48785. );
  48786. box(
  48787. // Buttons in controller are layout always horizontally.
  48788. 'horizontal',
  48789. controllerGroup,
  48790. legendModel.get('pageButtonItemGap', true)
  48791. );
  48792. var contentRect = contentGroup.getBoundingRect();
  48793. var controllerRect = controllerGroup.getBoundingRect();
  48794. var showController = this._showController = contentRect[wh] > maxSize[wh];
  48795. var contentPos = [-contentRect.x, -contentRect.y];
  48796. // Remain contentPos when scroll animation perfroming.
  48797. contentPos[orientIdx] = contentGroup.position[orientIdx];
  48798. // Layout container group based on 0.
  48799. var containerPos = [0, 0];
  48800. var controllerPos = [-controllerRect.x, -controllerRect.y];
  48801. var pageButtonGap = retrieve2(
  48802. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  48803. );
  48804. // Place containerGroup and controllerGroup and contentGroup.
  48805. if (showController) {
  48806. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  48807. // controller is on the right / bottom.
  48808. if (pageButtonPosition === 'end') {
  48809. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  48810. }
  48811. // controller is on the left / top.
  48812. else {
  48813. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  48814. }
  48815. }
  48816. // Always align controller to content as 'middle'.
  48817. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  48818. contentGroup.attr('position', contentPos);
  48819. containerGroup.attr('position', containerPos);
  48820. controllerGroup.attr('position', controllerPos);
  48821. // Calculate `mainRect` and set `clipPath`.
  48822. // mainRect should not be calculated by `this.group.getBoundingRect()`
  48823. // for sake of the overflow.
  48824. var mainRect = this.group.getBoundingRect();
  48825. var mainRect = {x: 0, y: 0};
  48826. // Consider content may be overflow (should be clipped).
  48827. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  48828. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  48829. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  48830. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  48831. containerGroup.__rectSize = maxSize[wh];
  48832. if (showController) {
  48833. var clipShape = {x: 0, y: 0};
  48834. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  48835. clipShape[hw] = mainRect[hw];
  48836. containerGroup.setClipPath(new Rect({shape: clipShape}));
  48837. // Consider content may be larger than container, container rect
  48838. // can not be obtained from `containerGroup.getBoundingRect()`.
  48839. containerGroup.__rectSize = clipShape[wh];
  48840. }
  48841. else {
  48842. // Do not remove or ignore controller. Keep them set as place holders.
  48843. controllerGroup.eachChild(function (child) {
  48844. child.attr({invisible: true, silent: true});
  48845. });
  48846. }
  48847. // Content translate animation.
  48848. var pageInfo = this._getPageInfo(legendModel);
  48849. pageInfo.pageIndex != null && updateProps(
  48850. contentGroup,
  48851. {position: pageInfo.contentPosition},
  48852. // When switch from "show controller" to "not show controller", view should be
  48853. // updated immediately without animation, otherwise causes weird efffect.
  48854. showController ? legendModel : false
  48855. );
  48856. this._updatePageInfoView(legendModel, pageInfo);
  48857. return mainRect;
  48858. },
  48859. _pageGo: function (to, legendModel, api) {
  48860. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  48861. scrollDataIndex != null && api.dispatchAction({
  48862. type: 'legendScroll',
  48863. scrollDataIndex: scrollDataIndex,
  48864. legendId: legendModel.id
  48865. });
  48866. },
  48867. _updatePageInfoView: function (legendModel, pageInfo) {
  48868. var controllerGroup = this._controllerGroup;
  48869. each$1(['pagePrev', 'pageNext'], function (name) {
  48870. var canJump = pageInfo[name + 'DataIndex'] != null;
  48871. var icon = controllerGroup.childOfName(name);
  48872. if (icon) {
  48873. icon.setStyle(
  48874. 'fill',
  48875. canJump
  48876. ? legendModel.get('pageIconColor', true)
  48877. : legendModel.get('pageIconInactiveColor', true)
  48878. );
  48879. icon.cursor = canJump ? 'pointer' : 'default';
  48880. }
  48881. });
  48882. var pageText = controllerGroup.childOfName('pageText');
  48883. var pageFormatter = legendModel.get('pageFormatter');
  48884. var pageIndex = pageInfo.pageIndex;
  48885. var current = pageIndex != null ? pageIndex + 1 : 0;
  48886. var total = pageInfo.pageCount;
  48887. pageText && pageFormatter && pageText.setStyle(
  48888. 'text',
  48889. isString(pageFormatter)
  48890. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  48891. : pageFormatter({current: current, total: total})
  48892. );
  48893. },
  48894. /**
  48895. * @param {module:echarts/model/Model} legendModel
  48896. * @return {Object} {
  48897. * contentPosition: Array.<number>, null when data item not found.
  48898. * pageIndex: number, null when data item not found.
  48899. * pageCount: number, always be a number, can be 0.
  48900. * pagePrevDataIndex: number, null when no next page.
  48901. * pageNextDataIndex: number, null when no previous page.
  48902. * }
  48903. */
  48904. _getPageInfo: function (legendModel) {
  48905. // Align left or top by the current dataIndex.
  48906. var currDataIndex = legendModel.get('scrollDataIndex', true);
  48907. var contentGroup = this.getContentGroup();
  48908. var contentRect = contentGroup.getBoundingRect();
  48909. var containerRectSize = this._containerGroup.__rectSize;
  48910. var orientIdx = legendModel.getOrient().index;
  48911. var wh = WH$1[orientIdx];
  48912. var hw = WH$1[1 - orientIdx];
  48913. var xy = XY$1[orientIdx];
  48914. var contentPos = contentGroup.position.slice();
  48915. var pageIndex;
  48916. var pagePrevDataIndex;
  48917. var pageNextDataIndex;
  48918. var targetItemGroup;
  48919. if (this._showController) {
  48920. contentGroup.eachChild(function (child) {
  48921. if (child.__legendDataIndex === currDataIndex) {
  48922. targetItemGroup = child;
  48923. }
  48924. });
  48925. }
  48926. else {
  48927. targetItemGroup = contentGroup.childAt(0);
  48928. }
  48929. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  48930. if (targetItemGroup) {
  48931. var itemRect = targetItemGroup.getBoundingRect();
  48932. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  48933. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  48934. pageIndex = Math.floor(
  48935. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  48936. );
  48937. pageIndex = (contentRect[wh] && pageCount)
  48938. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  48939. : -1;
  48940. var winRect = {x: 0, y: 0};
  48941. winRect[wh] = containerRectSize;
  48942. winRect[hw] = contentRect[hw];
  48943. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  48944. var startIdx;
  48945. var children = contentGroup.children();
  48946. contentGroup.eachChild(function (child, index) {
  48947. var itemRect = getItemRect(child);
  48948. if (itemRect.intersect(winRect)) {
  48949. startIdx == null && (startIdx = index);
  48950. // It is user-friendly that the last item shown in the
  48951. // current window is shown at the begining of next window.
  48952. pageNextDataIndex = child.__legendDataIndex;
  48953. }
  48954. // If the last item is shown entirely, no next page.
  48955. if (index === children.length - 1
  48956. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  48957. ) {
  48958. pageNextDataIndex = null;
  48959. }
  48960. });
  48961. // Always align based on the left/top most item, so the left/top most
  48962. // item in the previous window is needed to be found here.
  48963. if (startIdx != null) {
  48964. var startItem = children[startIdx];
  48965. var startRect = getItemRect(startItem);
  48966. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  48967. // If the first item is shown entirely, no previous page.
  48968. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  48969. pagePrevDataIndex = null;
  48970. }
  48971. else {
  48972. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  48973. startIdx--;
  48974. }
  48975. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  48976. }
  48977. }
  48978. }
  48979. return {
  48980. contentPosition: contentPos,
  48981. pageIndex: pageIndex,
  48982. pageCount: pageCount,
  48983. pagePrevDataIndex: pagePrevDataIndex,
  48984. pageNextDataIndex: pageNextDataIndex
  48985. };
  48986. function getItemRect(el) {
  48987. var itemRect = el.getBoundingRect().clone();
  48988. itemRect[xy] += el.position[orientIdx];
  48989. return itemRect;
  48990. }
  48991. }
  48992. });
  48993. /**
  48994. * @event legendScroll
  48995. * @type {Object}
  48996. * @property {string} type 'legendScroll'
  48997. * @property {string} scrollDataIndex
  48998. */
  48999. registerAction(
  49000. 'legendScroll', 'legendscroll',
  49001. function (payload, ecModel) {
  49002. var scrollDataIndex = payload.scrollDataIndex;
  49003. scrollDataIndex != null && ecModel.eachComponent(
  49004. {mainType: 'legend', subType: 'scroll', query: payload},
  49005. function (legendModel) {
  49006. legendModel.setScrollDataIndex(scrollDataIndex);
  49007. }
  49008. );
  49009. }
  49010. );
  49011. /**
  49012. * Legend component entry file8
  49013. */
  49014. extendComponentModel({
  49015. type: 'tooltip',
  49016. dependencies: ['axisPointer'],
  49017. defaultOption: {
  49018. zlevel: 0,
  49019. z: 8,
  49020. show: true,
  49021. // tooltip主体内容
  49022. showContent: true,
  49023. // 'trigger' only works on coordinate system.
  49024. // 'item' | 'axis' | 'none'
  49025. trigger: 'item',
  49026. // 'click' | 'mousemove' | 'none'
  49027. triggerOn: 'mousemove|click',
  49028. alwaysShowContent: false,
  49029. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  49030. // 位置 {Array} | {Function}
  49031. // position: null
  49032. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  49033. // align: null,
  49034. // verticalAlign: null,
  49035. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  49036. confine: false,
  49037. // 内容格式器:{string}(Template) ¦ {Function}
  49038. // formatter: null
  49039. showDelay: 0,
  49040. // 隐藏延迟,单位ms
  49041. hideDelay: 100,
  49042. // 动画变换时间,单位s
  49043. transitionDuration: 0.4,
  49044. enterable: false,
  49045. // 提示背景颜色,默认为透明度为0.7的黑色
  49046. backgroundColor: 'rgba(50,50,50,0.7)',
  49047. // 提示边框颜色
  49048. borderColor: '#333',
  49049. // 提示边框圆角,单位px,默认为4
  49050. borderRadius: 4,
  49051. // 提示边框线宽,单位px,默认为0(无边框)
  49052. borderWidth: 0,
  49053. // 提示内边距,单位px,默认各方向内边距为5,
  49054. // 接受数组分别设定上右下左边距,同css
  49055. padding: 5,
  49056. // Extra css text
  49057. extraCssText: '',
  49058. // 坐标轴指示器,坐标轴触发有效
  49059. axisPointer: {
  49060. // 默认为直线
  49061. // 可选为:'line' | 'shadow' | 'cross'
  49062. type: 'line',
  49063. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  49064. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  49065. // 默认 'auto',会选择类型为 cateogry 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  49066. // 极坐标系会默认选择 angle 轴
  49067. axis: 'auto',
  49068. animation: 'auto',
  49069. animationDurationUpdate: 200,
  49070. animationEasingUpdate: 'exponentialOut',
  49071. crossStyle: {
  49072. color: '#999',
  49073. width: 1,
  49074. type: 'dashed',
  49075. // TODO formatter
  49076. textStyle: {}
  49077. }
  49078. // lineStyle and shadowStyle should not be specified here,
  49079. // otherwise it will always override those styles on option.axisPointer.
  49080. },
  49081. textStyle: {
  49082. color: '#fff',
  49083. fontSize: 14
  49084. }
  49085. }
  49086. });
  49087. var each$21 = each$1;
  49088. var toCamelCase$1 = toCamelCase;
  49089. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  49090. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  49091. /**
  49092. * @param {number} duration
  49093. * @return {string}
  49094. * @inner
  49095. */
  49096. function assembleTransition(duration) {
  49097. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  49098. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  49099. + 'top ' + duration + 's ' + transitionCurve;
  49100. return map(vendors, function (vendorPrefix) {
  49101. return vendorPrefix + 'transition:' + transitionText;
  49102. }).join(';');
  49103. }
  49104. /**
  49105. * @param {Object} textStyle
  49106. * @return {string}
  49107. * @inner
  49108. */
  49109. function assembleFont(textStyleModel) {
  49110. var cssText = [];
  49111. var fontSize = textStyleModel.get('fontSize');
  49112. var color = textStyleModel.getTextColor();
  49113. color && cssText.push('color:' + color);
  49114. cssText.push('font:' + textStyleModel.getFont());
  49115. fontSize &&
  49116. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  49117. each$21(['decoration', 'align'], function (name) {
  49118. var val = textStyleModel.get(name);
  49119. val && cssText.push('text-' + name + ':' + val);
  49120. });
  49121. return cssText.join(';');
  49122. }
  49123. /**
  49124. * @param {Object} tooltipModel
  49125. * @return {string}
  49126. * @inner
  49127. */
  49128. function assembleCssText(tooltipModel) {
  49129. var cssText = [];
  49130. var transitionDuration = tooltipModel.get('transitionDuration');
  49131. var backgroundColor = tooltipModel.get('backgroundColor');
  49132. var textStyleModel = tooltipModel.getModel('textStyle');
  49133. var padding = tooltipModel.get('padding');
  49134. // Animation transition. Do not animate when transitionDuration is 0.
  49135. transitionDuration &&
  49136. cssText.push(assembleTransition(transitionDuration));
  49137. if (backgroundColor) {
  49138. if (env$1.canvasSupported) {
  49139. cssText.push('background-Color:' + backgroundColor);
  49140. }
  49141. else {
  49142. // for ie
  49143. cssText.push(
  49144. 'background-Color:#' + toHex(backgroundColor)
  49145. );
  49146. cssText.push('filter:alpha(opacity=70)');
  49147. }
  49148. }
  49149. // Border style
  49150. each$21(['width', 'color', 'radius'], function (name) {
  49151. var borderName = 'border-' + name;
  49152. var camelCase = toCamelCase$1(borderName);
  49153. var val = tooltipModel.get(camelCase);
  49154. val != null &&
  49155. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  49156. });
  49157. // Text style
  49158. cssText.push(assembleFont(textStyleModel));
  49159. // Padding
  49160. if (padding != null) {
  49161. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  49162. }
  49163. return cssText.join(';') + ';';
  49164. }
  49165. /**
  49166. * @alias module:echarts/component/tooltip/TooltipContent
  49167. * @constructor
  49168. */
  49169. function TooltipContent(container, api) {
  49170. var el = document.createElement('div');
  49171. var zr = this._zr = api.getZr();
  49172. this.el = el;
  49173. this._x = api.getWidth() / 2;
  49174. this._y = api.getHeight() / 2;
  49175. container.appendChild(el);
  49176. this._container = container;
  49177. this._show = false;
  49178. /**
  49179. * @private
  49180. */
  49181. this._hideTimeout;
  49182. var self = this;
  49183. el.onmouseenter = function () {
  49184. // clear the timeout in hideLater and keep showing tooltip
  49185. if (self._enterable) {
  49186. clearTimeout(self._hideTimeout);
  49187. self._show = true;
  49188. }
  49189. self._inContent = true;
  49190. };
  49191. el.onmousemove = function (e) {
  49192. e = e || window.event;
  49193. if (!self._enterable) {
  49194. // Try trigger zrender event to avoid mouse
  49195. // in and out shape too frequently
  49196. var handler = zr.handler;
  49197. normalizeEvent(container, e, true);
  49198. handler.dispatch('mousemove', e);
  49199. }
  49200. };
  49201. el.onmouseleave = function () {
  49202. if (self._enterable) {
  49203. if (self._show) {
  49204. self.hideLater(self._hideDelay);
  49205. }
  49206. }
  49207. self._inContent = false;
  49208. };
  49209. }
  49210. TooltipContent.prototype = {
  49211. constructor: TooltipContent,
  49212. /**
  49213. * @private
  49214. * @type {boolean}
  49215. */
  49216. _enterable: true,
  49217. /**
  49218. * Update when tooltip is rendered
  49219. */
  49220. update: function () {
  49221. // FIXME
  49222. // Move this logic to ec main?
  49223. var container = this._container;
  49224. var stl = container.currentStyle
  49225. || document.defaultView.getComputedStyle(container);
  49226. var domStyle = container.style;
  49227. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  49228. domStyle.position = 'relative';
  49229. }
  49230. // Hide the tooltip
  49231. // PENDING
  49232. // this.hide();
  49233. },
  49234. show: function (tooltipModel) {
  49235. clearTimeout(this._hideTimeout);
  49236. var el = this.el;
  49237. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  49238. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  49239. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  49240. + (tooltipModel.get('extraCssText') || '');
  49241. el.style.display = el.innerHTML ? 'block' : 'none';
  49242. this._show = true;
  49243. },
  49244. setContent: function (content) {
  49245. this.el.innerHTML = content == null ? '' : content;
  49246. },
  49247. setEnterable: function (enterable) {
  49248. this._enterable = enterable;
  49249. },
  49250. getSize: function () {
  49251. var el = this.el;
  49252. return [el.clientWidth, el.clientHeight];
  49253. },
  49254. moveTo: function (x, y) {
  49255. // xy should be based on canvas root. But tooltipContent is
  49256. // the sibling of canvas root. So padding of ec container
  49257. // should be considered here.
  49258. var zr = this._zr;
  49259. var viewportRootOffset;
  49260. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  49261. x += viewportRootOffset.offsetLeft;
  49262. y += viewportRootOffset.offsetTop;
  49263. }
  49264. var style = this.el.style;
  49265. style.left = x + 'px';
  49266. style.top = y + 'px';
  49267. this._x = x;
  49268. this._y = y;
  49269. },
  49270. hide: function () {
  49271. this.el.style.display = 'none';
  49272. this._show = false;
  49273. },
  49274. hideLater: function (time) {
  49275. if (this._show && !(this._inContent && this._enterable)) {
  49276. if (time) {
  49277. this._hideDelay = time;
  49278. // Set show false to avoid invoke hideLater mutiple times
  49279. this._show = false;
  49280. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  49281. }
  49282. else {
  49283. this.hide();
  49284. }
  49285. }
  49286. },
  49287. isShow: function () {
  49288. return this._show;
  49289. }
  49290. };
  49291. var bind$3 = bind;
  49292. var each$20 = each$1;
  49293. var parsePercent$2 = parsePercent$1;
  49294. var proxyRect = new Rect({
  49295. shape: {x: -1, y: -1, width: 2, height: 2}
  49296. });
  49297. extendComponentView({
  49298. type: 'tooltip',
  49299. init: function (ecModel, api) {
  49300. if (env$1.node) {
  49301. return;
  49302. }
  49303. var tooltipContent = new TooltipContent(api.getDom(), api);
  49304. this._tooltipContent = tooltipContent;
  49305. },
  49306. render: function (tooltipModel, ecModel, api) {
  49307. if (env$1.node) {
  49308. return;
  49309. }
  49310. // Reset
  49311. this.group.removeAll();
  49312. /**
  49313. * @private
  49314. * @type {module:echarts/component/tooltip/TooltipModel}
  49315. */
  49316. this._tooltipModel = tooltipModel;
  49317. /**
  49318. * @private
  49319. * @type {module:echarts/model/Global}
  49320. */
  49321. this._ecModel = ecModel;
  49322. /**
  49323. * @private
  49324. * @type {module:echarts/ExtensionAPI}
  49325. */
  49326. this._api = api;
  49327. /**
  49328. * Should be cleaned when render.
  49329. * @private
  49330. * @type {Array.<Array.<Object>>}
  49331. */
  49332. this._lastDataByCoordSys = null;
  49333. /**
  49334. * @private
  49335. * @type {boolean}
  49336. */
  49337. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  49338. var tooltipContent = this._tooltipContent;
  49339. tooltipContent.update();
  49340. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  49341. this._initGlobalListener();
  49342. this._keepShow();
  49343. },
  49344. _initGlobalListener: function () {
  49345. var tooltipModel = this._tooltipModel;
  49346. var triggerOn = tooltipModel.get('triggerOn');
  49347. register(
  49348. 'itemTooltip',
  49349. this._api,
  49350. bind$3(function (currTrigger, e, dispatchAction) {
  49351. // If 'none', it is not controlled by mouse totally.
  49352. if (triggerOn !== 'none') {
  49353. if (triggerOn.indexOf(currTrigger) >= 0) {
  49354. this._tryShow(e, dispatchAction);
  49355. }
  49356. else if (currTrigger === 'leave') {
  49357. this._hide(dispatchAction);
  49358. }
  49359. }
  49360. }, this)
  49361. );
  49362. },
  49363. _keepShow: function () {
  49364. var tooltipModel = this._tooltipModel;
  49365. var ecModel = this._ecModel;
  49366. var api = this._api;
  49367. // Try to keep the tooltip show when refreshing
  49368. if (this._lastX != null
  49369. && this._lastY != null
  49370. // When user is willing to control tooltip totally using API,
  49371. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  49372. // which is not expected.
  49373. && tooltipModel.get('triggerOn') !== 'none'
  49374. ) {
  49375. var self = this;
  49376. clearTimeout(this._refreshUpdateTimeout);
  49377. this._refreshUpdateTimeout = setTimeout(function () {
  49378. // Show tip next tick after other charts are rendered
  49379. // In case highlight action has wrong result
  49380. // FIXME
  49381. self.manuallyShowTip(tooltipModel, ecModel, api, {
  49382. x: self._lastX,
  49383. y: self._lastY
  49384. });
  49385. });
  49386. }
  49387. },
  49388. /**
  49389. * Show tip manually by
  49390. * dispatchAction({
  49391. * type: 'showTip',
  49392. * x: 10,
  49393. * y: 10
  49394. * });
  49395. * Or
  49396. * dispatchAction({
  49397. * type: 'showTip',
  49398. * seriesIndex: 0,
  49399. * dataIndex or dataIndexInside or name
  49400. * });
  49401. *
  49402. * TODO Batch
  49403. */
  49404. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  49405. if (payload.from === this.uid || env$1.node) {
  49406. return;
  49407. }
  49408. var dispatchAction = makeDispatchAction$1(payload, api);
  49409. // Reset ticket
  49410. this._ticket = '';
  49411. // When triggered from axisPointer.
  49412. var dataByCoordSys = payload.dataByCoordSys;
  49413. if (payload.tooltip && payload.x != null && payload.y != null) {
  49414. var el = proxyRect;
  49415. el.position = [payload.x, payload.y];
  49416. el.update();
  49417. el.tooltip = payload.tooltip;
  49418. // Manually show tooltip while view is not using zrender elements.
  49419. this._tryShow({
  49420. offsetX: payload.x,
  49421. offsetY: payload.y,
  49422. target: el
  49423. }, dispatchAction);
  49424. }
  49425. else if (dataByCoordSys) {
  49426. this._tryShow({
  49427. offsetX: payload.x,
  49428. offsetY: payload.y,
  49429. position: payload.position,
  49430. event: {},
  49431. dataByCoordSys: payload.dataByCoordSys,
  49432. tooltipOption: payload.tooltipOption
  49433. }, dispatchAction);
  49434. }
  49435. else if (payload.seriesIndex != null) {
  49436. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  49437. return;
  49438. }
  49439. var pointInfo = findPointFromSeries(payload, ecModel);
  49440. var cx = pointInfo.point[0];
  49441. var cy = pointInfo.point[1];
  49442. if (cx != null && cy != null) {
  49443. this._tryShow({
  49444. offsetX: cx,
  49445. offsetY: cy,
  49446. position: payload.position,
  49447. target: pointInfo.el,
  49448. event: {}
  49449. }, dispatchAction);
  49450. }
  49451. }
  49452. else if (payload.x != null && payload.y != null) {
  49453. // FIXME
  49454. // should wrap dispatchAction like `axisPointer/globalListener` ?
  49455. api.dispatchAction({
  49456. type: 'updateAxisPointer',
  49457. x: payload.x,
  49458. y: payload.y
  49459. });
  49460. this._tryShow({
  49461. offsetX: payload.x,
  49462. offsetY: payload.y,
  49463. position: payload.position,
  49464. target: api.getZr().findHover(payload.x, payload.y).target,
  49465. event: {}
  49466. }, dispatchAction);
  49467. }
  49468. },
  49469. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  49470. var tooltipContent = this._tooltipContent;
  49471. if (!this._alwaysShowContent) {
  49472. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  49473. }
  49474. this._lastX = this._lastY = null;
  49475. if (payload.from !== this.uid) {
  49476. this._hide(makeDispatchAction$1(payload, api));
  49477. }
  49478. },
  49479. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  49480. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  49481. // and tooltip.
  49482. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  49483. var seriesIndex = payload.seriesIndex;
  49484. var dataIndex = payload.dataIndex;
  49485. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  49486. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  49487. return;
  49488. }
  49489. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  49490. if (!seriesModel) {
  49491. return;
  49492. }
  49493. var data = seriesModel.getData();
  49494. var tooltipModel = buildTooltipModel([
  49495. data.getItemModel(dataIndex),
  49496. seriesModel,
  49497. (seriesModel.coordinateSystem || {}).model,
  49498. tooltipModel
  49499. ]);
  49500. if (tooltipModel.get('trigger') !== 'axis') {
  49501. return;
  49502. }
  49503. api.dispatchAction({
  49504. type: 'updateAxisPointer',
  49505. seriesIndex: seriesIndex,
  49506. dataIndex: dataIndex,
  49507. position: payload.position
  49508. });
  49509. return true;
  49510. },
  49511. _tryShow: function (e, dispatchAction) {
  49512. var el = e.target;
  49513. var tooltipModel = this._tooltipModel;
  49514. if (!tooltipModel) {
  49515. return;
  49516. }
  49517. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  49518. this._lastX = e.offsetX;
  49519. this._lastY = e.offsetY;
  49520. var dataByCoordSys = e.dataByCoordSys;
  49521. if (dataByCoordSys && dataByCoordSys.length) {
  49522. this._showAxisTooltip(dataByCoordSys, e);
  49523. }
  49524. // Always show item tooltip if mouse is on the element with dataIndex
  49525. else if (el && el.dataIndex != null) {
  49526. this._lastDataByCoordSys = null;
  49527. this._showSeriesItemTooltip(e, el, dispatchAction);
  49528. }
  49529. // Tooltip provided directly. Like legend.
  49530. else if (el && el.tooltip) {
  49531. this._lastDataByCoordSys = null;
  49532. this._showComponentItemTooltip(e, el, dispatchAction);
  49533. }
  49534. else {
  49535. this._lastDataByCoordSys = null;
  49536. this._hide(dispatchAction);
  49537. }
  49538. },
  49539. _showOrMove: function (tooltipModel, cb) {
  49540. // showDelay is used in this case: tooltip.enterable is set
  49541. // as true. User intent to move mouse into tooltip and click
  49542. // something. `showDelay` makes it easyer to enter the content
  49543. // but tooltip do not move immediately.
  49544. var delay = tooltipModel.get('showDelay');
  49545. cb = bind(cb, this);
  49546. clearTimeout(this._showTimout);
  49547. delay > 0
  49548. ? (this._showTimout = setTimeout(cb, delay))
  49549. : cb();
  49550. },
  49551. _showAxisTooltip: function (dataByCoordSys, e) {
  49552. var ecModel = this._ecModel;
  49553. var globalTooltipModel = this._tooltipModel;
  49554. var point = [e.offsetX, e.offsetY];
  49555. var singleDefaultHTML = [];
  49556. var singleParamsList = [];
  49557. var singleTooltipModel = buildTooltipModel([
  49558. e.tooltipOption,
  49559. globalTooltipModel
  49560. ]);
  49561. each$20(dataByCoordSys, function (itemCoordSys) {
  49562. // var coordParamList = [];
  49563. // var coordDefaultHTML = [];
  49564. // var coordTooltipModel = buildTooltipModel([
  49565. // e.tooltipOption,
  49566. // itemCoordSys.tooltipOption,
  49567. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  49568. // globalTooltipModel
  49569. // ]);
  49570. // var displayMode = coordTooltipModel.get('displayMode');
  49571. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  49572. each$20(itemCoordSys.dataByAxis, function (item) {
  49573. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  49574. var axisValue = item.value;
  49575. var seriesDefaultHTML = [];
  49576. if (!axisModel || axisValue == null) {
  49577. return;
  49578. }
  49579. var valueLabel = getValueLabel(
  49580. axisValue, axisModel.axis, ecModel,
  49581. item.seriesDataIndices,
  49582. item.valueLabelOpt
  49583. );
  49584. each$1(item.seriesDataIndices, function (idxItem) {
  49585. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  49586. var dataIndex = idxItem.dataIndexInside;
  49587. var dataParams = series && series.getDataParams(dataIndex);
  49588. dataParams.axisDim = item.axisDim;
  49589. dataParams.axisIndex = item.axisIndex;
  49590. dataParams.axisType = item.axisType;
  49591. dataParams.axisId = item.axisId;
  49592. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  49593. dataParams.axisValueLabel = valueLabel;
  49594. if (dataParams) {
  49595. singleParamsList.push(dataParams);
  49596. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  49597. }
  49598. });
  49599. // Default tooltip content
  49600. // FIXME
  49601. // (1) shold be the first data which has name?
  49602. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  49603. var firstLine = valueLabel;
  49604. singleDefaultHTML.push(
  49605. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  49606. + seriesDefaultHTML.join('<br />')
  49607. );
  49608. });
  49609. }, this);
  49610. // In most case, the second axis is shown upper than the first one.
  49611. singleDefaultHTML.reverse();
  49612. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  49613. var positionExpr = e.position;
  49614. this._showOrMove(singleTooltipModel, function () {
  49615. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  49616. this._updatePosition(
  49617. singleTooltipModel,
  49618. positionExpr,
  49619. point[0], point[1],
  49620. this._tooltipContent,
  49621. singleParamsList
  49622. );
  49623. }
  49624. else {
  49625. this._showTooltipContent(
  49626. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  49627. point[0], point[1], positionExpr
  49628. );
  49629. }
  49630. });
  49631. // Do not trigger events here, because this branch only be entered
  49632. // from dispatchAction.
  49633. },
  49634. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  49635. var ecModel = this._ecModel;
  49636. // Use dataModel in element if possible
  49637. // Used when mouseover on a element like markPoint or edge
  49638. // In which case, the data is not main data in series.
  49639. var seriesIndex = el.seriesIndex;
  49640. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  49641. // For example, graph link.
  49642. var dataModel = el.dataModel || seriesModel;
  49643. var dataIndex = el.dataIndex;
  49644. var dataType = el.dataType;
  49645. var data = dataModel.getData();
  49646. var tooltipModel = buildTooltipModel([
  49647. data.getItemModel(dataIndex),
  49648. dataModel,
  49649. seriesModel && (seriesModel.coordinateSystem || {}).model,
  49650. this._tooltipModel
  49651. ]);
  49652. var tooltipTrigger = tooltipModel.get('trigger');
  49653. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  49654. return;
  49655. }
  49656. var params = dataModel.getDataParams(dataIndex, dataType);
  49657. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  49658. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  49659. this._showOrMove(tooltipModel, function () {
  49660. this._showTooltipContent(
  49661. tooltipModel, defaultHtml, params, asyncTicket,
  49662. e.offsetX, e.offsetY, e.position, e.target
  49663. );
  49664. });
  49665. // FIXME
  49666. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  49667. dispatchAction({
  49668. type: 'showTip',
  49669. dataIndexInside: dataIndex,
  49670. dataIndex: data.getRawIndex(dataIndex),
  49671. seriesIndex: seriesIndex,
  49672. from: this.uid
  49673. });
  49674. },
  49675. _showComponentItemTooltip: function (e, el, dispatchAction) {
  49676. var tooltipOpt = el.tooltip;
  49677. if (typeof tooltipOpt === 'string') {
  49678. var content = tooltipOpt;
  49679. tooltipOpt = {
  49680. content: content,
  49681. // Fixed formatter
  49682. formatter: content
  49683. };
  49684. }
  49685. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  49686. var defaultHtml = subTooltipModel.get('content');
  49687. var asyncTicket = Math.random();
  49688. // Do not check whether `trigger` is 'none' here, because `trigger`
  49689. // only works on cooridinate system. In fact, we have not found case
  49690. // that requires setting `trigger` nothing on component yet.
  49691. this._showOrMove(subTooltipModel, function () {
  49692. this._showTooltipContent(
  49693. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  49694. asyncTicket, e.offsetX, e.offsetY, e.position, el
  49695. );
  49696. });
  49697. // If not dispatch showTip, tip may be hide triggered by axis.
  49698. dispatchAction({
  49699. type: 'showTip',
  49700. from: this.uid
  49701. });
  49702. },
  49703. _showTooltipContent: function (
  49704. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  49705. ) {
  49706. // Reset ticket
  49707. this._ticket = '';
  49708. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  49709. return;
  49710. }
  49711. var tooltipContent = this._tooltipContent;
  49712. var formatter = tooltipModel.get('formatter');
  49713. positionExpr = positionExpr || tooltipModel.get('position');
  49714. var html = defaultHtml;
  49715. if (formatter && typeof formatter === 'string') {
  49716. html = formatTpl(formatter, params, true);
  49717. }
  49718. else if (typeof formatter === 'function') {
  49719. var callback = bind$3(function (cbTicket, html) {
  49720. if (cbTicket === this._ticket) {
  49721. tooltipContent.setContent(html);
  49722. this._updatePosition(
  49723. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  49724. );
  49725. }
  49726. }, this);
  49727. this._ticket = asyncTicket;
  49728. html = formatter(params, asyncTicket, callback);
  49729. }
  49730. tooltipContent.setContent(html);
  49731. tooltipContent.show(tooltipModel);
  49732. this._updatePosition(
  49733. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  49734. );
  49735. },
  49736. /**
  49737. * @param {string|Function|Array.<number>|Object} positionExpr
  49738. * @param {number} x Mouse x
  49739. * @param {number} y Mouse y
  49740. * @param {boolean} confine Whether confine tooltip content in view rect.
  49741. * @param {Object|<Array.<Object>} params
  49742. * @param {module:zrender/Element} el target element
  49743. * @param {module:echarts/ExtensionAPI} api
  49744. * @return {Array.<number>}
  49745. */
  49746. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  49747. var viewWidth = this._api.getWidth();
  49748. var viewHeight = this._api.getHeight();
  49749. positionExpr = positionExpr || tooltipModel.get('position');
  49750. var contentSize = content.getSize();
  49751. var align = tooltipModel.get('align');
  49752. var vAlign = tooltipModel.get('verticalAlign');
  49753. var rect = el && el.getBoundingRect().clone();
  49754. el && rect.applyTransform(el.transform);
  49755. if (typeof positionExpr === 'function') {
  49756. // Callback of position can be an array or a string specify the position
  49757. positionExpr = positionExpr([x, y], params, content.el, rect, {
  49758. viewSize: [viewWidth, viewHeight],
  49759. contentSize: contentSize.slice()
  49760. });
  49761. }
  49762. if (isArray(positionExpr)) {
  49763. x = parsePercent$2(positionExpr[0], viewWidth);
  49764. y = parsePercent$2(positionExpr[1], viewHeight);
  49765. }
  49766. else if (isObject(positionExpr)) {
  49767. positionExpr.width = contentSize[0];
  49768. positionExpr.height = contentSize[1];
  49769. var layoutRect = getLayoutRect(
  49770. positionExpr, {width: viewWidth, height: viewHeight}
  49771. );
  49772. x = layoutRect.x;
  49773. y = layoutRect.y;
  49774. align = null;
  49775. // When positionExpr is left/top/right/bottom,
  49776. // align and verticalAlign will not work.
  49777. vAlign = null;
  49778. }
  49779. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  49780. else if (typeof positionExpr === 'string' && el) {
  49781. var pos = calcTooltipPosition(
  49782. positionExpr, rect, contentSize
  49783. );
  49784. x = pos[0];
  49785. y = pos[1];
  49786. }
  49787. else {
  49788. var pos = refixTooltipPosition(
  49789. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  49790. );
  49791. x = pos[0];
  49792. y = pos[1];
  49793. }
  49794. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  49795. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  49796. if (tooltipModel.get('confine')) {
  49797. var pos = confineTooltipPosition(
  49798. x, y, content.el, viewWidth, viewHeight
  49799. );
  49800. x = pos[0];
  49801. y = pos[1];
  49802. }
  49803. content.moveTo(x, y);
  49804. },
  49805. // FIXME
  49806. // Should we remove this but leave this to user?
  49807. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  49808. var lastCoordSys = this._lastDataByCoordSys;
  49809. var contentNotChanged = !!lastCoordSys
  49810. && lastCoordSys.length === dataByCoordSys.length;
  49811. contentNotChanged && each$20(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  49812. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  49813. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  49814. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  49815. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  49816. contentNotChanged && each$20(lastDataByAxis, function (lastItem, indexAxis) {
  49817. var thisItem = thisDataByAxis[indexAxis] || {};
  49818. var lastIndices = lastItem.seriesDataIndices || [];
  49819. var newIndices = thisItem.seriesDataIndices || [];
  49820. contentNotChanged &=
  49821. lastItem.value === thisItem.value
  49822. && lastItem.axisType === thisItem.axisType
  49823. && lastItem.axisId === thisItem.axisId
  49824. && lastIndices.length === newIndices.length;
  49825. contentNotChanged && each$20(lastIndices, function (lastIdxItem, j) {
  49826. var newIdxItem = newIndices[j];
  49827. contentNotChanged &=
  49828. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  49829. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  49830. });
  49831. });
  49832. });
  49833. this._lastDataByCoordSys = dataByCoordSys;
  49834. return !!contentNotChanged;
  49835. },
  49836. _hide: function (dispatchAction) {
  49837. // Do not directly hideLater here, because this behavior may be prevented
  49838. // in dispatchAction when showTip is dispatched.
  49839. // FIXME
  49840. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  49841. this._lastDataByCoordSys = null;
  49842. dispatchAction({
  49843. type: 'hideTip',
  49844. from: this.uid
  49845. });
  49846. },
  49847. dispose: function (ecModel, api) {
  49848. if (env$1.node) {
  49849. return;
  49850. }
  49851. this._tooltipContent.hide();
  49852. unregister('itemTooltip', api);
  49853. }
  49854. });
  49855. /**
  49856. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  49857. * From top to bottom. (the last one should be globalTooltipModel);
  49858. */
  49859. function buildTooltipModel(modelCascade) {
  49860. var resultModel = modelCascade.pop();
  49861. while (modelCascade.length) {
  49862. var tooltipOpt = modelCascade.pop();
  49863. if (tooltipOpt) {
  49864. if (tooltipOpt instanceof Model) {
  49865. tooltipOpt = tooltipOpt.get('tooltip', true);
  49866. }
  49867. // In each data item tooltip can be simply write:
  49868. // {
  49869. // value: 10,
  49870. // tooltip: 'Something you need to know'
  49871. // }
  49872. if (typeof tooltipOpt === 'string') {
  49873. tooltipOpt = {formatter: tooltipOpt};
  49874. }
  49875. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  49876. }
  49877. }
  49878. return resultModel;
  49879. }
  49880. function makeDispatchAction$1(payload, api) {
  49881. return payload.dispatchAction || bind(api.dispatchAction, api);
  49882. }
  49883. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  49884. var size = getOuterSize(el);
  49885. var width = size.width;
  49886. var height = size.height;
  49887. if (gapH != null) {
  49888. if (x + width + gapH > viewWidth) {
  49889. x -= width + gapH;
  49890. }
  49891. else {
  49892. x += gapH;
  49893. }
  49894. }
  49895. if (gapV != null) {
  49896. if (y + height + gapV > viewHeight) {
  49897. y -= height + gapV;
  49898. }
  49899. else {
  49900. y += gapV;
  49901. }
  49902. }
  49903. return [x, y];
  49904. }
  49905. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  49906. var size = getOuterSize(el);
  49907. var width = size.width;
  49908. var height = size.height;
  49909. x = Math.min(x + width, viewWidth) - width;
  49910. y = Math.min(y + height, viewHeight) - height;
  49911. x = Math.max(x, 0);
  49912. y = Math.max(y, 0);
  49913. return [x, y];
  49914. }
  49915. function getOuterSize(el) {
  49916. var width = el.clientWidth;
  49917. var height = el.clientHeight;
  49918. // Consider browser compatibility.
  49919. // IE8 does not support getComputedStyle.
  49920. if (document.defaultView && document.defaultView.getComputedStyle) {
  49921. var stl = document.defaultView.getComputedStyle(el);
  49922. if (stl) {
  49923. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  49924. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  49925. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  49926. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  49927. }
  49928. }
  49929. return {width: width, height: height};
  49930. }
  49931. function calcTooltipPosition(position, rect, contentSize) {
  49932. var domWidth = contentSize[0];
  49933. var domHeight = contentSize[1];
  49934. var gap = 5;
  49935. var x = 0;
  49936. var y = 0;
  49937. var rectWidth = rect.width;
  49938. var rectHeight = rect.height;
  49939. switch (position) {
  49940. case 'inside':
  49941. x = rect.x + rectWidth / 2 - domWidth / 2;
  49942. y = rect.y + rectHeight / 2 - domHeight / 2;
  49943. break;
  49944. case 'top':
  49945. x = rect.x + rectWidth / 2 - domWidth / 2;
  49946. y = rect.y - domHeight - gap;
  49947. break;
  49948. case 'bottom':
  49949. x = rect.x + rectWidth / 2 - domWidth / 2;
  49950. y = rect.y + rectHeight + gap;
  49951. break;
  49952. case 'left':
  49953. x = rect.x - domWidth - gap;
  49954. y = rect.y + rectHeight / 2 - domHeight / 2;
  49955. break;
  49956. case 'right':
  49957. x = rect.x + rectWidth + gap;
  49958. y = rect.y + rectHeight / 2 - domHeight / 2;
  49959. }
  49960. return [x, y];
  49961. }
  49962. function isCenterAlign(align) {
  49963. return align === 'center' || align === 'middle';
  49964. }
  49965. // FIXME Better way to pack data in graphic element
  49966. /**
  49967. * @action
  49968. * @property {string} type
  49969. * @property {number} seriesIndex
  49970. * @property {number} dataIndex
  49971. * @property {number} [x]
  49972. * @property {number} [y]
  49973. */
  49974. registerAction(
  49975. {
  49976. type: 'showTip',
  49977. event: 'showTip',
  49978. update: 'tooltip:manuallyShowTip'
  49979. },
  49980. // noop
  49981. function () {}
  49982. );
  49983. registerAction(
  49984. {
  49985. type: 'hideTip',
  49986. event: 'hideTip',
  49987. update: 'tooltip:manuallyHideTip'
  49988. },
  49989. // noop
  49990. function () {}
  49991. );
  49992. function getSeriesStackId$1(seriesModel) {
  49993. return seriesModel.get('stack')
  49994. || '__ec_stack_' + seriesModel.seriesIndex;
  49995. }
  49996. function getAxisKey$1(axis) {
  49997. return axis.dim;
  49998. }
  49999. /**
  50000. * @param {string} seriesType
  50001. * @param {module:echarts/model/Global} ecModel
  50002. * @param {module:echarts/ExtensionAPI} api
  50003. */
  50004. function barLayoutPolar(seriesType, ecModel, api) {
  50005. var width = api.getWidth();
  50006. var height = api.getHeight();
  50007. var lastStackCoords = {};
  50008. var lastStackCoordsOrigin = {};
  50009. var barWidthAndOffset = calRadialBar(
  50010. filter(
  50011. ecModel.getSeriesByType(seriesType),
  50012. function (seriesModel) {
  50013. return !ecModel.isSeriesFiltered(seriesModel)
  50014. && seriesModel.coordinateSystem
  50015. && seriesModel.coordinateSystem.type === 'polar';
  50016. }
  50017. )
  50018. );
  50019. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  50020. // Check series coordinate, do layout for polar only
  50021. if (seriesModel.coordinateSystem.type !== 'polar') {
  50022. return;
  50023. }
  50024. var data = seriesModel.getData();
  50025. var polar = seriesModel.coordinateSystem;
  50026. var angleAxis = polar.getAngleAxis();
  50027. var baseAxis = polar.getBaseAxis();
  50028. var stackId = getSeriesStackId$1(seriesModel);
  50029. var columnLayoutInfo
  50030. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  50031. var columnOffset = columnLayoutInfo.offset;
  50032. var columnWidth = columnLayoutInfo.width;
  50033. var valueAxis = polar.getOtherAxis(baseAxis);
  50034. var center = seriesModel.get('center') || ['50%', '50%'];
  50035. var cx = parsePercent$1(center[0], width);
  50036. var cy = parsePercent$1(center[1], height);
  50037. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  50038. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  50039. var valueAxisStart = valueAxis.getExtent()[0];
  50040. var valueMax = valueAxis.model.get('max');
  50041. var valueMin = valueAxis.model.get('min');
  50042. var coordDims = [
  50043. seriesModel.coordDimToDataDim('radius')[0],
  50044. seriesModel.coordDimToDataDim('angle')[0]
  50045. ];
  50046. var coords = data.mapArray(coordDims, function (radius, angle) {
  50047. return polar.dataToPoint([radius, angle]);
  50048. }, true);
  50049. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  50050. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  50051. data.each(seriesModel.coordDimToDataDim(valueAxis.dim)[0], function (value, idx) {
  50052. if (isNaN(value)) {
  50053. return;
  50054. }
  50055. if (!lastStackCoords[stackId][idx]) {
  50056. lastStackCoords[stackId][idx] = {
  50057. p: valueAxisStart, // Positive stack
  50058. n: valueAxisStart // Negative stack
  50059. };
  50060. lastStackCoordsOrigin[stackId][idx] = {
  50061. p: valueAxisStart, // Positive stack
  50062. n: valueAxisStart // Negative stack
  50063. };
  50064. }
  50065. var sign = value >= 0 ? 'p' : 'n';
  50066. var coord = polar.pointToCoord(coords[idx]);
  50067. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  50068. var r0;
  50069. var r;
  50070. var startAngle;
  50071. var endAngle;
  50072. if (valueAxis.dim === 'radius') {
  50073. // radial sector
  50074. r0 = lastCoordOrigin;
  50075. r = coord[0];
  50076. startAngle = (-coord[1] + columnOffset) * Math.PI / 180;
  50077. endAngle = startAngle + columnWidth * Math.PI / 180;
  50078. if (Math.abs(r) < barMinHeight) {
  50079. r = r0 + (r < 0 ? -1 : 1) * barMinHeight;
  50080. }
  50081. lastStackCoordsOrigin[stackId][idx][sign] = r;
  50082. }
  50083. else {
  50084. // tangential sector
  50085. r0 = coord[0] + columnOffset;
  50086. r = r0 + columnWidth;
  50087. // clamp data if min or max is defined for valueAxis
  50088. if (valueMax != null) {
  50089. value = Math.min(value, valueMax);
  50090. }
  50091. if (valueMin != null) {
  50092. value = Math.max(value, valueMin);
  50093. }
  50094. var angle = angleAxis.dataToAngle(value);
  50095. if (Math.abs(angle - lastCoordOrigin) < barMinAngle) {
  50096. angle = lastCoordOrigin - (value < 0 ? -1 : 1)
  50097. * barMinAngle;
  50098. }
  50099. startAngle = -lastCoordOrigin * Math.PI / 180;
  50100. endAngle = -angle * Math.PI / 180;
  50101. // if the previous stack is at the end of the ring,
  50102. // add a round to differentiate it from origin
  50103. var extent = angleAxis.getExtent();
  50104. var stackCoord = angle;
  50105. if (stackCoord === extent[0] && value > 0) {
  50106. stackCoord = extent[1];
  50107. }
  50108. else if (stackCoord === extent[1] && value < 0) {
  50109. stackCoord = extent[0];
  50110. }
  50111. lastStackCoordsOrigin[stackId][idx][sign] = stackCoord;
  50112. }
  50113. data.setItemLayout(idx, {
  50114. cx: cx,
  50115. cy: cy,
  50116. r0: r0,
  50117. r: r,
  50118. startAngle: startAngle,
  50119. endAngle: endAngle
  50120. });
  50121. }, true);
  50122. }, this);
  50123. }
  50124. /**
  50125. * Calculate bar width and offset for radial bar charts
  50126. */
  50127. function calRadialBar(barSeries, api) {
  50128. // Columns info on each category axis. Key is polar name
  50129. var columnsMap = {};
  50130. each$1(barSeries, function (seriesModel, idx) {
  50131. var data = seriesModel.getData();
  50132. var polar = seriesModel.coordinateSystem;
  50133. var baseAxis = polar.getBaseAxis();
  50134. var axisExtent = baseAxis.getExtent();
  50135. var bandWidth = baseAxis.type === 'category'
  50136. ? baseAxis.getBandWidth()
  50137. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  50138. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  50139. bandWidth: bandWidth,
  50140. remainedWidth: bandWidth,
  50141. autoWidthCount: 0,
  50142. categoryGap: '20%',
  50143. gap: '30%',
  50144. stacks: {}
  50145. };
  50146. var stacks = columnsOnAxis.stacks;
  50147. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  50148. var stackId = getSeriesStackId$1(seriesModel);
  50149. if (!stacks[stackId]) {
  50150. columnsOnAxis.autoWidthCount++;
  50151. }
  50152. stacks[stackId] = stacks[stackId] || {
  50153. width: 0,
  50154. maxWidth: 0
  50155. };
  50156. var barWidth = parsePercent$1(
  50157. seriesModel.get('barWidth'),
  50158. bandWidth
  50159. );
  50160. var barMaxWidth = parsePercent$1(
  50161. seriesModel.get('barMaxWidth'),
  50162. bandWidth
  50163. );
  50164. var barGap = seriesModel.get('barGap');
  50165. var barCategoryGap = seriesModel.get('barCategoryGap');
  50166. if (barWidth && !stacks[stackId].width) {
  50167. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  50168. stacks[stackId].width = barWidth;
  50169. columnsOnAxis.remainedWidth -= barWidth;
  50170. }
  50171. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  50172. (barGap != null) && (columnsOnAxis.gap = barGap);
  50173. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  50174. });
  50175. var result = {};
  50176. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  50177. result[coordSysName] = {};
  50178. var stacks = columnsOnAxis.stacks;
  50179. var bandWidth = columnsOnAxis.bandWidth;
  50180. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  50181. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  50182. var remainedWidth = columnsOnAxis.remainedWidth;
  50183. var autoWidthCount = columnsOnAxis.autoWidthCount;
  50184. var autoWidth = (remainedWidth - categoryGap)
  50185. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  50186. autoWidth = Math.max(autoWidth, 0);
  50187. // Find if any auto calculated bar exceeded maxBarWidth
  50188. each$1(stacks, function (column, stack) {
  50189. var maxWidth = column.maxWidth;
  50190. if (maxWidth && maxWidth < autoWidth) {
  50191. maxWidth = Math.min(maxWidth, remainedWidth);
  50192. if (column.width) {
  50193. maxWidth = Math.min(maxWidth, column.width);
  50194. }
  50195. remainedWidth -= maxWidth;
  50196. column.width = maxWidth;
  50197. autoWidthCount--;
  50198. }
  50199. });
  50200. // Recalculate width again
  50201. autoWidth = (remainedWidth - categoryGap)
  50202. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  50203. autoWidth = Math.max(autoWidth, 0);
  50204. var widthSum = 0;
  50205. var lastColumn;
  50206. each$1(stacks, function (column, idx) {
  50207. if (!column.width) {
  50208. column.width = autoWidth;
  50209. }
  50210. lastColumn = column;
  50211. widthSum += column.width * (1 + barGapPercent);
  50212. });
  50213. if (lastColumn) {
  50214. widthSum -= lastColumn.width * barGapPercent;
  50215. }
  50216. var offset = -widthSum / 2;
  50217. each$1(stacks, function (column, stackId) {
  50218. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  50219. offset: offset,
  50220. width: column.width
  50221. };
  50222. offset += column.width * (1 + barGapPercent);
  50223. });
  50224. });
  50225. return result;
  50226. }
  50227. function RadiusAxis(scale, radiusExtent) {
  50228. Axis.call(this, 'radius', scale, radiusExtent);
  50229. /**
  50230. * Axis type
  50231. * - 'category'
  50232. * - 'value'
  50233. * - 'time'
  50234. * - 'log'
  50235. * @type {string}
  50236. */
  50237. this.type = 'category';
  50238. }
  50239. RadiusAxis.prototype = {
  50240. constructor: RadiusAxis,
  50241. /**
  50242. * @override
  50243. */
  50244. pointToData: function (point, clamp) {
  50245. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  50246. },
  50247. dataToRadius: Axis.prototype.dataToCoord,
  50248. radiusToData: Axis.prototype.coordToData
  50249. };
  50250. inherits(RadiusAxis, Axis);
  50251. function AngleAxis(scale, angleExtent) {
  50252. angleExtent = angleExtent || [0, 360];
  50253. Axis.call(this, 'angle', scale, angleExtent);
  50254. /**
  50255. * Axis type
  50256. * - 'category'
  50257. * - 'value'
  50258. * - 'time'
  50259. * - 'log'
  50260. * @type {string}
  50261. */
  50262. this.type = 'category';
  50263. }
  50264. AngleAxis.prototype = {
  50265. constructor: AngleAxis,
  50266. /**
  50267. * @override
  50268. */
  50269. pointToData: function (point, clamp) {
  50270. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  50271. },
  50272. dataToAngle: Axis.prototype.dataToCoord,
  50273. angleToData: Axis.prototype.coordToData
  50274. };
  50275. inherits(AngleAxis, Axis);
  50276. /**
  50277. * @module echarts/coord/polar/Polar
  50278. */
  50279. /**
  50280. * @alias {module:echarts/coord/polar/Polar}
  50281. * @constructor
  50282. * @param {string} name
  50283. */
  50284. var Polar = function (name) {
  50285. /**
  50286. * @type {string}
  50287. */
  50288. this.name = name || '';
  50289. /**
  50290. * x of polar center
  50291. * @type {number}
  50292. */
  50293. this.cx = 0;
  50294. /**
  50295. * y of polar center
  50296. * @type {number}
  50297. */
  50298. this.cy = 0;
  50299. /**
  50300. * @type {module:echarts/coord/polar/RadiusAxis}
  50301. * @private
  50302. */
  50303. this._radiusAxis = new RadiusAxis();
  50304. /**
  50305. * @type {module:echarts/coord/polar/AngleAxis}
  50306. * @private
  50307. */
  50308. this._angleAxis = new AngleAxis();
  50309. this._radiusAxis.polar = this._angleAxis.polar = this;
  50310. };
  50311. Polar.prototype = {
  50312. type: 'polar',
  50313. axisPointerEnabled: true,
  50314. constructor: Polar,
  50315. /**
  50316. * @param {Array.<string>}
  50317. * @readOnly
  50318. */
  50319. dimensions: ['radius', 'angle'],
  50320. /**
  50321. * @type {module:echarts/coord/PolarModel}
  50322. */
  50323. model: null,
  50324. /**
  50325. * If contain coord
  50326. * @param {Array.<number>} point
  50327. * @return {boolean}
  50328. */
  50329. containPoint: function (point) {
  50330. var coord = this.pointToCoord(point);
  50331. return this._radiusAxis.contain(coord[0])
  50332. && this._angleAxis.contain(coord[1]);
  50333. },
  50334. /**
  50335. * If contain data
  50336. * @param {Array.<number>} data
  50337. * @return {boolean}
  50338. */
  50339. containData: function (data) {
  50340. return this._radiusAxis.containData(data[0])
  50341. && this._angleAxis.containData(data[1]);
  50342. },
  50343. /**
  50344. * @param {string} dim
  50345. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50346. */
  50347. getAxis: function (dim) {
  50348. return this['_' + dim + 'Axis'];
  50349. },
  50350. /**
  50351. * @return {Array.<module:echarts/coord/Axis>}
  50352. */
  50353. getAxes: function () {
  50354. return [this._radiusAxis, this._angleAxis];
  50355. },
  50356. /**
  50357. * Get axes by type of scale
  50358. * @param {string} scaleType
  50359. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50360. */
  50361. getAxesByScale: function (scaleType) {
  50362. var axes = [];
  50363. var angleAxis = this._angleAxis;
  50364. var radiusAxis = this._radiusAxis;
  50365. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  50366. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  50367. return axes;
  50368. },
  50369. /**
  50370. * @return {module:echarts/coord/polar/AngleAxis}
  50371. */
  50372. getAngleAxis: function () {
  50373. return this._angleAxis;
  50374. },
  50375. /**
  50376. * @return {module:echarts/coord/polar/RadiusAxis}
  50377. */
  50378. getRadiusAxis: function () {
  50379. return this._radiusAxis;
  50380. },
  50381. /**
  50382. * @param {module:echarts/coord/polar/Axis}
  50383. * @return {module:echarts/coord/polar/Axis}
  50384. */
  50385. getOtherAxis: function (axis) {
  50386. var angleAxis = this._angleAxis;
  50387. return axis === angleAxis ? this._radiusAxis : angleAxis;
  50388. },
  50389. /**
  50390. * Base axis will be used on stacking.
  50391. *
  50392. * @return {module:echarts/coord/polar/Axis}
  50393. */
  50394. getBaseAxis: function () {
  50395. return this.getAxesByScale('ordinal')[0]
  50396. || this.getAxesByScale('time')[0]
  50397. || this.getAngleAxis();
  50398. },
  50399. /**
  50400. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  50401. * @return {Object} {baseAxes: [], otherAxes: []}
  50402. */
  50403. getTooltipAxes: function (dim) {
  50404. var baseAxis = (dim != null && dim !== 'auto')
  50405. ? this.getAxis(dim) : this.getBaseAxis();
  50406. return {
  50407. baseAxes: [baseAxis],
  50408. otherAxes: [this.getOtherAxis(baseAxis)]
  50409. };
  50410. },
  50411. /**
  50412. * Convert a single data item to (x, y) point.
  50413. * Parameter data is an array which the first element is radius and the second is angle
  50414. * @param {Array.<number>} data
  50415. * @param {boolean} [clamp=false]
  50416. * @return {Array.<number>}
  50417. */
  50418. dataToPoint: function (data, clamp) {
  50419. return this.coordToPoint([
  50420. this._radiusAxis.dataToRadius(data[0], clamp),
  50421. this._angleAxis.dataToAngle(data[1], clamp)
  50422. ]);
  50423. },
  50424. /**
  50425. * Convert a (x, y) point to data
  50426. * @param {Array.<number>} point
  50427. * @param {boolean} [clamp=false]
  50428. * @return {Array.<number>}
  50429. */
  50430. pointToData: function (point, clamp) {
  50431. var coord = this.pointToCoord(point);
  50432. return [
  50433. this._radiusAxis.radiusToData(coord[0], clamp),
  50434. this._angleAxis.angleToData(coord[1], clamp)
  50435. ];
  50436. },
  50437. /**
  50438. * Convert a (x, y) point to (radius, angle) coord
  50439. * @param {Array.<number>} point
  50440. * @return {Array.<number>}
  50441. */
  50442. pointToCoord: function (point) {
  50443. var dx = point[0] - this.cx;
  50444. var dy = point[1] - this.cy;
  50445. var angleAxis = this.getAngleAxis();
  50446. var extent = angleAxis.getExtent();
  50447. var minAngle = Math.min(extent[0], extent[1]);
  50448. var maxAngle = Math.max(extent[0], extent[1]);
  50449. // Fix fixed extent in polarCreator
  50450. // FIXME
  50451. angleAxis.inverse
  50452. ? (minAngle = maxAngle - 360)
  50453. : (maxAngle = minAngle + 360);
  50454. var radius = Math.sqrt(dx * dx + dy * dy);
  50455. dx /= radius;
  50456. dy /= radius;
  50457. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  50458. // move to angleExtent
  50459. var dir = radian < minAngle ? 1 : -1;
  50460. while (radian < minAngle || radian > maxAngle) {
  50461. radian += dir * 360;
  50462. }
  50463. return [radius, radian];
  50464. },
  50465. /**
  50466. * Convert a (radius, angle) coord to (x, y) point
  50467. * @param {Array.<number>} coord
  50468. * @return {Array.<number>}
  50469. */
  50470. coordToPoint: function (coord) {
  50471. var radius = coord[0];
  50472. var radian = coord[1] / 180 * Math.PI;
  50473. var x = Math.cos(radian) * radius + this.cx;
  50474. // Inverse the y
  50475. var y = -Math.sin(radian) * radius + this.cy;
  50476. return [x, y];
  50477. }
  50478. };
  50479. var PolarAxisModel = ComponentModel.extend({
  50480. type: 'polarAxis',
  50481. /**
  50482. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50483. */
  50484. axis: null,
  50485. /**
  50486. * @override
  50487. */
  50488. getCoordSysModel: function () {
  50489. return this.ecModel.queryComponents({
  50490. mainType: 'polar',
  50491. index: this.option.polarIndex,
  50492. id: this.option.polarId
  50493. })[0];
  50494. }
  50495. });
  50496. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  50497. var polarAxisDefaultExtendedOption = {
  50498. angle: {
  50499. // polarIndex: 0,
  50500. // polarId: '',
  50501. startAngle: 90,
  50502. clockwise: true,
  50503. splitNumber: 12,
  50504. axisLabel: {
  50505. rotate: false
  50506. }
  50507. },
  50508. radius: {
  50509. // polarIndex: 0,
  50510. // polarId: '',
  50511. splitNumber: 5
  50512. }
  50513. };
  50514. function getAxisType$3(axisDim, option) {
  50515. // Default axis with data is category axis
  50516. return option.type || (option.data ? 'category' : 'value');
  50517. }
  50518. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  50519. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  50520. extendComponentModel({
  50521. type: 'polar',
  50522. dependencies: ['polarAxis', 'angleAxis'],
  50523. /**
  50524. * @type {module:echarts/coord/polar/Polar}
  50525. */
  50526. coordinateSystem: null,
  50527. /**
  50528. * @param {string} axisType
  50529. * @return {module:echarts/coord/polar/AxisModel}
  50530. */
  50531. findAxisModel: function (axisType) {
  50532. var foundAxisModel;
  50533. var ecModel = this.ecModel;
  50534. ecModel.eachComponent(axisType, function (axisModel) {
  50535. if (axisModel.getCoordSysModel() === this) {
  50536. foundAxisModel = axisModel;
  50537. }
  50538. }, this);
  50539. return foundAxisModel;
  50540. },
  50541. defaultOption: {
  50542. zlevel: 0,
  50543. z: 0,
  50544. center: ['50%', '50%'],
  50545. radius: '80%'
  50546. }
  50547. });
  50548. // TODO Axis scale
  50549. // 依赖 PolarModel 做预处理
  50550. /**
  50551. * Resize method bound to the polar
  50552. * @param {module:echarts/coord/polar/PolarModel} polarModel
  50553. * @param {module:echarts/ExtensionAPI} api
  50554. */
  50555. function resizePolar(polar, polarModel, api) {
  50556. var center = polarModel.get('center');
  50557. var width = api.getWidth();
  50558. var height = api.getHeight();
  50559. polar.cx = parsePercent$1(center[0], width);
  50560. polar.cy = parsePercent$1(center[1], height);
  50561. var radiusAxis = polar.getRadiusAxis();
  50562. var size = Math.min(width, height) / 2;
  50563. var radius = parsePercent$1(polarModel.get('radius'), size);
  50564. radiusAxis.inverse
  50565. ? radiusAxis.setExtent(radius, 0)
  50566. : radiusAxis.setExtent(0, radius);
  50567. }
  50568. /**
  50569. * Update polar
  50570. */
  50571. function updatePolarScale(ecModel, api) {
  50572. var polar = this;
  50573. var angleAxis = polar.getAngleAxis();
  50574. var radiusAxis = polar.getRadiusAxis();
  50575. // Reset scale
  50576. angleAxis.scale.setExtent(Infinity, -Infinity);
  50577. radiusAxis.scale.setExtent(Infinity, -Infinity);
  50578. ecModel.eachSeries(function (seriesModel) {
  50579. if (seriesModel.coordinateSystem === polar) {
  50580. var data = seriesModel.getData();
  50581. radiusAxis.scale.unionExtentFromData(data, 'radius');
  50582. angleAxis.scale.unionExtentFromData(data, 'angle');
  50583. }
  50584. });
  50585. niceScaleExtent(angleAxis.scale, angleAxis.model);
  50586. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  50587. // Fix extent of category angle axis
  50588. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  50589. var extent = angleAxis.getExtent();
  50590. var diff = 360 / angleAxis.scale.count();
  50591. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  50592. angleAxis.setExtent(extent[0], extent[1]);
  50593. }
  50594. }
  50595. /**
  50596. * Set common axis properties
  50597. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  50598. * @param {module:echarts/coord/polar/AxisModel}
  50599. * @inner
  50600. */
  50601. function setAxis(axis, axisModel) {
  50602. axis.type = axisModel.get('type');
  50603. axis.scale = createScaleByModel(axisModel);
  50604. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  50605. axis.inverse = axisModel.get('inverse');
  50606. if (axisModel.mainType === 'angleAxis') {
  50607. axis.inverse ^= axisModel.get('clockwise');
  50608. var startAngle = axisModel.get('startAngle');
  50609. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  50610. }
  50611. // Inject axis instance
  50612. axisModel.axis = axis;
  50613. axis.model = axisModel;
  50614. }
  50615. var polarCreator = {
  50616. dimensions: Polar.prototype.dimensions,
  50617. create: function (ecModel, api) {
  50618. var polarList = [];
  50619. ecModel.eachComponent('polar', function (polarModel, idx) {
  50620. var polar = new Polar(idx);
  50621. // Inject resize and update method
  50622. polar.update = updatePolarScale;
  50623. var radiusAxis = polar.getRadiusAxis();
  50624. var angleAxis = polar.getAngleAxis();
  50625. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  50626. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  50627. setAxis(radiusAxis, radiusAxisModel);
  50628. setAxis(angleAxis, angleAxisModel);
  50629. resizePolar(polar, polarModel, api);
  50630. polarList.push(polar);
  50631. polarModel.coordinateSystem = polar;
  50632. polar.model = polarModel;
  50633. });
  50634. // Inject coordinateSystem to series
  50635. ecModel.eachSeries(function (seriesModel) {
  50636. if (seriesModel.get('coordinateSystem') === 'polar') {
  50637. var polarModel = ecModel.queryComponents({
  50638. mainType: 'polar',
  50639. index: seriesModel.get('polarIndex'),
  50640. id: seriesModel.get('polarId')
  50641. })[0];
  50642. if (__DEV__) {
  50643. if (!polarModel) {
  50644. throw new Error(
  50645. 'Polar "' + retrieve(
  50646. seriesModel.get('polarIndex'),
  50647. seriesModel.get('polarId'),
  50648. 0
  50649. ) + '" not found'
  50650. );
  50651. }
  50652. }
  50653. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  50654. }
  50655. });
  50656. return polarList;
  50657. }
  50658. };
  50659. CoordinateSystemManager.register('polar', polarCreator);
  50660. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  50661. function getAxisLineShape(polar, rExtent, angle) {
  50662. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  50663. var start = polar.coordToPoint([rExtent[0], angle]);
  50664. var end = polar.coordToPoint([rExtent[1], angle]);
  50665. return {
  50666. x1: start[0],
  50667. y1: start[1],
  50668. x2: end[0],
  50669. y2: end[1]
  50670. };
  50671. }
  50672. function getRadiusIdx(polar) {
  50673. var radiusAxis = polar.getRadiusAxis();
  50674. return radiusAxis.inverse ? 0 : 1;
  50675. }
  50676. AxisView.extend({
  50677. type: 'angleAxis',
  50678. axisPointerClass: 'PolarAxisPointer',
  50679. render: function (angleAxisModel, ecModel) {
  50680. this.group.removeAll();
  50681. if (!angleAxisModel.get('show')) {
  50682. return;
  50683. }
  50684. var angleAxis = angleAxisModel.axis;
  50685. var polar = angleAxis.polar;
  50686. var radiusExtent = polar.getRadiusAxis().getExtent();
  50687. var ticksAngles = angleAxis.getTicksCoords();
  50688. if (angleAxis.type !== 'category') {
  50689. // Remove the last tick which will overlap the first tick
  50690. ticksAngles.pop();
  50691. }
  50692. each$1(elementList$1, function (name) {
  50693. if (angleAxisModel.get(name +'.show')
  50694. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  50695. ) {
  50696. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent);
  50697. }
  50698. }, this);
  50699. },
  50700. /**
  50701. * @private
  50702. */
  50703. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50704. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  50705. var circle = new Circle({
  50706. shape: {
  50707. cx: polar.cx,
  50708. cy: polar.cy,
  50709. r: radiusExtent[getRadiusIdx(polar)]
  50710. },
  50711. style: lineStyleModel.getLineStyle(),
  50712. z2: 1,
  50713. silent: true
  50714. });
  50715. circle.style.fill = null;
  50716. this.group.add(circle);
  50717. },
  50718. /**
  50719. * @private
  50720. */
  50721. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50722. var tickModel = angleAxisModel.getModel('axisTick');
  50723. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  50724. var radius = radiusExtent[getRadiusIdx(polar)];
  50725. var lines = map(ticksAngles, function (tickAngle) {
  50726. return new Line({
  50727. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngle)
  50728. });
  50729. });
  50730. this.group.add(mergePath(
  50731. lines, {
  50732. style: defaults(
  50733. tickModel.getModel('lineStyle').getLineStyle(),
  50734. {
  50735. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  50736. }
  50737. )
  50738. }
  50739. ));
  50740. },
  50741. /**
  50742. * @private
  50743. */
  50744. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50745. var axis = angleAxisModel.axis;
  50746. var categoryData = angleAxisModel.get('data');
  50747. var labelModel = angleAxisModel.getModel('axisLabel');
  50748. var labels = angleAxisModel.getFormattedLabels();
  50749. var labelMargin = labelModel.get('margin');
  50750. var labelsAngles = axis.getLabelsCoords();
  50751. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  50752. for (var i = 0; i < ticksAngles.length; i++) {
  50753. var r = radiusExtent[getRadiusIdx(polar)];
  50754. var p = polar.coordToPoint([r + labelMargin, labelsAngles[i]]);
  50755. var cx = polar.cx;
  50756. var cy = polar.cy;
  50757. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  50758. ? 'center' : (p[0] > cx ? 'left' : 'right');
  50759. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  50760. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  50761. if (categoryData && categoryData[i] && categoryData[i].textStyle) {
  50762. labelModel = new Model(categoryData[i].textStyle, labelModel, labelModel.ecModel);
  50763. }
  50764. var textEl = new Text({silent: true});
  50765. this.group.add(textEl);
  50766. setTextStyle(textEl.style, labelModel, {
  50767. x: p[0],
  50768. y: p[1],
  50769. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  50770. text: labels[i],
  50771. textAlign: labelTextAlign,
  50772. textVerticalAlign: labelTextVerticalAlign
  50773. });
  50774. }
  50775. },
  50776. /**
  50777. * @private
  50778. */
  50779. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50780. var splitLineModel = angleAxisModel.getModel('splitLine');
  50781. var lineStyleModel = splitLineModel.getModel('lineStyle');
  50782. var lineColors = lineStyleModel.get('color');
  50783. var lineCount = 0;
  50784. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  50785. var splitLines = [];
  50786. for (var i = 0; i < ticksAngles.length; i++) {
  50787. var colorIndex = (lineCount++) % lineColors.length;
  50788. splitLines[colorIndex] = splitLines[colorIndex] || [];
  50789. splitLines[colorIndex].push(new Line({
  50790. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i])
  50791. }));
  50792. }
  50793. // Simple optimization
  50794. // Batching the lines if color are the same
  50795. for (var i = 0; i < splitLines.length; i++) {
  50796. this.group.add(mergePath(splitLines[i], {
  50797. style: defaults({
  50798. stroke: lineColors[i % lineColors.length]
  50799. }, lineStyleModel.getLineStyle()),
  50800. silent: true,
  50801. z: angleAxisModel.get('z')
  50802. }));
  50803. }
  50804. },
  50805. /**
  50806. * @private
  50807. */
  50808. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  50809. var splitAreaModel = angleAxisModel.getModel('splitArea');
  50810. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  50811. var areaColors = areaStyleModel.get('color');
  50812. var lineCount = 0;
  50813. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  50814. var splitAreas = [];
  50815. var RADIAN = Math.PI / 180;
  50816. var prevAngle = -ticksAngles[0] * RADIAN;
  50817. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  50818. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  50819. var clockwise = angleAxisModel.get('clockwise');
  50820. for (var i = 1; i < ticksAngles.length; i++) {
  50821. var colorIndex = (lineCount++) % areaColors.length;
  50822. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  50823. splitAreas[colorIndex].push(new Sector({
  50824. shape: {
  50825. cx: polar.cx,
  50826. cy: polar.cy,
  50827. r0: r0,
  50828. r: r1,
  50829. startAngle: prevAngle,
  50830. endAngle: -ticksAngles[i] * RADIAN,
  50831. clockwise: clockwise
  50832. },
  50833. silent: true
  50834. }));
  50835. prevAngle = -ticksAngles[i] * RADIAN;
  50836. }
  50837. // Simple optimization
  50838. // Batching the lines if color are the same
  50839. for (var i = 0; i < splitAreas.length; i++) {
  50840. this.group.add(mergePath(splitAreas[i], {
  50841. style: defaults({
  50842. fill: areaColors[i % areaColors.length]
  50843. }, areaStyleModel.getAreaStyle()),
  50844. silent: true
  50845. }));
  50846. }
  50847. }
  50848. });
  50849. var axisBuilderAttrs$3 = [
  50850. 'axisLine', 'axisTickLabel', 'axisName'
  50851. ];
  50852. var selfBuilderAttrs$1 = [
  50853. 'splitLine', 'splitArea'
  50854. ];
  50855. AxisView.extend({
  50856. type: 'radiusAxis',
  50857. axisPointerClass: 'PolarAxisPointer',
  50858. render: function (radiusAxisModel, ecModel) {
  50859. this.group.removeAll();
  50860. if (!radiusAxisModel.get('show')) {
  50861. return;
  50862. }
  50863. var radiusAxis = radiusAxisModel.axis;
  50864. var polar = radiusAxis.polar;
  50865. var angleAxis = polar.getAngleAxis();
  50866. var ticksCoords = radiusAxis.getTicksCoords();
  50867. var axisAngle = angleAxis.getExtent()[0];
  50868. var radiusExtent = radiusAxis.getExtent();
  50869. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  50870. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  50871. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  50872. this.group.add(axisBuilder.getGroup());
  50873. each$1(selfBuilderAttrs$1, function (name) {
  50874. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  50875. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  50876. }
  50877. }, this);
  50878. },
  50879. /**
  50880. * @private
  50881. */
  50882. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  50883. var splitLineModel = radiusAxisModel.getModel('splitLine');
  50884. var lineStyleModel = splitLineModel.getModel('lineStyle');
  50885. var lineColors = lineStyleModel.get('color');
  50886. var lineCount = 0;
  50887. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  50888. var splitLines = [];
  50889. for (var i = 0; i < ticksCoords.length; i++) {
  50890. var colorIndex = (lineCount++) % lineColors.length;
  50891. splitLines[colorIndex] = splitLines[colorIndex] || [];
  50892. splitLines[colorIndex].push(new Circle({
  50893. shape: {
  50894. cx: polar.cx,
  50895. cy: polar.cy,
  50896. r: ticksCoords[i]
  50897. },
  50898. silent: true
  50899. }));
  50900. }
  50901. // Simple optimization
  50902. // Batching the lines if color are the same
  50903. for (var i = 0; i < splitLines.length; i++) {
  50904. this.group.add(mergePath(splitLines[i], {
  50905. style: defaults({
  50906. stroke: lineColors[i % lineColors.length],
  50907. fill: null
  50908. }, lineStyleModel.getLineStyle()),
  50909. silent: true
  50910. }));
  50911. }
  50912. },
  50913. /**
  50914. * @private
  50915. */
  50916. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  50917. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  50918. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  50919. var areaColors = areaStyleModel.get('color');
  50920. var lineCount = 0;
  50921. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  50922. var splitAreas = [];
  50923. var prevRadius = ticksCoords[0];
  50924. for (var i = 1; i < ticksCoords.length; i++) {
  50925. var colorIndex = (lineCount++) % areaColors.length;
  50926. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  50927. splitAreas[colorIndex].push(new Sector({
  50928. shape: {
  50929. cx: polar.cx,
  50930. cy: polar.cy,
  50931. r0: prevRadius,
  50932. r: ticksCoords[i],
  50933. startAngle: 0,
  50934. endAngle: Math.PI * 2
  50935. },
  50936. silent: true
  50937. }));
  50938. prevRadius = ticksCoords[i];
  50939. }
  50940. // Simple optimization
  50941. // Batching the lines if color are the same
  50942. for (var i = 0; i < splitAreas.length; i++) {
  50943. this.group.add(mergePath(splitAreas[i], {
  50944. style: defaults({
  50945. fill: areaColors[i % areaColors.length]
  50946. }, areaStyleModel.getAreaStyle()),
  50947. silent: true
  50948. }));
  50949. }
  50950. }
  50951. });
  50952. /**
  50953. * @inner
  50954. */
  50955. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  50956. return {
  50957. position: [polar.cx, polar.cy],
  50958. rotation: axisAngle / 180 * Math.PI,
  50959. labelDirection: -1,
  50960. tickDirection: -1,
  50961. nameDirection: 1,
  50962. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  50963. // Over splitLine and splitArea
  50964. z2: 1
  50965. };
  50966. }
  50967. var PolarAxisPointer = BaseAxisPointer.extend({
  50968. /**
  50969. * @override
  50970. */
  50971. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50972. var axis = axisModel.axis;
  50973. if (axis.dim === 'angle') {
  50974. this.animationThreshold = Math.PI / 18;
  50975. }
  50976. var polar = axis.polar;
  50977. var otherAxis = polar.getOtherAxis(axis);
  50978. var otherExtent = otherAxis.getExtent();
  50979. var coordValue;
  50980. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  50981. var axisPointerType = axisPointerModel.get('type');
  50982. if (axisPointerType && axisPointerType !== 'none') {
  50983. var elStyle = buildElStyle(axisPointerModel);
  50984. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  50985. axis, polar, coordValue, otherExtent, elStyle
  50986. );
  50987. pointerOption.style = elStyle;
  50988. elOption.graphicKey = pointerOption.type;
  50989. elOption.pointer = pointerOption;
  50990. }
  50991. var labelMargin = axisPointerModel.get('label.margin');
  50992. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  50993. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  50994. }
  50995. // Do not support handle, utill any user requires it.
  50996. });
  50997. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  50998. var axis = axisModel.axis;
  50999. var coord = axis.dataToCoord(value);
  51000. var axisAngle = polar.getAngleAxis().getExtent()[0];
  51001. axisAngle = axisAngle / 180 * Math.PI;
  51002. var radiusExtent = polar.getRadiusAxis().getExtent();
  51003. var position;
  51004. var align;
  51005. var verticalAlign;
  51006. if (axis.dim === 'radius') {
  51007. var transform = create$1();
  51008. rotate(transform, transform, axisAngle);
  51009. translate(transform, transform, [polar.cx, polar.cy]);
  51010. position = applyTransform$1([coord, -labelMargin], transform);
  51011. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  51012. var labelLayout = AxisBuilder.innerTextLayout(
  51013. axisAngle, labelRotation * Math.PI / 180, -1
  51014. );
  51015. align = labelLayout.textAlign;
  51016. verticalAlign = labelLayout.textVerticalAlign;
  51017. }
  51018. else { // angle axis
  51019. var r = radiusExtent[1];
  51020. position = polar.coordToPoint([r + labelMargin, coord]);
  51021. var cx = polar.cx;
  51022. var cy = polar.cy;
  51023. align = Math.abs(position[0] - cx) / r < 0.3
  51024. ? 'center' : (position[0] > cx ? 'left' : 'right');
  51025. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  51026. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  51027. }
  51028. return {
  51029. position: position,
  51030. align: align,
  51031. verticalAlign: verticalAlign
  51032. };
  51033. }
  51034. var pointerShapeBuilder$2 = {
  51035. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  51036. return axis.dim === 'angle'
  51037. ? {
  51038. type: 'Line',
  51039. shape: makeLineShape(
  51040. polar.coordToPoint([otherExtent[0], coordValue]),
  51041. polar.coordToPoint([otherExtent[1], coordValue])
  51042. )
  51043. }
  51044. : {
  51045. type: 'Circle',
  51046. shape: {
  51047. cx: polar.cx,
  51048. cy: polar.cy,
  51049. r: coordValue
  51050. }
  51051. };
  51052. },
  51053. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  51054. var bandWidth = axis.getBandWidth();
  51055. var radian = Math.PI / 180;
  51056. return axis.dim === 'angle'
  51057. ? {
  51058. type: 'Sector',
  51059. shape: makeSectorShape(
  51060. polar.cx, polar.cy,
  51061. otherExtent[0], otherExtent[1],
  51062. // In ECharts y is negative if angle is positive
  51063. (-coordValue - bandWidth / 2) * radian,
  51064. (-coordValue + bandWidth / 2) * radian
  51065. )
  51066. }
  51067. : {
  51068. type: 'Sector',
  51069. shape: makeSectorShape(
  51070. polar.cx, polar.cy,
  51071. coordValue - bandWidth / 2,
  51072. coordValue + bandWidth / 2,
  51073. 0, Math.PI * 2
  51074. )
  51075. };
  51076. }
  51077. };
  51078. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  51079. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  51080. registerLayout(curry(barLayoutPolar, 'bar'));
  51081. // Polar view
  51082. extendComponentView({
  51083. type: 'polar'
  51084. });
  51085. var GeoModel = ComponentModel.extend({
  51086. type: 'geo',
  51087. /**
  51088. * @type {module:echarts/coord/geo/Geo}
  51089. */
  51090. coordinateSystem: null,
  51091. layoutMode: 'box',
  51092. init: function (option) {
  51093. ComponentModel.prototype.init.apply(this, arguments);
  51094. // Default label emphasis `show`
  51095. defaultEmphasis(option.label, ['show']);
  51096. },
  51097. optionUpdated: function () {
  51098. var option = this.option;
  51099. var self = this;
  51100. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  51101. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  51102. if (regionOpt.name) {
  51103. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  51104. }
  51105. return optionModelMap;
  51106. }, createHashMap());
  51107. this.updateSelectedMap(option.regions);
  51108. },
  51109. defaultOption: {
  51110. zlevel: 0,
  51111. z: 0,
  51112. show: true,
  51113. left: 'center',
  51114. top: 'center',
  51115. // width:,
  51116. // height:,
  51117. // right
  51118. // bottom
  51119. // Aspect is width / height. Inited to be geoJson bbox aspect
  51120. // This parameter is used for scale this aspect
  51121. aspectScale: 0.75,
  51122. ///// Layout with center and size
  51123. // If you wan't to put map in a fixed size box with right aspect ratio
  51124. // This two properties may more conveninet
  51125. // layoutCenter: [50%, 50%]
  51126. // layoutSize: 100
  51127. silent: false,
  51128. // Map type
  51129. map: '',
  51130. // Define left-top, right-bottom coords to control view
  51131. // For example, [ [180, 90], [-180, -90] ]
  51132. boundingCoords: null,
  51133. // Default on center of map
  51134. center: null,
  51135. zoom: 1,
  51136. scaleLimit: null,
  51137. // selectedMode: false
  51138. label: {
  51139. normal: {
  51140. show: false,
  51141. color: '#000'
  51142. },
  51143. emphasis: {
  51144. show: true,
  51145. color: 'rgb(100,0,0)'
  51146. }
  51147. },
  51148. itemStyle: {
  51149. normal: {
  51150. // color: 各异,
  51151. borderWidth: 0.5,
  51152. borderColor: '#444',
  51153. color: '#eee'
  51154. },
  51155. emphasis: { // 也是选中样式
  51156. color: 'rgba(255,215,0,0.8)'
  51157. }
  51158. },
  51159. regions: []
  51160. },
  51161. /**
  51162. * Get model of region
  51163. * @param {string} name
  51164. * @return {module:echarts/model/Model}
  51165. */
  51166. getRegionModel: function (name) {
  51167. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  51168. },
  51169. /**
  51170. * Format label
  51171. * @param {string} name Region name
  51172. * @param {string} [status='normal'] 'normal' or 'emphasis'
  51173. * @return {string}
  51174. */
  51175. getFormattedLabel: function (name, status) {
  51176. var regionModel = this.getRegionModel(name);
  51177. var formatter = regionModel.get('label.' + status + '.formatter');
  51178. var params = {
  51179. name: name
  51180. };
  51181. if (typeof formatter === 'function') {
  51182. params.status = status;
  51183. return formatter(params);
  51184. }
  51185. else if (typeof formatter === 'string') {
  51186. return formatter.replace('{a}', name != null ? name : '');
  51187. }
  51188. },
  51189. setZoom: function (zoom) {
  51190. this.option.zoom = zoom;
  51191. },
  51192. setCenter: function (center) {
  51193. this.option.center = center;
  51194. }
  51195. });
  51196. mixin(GeoModel, selectableMixin);
  51197. extendComponentView({
  51198. type: 'geo',
  51199. init: function (ecModel, api) {
  51200. var mapDraw = new MapDraw(api, true);
  51201. this._mapDraw = mapDraw;
  51202. this.group.add(mapDraw.group);
  51203. },
  51204. render: function (geoModel, ecModel, api, payload) {
  51205. // Not render if it is an toggleSelect action from self
  51206. if (payload && payload.type === 'geoToggleSelect'
  51207. && payload.from === this.uid
  51208. ) {
  51209. return;
  51210. }
  51211. var mapDraw = this._mapDraw;
  51212. if (geoModel.get('show')) {
  51213. mapDraw.draw(geoModel, ecModel, api, this, payload);
  51214. }
  51215. else {
  51216. this._mapDraw.group.removeAll();
  51217. }
  51218. this.group.silent = geoModel.get('silent');
  51219. },
  51220. dispose: function () {
  51221. this._mapDraw && this._mapDraw.remove();
  51222. }
  51223. });
  51224. function makeAction(method, actionInfo) {
  51225. actionInfo.update = 'updateView';
  51226. registerAction(actionInfo, function (payload, ecModel) {
  51227. var selected = {};
  51228. ecModel.eachComponent(
  51229. { mainType: 'geo', query: payload},
  51230. function (geoModel) {
  51231. geoModel[method](payload.name);
  51232. var geo = geoModel.coordinateSystem;
  51233. each$1(geo.regions, function (region) {
  51234. selected[region.name] = geoModel.isSelected(region.name) || false;
  51235. });
  51236. }
  51237. );
  51238. return {
  51239. selected: selected,
  51240. name: payload.name
  51241. };
  51242. });
  51243. }
  51244. makeAction('toggleSelected', {
  51245. type: 'geoToggleSelect',
  51246. event: 'geoselectchanged'
  51247. });
  51248. makeAction('select', {
  51249. type: 'geoSelect',
  51250. event: 'geoselected'
  51251. });
  51252. makeAction('unSelect', {
  51253. type: 'geoUnSelect',
  51254. event: 'geounselected'
  51255. });
  51256. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  51257. var preprocessor$1 = function (option, isNew) {
  51258. var brushComponents = option && option.brush;
  51259. if (!isArray(brushComponents)) {
  51260. brushComponents = brushComponents ? [brushComponents] : [];
  51261. }
  51262. if (!brushComponents.length) {
  51263. return;
  51264. }
  51265. var brushComponentSpecifiedBtns = [];
  51266. each$1(brushComponents, function (brushOpt) {
  51267. var tbs = brushOpt.hasOwnProperty('toolbox')
  51268. ? brushOpt.toolbox : [];
  51269. if (tbs instanceof Array) {
  51270. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  51271. }
  51272. });
  51273. var toolbox = option && option.toolbox;
  51274. if (isArray(toolbox)) {
  51275. toolbox = toolbox[0];
  51276. }
  51277. if (!toolbox) {
  51278. toolbox = {feature: {}};
  51279. option.toolbox = [toolbox];
  51280. }
  51281. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  51282. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  51283. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  51284. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  51285. removeDuplicate(brushTypes);
  51286. if (isNew && !brushTypes.length) {
  51287. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  51288. }
  51289. };
  51290. function removeDuplicate(arr) {
  51291. var map$$1 = {};
  51292. each$1(arr, function (val) {
  51293. map$$1[val] = 1;
  51294. });
  51295. arr.length = 0;
  51296. each$1(map$$1, function (flag, val) {
  51297. arr.push(val);
  51298. });
  51299. }
  51300. /**
  51301. * @file Visual solution, for consistent option specification.
  51302. */
  51303. var each$22 = each$1;
  51304. function hasKeys(obj) {
  51305. if (obj) {
  51306. for (var name in obj){
  51307. if (obj.hasOwnProperty(name)) {
  51308. return true;
  51309. }
  51310. }
  51311. }
  51312. }
  51313. /**
  51314. * @param {Object} option
  51315. * @param {Array.<string>} stateList
  51316. * @param {Function} [supplementVisualOption]
  51317. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  51318. */
  51319. function createVisualMappings(option, stateList, supplementVisualOption) {
  51320. var visualMappings = {};
  51321. each$22(stateList, function (state) {
  51322. var mappings = visualMappings[state] = createMappings();
  51323. each$22(option[state], function (visualData, visualType) {
  51324. if (!VisualMapping.isValidType(visualType)) {
  51325. return;
  51326. }
  51327. var mappingOption = {
  51328. type: visualType,
  51329. visual: visualData
  51330. };
  51331. supplementVisualOption && supplementVisualOption(mappingOption, state);
  51332. mappings[visualType] = new VisualMapping(mappingOption);
  51333. // Prepare a alpha for opacity, for some case that opacity
  51334. // is not supported, such as rendering using gradient color.
  51335. if (visualType === 'opacity') {
  51336. mappingOption = clone(mappingOption);
  51337. mappingOption.type = 'colorAlpha';
  51338. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  51339. }
  51340. });
  51341. });
  51342. return visualMappings;
  51343. function createMappings() {
  51344. var Creater = function () {};
  51345. // Make sure hidden fields will not be visited by
  51346. // object iteration (with hasOwnProperty checking).
  51347. Creater.prototype.__hidden = Creater.prototype;
  51348. var obj = new Creater();
  51349. return obj;
  51350. }
  51351. }
  51352. /**
  51353. * @param {Object} thisOption
  51354. * @param {Object} newOption
  51355. * @param {Array.<string>} keys
  51356. */
  51357. function replaceVisualOption(thisOption, newOption, keys) {
  51358. // Visual attributes merge is not supported, otherwise it
  51359. // brings overcomplicated merge logic. See #2853. So if
  51360. // newOption has anyone of these keys, all of these keys
  51361. // will be reset. Otherwise, all keys remain.
  51362. var has;
  51363. each$1(keys, function (key) {
  51364. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  51365. has = true;
  51366. }
  51367. });
  51368. has && each$1(keys, function (key) {
  51369. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  51370. thisOption[key] = clone(newOption[key]);
  51371. }
  51372. else {
  51373. delete thisOption[key];
  51374. }
  51375. });
  51376. }
  51377. /**
  51378. * @param {Array.<string>} stateList
  51379. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  51380. * @param {module:echarts/data/List} list
  51381. * @param {Function} getValueState param: valueOrIndex, return: state.
  51382. * @param {object} [scope] Scope for getValueState
  51383. * @param {string} [dimension] Concrete dimension, if used.
  51384. */
  51385. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  51386. var visualTypesMap = {};
  51387. each$1(stateList, function (state) {
  51388. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  51389. visualTypesMap[state] = visualTypes;
  51390. });
  51391. var dataIndex;
  51392. function getVisual(key) {
  51393. return data.getItemVisual(dataIndex, key);
  51394. }
  51395. function setVisual(key, value) {
  51396. data.setItemVisual(dataIndex, key, value);
  51397. }
  51398. if (dimension == null) {
  51399. data.each(eachItem, true);
  51400. }
  51401. else {
  51402. data.each([dimension], eachItem, true);
  51403. }
  51404. function eachItem(valueOrIndex, index) {
  51405. dataIndex = dimension == null ? valueOrIndex : index;
  51406. var rawDataItem = data.getRawDataItem(dataIndex);
  51407. // Consider performance
  51408. if (rawDataItem && rawDataItem.visualMap === false) {
  51409. return;
  51410. }
  51411. var valueState = getValueState.call(scope, valueOrIndex);
  51412. var mappings = visualMappings[valueState];
  51413. var visualTypes = visualTypesMap[valueState];
  51414. for (var i = 0, len = visualTypes.length; i < len; i++) {
  51415. var type = visualTypes[i];
  51416. mappings[type] && mappings[type].applyVisual(
  51417. valueOrIndex, getVisual, setVisual
  51418. );
  51419. }
  51420. }
  51421. }
  51422. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  51423. // Key of the second level is chart element type: `point`, `rect`.
  51424. // See moudule:echarts/component/helper/BrushController
  51425. // function param:
  51426. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  51427. // {Object} selectors {point: selector, rect: selector, ...}
  51428. // {Object} area {range: [[], [], ..], boudingRect}
  51429. // function return:
  51430. // {boolean} Whether in the given brush.
  51431. var selector = {
  51432. lineX: getLineSelectors(0),
  51433. lineY: getLineSelectors(1),
  51434. rect: {
  51435. point: function (itemLayout, selectors, area) {
  51436. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  51437. },
  51438. rect: function (itemLayout, selectors, area) {
  51439. return itemLayout && area.boundingRect.intersect(itemLayout);
  51440. }
  51441. },
  51442. polygon: {
  51443. point: function (itemLayout, selectors, area) {
  51444. return itemLayout
  51445. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  51446. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  51447. },
  51448. rect: function (itemLayout, selectors, area) {
  51449. var points = area.range;
  51450. if (!itemLayout || points.length <= 1) {
  51451. return false;
  51452. }
  51453. var x = itemLayout.x;
  51454. var y = itemLayout.y;
  51455. var width = itemLayout.width;
  51456. var height = itemLayout.height;
  51457. var p = points[0];
  51458. if (contain$1(points, x, y)
  51459. || contain$1(points, x + width, y)
  51460. || contain$1(points, x, y + height)
  51461. || contain$1(points, x + width, y + height)
  51462. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  51463. || lineIntersectPolygon(x, y, x + width, y, points)
  51464. || lineIntersectPolygon(x, y, x, y + height, points)
  51465. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  51466. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  51467. ) {
  51468. return true;
  51469. }
  51470. }
  51471. }
  51472. };
  51473. function getLineSelectors(xyIndex) {
  51474. var xy = ['x', 'y'];
  51475. var wh = ['width', 'height'];
  51476. return {
  51477. point: function (itemLayout, selectors, area) {
  51478. if (itemLayout) {
  51479. var range = area.range;
  51480. var p = itemLayout[xyIndex];
  51481. return inLineRange(p, range);
  51482. }
  51483. },
  51484. rect: function (itemLayout, selectors, area) {
  51485. if (itemLayout) {
  51486. var range = area.range;
  51487. var layoutRange = [
  51488. itemLayout[xy[xyIndex]],
  51489. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  51490. ];
  51491. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  51492. return inLineRange(layoutRange[0], range)
  51493. || inLineRange(layoutRange[1], range)
  51494. || inLineRange(range[0], layoutRange)
  51495. || inLineRange(range[1], layoutRange);
  51496. }
  51497. }
  51498. };
  51499. }
  51500. function inLineRange(p, range) {
  51501. return range[0] <= p && p <= range[1];
  51502. }
  51503. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  51504. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  51505. var p = points[i];
  51506. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  51507. return true;
  51508. }
  51509. p2 = p;
  51510. }
  51511. }
  51512. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  51513. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  51514. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  51515. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  51516. if (nearZero(delta)) { // parallel
  51517. return false;
  51518. }
  51519. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  51520. if (namenda < 0 || namenda > 1) {
  51521. return false;
  51522. }
  51523. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  51524. if (miu < 0 || miu > 1) {
  51525. return false;
  51526. }
  51527. return true;
  51528. }
  51529. function nearZero(val) {
  51530. return val <= (1e-6) && val >= -(1e-6);
  51531. }
  51532. function determinant(v1, v2, v3, v4) {
  51533. return v1 * v4 - v2 * v3;
  51534. }
  51535. var each$23 = each$1;
  51536. var indexOf$2 = indexOf;
  51537. var curry$5 = curry;
  51538. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  51539. // FIXME
  51540. // how to genarialize to more coordinate systems.
  51541. var INCLUDE_FINDER_MAIN_TYPES = [
  51542. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  51543. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  51544. ];
  51545. /**
  51546. * [option in constructor]:
  51547. * {
  51548. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51549. * }
  51550. *
  51551. *
  51552. * [targetInfo]:
  51553. *
  51554. * There can be multiple axes in a single targetInfo. Consider the case
  51555. * of `grid` component, a targetInfo represents a grid which contains one or more
  51556. * cartesian and one or more axes. And consider the case of parallel system,
  51557. * which has multiple axes in a coordinate system.
  51558. * Can be {
  51559. * panelId: ...,
  51560. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  51561. * coordSyses: all cartesians.
  51562. * gridModel: <grid component>
  51563. * xAxes: correspond to coordSyses on index
  51564. * yAxes: correspond to coordSyses on index
  51565. * }
  51566. * or {
  51567. * panelId: ...,
  51568. * coordSys: <geo coord sys>
  51569. * coordSyses: [<geo coord sys>]
  51570. * geoModel: <geo component>
  51571. * }
  51572. *
  51573. *
  51574. * [panelOpt]:
  51575. *
  51576. * Make from targetInfo. Input to BrushController.
  51577. * {
  51578. * panelId: ...,
  51579. * rect: ...
  51580. * }
  51581. *
  51582. *
  51583. * [area]:
  51584. *
  51585. * Generated by BrushController or user input.
  51586. * {
  51587. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  51588. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  51589. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  51590. * range: pixel range.
  51591. * coordRange: representitive coord range (the first one of coordRanges).
  51592. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  51593. * }
  51594. */
  51595. /**
  51596. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  51597. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  51598. * @param {module:echarts/model/Global} ecModel
  51599. * @param {Object} [opt]
  51600. * @param {Array.<string>} [opt.include] include coordinate system types.
  51601. */
  51602. function BrushTargetManager(option, ecModel, opt) {
  51603. /**
  51604. * @private
  51605. * @type {Array.<Object>}
  51606. */
  51607. var targetInfoList = this._targetInfoList = [];
  51608. var info = {};
  51609. var foundCpts = parseFinder$1(ecModel, option);
  51610. each$23(targetInfoBuilders, function (builder, type) {
  51611. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  51612. builder(foundCpts, targetInfoList, info);
  51613. }
  51614. });
  51615. }
  51616. var proto = BrushTargetManager.prototype;
  51617. proto.setOutputRanges = function (areas, ecModel) {
  51618. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  51619. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  51620. // area.coordRange is the first of area.coordRanges
  51621. if (!area.coordRange) {
  51622. area.coordRange = coordRange;
  51623. // In 'category' axis, coord to pixel is not reversible, so we can not
  51624. // rebuild range by coordRange accrately, which may bring trouble when
  51625. // brushing only one item. So we use __rangeOffset to rebuilding range
  51626. // by coordRange. And this it only used in brush component so it is no
  51627. // need to be adapted to coordRanges.
  51628. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  51629. area.__rangeOffset = {
  51630. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  51631. xyMinMax: result.xyMinMax
  51632. };
  51633. }
  51634. });
  51635. };
  51636. proto.matchOutputRanges = function (areas, ecModel, cb) {
  51637. each$23(areas, function (area) {
  51638. var targetInfo = this.findTargetInfo(area, ecModel);
  51639. if (targetInfo && targetInfo !== true) {
  51640. each$1(
  51641. targetInfo.coordSyses,
  51642. function (coordSys) {
  51643. var result = coordConvert[area.brushType](1, coordSys, area.range);
  51644. cb(area, result.values, coordSys, ecModel);
  51645. }
  51646. );
  51647. }
  51648. }, this);
  51649. };
  51650. proto.setInputRanges = function (areas, ecModel) {
  51651. each$23(areas, function (area) {
  51652. var targetInfo = this.findTargetInfo(area, ecModel);
  51653. if (__DEV__) {
  51654. assert(
  51655. !targetInfo || targetInfo === true || area.coordRange,
  51656. 'coordRange must be specified when coord index specified.'
  51657. );
  51658. assert(
  51659. !targetInfo || targetInfo !== true || area.range,
  51660. 'range must be specified in global brush.'
  51661. );
  51662. }
  51663. area.range = area.range || [];
  51664. // convert coordRange to global range and set panelId.
  51665. if (targetInfo && targetInfo !== true) {
  51666. area.panelId = targetInfo.panelId;
  51667. // (1) area.range shoule always be calculate from coordRange but does
  51668. // not keep its original value, for the sake of the dataZoom scenario,
  51669. // where area.coordRange remains unchanged but area.range may be changed.
  51670. // (2) Only support converting one coordRange to pixel range in brush
  51671. // component. So do not consider `coordRanges`.
  51672. // (3) About __rangeOffset, see comment above.
  51673. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  51674. var rangeOffset = area.__rangeOffset;
  51675. area.range = rangeOffset
  51676. ? diffProcessor[area.brushType](
  51677. result.values,
  51678. rangeOffset.offset,
  51679. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  51680. )
  51681. : result.values;
  51682. }
  51683. }, this);
  51684. };
  51685. proto.makePanelOpts = function (api, getDefaultBrushType) {
  51686. return map(this._targetInfoList, function (targetInfo) {
  51687. var rect = targetInfo.getPanelRect();
  51688. return {
  51689. panelId: targetInfo.panelId,
  51690. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  51691. clipPath: makeRectPanelClipPath(rect),
  51692. isTargetByCursor: makeRectIsTargetByCursor(
  51693. rect, api, targetInfo.coordSysModel
  51694. ),
  51695. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  51696. };
  51697. });
  51698. };
  51699. proto.controlSeries = function (area, seriesModel, ecModel) {
  51700. // Check whether area is bound in coord, and series do not belong to that coord.
  51701. // If do not do this check, some brush (like lineX) will controll all axes.
  51702. var targetInfo = this.findTargetInfo(area, ecModel);
  51703. return targetInfo === true || (
  51704. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  51705. );
  51706. };
  51707. /**
  51708. * If return Object, a coord found.
  51709. * If reutrn true, global found.
  51710. * Otherwise nothing found.
  51711. *
  51712. * @param {Object} area
  51713. * @param {Array} targetInfoList
  51714. * @return {Object|boolean}
  51715. */
  51716. proto.findTargetInfo = function (area, ecModel) {
  51717. var targetInfoList = this._targetInfoList;
  51718. var foundCpts = parseFinder$1(ecModel, area);
  51719. for (var i = 0; i < targetInfoList.length; i++) {
  51720. var targetInfo = targetInfoList[i];
  51721. var areaPanelId = area.panelId;
  51722. if (areaPanelId) {
  51723. if (targetInfo.panelId === areaPanelId) {
  51724. return targetInfo;
  51725. }
  51726. }
  51727. else {
  51728. for (var i = 0; i < targetInfoMatchers.length; i++) {
  51729. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  51730. return targetInfo;
  51731. }
  51732. }
  51733. }
  51734. }
  51735. return true;
  51736. };
  51737. function formatMinMax(minMax) {
  51738. minMax[0] > minMax[1] && minMax.reverse();
  51739. return minMax;
  51740. }
  51741. function parseFinder$1(ecModel, option) {
  51742. return parseFinder(
  51743. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  51744. );
  51745. }
  51746. var targetInfoBuilders = {
  51747. grid: function (foundCpts, targetInfoList) {
  51748. var xAxisModels = foundCpts.xAxisModels;
  51749. var yAxisModels = foundCpts.yAxisModels;
  51750. var gridModels = foundCpts.gridModels;
  51751. // Remove duplicated.
  51752. var gridModelMap = createHashMap();
  51753. var xAxesHas = {};
  51754. var yAxesHas = {};
  51755. if (!xAxisModels && !yAxisModels && !gridModels) {
  51756. return;
  51757. }
  51758. each$23(xAxisModels, function (axisModel) {
  51759. var gridModel = axisModel.axis.grid.model;
  51760. gridModelMap.set(gridModel.id, gridModel);
  51761. xAxesHas[gridModel.id] = true;
  51762. });
  51763. each$23(yAxisModels, function (axisModel) {
  51764. var gridModel = axisModel.axis.grid.model;
  51765. gridModelMap.set(gridModel.id, gridModel);
  51766. yAxesHas[gridModel.id] = true;
  51767. });
  51768. each$23(gridModels, function (gridModel) {
  51769. gridModelMap.set(gridModel.id, gridModel);
  51770. xAxesHas[gridModel.id] = true;
  51771. yAxesHas[gridModel.id] = true;
  51772. });
  51773. gridModelMap.each(function (gridModel) {
  51774. var grid = gridModel.coordinateSystem;
  51775. var cartesians = [];
  51776. each$23(grid.getCartesians(), function (cartesian, index) {
  51777. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  51778. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  51779. ) {
  51780. cartesians.push(cartesian);
  51781. }
  51782. });
  51783. targetInfoList.push({
  51784. panelId: 'grid--' + gridModel.id,
  51785. gridModel: gridModel,
  51786. coordSysModel: gridModel,
  51787. // Use the first one as the representitive coordSys.
  51788. coordSys: cartesians[0],
  51789. coordSyses: cartesians,
  51790. getPanelRect: panelRectBuilder.grid,
  51791. xAxisDeclared: xAxesHas[gridModel.id],
  51792. yAxisDeclared: yAxesHas[gridModel.id]
  51793. });
  51794. });
  51795. },
  51796. geo: function (foundCpts, targetInfoList) {
  51797. each$23(foundCpts.geoModels, function (geoModel) {
  51798. var coordSys = geoModel.coordinateSystem;
  51799. targetInfoList.push({
  51800. panelId: 'geo--' + geoModel.id,
  51801. geoModel: geoModel,
  51802. coordSysModel: geoModel,
  51803. coordSys: coordSys,
  51804. coordSyses: [coordSys],
  51805. getPanelRect: panelRectBuilder.geo
  51806. });
  51807. });
  51808. }
  51809. };
  51810. var targetInfoMatchers = [
  51811. // grid
  51812. function (foundCpts, targetInfo) {
  51813. var xAxisModel = foundCpts.xAxisModel;
  51814. var yAxisModel = foundCpts.yAxisModel;
  51815. var gridModel = foundCpts.gridModel;
  51816. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  51817. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  51818. return gridModel && gridModel === targetInfo.gridModel;
  51819. },
  51820. // geo
  51821. function (foundCpts, targetInfo) {
  51822. var geoModel = foundCpts.geoModel;
  51823. return geoModel && geoModel === targetInfo.geoModel;
  51824. }
  51825. ];
  51826. var panelRectBuilder = {
  51827. grid: function () {
  51828. // grid is not Transformable.
  51829. return this.coordSys.grid.getRect().clone();
  51830. },
  51831. geo: function () {
  51832. var coordSys = this.coordSys;
  51833. var rect = coordSys.getBoundingRect().clone();
  51834. // geo roam and zoom transform
  51835. rect.applyTransform(getTransform(coordSys));
  51836. return rect;
  51837. }
  51838. };
  51839. var coordConvert = {
  51840. lineX: curry$5(axisConvert, 0),
  51841. lineY: curry$5(axisConvert, 1),
  51842. rect: function (to, coordSys, rangeOrCoordRange) {
  51843. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  51844. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  51845. var values = [
  51846. formatMinMax([xminymin[0], xmaxymax[0]]),
  51847. formatMinMax([xminymin[1], xmaxymax[1]])
  51848. ];
  51849. return {values: values, xyMinMax: values};
  51850. },
  51851. polygon: function (to, coordSys, rangeOrCoordRange) {
  51852. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  51853. var values = map(rangeOrCoordRange, function (item) {
  51854. var p = coordSys[COORD_CONVERTS[to]](item);
  51855. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  51856. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  51857. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  51858. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  51859. return p;
  51860. });
  51861. return {values: values, xyMinMax: xyMinMax};
  51862. }
  51863. };
  51864. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  51865. if (__DEV__) {
  51866. assert(
  51867. coordSys.type === 'cartesian2d',
  51868. 'lineX/lineY brush is available only in cartesian2d.'
  51869. );
  51870. }
  51871. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  51872. var values = formatMinMax(map([0, 1], function (i) {
  51873. return to
  51874. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  51875. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  51876. }));
  51877. var xyMinMax = [];
  51878. xyMinMax[axisNameIndex] = values;
  51879. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  51880. return {values: values, xyMinMax: xyMinMax};
  51881. }
  51882. var diffProcessor = {
  51883. lineX: curry$5(axisDiffProcessor, 0),
  51884. lineY: curry$5(axisDiffProcessor, 1),
  51885. rect: function (values, refer, scales) {
  51886. return [
  51887. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  51888. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  51889. ];
  51890. },
  51891. polygon: function (values, refer, scales) {
  51892. return map(values, function (item, idx) {
  51893. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  51894. });
  51895. }
  51896. };
  51897. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  51898. return [
  51899. values[0] - scales[axisNameIndex] * refer[0],
  51900. values[1] - scales[axisNameIndex] * refer[1]
  51901. ];
  51902. }
  51903. // We have to process scale caused by dataZoom manually,
  51904. // although it might be not accurate.
  51905. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  51906. var sizeCurr = getSize(xyMinMaxCurr);
  51907. var sizeOrigin = getSize(xyMinMaxOrigin);
  51908. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  51909. isNaN(scales[0]) && (scales[0] = 1);
  51910. isNaN(scales[1]) && (scales[1] = 1);
  51911. return scales;
  51912. }
  51913. function getSize(xyMinMax) {
  51914. return xyMinMax
  51915. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  51916. : [NaN, NaN];
  51917. }
  51918. var STATE_LIST = ['inBrush', 'outOfBrush'];
  51919. var DISPATCH_METHOD = '__ecBrushSelect';
  51920. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  51921. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  51922. /**
  51923. * Layout for visual, the priority higher than other layout, and before brush visual.
  51924. */
  51925. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  51926. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  51927. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  51928. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  51929. );
  51930. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  51931. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  51932. });
  51933. });
  51934. /**
  51935. * Register the visual encoding if this modules required.
  51936. */
  51937. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  51938. var brushSelected = [];
  51939. var throttleType;
  51940. var throttleDelay;
  51941. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  51942. var thisBrushSelected = {
  51943. brushId: brushModel.id,
  51944. brushIndex: brushIndex,
  51945. brushName: brushModel.name,
  51946. areas: clone(brushModel.areas),
  51947. selected: []
  51948. };
  51949. // Every brush component exists in event params, convenient
  51950. // for user to find by index.
  51951. brushSelected.push(thisBrushSelected);
  51952. var brushOption = brushModel.option;
  51953. var brushLink = brushOption.brushLink;
  51954. var linkedSeriesMap = [];
  51955. var selectedDataIndexForLink = [];
  51956. var rangeInfoBySeries = [];
  51957. var hasBrushExists = 0;
  51958. if (!brushIndex) { // Only the first throttle setting works.
  51959. throttleType = brushOption.throttleType;
  51960. throttleDelay = brushOption.throttleDelay;
  51961. }
  51962. // Add boundingRect and selectors to range.
  51963. var areas = map(brushModel.areas, function (area) {
  51964. return bindSelector(
  51965. defaults(
  51966. {boundingRect: boundingRectBuilders[area.brushType](area)},
  51967. area
  51968. )
  51969. );
  51970. });
  51971. var visualMappings = createVisualMappings(
  51972. brushModel.option, STATE_LIST, function (mappingOption) {
  51973. mappingOption.mappingMethod = 'fixed';
  51974. }
  51975. );
  51976. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  51977. linkedSeriesMap[seriesIndex] = 1;
  51978. });
  51979. function linkOthers(seriesIndex) {
  51980. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  51981. }
  51982. // If no supported brush or no brush on the series,
  51983. // all visuals should be in original state.
  51984. function brushed(rangeInfoList) {
  51985. return !!rangeInfoList.length;
  51986. }
  51987. /**
  51988. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  51989. *
  51990. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  51991. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  51992. * └!hasBrushExist┘ └nothing.
  51993. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  51994. * └!hasBrushExist┘ └nothing.
  51995. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  51996. * !brushed┘ └nothing.
  51997. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  51998. */
  51999. // Step A
  52000. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  52001. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  52002. seriesModel.subType === 'parallel'
  52003. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  52004. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  52005. });
  52006. function stepAParallel(seriesModel, seriesIndex) {
  52007. var coordSys = seriesModel.coordinateSystem;
  52008. hasBrushExists |= coordSys.hasAxisBrushed();
  52009. linkOthers(seriesIndex) && coordSys.eachActiveState(
  52010. seriesModel.getData(),
  52011. function (activeState, dataIndex) {
  52012. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  52013. }
  52014. );
  52015. }
  52016. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  52017. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  52018. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  52019. return;
  52020. }
  52021. each$1(areas, function (area) {
  52022. selectorsByBrushType[area.brushType]
  52023. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  52024. && rangeInfoList.push(area);
  52025. hasBrushExists |= brushed(rangeInfoList);
  52026. });
  52027. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  52028. var data = seriesModel.getData();
  52029. data.each(function (dataIndex) {
  52030. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  52031. selectedDataIndexForLink[dataIndex] = 1;
  52032. }
  52033. });
  52034. }
  52035. }
  52036. // Step B
  52037. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  52038. var seriesBrushSelected = {
  52039. seriesId: seriesModel.id,
  52040. seriesIndex: seriesIndex,
  52041. seriesName: seriesModel.name,
  52042. dataIndex: []
  52043. };
  52044. // Every series exists in event params, convenient
  52045. // for user to find series by seriesIndex.
  52046. thisBrushSelected.selected.push(seriesBrushSelected);
  52047. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  52048. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  52049. var data = seriesModel.getData();
  52050. var getValueState = linkOthers(seriesIndex)
  52051. ? function (dataIndex) {
  52052. return selectedDataIndexForLink[dataIndex]
  52053. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  52054. : 'outOfBrush';
  52055. }
  52056. : function (dataIndex) {
  52057. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  52058. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  52059. : 'outOfBrush';
  52060. };
  52061. // If no supported brush or no brush, all visuals are in original state.
  52062. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  52063. && applyVisual(
  52064. STATE_LIST, visualMappings, data, getValueState
  52065. );
  52066. });
  52067. });
  52068. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  52069. });
  52070. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  52071. // This event will not be triggered when `setOpion`, otherwise dead lock may
  52072. // triggered when do `setOption` in event listener, which we do not find
  52073. // satisfactory way to solve yet. Some considered resolutions:
  52074. // (a) Diff with prevoius selected data ant only trigger event when changed.
  52075. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  52076. // also detect value changes in selected data) might bring complexity or fragility.
  52077. // (b) Use spectial param like `silent` to suppress event triggering.
  52078. // But such kind of volatile param may be weird in `setOption`.
  52079. if (!payload) {
  52080. return;
  52081. }
  52082. var zr = api.getZr();
  52083. if (zr[DISPATCH_FLAG]) {
  52084. return;
  52085. }
  52086. if (!zr[DISPATCH_METHOD]) {
  52087. zr[DISPATCH_METHOD] = doDispatch;
  52088. }
  52089. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  52090. fn(api, brushSelected);
  52091. }
  52092. function doDispatch(api, brushSelected) {
  52093. if (!api.isDisposed()) {
  52094. var zr = api.getZr();
  52095. zr[DISPATCH_FLAG] = true;
  52096. api.dispatchAction({
  52097. type: 'brushSelect',
  52098. batch: brushSelected
  52099. });
  52100. zr[DISPATCH_FLAG] = false;
  52101. }
  52102. }
  52103. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  52104. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  52105. var area = rangeInfoList[i];
  52106. if (selectorsByBrushType[area.brushType](
  52107. dataIndex, data, area.selectors, area
  52108. )) {
  52109. return true;
  52110. }
  52111. }
  52112. }
  52113. function getSelectorsByBrushType(seriesModel) {
  52114. var brushSelector = seriesModel.brushSelector;
  52115. if (isString(brushSelector)) {
  52116. var sels = [];
  52117. each$1(selector, function (selectorsByElementType, brushType) {
  52118. sels[brushType] = function (dataIndex, data, selectors, area) {
  52119. var itemLayout = data.getItemLayout(dataIndex);
  52120. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  52121. };
  52122. });
  52123. return sels;
  52124. }
  52125. else if (isFunction(brushSelector)) {
  52126. var bSelector = {};
  52127. each$1(selector, function (sel, brushType) {
  52128. bSelector[brushType] = brushSelector;
  52129. });
  52130. return bSelector;
  52131. }
  52132. return brushSelector;
  52133. }
  52134. function brushModelNotControll(brushModel, seriesIndex) {
  52135. var seriesIndices = brushModel.option.seriesIndex;
  52136. return seriesIndices != null
  52137. && seriesIndices !== 'all'
  52138. && (
  52139. isArray(seriesIndices)
  52140. ? indexOf(seriesIndices, seriesIndex) < 0
  52141. : seriesIndex !== seriesIndices
  52142. );
  52143. }
  52144. function bindSelector(area) {
  52145. var selectors = area.selectors = {};
  52146. each$1(selector[area.brushType], function (selFn, elType) {
  52147. // Do not use function binding or curry for performance.
  52148. selectors[elType] = function (itemLayout) {
  52149. return selFn(itemLayout, selectors, area);
  52150. };
  52151. });
  52152. return area;
  52153. }
  52154. var boundingRectBuilders = {
  52155. lineX: noop,
  52156. lineY: noop,
  52157. rect: function (area) {
  52158. return getBoundingRectFromMinMax(area.range);
  52159. },
  52160. polygon: function (area) {
  52161. var minMax;
  52162. var range = area.range;
  52163. for (var i = 0, len = range.length; i < len; i++) {
  52164. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  52165. var rg = range[i];
  52166. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  52167. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  52168. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  52169. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  52170. }
  52171. return minMax && getBoundingRectFromMinMax(minMax);
  52172. }
  52173. };
  52174. function getBoundingRectFromMinMax(minMax) {
  52175. return new BoundingRect(
  52176. minMax[0][0],
  52177. minMax[1][0],
  52178. minMax[0][1] - minMax[0][0],
  52179. minMax[1][1] - minMax[1][0]
  52180. );
  52181. }
  52182. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  52183. var BrushModel = extendComponentModel({
  52184. type: 'brush',
  52185. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  52186. /**
  52187. * @protected
  52188. */
  52189. defaultOption: {
  52190. // inBrush: null,
  52191. // outOfBrush: null,
  52192. toolbox: null, // Default value see preprocessor.
  52193. brushLink: null, // Series indices array, broadcast using dataIndex.
  52194. // or 'all', which means all series. 'none' or null means no series.
  52195. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  52196. geoIndex: null, //
  52197. xAxisIndex: null,
  52198. yAxisIndex: null,
  52199. brushType: 'rect', // Default brushType, see BrushController.
  52200. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  52201. transformable: true, // Default transformable.
  52202. brushStyle: { // Default brushStyle
  52203. borderWidth: 1,
  52204. color: 'rgba(120,140,180,0.3)',
  52205. borderColor: 'rgba(120,140,180,0.8)'
  52206. },
  52207. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  52208. // If null, no throttle. Valid only in the first brush component
  52209. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  52210. // FIXME
  52211. // 试验效果
  52212. removeOnClick: true,
  52213. z: 10000
  52214. },
  52215. /**
  52216. * @readOnly
  52217. * @type {Array.<Object>}
  52218. */
  52219. areas: [],
  52220. /**
  52221. * Current activated brush type.
  52222. * If null, brush is inactived.
  52223. * see module:echarts/component/helper/BrushController
  52224. * @readOnly
  52225. * @type {string}
  52226. */
  52227. brushType: null,
  52228. /**
  52229. * Current brush opt.
  52230. * see module:echarts/component/helper/BrushController
  52231. * @readOnly
  52232. * @type {Object}
  52233. */
  52234. brushOption: {},
  52235. /**
  52236. * @readOnly
  52237. * @type {Array.<Object>}
  52238. */
  52239. coordInfoList: [],
  52240. optionUpdated: function (newOption, isInit) {
  52241. var thisOption = this.option;
  52242. !isInit && replaceVisualOption(
  52243. thisOption, newOption, ['inBrush', 'outOfBrush']
  52244. );
  52245. thisOption.inBrush = thisOption.inBrush || {};
  52246. // Always give default visual, consider setOption at the second time.
  52247. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  52248. },
  52249. /**
  52250. * If ranges is null/undefined, range state remain.
  52251. *
  52252. * @param {Array.<Object>} [ranges]
  52253. */
  52254. setAreas: function (areas) {
  52255. if (__DEV__) {
  52256. assert(isArray(areas));
  52257. each$1(areas, function (area) {
  52258. assert(area.brushType, 'Illegal areas');
  52259. });
  52260. }
  52261. // If ranges is null/undefined, range state remain.
  52262. // This helps user to dispatchAction({type: 'brush'}) with no areas
  52263. // set but just want to get the current brush select info from a `brush` event.
  52264. if (!areas) {
  52265. return;
  52266. }
  52267. this.areas = map(areas, function (area) {
  52268. return generateBrushOption(this.option, area);
  52269. }, this);
  52270. },
  52271. /**
  52272. * see module:echarts/component/helper/BrushController
  52273. * @param {Object} brushOption
  52274. */
  52275. setBrushOption: function (brushOption) {
  52276. this.brushOption = generateBrushOption(this.option, brushOption);
  52277. this.brushType = this.brushOption.brushType;
  52278. }
  52279. });
  52280. function generateBrushOption(option, brushOption) {
  52281. return merge(
  52282. {
  52283. brushType: option.brushType,
  52284. brushMode: option.brushMode,
  52285. transformable: option.transformable,
  52286. brushStyle: new Model(option.brushStyle).getItemStyle(),
  52287. removeOnClick: option.removeOnClick,
  52288. z: option.z
  52289. },
  52290. brushOption,
  52291. true
  52292. );
  52293. }
  52294. extendComponentView({
  52295. type: 'brush',
  52296. init: function (ecModel, api) {
  52297. /**
  52298. * @readOnly
  52299. * @type {module:echarts/model/Global}
  52300. */
  52301. this.ecModel = ecModel;
  52302. /**
  52303. * @readOnly
  52304. * @type {module:echarts/ExtensionAPI}
  52305. */
  52306. this.api = api;
  52307. /**
  52308. * @readOnly
  52309. * @type {module:echarts/component/brush/BrushModel}
  52310. */
  52311. this.model;
  52312. /**
  52313. * @private
  52314. * @type {module:echarts/component/helper/BrushController}
  52315. */
  52316. (this._brushController = new BrushController(api.getZr()))
  52317. .on('brush', bind(this._onBrush, this))
  52318. .mount();
  52319. },
  52320. /**
  52321. * @override
  52322. */
  52323. render: function (brushModel) {
  52324. this.model = brushModel;
  52325. return updateController.apply(this, arguments);
  52326. },
  52327. /**
  52328. * @override
  52329. */
  52330. updateView: updateController,
  52331. /**
  52332. * @override
  52333. */
  52334. updateLayout: updateController,
  52335. /**
  52336. * @override
  52337. */
  52338. updateVisual: updateController,
  52339. /**
  52340. * @override
  52341. */
  52342. dispose: function () {
  52343. this._brushController.dispose();
  52344. },
  52345. /**
  52346. * @private
  52347. */
  52348. _onBrush: function (areas, opt) {
  52349. var modelId = this.model.id;
  52350. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  52351. // Action is not dispatched on drag end, because the drag end
  52352. // emits the same params with the last drag move event, and
  52353. // may have some delay when using touch pad, which makes
  52354. // animation not smooth (when using debounce).
  52355. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  52356. type: 'brush',
  52357. brushId: modelId,
  52358. areas: clone(areas),
  52359. $from: modelId
  52360. });
  52361. }
  52362. });
  52363. function updateController(brushModel, ecModel, api, payload) {
  52364. // Do not update controller when drawing.
  52365. (!payload || payload.$from !== brushModel.id) && this._brushController
  52366. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  52367. .enableBrush(brushModel.brushOption)
  52368. .updateCovers(brushModel.areas.slice());
  52369. }
  52370. /**
  52371. * payload: {
  52372. * brushIndex: number, or,
  52373. * brushId: string, or,
  52374. * brushName: string,
  52375. * globalRanges: Array
  52376. * }
  52377. */
  52378. registerAction(
  52379. {type: 'brush', event: 'brush', update: 'updateView'},
  52380. function (payload, ecModel) {
  52381. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  52382. brushModel.setAreas(payload.areas);
  52383. });
  52384. }
  52385. );
  52386. /**
  52387. * payload: {
  52388. * brushComponents: [
  52389. * {
  52390. * brushId,
  52391. * brushIndex,
  52392. * brushName,
  52393. * series: [
  52394. * {
  52395. * seriesId,
  52396. * seriesIndex,
  52397. * seriesName,
  52398. * rawIndices: [21, 34, ...]
  52399. * },
  52400. * ...
  52401. * ]
  52402. * },
  52403. * ...
  52404. * ]
  52405. * }
  52406. */
  52407. registerAction(
  52408. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  52409. function () {}
  52410. );
  52411. var features = {};
  52412. function register$1(name, ctor) {
  52413. features[name] = ctor;
  52414. }
  52415. function get$5(name) {
  52416. return features[name];
  52417. }
  52418. var lang = {
  52419. toolbox: {
  52420. brush: {
  52421. title: {
  52422. rect: '矩形选择',
  52423. polygon: '圈选',
  52424. lineX: '横向选择',
  52425. lineY: '纵向选择',
  52426. keep: '保持选择',
  52427. clear: '清除选择'
  52428. }
  52429. },
  52430. dataView: {
  52431. title: '数据视图',
  52432. lang: ['数据视图', '关闭', '刷新']
  52433. },
  52434. dataZoom: {
  52435. title: {
  52436. zoom: '区域缩放',
  52437. back: '区域缩放还原'
  52438. }
  52439. },
  52440. magicType: {
  52441. title: {
  52442. line: '切换为折线图',
  52443. bar: '切换为柱状图',
  52444. stack: '切换为堆叠',
  52445. tiled: '切换为平铺'
  52446. }
  52447. },
  52448. restore: {
  52449. title: '还原'
  52450. },
  52451. saveAsImage: {
  52452. title: '保存为图片',
  52453. lang: ['右键另存为图片']
  52454. }
  52455. }
  52456. };
  52457. var brushLang = lang.toolbox.brush;
  52458. function Brush(model, ecModel, api) {
  52459. this.model = model;
  52460. this.ecModel = ecModel;
  52461. this.api = api;
  52462. /**
  52463. * @private
  52464. * @type {string}
  52465. */
  52466. this._brushType;
  52467. /**
  52468. * @private
  52469. * @type {string}
  52470. */
  52471. this._brushMode;
  52472. }
  52473. Brush.defaultOption = {
  52474. show: true,
  52475. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  52476. icon: {
  52477. 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
  52478. 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
  52479. 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
  52480. 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
  52481. 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
  52482. 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
  52483. },
  52484. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  52485. title: clone(brushLang.title)
  52486. };
  52487. var proto$1 = Brush.prototype;
  52488. proto$1.render =
  52489. proto$1.updateView =
  52490. proto$1.updateLayout = function (featureModel, ecModel, api) {
  52491. var brushType;
  52492. var brushMode;
  52493. var isBrushed;
  52494. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  52495. brushType = brushModel.brushType;
  52496. brushMode = brushModel.brushOption.brushMode || 'single';
  52497. isBrushed |= brushModel.areas.length;
  52498. });
  52499. this._brushType = brushType;
  52500. this._brushMode = brushMode;
  52501. each$1(featureModel.get('type', true), function (type) {
  52502. featureModel.setIconStatus(
  52503. type,
  52504. (
  52505. type === 'keep'
  52506. ? brushMode === 'multiple'
  52507. : type === 'clear'
  52508. ? isBrushed
  52509. : type === brushType
  52510. ) ? 'emphasis' : 'normal'
  52511. );
  52512. });
  52513. };
  52514. proto$1.getIcons = function () {
  52515. var model = this.model;
  52516. var availableIcons = model.get('icon', true);
  52517. var icons = {};
  52518. each$1(model.get('type', true), function (type) {
  52519. if (availableIcons[type]) {
  52520. icons[type] = availableIcons[type];
  52521. }
  52522. });
  52523. return icons;
  52524. };
  52525. proto$1.onclick = function (ecModel, api, type) {
  52526. var brushType = this._brushType;
  52527. var brushMode = this._brushMode;
  52528. if (type === 'clear') {
  52529. // Trigger parallel action firstly
  52530. api.dispatchAction({
  52531. type: 'axisAreaSelect',
  52532. intervals: []
  52533. });
  52534. api.dispatchAction({
  52535. type: 'brush',
  52536. command: 'clear',
  52537. // Clear all areas of all brush components.
  52538. areas: []
  52539. });
  52540. }
  52541. else {
  52542. api.dispatchAction({
  52543. type: 'takeGlobalCursor',
  52544. key: 'brush',
  52545. brushOption: {
  52546. brushType: type === 'keep'
  52547. ? brushType
  52548. : (brushType === type ? false : type),
  52549. brushMode: type === 'keep'
  52550. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  52551. : brushMode
  52552. }
  52553. });
  52554. }
  52555. };
  52556. register$1('brush', Brush);
  52557. /**
  52558. * Brush component entry
  52559. */
  52560. registerPreprocessor(preprocessor$1);
  52561. // (24*60*60*1000)
  52562. var PROXIMATE_ONE_DAY = 86400000;
  52563. /**
  52564. * Calendar
  52565. *
  52566. * @constructor
  52567. *
  52568. * @param {Object} calendarModel calendarModel
  52569. * @param {Object} ecModel ecModel
  52570. * @param {Object} api api
  52571. */
  52572. function Calendar(calendarModel, ecModel, api) {
  52573. this._model = calendarModel;
  52574. }
  52575. Calendar.prototype = {
  52576. constructor: Calendar,
  52577. type: 'calendar',
  52578. dimensions: ['time', 'value'],
  52579. // Required in createListFromData
  52580. getDimensionsInfo: function () {
  52581. return [{name: 'time', type: 'time'}];
  52582. },
  52583. getRangeInfo: function () {
  52584. return this._rangeInfo;
  52585. },
  52586. getModel: function () {
  52587. return this._model;
  52588. },
  52589. getRect: function () {
  52590. return this._rect;
  52591. },
  52592. getCellWidth: function () {
  52593. return this._sw;
  52594. },
  52595. getCellHeight: function () {
  52596. return this._sh;
  52597. },
  52598. getOrient: function () {
  52599. return this._orient;
  52600. },
  52601. /**
  52602. * getFirstDayOfWeek
  52603. *
  52604. * @example
  52605. * 0 : start at Sunday
  52606. * 1 : start at Monday
  52607. *
  52608. * @return {number}
  52609. */
  52610. getFirstDayOfWeek: function () {
  52611. return this._firstDayOfWeek;
  52612. },
  52613. /**
  52614. * get date info
  52615. *
  52616. * @param {string|number} date date
  52617. * @return {Object}
  52618. * {
  52619. * y: string, local full year, eg., '1940',
  52620. * m: string, local month, from '01' ot '12',
  52621. * d: string, local date, from '01' to '31' (if exists),
  52622. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  52623. * time: timestamp,
  52624. * formatedDate: string, yyyy-MM-dd,
  52625. * date: original date object.
  52626. * }
  52627. */
  52628. getDateInfo: function (date) {
  52629. date = parseDate(date);
  52630. var y = date.getFullYear();
  52631. var m = date.getMonth() + 1;
  52632. m = m < 10 ? '0' + m : m;
  52633. var d = date.getDate();
  52634. d = d < 10 ? '0' + d : d;
  52635. var day = date.getDay();
  52636. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  52637. return {
  52638. y: y,
  52639. m: m,
  52640. d: d,
  52641. day: day,
  52642. time: date.getTime(),
  52643. formatedDate: y + '-' + m + '-' + d,
  52644. date: date
  52645. };
  52646. },
  52647. getNextNDay: function (date, n) {
  52648. n = n || 0;
  52649. if (n === 0) {
  52650. return this.getDateInfo(date);
  52651. }
  52652. date = new Date(this.getDateInfo(date).time);
  52653. date.setDate(date.getDate() + n);
  52654. return this.getDateInfo(date);
  52655. },
  52656. update: function (ecModel, api) {
  52657. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  52658. this._orient = this._model.get('orient');
  52659. this._lineWidth = this._model.getModel('itemStyle.normal').getItemStyle().lineWidth || 0;
  52660. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  52661. var weeks = this._rangeInfo.weeks || 1;
  52662. var whNames = ['width', 'height'];
  52663. var cellSize = this._model.get('cellSize').slice();
  52664. var layoutParams = this._model.getBoxLayoutParams();
  52665. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  52666. each$1([0, 1], function (idx) {
  52667. if (cellSizeSpecified(cellSize, idx)) {
  52668. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  52669. }
  52670. });
  52671. var whGlobal = {
  52672. width: api.getWidth(),
  52673. height: api.getHeight()
  52674. };
  52675. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  52676. each$1([0, 1], function (idx) {
  52677. if (!cellSizeSpecified(cellSize, idx)) {
  52678. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  52679. }
  52680. });
  52681. function cellSizeSpecified(cellSize, idx) {
  52682. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  52683. }
  52684. this._sw = cellSize[0];
  52685. this._sh = cellSize[1];
  52686. },
  52687. /**
  52688. * Convert a time data(time, value) item to (x, y) point.
  52689. *
  52690. * @override
  52691. * @param {Array|number} data data
  52692. * @param {boolean} [clamp=true] out of range
  52693. * @return {Array} point
  52694. */
  52695. dataToPoint: function (data, clamp) {
  52696. isArray(data) && (data = data[0]);
  52697. clamp == null && (clamp = true);
  52698. var dayInfo = this.getDateInfo(data);
  52699. var range = this._rangeInfo;
  52700. var date = dayInfo.formatedDate;
  52701. // if not in range return [NaN, NaN]
  52702. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) {
  52703. return [NaN, NaN];
  52704. }
  52705. var week = dayInfo.day;
  52706. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  52707. if (this._orient === 'vertical') {
  52708. return [
  52709. this._rect.x + week * this._sw + this._sw / 2,
  52710. this._rect.y + nthWeek * this._sh + this._sh / 2
  52711. ];
  52712. }
  52713. return [
  52714. this._rect.x + nthWeek * this._sw + this._sw / 2,
  52715. this._rect.y + week * this._sh + this._sh / 2
  52716. ];
  52717. },
  52718. /**
  52719. * Convert a (x, y) point to time data
  52720. *
  52721. * @override
  52722. * @param {string} point point
  52723. * @return {string} data
  52724. */
  52725. pointToData: function (point) {
  52726. var date = this.pointToDate(point);
  52727. return date && date.time;
  52728. },
  52729. /**
  52730. * Convert a time date item to (x, y) four point.
  52731. *
  52732. * @param {Array} data date[0] is date
  52733. * @param {boolean} [clamp=true] out of range
  52734. * @return {Object} point
  52735. */
  52736. dataToRect: function (data, clamp) {
  52737. var point = this.dataToPoint(data, clamp);
  52738. return {
  52739. contentShape: {
  52740. x: point[0] - (this._sw - this._lineWidth) / 2,
  52741. y: point[1] - (this._sh - this._lineWidth) / 2,
  52742. width: this._sw - this._lineWidth,
  52743. height: this._sh - this._lineWidth
  52744. },
  52745. center: point,
  52746. tl: [
  52747. point[0] - this._sw / 2,
  52748. point[1] - this._sh / 2
  52749. ],
  52750. tr: [
  52751. point[0] + this._sw / 2,
  52752. point[1] - this._sh / 2
  52753. ],
  52754. br: [
  52755. point[0] + this._sw / 2,
  52756. point[1] + this._sh / 2
  52757. ],
  52758. bl: [
  52759. point[0] - this._sw / 2,
  52760. point[1] + this._sh / 2
  52761. ]
  52762. };
  52763. },
  52764. /**
  52765. * Convert a (x, y) point to time date
  52766. *
  52767. * @param {Array} point point
  52768. * @return {Object} date
  52769. */
  52770. pointToDate: function (point) {
  52771. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  52772. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  52773. var range = this._rangeInfo.range;
  52774. if (this._orient === 'vertical') {
  52775. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  52776. }
  52777. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  52778. },
  52779. /**
  52780. * @inheritDoc
  52781. */
  52782. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  52783. /**
  52784. * @inheritDoc
  52785. */
  52786. convertFromPixel: curry(doConvert$2, 'pointToData'),
  52787. /**
  52788. * initRange
  52789. *
  52790. * @private
  52791. * @return {Array} [start, end]
  52792. */
  52793. _initRangeOption: function () {
  52794. var range = this._model.get('range');
  52795. var rg = range;
  52796. if (isArray(rg) && rg.length === 1) {
  52797. rg = rg[0];
  52798. }
  52799. if (/^\d{4}$/.test(rg)) {
  52800. range = [rg + '-01-01', rg + '-12-31'];
  52801. }
  52802. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  52803. var start = this.getDateInfo(rg);
  52804. var firstDay = start.date;
  52805. firstDay.setMonth(firstDay.getMonth() + 1);
  52806. var end = this.getNextNDay(firstDay, -1);
  52807. range = [start.formatedDate, end.formatedDate];
  52808. }
  52809. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  52810. range = [rg, rg];
  52811. }
  52812. var tmp = this._getRangeInfo(range);
  52813. if (tmp.start.time > tmp.end.time) {
  52814. range.reverse();
  52815. }
  52816. return range;
  52817. },
  52818. /**
  52819. * range info
  52820. *
  52821. * @private
  52822. * @param {Array} range range ['2017-01-01', '2017-07-08']
  52823. * If range[0] > range[1], they will not be reversed.
  52824. * @return {Object} obj
  52825. */
  52826. _getRangeInfo: function (range) {
  52827. range = [
  52828. this.getDateInfo(range[0]),
  52829. this.getDateInfo(range[1])
  52830. ];
  52831. var reversed;
  52832. if (range[0].time > range[1].time) {
  52833. reversed = true;
  52834. range.reverse();
  52835. }
  52836. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  52837. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  52838. // Consider case:
  52839. // Firstly set system timezone as "Time Zone: America/Toronto",
  52840. // ```
  52841. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  52842. // var second = new Date(1478412000000);
  52843. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  52844. // ```
  52845. // will get wrong result because of DST. So we should fix it.
  52846. var date = new Date(range[0].time);
  52847. var startDateNum = date.getDate();
  52848. var endDateNum = range[1].date.getDate();
  52849. date.setDate(startDateNum + allDay - 1);
  52850. // The bias can not over a month, so just compare date.
  52851. if (date.getDate() !== endDateNum) {
  52852. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  52853. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  52854. allDay -= sign;
  52855. date.setDate(startDateNum + allDay - 1);
  52856. }
  52857. }
  52858. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  52859. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  52860. reversed && range.reverse();
  52861. return {
  52862. range: [range[0].formatedDate, range[1].formatedDate],
  52863. start: range[0],
  52864. end: range[1],
  52865. allDay: allDay,
  52866. weeks: weeks,
  52867. // From 0.
  52868. nthWeek: nthWeek,
  52869. fweek: range[0].day,
  52870. lweek: range[1].day
  52871. };
  52872. },
  52873. /**
  52874. * get date by nthWeeks and week day in range
  52875. *
  52876. * @private
  52877. * @param {number} nthWeek the week
  52878. * @param {number} day the week day
  52879. * @param {Array} range [d1, d2]
  52880. * @return {Object}
  52881. */
  52882. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  52883. var rangeInfo = this._getRangeInfo(range);
  52884. if (nthWeek > rangeInfo.weeks
  52885. || (nthWeek === 0 && day < rangeInfo.fweek)
  52886. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  52887. ) {
  52888. return false;
  52889. }
  52890. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  52891. var date = new Date(rangeInfo.start.time);
  52892. date.setDate(rangeInfo.start.d + nthDay);
  52893. return this.getDateInfo(date);
  52894. }
  52895. };
  52896. Calendar.dimensions = Calendar.prototype.dimensions;
  52897. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  52898. Calendar.create = function (ecModel, api) {
  52899. var calendarList = [];
  52900. ecModel.eachComponent('calendar', function (calendarModel) {
  52901. var calendar = new Calendar(calendarModel, ecModel, api);
  52902. calendarList.push(calendar);
  52903. calendarModel.coordinateSystem = calendar;
  52904. });
  52905. ecModel.eachSeries(function (calendarSeries) {
  52906. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  52907. // Inject coordinate system
  52908. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  52909. }
  52910. });
  52911. return calendarList;
  52912. };
  52913. function doConvert$2(methodName, ecModel, finder, value) {
  52914. var calendarModel = finder.calendarModel;
  52915. var seriesModel = finder.seriesModel;
  52916. var coordSys = calendarModel
  52917. ? calendarModel.coordinateSystem
  52918. : seriesModel
  52919. ? seriesModel.coordinateSystem
  52920. : null;
  52921. return coordSys === this ? coordSys[methodName](value) : null;
  52922. }
  52923. CoordinateSystemManager.register('calendar', Calendar);
  52924. var CalendarModel = ComponentModel.extend({
  52925. type: 'calendar',
  52926. /**
  52927. * @type {module:echarts/coord/calendar/Calendar}
  52928. */
  52929. coordinateSystem: null,
  52930. defaultOption: {
  52931. zlevel: 0,
  52932. z: 2,
  52933. left: 80,
  52934. top: 60,
  52935. cellSize: 20,
  52936. // horizontal vertical
  52937. orient: 'horizontal',
  52938. // month separate line style
  52939. splitLine: {
  52940. show: true,
  52941. lineStyle: {
  52942. color: '#000',
  52943. width: 1,
  52944. type: 'solid'
  52945. }
  52946. },
  52947. // rect style temporarily unused emphasis
  52948. itemStyle: {
  52949. normal: {
  52950. color: '#fff',
  52951. borderWidth: 1,
  52952. borderColor: '#ccc'
  52953. }
  52954. },
  52955. // week text style
  52956. dayLabel: {
  52957. show: true,
  52958. // a week first day
  52959. firstDay: 0,
  52960. // start end
  52961. position: 'start',
  52962. margin: '50%', // 50% of cellSize
  52963. nameMap: 'en',
  52964. color: '#000'
  52965. },
  52966. // month text style
  52967. monthLabel: {
  52968. show: true,
  52969. // start end
  52970. position: 'start',
  52971. margin: 5,
  52972. // center or left
  52973. align: 'center',
  52974. // cn en []
  52975. nameMap: 'en',
  52976. formatter: null,
  52977. color: '#000'
  52978. },
  52979. // year text style
  52980. yearLabel: {
  52981. show: true,
  52982. // top bottom left right
  52983. position: null,
  52984. margin: 30,
  52985. formatter: null,
  52986. color: '#ccc',
  52987. fontFamily: 'sans-serif',
  52988. fontWeight: 'bolder',
  52989. fontSize: 20
  52990. }
  52991. },
  52992. /**
  52993. * @override
  52994. */
  52995. init: function (option, parentModel, ecModel, extraOpt) {
  52996. var inputPositionParams = getLayoutParams(option);
  52997. CalendarModel.superApply(this, 'init', arguments);
  52998. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  52999. },
  53000. /**
  53001. * @override
  53002. */
  53003. mergeOption: function (option, extraOpt) {
  53004. CalendarModel.superApply(this, 'mergeOption', arguments);
  53005. mergeAndNormalizeLayoutParams$1(this.option, option);
  53006. }
  53007. });
  53008. function mergeAndNormalizeLayoutParams$1(target, raw) {
  53009. // Normalize cellSize
  53010. var cellSize = target.cellSize;
  53011. if (!isArray(cellSize)) {
  53012. cellSize = target.cellSize = [cellSize, cellSize];
  53013. }
  53014. else if (cellSize.length === 1) {
  53015. cellSize[1] = cellSize[0];
  53016. }
  53017. var ignoreSize = map([0, 1], function (hvIdx) {
  53018. // If user have set `width` or both `left` and `right`, cellSize
  53019. // will be automatically set to 'auto', otherwise the default
  53020. // setting of cellSize will make `width` setting not work.
  53021. if (sizeCalculable(raw, hvIdx)) {
  53022. cellSize[hvIdx] = 'auto';
  53023. }
  53024. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  53025. });
  53026. mergeLayoutParam(target, raw, {
  53027. type: 'box', ignoreSize: ignoreSize
  53028. });
  53029. }
  53030. var MONTH_TEXT = {
  53031. EN: [
  53032. 'Jan', 'Feb', 'Mar',
  53033. 'Apr', 'May', 'Jun',
  53034. 'Jul', 'Aug', 'Sep',
  53035. 'Oct', 'Nov', 'Dec'
  53036. ],
  53037. CN: [
  53038. '一月', '二月', '三月',
  53039. '四月', '五月', '六月',
  53040. '七月', '八月', '九月',
  53041. '十月', '十一月', '十二月'
  53042. ]
  53043. };
  53044. var WEEK_TEXT = {
  53045. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  53046. CN: ['日', '一', '二', '三', '四', '五', '六']
  53047. };
  53048. extendComponentView({
  53049. type: 'calendar',
  53050. /**
  53051. * top/left line points
  53052. * @private
  53053. */
  53054. _tlpoints: null,
  53055. /**
  53056. * bottom/right line points
  53057. * @private
  53058. */
  53059. _blpoints: null,
  53060. /**
  53061. * first day of month
  53062. * @private
  53063. */
  53064. _firstDayOfMonth: null,
  53065. /**
  53066. * first day point of month
  53067. * @private
  53068. */
  53069. _firstDayPoints: null,
  53070. render: function (calendarModel, ecModel, api) {
  53071. var group = this.group;
  53072. group.removeAll();
  53073. var coordSys = calendarModel.coordinateSystem;
  53074. // range info
  53075. var rangeData = coordSys.getRangeInfo();
  53076. var orient = coordSys.getOrient();
  53077. this._renderDayRect(calendarModel, rangeData, group);
  53078. // _renderLines must be called prior to following function
  53079. this._renderLines(calendarModel, rangeData, orient, group);
  53080. this._renderYearText(calendarModel, rangeData, orient, group);
  53081. this._renderMonthText(calendarModel, orient, group);
  53082. this._renderWeekText(calendarModel, rangeData, orient, group);
  53083. },
  53084. // render day rect
  53085. _renderDayRect: function (calendarModel, rangeData, group) {
  53086. var coordSys = calendarModel.coordinateSystem;
  53087. var itemRectStyleModel = calendarModel.getModel('itemStyle.normal').getItemStyle();
  53088. var sw = coordSys.getCellWidth();
  53089. var sh = coordSys.getCellHeight();
  53090. for (var i = rangeData.start.time;
  53091. i <= rangeData.end.time;
  53092. i = coordSys.getNextNDay(i, 1).time
  53093. ) {
  53094. var point = coordSys.dataToRect([i], false).tl;
  53095. // every rect
  53096. var rect = new Rect({
  53097. shape: {
  53098. x: point[0],
  53099. y: point[1],
  53100. width: sw,
  53101. height: sh
  53102. },
  53103. cursor: 'default',
  53104. style: itemRectStyleModel
  53105. });
  53106. group.add(rect);
  53107. }
  53108. },
  53109. // render separate line
  53110. _renderLines: function (calendarModel, rangeData, orient, group) {
  53111. var self = this;
  53112. var coordSys = calendarModel.coordinateSystem;
  53113. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  53114. var show = calendarModel.get('splitLine.show');
  53115. var lineWidth = lineStyleModel.lineWidth;
  53116. this._tlpoints = [];
  53117. this._blpoints = [];
  53118. this._firstDayOfMonth = [];
  53119. this._firstDayPoints = [];
  53120. var firstDay = rangeData.start;
  53121. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  53122. addPoints(firstDay.formatedDate);
  53123. if (i === 0) {
  53124. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  53125. }
  53126. var date = firstDay.date;
  53127. date.setMonth(date.getMonth() + 1);
  53128. firstDay = coordSys.getDateInfo(date);
  53129. }
  53130. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  53131. function addPoints(date) {
  53132. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  53133. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  53134. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  53135. self._tlpoints.push(points[0]);
  53136. self._blpoints.push(points[points.length - 1]);
  53137. show && self._drawSplitline(points, lineStyleModel, group);
  53138. }
  53139. // render top/left line
  53140. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  53141. // render bottom/right line
  53142. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  53143. },
  53144. // get points at both ends
  53145. _getEdgesPoints: function (points, lineWidth, orient) {
  53146. var rs = [points[0].slice(), points[points.length - 1].slice()];
  53147. var idx = orient === 'horizontal' ? 0 : 1;
  53148. // both ends of the line are extend half lineWidth
  53149. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  53150. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  53151. return rs;
  53152. },
  53153. // render split line
  53154. _drawSplitline: function (points, lineStyleModel, group) {
  53155. var poyline = new Polyline({
  53156. z2: 20,
  53157. shape: {
  53158. points: points
  53159. },
  53160. style: lineStyleModel
  53161. });
  53162. group.add(poyline);
  53163. },
  53164. // render month line of one week points
  53165. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  53166. var coordSys = calendarModel.coordinateSystem;
  53167. date = coordSys.getDateInfo(date);
  53168. var points = [];
  53169. for (var i = 0; i < 7; i++) {
  53170. var tmpD = coordSys.getNextNDay(date.time, i);
  53171. var point = coordSys.dataToRect([tmpD.time], false);
  53172. points[2 * tmpD.day] = point.tl;
  53173. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  53174. }
  53175. return points;
  53176. },
  53177. _formatterLabel: function (formatter, params) {
  53178. if (typeof formatter === 'string' && formatter) {
  53179. return formatTplSimple(formatter, params);
  53180. }
  53181. if (typeof formatter === 'function') {
  53182. return formatter(params);
  53183. }
  53184. return params.nameMap;
  53185. },
  53186. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  53187. point = point.slice();
  53188. var aligns = ['center', 'bottom'];
  53189. if (position === 'bottom') {
  53190. point[1] += margin;
  53191. aligns = ['center', 'top'];
  53192. }
  53193. else if (position === 'left') {
  53194. point[0] -= margin;
  53195. }
  53196. else if (position === 'right') {
  53197. point[0] += margin;
  53198. aligns = ['center', 'top'];
  53199. }
  53200. else { // top
  53201. point[1] -= margin;
  53202. }
  53203. var rotate = 0;
  53204. if (position === 'left' || position === 'right') {
  53205. rotate = Math.PI / 2;
  53206. }
  53207. return {
  53208. rotation: rotate,
  53209. position: point,
  53210. style: {
  53211. textAlign: aligns[0],
  53212. textVerticalAlign: aligns[1]
  53213. }
  53214. };
  53215. },
  53216. // render year
  53217. _renderYearText: function (calendarModel, rangeData, orient, group) {
  53218. var yearLabel = calendarModel.getModel('yearLabel');
  53219. if (!yearLabel.get('show')) {
  53220. return;
  53221. }
  53222. var margin = yearLabel.get('margin');
  53223. var pos = yearLabel.get('position');
  53224. if (!pos) {
  53225. pos = orient !== 'horizontal' ? 'top' : 'left';
  53226. }
  53227. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  53228. var xc = (points[0][0] + points[1][0]) / 2;
  53229. var yc = (points[0][1] + points[1][1]) / 2;
  53230. var idx = orient === 'horizontal' ? 0 : 1;
  53231. var posPoints = {
  53232. top: [xc, points[idx][1]],
  53233. bottom: [xc, points[1 - idx][1]],
  53234. left: [points[1 - idx][0], yc],
  53235. right: [points[idx][0], yc]
  53236. };
  53237. var name = rangeData.start.y;
  53238. if (+rangeData.end.y > +rangeData.start.y) {
  53239. name = name + '-' + rangeData.end.y;
  53240. }
  53241. var formatter = yearLabel.get('formatter');
  53242. var params = {
  53243. start: rangeData.start.y,
  53244. end: rangeData.end.y,
  53245. nameMap: name
  53246. };
  53247. var content = this._formatterLabel(formatter, params);
  53248. var yearText = new Text({z2: 30});
  53249. setTextStyle(yearText.style, yearLabel, {text: content}),
  53250. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  53251. group.add(yearText);
  53252. },
  53253. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  53254. var align = 'left';
  53255. var vAlign = 'top';
  53256. var x = point[0];
  53257. var y = point[1];
  53258. if (orient === 'horizontal') {
  53259. y = y + margin;
  53260. if (isCenter) {
  53261. align = 'center';
  53262. }
  53263. if (position === 'start') {
  53264. vAlign = 'bottom';
  53265. }
  53266. }
  53267. else {
  53268. x = x + margin;
  53269. if (isCenter) {
  53270. vAlign = 'middle';
  53271. }
  53272. if (position === 'start') {
  53273. align = 'right';
  53274. }
  53275. }
  53276. return {
  53277. x: x,
  53278. y: y,
  53279. textAlign: align,
  53280. textVerticalAlign: vAlign
  53281. };
  53282. },
  53283. // render month and year text
  53284. _renderMonthText: function (calendarModel, orient, group) {
  53285. var monthLabel = calendarModel.getModel('monthLabel');
  53286. if (!monthLabel.get('show')) {
  53287. return;
  53288. }
  53289. var nameMap = monthLabel.get('nameMap');
  53290. var margin = monthLabel.get('margin');
  53291. var pos = monthLabel.get('position');
  53292. var align = monthLabel.get('align');
  53293. var termPoints = [this._tlpoints, this._blpoints];
  53294. if (isString(nameMap)) {
  53295. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  53296. }
  53297. var idx = pos === 'start' ? 0 : 1;
  53298. var axis = orient === 'horizontal' ? 0 : 1;
  53299. margin = pos === 'start' ? -margin : margin;
  53300. var isCenter = (align === 'center');
  53301. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  53302. var tmp = termPoints[idx][i].slice();
  53303. var firstDay = this._firstDayOfMonth[i];
  53304. if (isCenter) {
  53305. var firstDayPoints = this._firstDayPoints[i];
  53306. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  53307. }
  53308. var formatter = monthLabel.get('formatter');
  53309. var name = nameMap[+firstDay.m - 1];
  53310. var params = {
  53311. yyyy: firstDay.y,
  53312. yy: (firstDay.y + '').slice(2),
  53313. MM: firstDay.m,
  53314. M: +firstDay.m,
  53315. nameMap: name
  53316. };
  53317. var content = this._formatterLabel(formatter, params);
  53318. var monthText = new Text({z2: 30});
  53319. extend(
  53320. setTextStyle(monthText.style, monthLabel, {text: content}),
  53321. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  53322. );
  53323. group.add(monthText);
  53324. }
  53325. },
  53326. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  53327. var align = 'center';
  53328. var vAlign = 'middle';
  53329. var x = point[0];
  53330. var y = point[1];
  53331. var isStart = position === 'start';
  53332. if (orient === 'horizontal') {
  53333. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  53334. align = isStart ? 'right' : 'left';
  53335. }
  53336. else {
  53337. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  53338. vAlign = isStart ? 'bottom' : 'top';
  53339. }
  53340. return {
  53341. x: x,
  53342. y: y,
  53343. textAlign: align,
  53344. textVerticalAlign: vAlign
  53345. };
  53346. },
  53347. // render weeks
  53348. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  53349. var dayLabel = calendarModel.getModel('dayLabel');
  53350. if (!dayLabel.get('show')) {
  53351. return;
  53352. }
  53353. var coordSys = calendarModel.coordinateSystem;
  53354. var pos = dayLabel.get('position');
  53355. var nameMap = dayLabel.get('nameMap');
  53356. var margin = dayLabel.get('margin');
  53357. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  53358. if (isString(nameMap)) {
  53359. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  53360. }
  53361. var start = coordSys.getNextNDay(
  53362. rangeData.end.time, (7 - rangeData.lweek)
  53363. ).time;
  53364. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  53365. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  53366. if (pos === 'start') {
  53367. start = coordSys.getNextNDay(
  53368. rangeData.start.time, -(7 + rangeData.fweek)
  53369. ).time;
  53370. margin = -margin;
  53371. }
  53372. for (var i = 0; i < 7; i++) {
  53373. var tmpD = coordSys.getNextNDay(start, i);
  53374. var point = coordSys.dataToRect([tmpD.time], false).center;
  53375. var day = i;
  53376. day = Math.abs((i + firstDayOfWeek) % 7);
  53377. var weekText = new Text({z2: 30});
  53378. extend(
  53379. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  53380. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  53381. );
  53382. group.add(weekText);
  53383. }
  53384. }
  53385. });
  53386. /**
  53387. * @file calendar.js
  53388. * @author dxh
  53389. */
  53390. // Model
  53391. extendComponentModel({
  53392. type: 'title',
  53393. layoutMode: {type: 'box', ignoreSize: true},
  53394. defaultOption: {
  53395. // 一级层叠
  53396. zlevel: 0,
  53397. // 二级层叠
  53398. z: 6,
  53399. show: true,
  53400. text: '',
  53401. // 超链接跳转
  53402. // link: null,
  53403. // 仅支持self | blank
  53404. target: 'blank',
  53405. subtext: '',
  53406. // 超链接跳转
  53407. // sublink: null,
  53408. // 仅支持self | blank
  53409. subtarget: 'blank',
  53410. // 'center' ¦ 'left' ¦ 'right'
  53411. // ¦ {number}(x坐标,单位px)
  53412. left: 0,
  53413. // 'top' ¦ 'bottom' ¦ 'center'
  53414. // ¦ {number}(y坐标,单位px)
  53415. top: 0,
  53416. // 水平对齐
  53417. // 'auto' | 'left' | 'right' | 'center'
  53418. // 默认根据 left 的位置判断是左对齐还是右对齐
  53419. // textAlign: null
  53420. //
  53421. // 垂直对齐
  53422. // 'auto' | 'top' | 'bottom' | 'middle'
  53423. // 默认根据 top 位置判断是上对齐还是下对齐
  53424. // textBaseline: null
  53425. backgroundColor: 'rgba(0,0,0,0)',
  53426. // 标题边框颜色
  53427. borderColor: '#ccc',
  53428. // 标题边框线宽,单位px,默认为0(无边框)
  53429. borderWidth: 0,
  53430. // 标题内边距,单位px,默认各方向内边距为5,
  53431. // 接受数组分别设定上右下左边距,同css
  53432. padding: 5,
  53433. // 主副标题纵向间隔,单位px,默认为10,
  53434. itemGap: 10,
  53435. textStyle: {
  53436. fontSize: 18,
  53437. fontWeight: 'bolder',
  53438. color: '#333'
  53439. },
  53440. subtextStyle: {
  53441. color: '#aaa'
  53442. }
  53443. }
  53444. });
  53445. // View
  53446. extendComponentView({
  53447. type: 'title',
  53448. render: function (titleModel, ecModel, api) {
  53449. this.group.removeAll();
  53450. if (!titleModel.get('show')) {
  53451. return;
  53452. }
  53453. var group = this.group;
  53454. var textStyleModel = titleModel.getModel('textStyle');
  53455. var subtextStyleModel = titleModel.getModel('subtextStyle');
  53456. var textAlign = titleModel.get('textAlign');
  53457. var textBaseline = titleModel.get('textBaseline');
  53458. var textEl = new Text({
  53459. style: setTextStyle({}, textStyleModel, {
  53460. text: titleModel.get('text'),
  53461. textFill: textStyleModel.getTextColor()
  53462. }, {disableBox: true}),
  53463. z2: 10
  53464. });
  53465. var textRect = textEl.getBoundingRect();
  53466. var subText = titleModel.get('subtext');
  53467. var subTextEl = new Text({
  53468. style: setTextStyle({}, subtextStyleModel, {
  53469. text: subText,
  53470. textFill: subtextStyleModel.getTextColor(),
  53471. y: textRect.height + titleModel.get('itemGap'),
  53472. textVerticalAlign: 'top'
  53473. }, {disableBox: true}),
  53474. z2: 10
  53475. });
  53476. var link = titleModel.get('link');
  53477. var sublink = titleModel.get('sublink');
  53478. textEl.silent = !link;
  53479. subTextEl.silent = !sublink;
  53480. if (link) {
  53481. textEl.on('click', function () {
  53482. window.open(link, '_' + titleModel.get('target'));
  53483. });
  53484. }
  53485. if (sublink) {
  53486. subTextEl.on('click', function () {
  53487. window.open(sublink, '_' + titleModel.get('subtarget'));
  53488. });
  53489. }
  53490. group.add(textEl);
  53491. subText && group.add(subTextEl);
  53492. // If no subText, but add subTextEl, there will be an empty line.
  53493. var groupRect = group.getBoundingRect();
  53494. var layoutOption = titleModel.getBoxLayoutParams();
  53495. layoutOption.width = groupRect.width;
  53496. layoutOption.height = groupRect.height;
  53497. var layoutRect = getLayoutRect(
  53498. layoutOption, {
  53499. width: api.getWidth(),
  53500. height: api.getHeight()
  53501. }, titleModel.get('padding')
  53502. );
  53503. // Adjust text align based on position
  53504. if (!textAlign) {
  53505. // Align left if title is on the left. center and right is same
  53506. textAlign = titleModel.get('left') || titleModel.get('right');
  53507. if (textAlign === 'middle') {
  53508. textAlign = 'center';
  53509. }
  53510. // Adjust layout by text align
  53511. if (textAlign === 'right') {
  53512. layoutRect.x += layoutRect.width;
  53513. }
  53514. else if (textAlign === 'center') {
  53515. layoutRect.x += layoutRect.width / 2;
  53516. }
  53517. }
  53518. if (!textBaseline) {
  53519. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  53520. if (textBaseline === 'center') {
  53521. textBaseline = 'middle';
  53522. }
  53523. if (textBaseline === 'bottom') {
  53524. layoutRect.y += layoutRect.height;
  53525. }
  53526. else if (textBaseline === 'middle') {
  53527. layoutRect.y += layoutRect.height / 2;
  53528. }
  53529. textBaseline = textBaseline || 'top';
  53530. }
  53531. group.attr('position', [layoutRect.x, layoutRect.y]);
  53532. var alignStyle = {
  53533. textAlign: textAlign,
  53534. textVerticalAlign: textBaseline
  53535. };
  53536. textEl.setStyle(alignStyle);
  53537. subTextEl.setStyle(alignStyle);
  53538. // Render background
  53539. // Get groupRect again because textAlign has been changed
  53540. groupRect = group.getBoundingRect();
  53541. var padding = layoutRect.margin;
  53542. var style = titleModel.getItemStyle(['color', 'opacity']);
  53543. style.fill = titleModel.get('backgroundColor');
  53544. var rect = new Rect({
  53545. shape: {
  53546. x: groupRect.x - padding[3],
  53547. y: groupRect.y - padding[0],
  53548. width: groupRect.width + padding[1] + padding[3],
  53549. height: groupRect.height + padding[0] + padding[2],
  53550. r: titleModel.get('borderRadius')
  53551. },
  53552. style: style,
  53553. silent: true
  53554. });
  53555. subPixelOptimizeRect(rect);
  53556. group.add(rect);
  53557. }
  53558. });
  53559. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  53560. // Default 'slider' when no type specified.
  53561. return 'slider';
  53562. });
  53563. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  53564. // Supported coords.
  53565. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  53566. /**
  53567. * @param {string} coordType
  53568. * @return {boolean}
  53569. */
  53570. function isCoordSupported(coordType) {
  53571. return indexOf(COORDS, coordType) >= 0;
  53572. }
  53573. /**
  53574. * Create "each" method to iterate names.
  53575. *
  53576. * @pubilc
  53577. * @param {Array.<string>} names
  53578. * @param {Array.<string>=} attrs
  53579. * @return {Function}
  53580. */
  53581. function createNameEach(names, attrs) {
  53582. names = names.slice();
  53583. var capitalNames = map(names, capitalFirst);
  53584. attrs = (attrs || []).slice();
  53585. var capitalAttrs = map(attrs, capitalFirst);
  53586. return function (callback, context) {
  53587. each$1(names, function (name, index) {
  53588. var nameObj = {name: name, capital: capitalNames[index]};
  53589. for (var j = 0; j < attrs.length; j++) {
  53590. nameObj[attrs[j]] = name + capitalAttrs[j];
  53591. }
  53592. callback.call(context, nameObj);
  53593. });
  53594. };
  53595. }
  53596. /**
  53597. * Iterate each dimension name.
  53598. *
  53599. * @public
  53600. * @param {Function} callback The parameter is like:
  53601. * {
  53602. * name: 'angle',
  53603. * capital: 'Angle',
  53604. * axis: 'angleAxis',
  53605. * axisIndex: 'angleAixs',
  53606. * index: 'angleIndex'
  53607. * }
  53608. * @param {Object} context
  53609. */
  53610. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  53611. /**
  53612. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  53613. * dataZoomModels and 'links' make up one or more graphics.
  53614. * This function finds the graphic where the source dataZoomModel is in.
  53615. *
  53616. * @public
  53617. * @param {Function} forEachNode Node iterator.
  53618. * @param {Function} forEachEdgeType edgeType iterator
  53619. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  53620. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  53621. */
  53622. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  53623. return function (sourceNode) {
  53624. var result = {
  53625. nodes: [],
  53626. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  53627. };
  53628. forEachEdgeType(function (edgeType) {
  53629. result.records[edgeType.name] = {};
  53630. });
  53631. if (!sourceNode) {
  53632. return result;
  53633. }
  53634. absorb(sourceNode, result);
  53635. var existsLink;
  53636. do {
  53637. existsLink = false;
  53638. forEachNode(processSingleNode);
  53639. }
  53640. while (existsLink);
  53641. function processSingleNode(node) {
  53642. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  53643. absorb(node, result);
  53644. existsLink = true;
  53645. }
  53646. }
  53647. return result;
  53648. };
  53649. function isNodeAbsorded(node, result) {
  53650. return indexOf(result.nodes, node) >= 0;
  53651. }
  53652. function isLinked(node, result) {
  53653. var hasLink = false;
  53654. forEachEdgeType(function (edgeType) {
  53655. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  53656. result.records[edgeType.name][edgeId] && (hasLink = true);
  53657. });
  53658. });
  53659. return hasLink;
  53660. }
  53661. function absorb(node, result) {
  53662. result.nodes.push(node);
  53663. forEachEdgeType(function (edgeType) {
  53664. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  53665. result.records[edgeType.name][edgeId] = true;
  53666. });
  53667. });
  53668. }
  53669. }
  53670. var each$25 = each$1;
  53671. var asc$1 = asc;
  53672. /**
  53673. * Operate single axis.
  53674. * One axis can only operated by one axis operator.
  53675. * Different dataZoomModels may be defined to operate the same axis.
  53676. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  53677. * So dataZoomModels share one axisProxy in that case.
  53678. *
  53679. * @class
  53680. */
  53681. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  53682. /**
  53683. * @private
  53684. * @type {string}
  53685. */
  53686. this._dimName = dimName;
  53687. /**
  53688. * @private
  53689. */
  53690. this._axisIndex = axisIndex;
  53691. /**
  53692. * @private
  53693. * @type {Array.<number>}
  53694. */
  53695. this._valueWindow;
  53696. /**
  53697. * @private
  53698. * @type {Array.<number>}
  53699. */
  53700. this._percentWindow;
  53701. /**
  53702. * @private
  53703. * @type {Array.<number>}
  53704. */
  53705. this._dataExtent;
  53706. /**
  53707. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  53708. * @private
  53709. * @type {Object}
  53710. */
  53711. this._minMaxSpan;
  53712. /**
  53713. * @readOnly
  53714. * @type {module: echarts/model/Global}
  53715. */
  53716. this.ecModel = ecModel;
  53717. /**
  53718. * @private
  53719. * @type {module: echarts/component/dataZoom/DataZoomModel}
  53720. */
  53721. this._dataZoomModel = dataZoomModel;
  53722. };
  53723. AxisProxy.prototype = {
  53724. constructor: AxisProxy,
  53725. /**
  53726. * Whether the axisProxy is hosted by dataZoomModel.
  53727. *
  53728. * @public
  53729. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53730. * @return {boolean}
  53731. */
  53732. hostedBy: function (dataZoomModel) {
  53733. return this._dataZoomModel === dataZoomModel;
  53734. },
  53735. /**
  53736. * @return {Array.<number>} Value can only be NaN or finite value.
  53737. */
  53738. getDataValueWindow: function () {
  53739. return this._valueWindow.slice();
  53740. },
  53741. /**
  53742. * @return {Array.<number>}
  53743. */
  53744. getDataPercentWindow: function () {
  53745. return this._percentWindow.slice();
  53746. },
  53747. /**
  53748. * @public
  53749. * @param {number} axisIndex
  53750. * @return {Array} seriesModels
  53751. */
  53752. getTargetSeriesModels: function () {
  53753. var seriesModels = [];
  53754. var ecModel = this.ecModel;
  53755. ecModel.eachSeries(function (seriesModel) {
  53756. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  53757. var dimName = this._dimName;
  53758. var axisModel = ecModel.queryComponents({
  53759. mainType: dimName + 'Axis',
  53760. index: seriesModel.get(dimName + 'AxisIndex'),
  53761. id: seriesModel.get(dimName + 'AxisId')
  53762. })[0];
  53763. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  53764. seriesModels.push(seriesModel);
  53765. }
  53766. }
  53767. }, this);
  53768. return seriesModels;
  53769. },
  53770. getAxisModel: function () {
  53771. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  53772. },
  53773. getOtherAxisModel: function () {
  53774. var axisDim = this._dimName;
  53775. var ecModel = this.ecModel;
  53776. var axisModel = this.getAxisModel();
  53777. var isCartesian = axisDim === 'x' || axisDim === 'y';
  53778. var otherAxisDim;
  53779. var coordSysIndexName;
  53780. if (isCartesian) {
  53781. coordSysIndexName = 'gridIndex';
  53782. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  53783. }
  53784. else {
  53785. coordSysIndexName = 'polarIndex';
  53786. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  53787. }
  53788. var foundOtherAxisModel;
  53789. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  53790. if ((otherAxisModel.get(coordSysIndexName) || 0)
  53791. === (axisModel.get(coordSysIndexName) || 0)
  53792. ) {
  53793. foundOtherAxisModel = otherAxisModel;
  53794. }
  53795. });
  53796. return foundOtherAxisModel;
  53797. },
  53798. getMinMaxSpan: function () {
  53799. return clone(this._minMaxSpan);
  53800. },
  53801. /**
  53802. * Only calculate by given range and this._dataExtent, do not change anything.
  53803. *
  53804. * @param {Object} opt
  53805. * @param {number} [opt.start]
  53806. * @param {number} [opt.end]
  53807. * @param {number} [opt.startValue]
  53808. * @param {number} [opt.endValue]
  53809. */
  53810. calculateDataWindow: function (opt) {
  53811. var dataExtent = this._dataExtent;
  53812. var axisModel = this.getAxisModel();
  53813. var scale = axisModel.axis.scale;
  53814. var rangePropMode = this._dataZoomModel.getRangePropMode();
  53815. var percentExtent = [0, 100];
  53816. var percentWindow = [
  53817. opt.start,
  53818. opt.end
  53819. ];
  53820. var valueWindow = [];
  53821. each$25(['startValue', 'endValue'], function (prop) {
  53822. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  53823. });
  53824. // Normalize bound.
  53825. each$25([0, 1], function (idx) {
  53826. var boundValue = valueWindow[idx];
  53827. var boundPercent = percentWindow[idx];
  53828. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  53829. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  53830. // for cases that a dataZoom component controls multiple axes with different
  53831. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  53832. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  53833. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  53834. // accurately (because all of values that are overflow the `dataExtent` will
  53835. // be calculated to percent '100%'). So we have to use
  53836. // `dataZoom.getRangePropMode()` to mark which prop is used.
  53837. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  53838. // it remains its original value.
  53839. if (rangePropMode[idx] === 'percent') {
  53840. if (boundPercent == null) {
  53841. boundPercent = percentExtent[idx];
  53842. }
  53843. // Use scale.parse to math round for category or time axis.
  53844. boundValue = scale.parse(linearMap(
  53845. boundPercent, percentExtent, dataExtent, true
  53846. ));
  53847. }
  53848. else {
  53849. // Calculating `percent` from `value` may be not accurate, because
  53850. // This calculation can not be inversed, because all of values that
  53851. // are overflow the `dataExtent` will be calculated to percent '100%'
  53852. boundPercent = linearMap(
  53853. boundValue, dataExtent, percentExtent, true
  53854. );
  53855. }
  53856. // valueWindow[idx] = round(boundValue);
  53857. // percentWindow[idx] = round(boundPercent);
  53858. valueWindow[idx] = boundValue;
  53859. percentWindow[idx] = boundPercent;
  53860. });
  53861. return {
  53862. valueWindow: asc$1(valueWindow),
  53863. percentWindow: asc$1(percentWindow)
  53864. };
  53865. },
  53866. /**
  53867. * Notice: reset should not be called before series.restoreData() called,
  53868. * so it is recommanded to be called in "process stage" but not "model init
  53869. * stage".
  53870. *
  53871. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53872. */
  53873. reset: function (dataZoomModel) {
  53874. if (dataZoomModel !== this._dataZoomModel) {
  53875. return;
  53876. }
  53877. // Culculate data window and data extent, and record them.
  53878. this._dataExtent = calculateDataExtent(
  53879. this, this._dimName, this.getTargetSeriesModels()
  53880. );
  53881. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  53882. this._valueWindow = dataWindow.valueWindow;
  53883. this._percentWindow = dataWindow.percentWindow;
  53884. setMinMaxSpan(this);
  53885. // Update axis setting then.
  53886. setAxisModel(this);
  53887. },
  53888. /**
  53889. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53890. */
  53891. restore: function (dataZoomModel) {
  53892. if (dataZoomModel !== this._dataZoomModel) {
  53893. return;
  53894. }
  53895. this._valueWindow = this._percentWindow = null;
  53896. setAxisModel(this, true);
  53897. },
  53898. /**
  53899. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  53900. */
  53901. filterData: function (dataZoomModel) {
  53902. if (dataZoomModel !== this._dataZoomModel) {
  53903. return;
  53904. }
  53905. var axisDim = this._dimName;
  53906. var seriesModels = this.getTargetSeriesModels();
  53907. var filterMode = dataZoomModel.get('filterMode');
  53908. var valueWindow = this._valueWindow;
  53909. if (filterMode === 'none') {
  53910. return;
  53911. }
  53912. // FIXME
  53913. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  53914. // with NaN data, NaN will be filtered and stack will be wrong.
  53915. // So we need to force the mode to be set empty.
  53916. // In fect, it is not a big deal that do not support filterMode-'filter'
  53917. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  53918. // selection" some day, which might need "adapt to data extent on the
  53919. // otherAxis", which is disabled by filterMode-'empty'.
  53920. var otherAxisModel = this.getOtherAxisModel();
  53921. if (dataZoomModel.get('$fromToolbox')
  53922. && otherAxisModel
  53923. && otherAxisModel.get('type') === 'category'
  53924. ) {
  53925. filterMode = 'empty';
  53926. }
  53927. // Process series data
  53928. each$25(seriesModels, function (seriesModel) {
  53929. var seriesData = seriesModel.getData();
  53930. var dataDims = seriesModel.coordDimToDataDim(axisDim);
  53931. if (filterMode === 'weakFilter') {
  53932. seriesData && seriesData.filterSelf(function (dataIndex) {
  53933. var leftOut;
  53934. var rightOut;
  53935. var hasValue;
  53936. for (var i = 0; i < dataDims.length; i++) {
  53937. var value = seriesData.get(dataDims[i], dataIndex);
  53938. var thisHasValue = !isNaN(value);
  53939. var thisLeftOut = value < valueWindow[0];
  53940. var thisRightOut = value > valueWindow[1];
  53941. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  53942. return true;
  53943. }
  53944. thisHasValue && (hasValue = true);
  53945. thisLeftOut && (leftOut = true);
  53946. thisRightOut && (rightOut = true);
  53947. }
  53948. // If both left out and right out, do not filter.
  53949. return hasValue && leftOut && rightOut;
  53950. });
  53951. }
  53952. else {
  53953. seriesData && each$25(dataDims, function (dim) {
  53954. if (filterMode === 'empty') {
  53955. seriesModel.setData(
  53956. seriesData.map(dim, function (value) {
  53957. return !isInWindow(value) ? NaN : value;
  53958. })
  53959. );
  53960. }
  53961. else {
  53962. seriesData.filterSelf(dim, isInWindow);
  53963. }
  53964. });
  53965. }
  53966. });
  53967. function isInWindow(value) {
  53968. return value >= valueWindow[0] && value <= valueWindow[1];
  53969. }
  53970. }
  53971. };
  53972. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  53973. var dataExtent = [Infinity, -Infinity];
  53974. each$25(seriesModels, function (seriesModel) {
  53975. var seriesData = seriesModel.getData();
  53976. if (seriesData) {
  53977. each$25(seriesModel.coordDimToDataDim(axisDim), function (dim) {
  53978. var seriesExtent = seriesData.getDataExtent(dim);
  53979. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  53980. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  53981. });
  53982. }
  53983. });
  53984. if (dataExtent[1] < dataExtent[0]) {
  53985. dataExtent = [NaN, NaN];
  53986. }
  53987. // It is important to get "consistent" extent when more then one axes is
  53988. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  53989. // when zooming. But it is difficult to know what is "consistent", considering
  53990. // axes have different type or even different meanings (For example, two
  53991. // time axes are used to compare data of the same date in different years).
  53992. // So basically dataZoom just obtains extent by series.data (in category axis
  53993. // extent can be obtained from axis.data).
  53994. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  53995. // consistent.
  53996. fixExtentByAxis(axisProxy, dataExtent);
  53997. return dataExtent;
  53998. }
  53999. function fixExtentByAxis(axisProxy, dataExtent) {
  54000. var axisModel = axisProxy.getAxisModel();
  54001. var min = axisModel.getMin(true);
  54002. // For category axis, if min/max/scale are not set, extent is determined
  54003. // by axis.data by default.
  54004. var isCategoryAxis = axisModel.get('type') === 'category';
  54005. var axisDataLen = isCategoryAxis && (axisModel.get('data') || []).length;
  54006. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  54007. dataExtent[0] = min;
  54008. }
  54009. else if (isCategoryAxis) {
  54010. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  54011. }
  54012. var max = axisModel.getMax(true);
  54013. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  54014. dataExtent[1] = max;
  54015. }
  54016. else if (isCategoryAxis) {
  54017. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  54018. }
  54019. if (!axisModel.get('scale', true)) {
  54020. dataExtent[0] > 0 && (dataExtent[0] = 0);
  54021. dataExtent[1] < 0 && (dataExtent[1] = 0);
  54022. }
  54023. // For value axis, if min/max/scale are not set, we just use the extent obtained
  54024. // by series data, which may be a little different from the extent calculated by
  54025. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  54026. // little when zooming. So it will not be fixed until some users require it strongly.
  54027. return dataExtent;
  54028. }
  54029. function setAxisModel(axisProxy, isRestore) {
  54030. var axisModel = axisProxy.getAxisModel();
  54031. var percentWindow = axisProxy._percentWindow;
  54032. var valueWindow = axisProxy._valueWindow;
  54033. if (!percentWindow) {
  54034. return;
  54035. }
  54036. // [0, 500]: arbitrary value, guess axis extent.
  54037. var precision = getPixelPrecision(valueWindow, [0, 500]);
  54038. precision = Math.min(precision, 20);
  54039. // isRestore or isFull
  54040. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  54041. axisModel.setRange(
  54042. useOrigin ? null : +valueWindow[0].toFixed(precision),
  54043. useOrigin ? null : +valueWindow[1].toFixed(precision)
  54044. );
  54045. }
  54046. function setMinMaxSpan(axisProxy) {
  54047. var minMaxSpan = axisProxy._minMaxSpan = {};
  54048. var dataZoomModel = axisProxy._dataZoomModel;
  54049. each$25(['min', 'max'], function (minMax) {
  54050. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  54051. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  54052. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  54053. if (valueSpan != null) {
  54054. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  54055. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  54056. if (valueSpan != null) {
  54057. var dataExtent = axisProxy._dataExtent;
  54058. minMaxSpan[minMax + 'Span'] = linearMap(
  54059. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  54060. );
  54061. }
  54062. }
  54063. });
  54064. }
  54065. var each$24 = each$1;
  54066. var eachAxisDim = eachAxisDim$1;
  54067. var DataZoomModel = extendComponentModel({
  54068. type: 'dataZoom',
  54069. dependencies: [
  54070. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  54071. ],
  54072. /**
  54073. * @protected
  54074. */
  54075. defaultOption: {
  54076. zlevel: 0,
  54077. z: 4, // Higher than normal component (z: 2).
  54078. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  54079. xAxisIndex: null, // Default the first horizontal category axis.
  54080. yAxisIndex: null, // Default the first vertical category axis.
  54081. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  54082. // 'filter': data items which are out of window will be removed. This option is
  54083. // applicable when filtering outliers. For each data item, it will be
  54084. // filtered if one of the relevant dimensions is out of the window.
  54085. // 'weakFilter': data items which are out of window will be removed. This option
  54086. // is applicable when filtering outliers. For each data item, it will be
  54087. // filtered only if all of the relevant dimensions are out of the same
  54088. // side of the window.
  54089. // 'empty': data items which are out of window will be set to empty.
  54090. // This option is applicable when user should not neglect
  54091. // that there are some data items out of window.
  54092. // 'none': Do not filter.
  54093. // Taking line chart as an example, line will be broken in
  54094. // the filtered points when filterModel is set to 'empty', but
  54095. // be connected when set to 'filter'.
  54096. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  54097. // default 100. Do not throttle when use null/undefined.
  54098. // If animation === true and animationDurationUpdate > 0,
  54099. // default value is 100, otherwise 20.
  54100. start: 0, // Start percent. 0 ~ 100
  54101. end: 100, // End percent. 0 ~ 100
  54102. startValue: null, // Start value. If startValue specified, start is ignored.
  54103. endValue: null, // End value. If endValue specified, end is ignored.
  54104. minSpan: null, // 0 ~ 100
  54105. maxSpan: null, // 0 ~ 100
  54106. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  54107. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  54108. rangeMode: null // Array, can be 'value' or 'percent'.
  54109. },
  54110. /**
  54111. * @override
  54112. */
  54113. init: function (option, parentModel, ecModel) {
  54114. /**
  54115. * key like x_0, y_1
  54116. * @private
  54117. * @type {Object}
  54118. */
  54119. this._dataIntervalByAxis = {};
  54120. /**
  54121. * @private
  54122. */
  54123. this._dataInfo = {};
  54124. /**
  54125. * key like x_0, y_1
  54126. * @private
  54127. */
  54128. this._axisProxies = {};
  54129. /**
  54130. * @readOnly
  54131. */
  54132. this.textStyleModel;
  54133. /**
  54134. * @private
  54135. */
  54136. this._autoThrottle = true;
  54137. /**
  54138. * 'percent' or 'value'
  54139. * @private
  54140. */
  54141. this._rangePropMode = ['percent', 'percent'];
  54142. var rawOption = retrieveRaw(option);
  54143. this.mergeDefaultAndTheme(option, ecModel);
  54144. this.doInit(rawOption);
  54145. },
  54146. /**
  54147. * @override
  54148. */
  54149. mergeOption: function (newOption) {
  54150. var rawOption = retrieveRaw(newOption);
  54151. //FIX #2591
  54152. merge(this.option, newOption, true);
  54153. this.doInit(rawOption);
  54154. },
  54155. /**
  54156. * @protected
  54157. */
  54158. doInit: function (rawOption) {
  54159. var thisOption = this.option;
  54160. // Disable realtime view update if canvas is not supported.
  54161. if (!env$1.canvasSupported) {
  54162. thisOption.realtime = false;
  54163. }
  54164. this._setDefaultThrottle(rawOption);
  54165. updateRangeUse(this, rawOption);
  54166. each$24([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  54167. // start/end has higher priority over startValue/endValue if they
  54168. // both set, but we should make chart.setOption({endValue: 1000})
  54169. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  54170. if (this._rangePropMode[index] === 'value') {
  54171. thisOption[names[0]] = null;
  54172. }
  54173. // Otherwise do nothing and use the merge result.
  54174. }, this);
  54175. this.textStyleModel = this.getModel('textStyle');
  54176. this._resetTarget();
  54177. this._giveAxisProxies();
  54178. },
  54179. /**
  54180. * @private
  54181. */
  54182. _giveAxisProxies: function () {
  54183. var axisProxies = this._axisProxies;
  54184. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  54185. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  54186. // If exists, share axisProxy with other dataZoomModels.
  54187. var axisProxy = axisModel.__dzAxisProxy || (
  54188. // Use the first dataZoomModel as the main model of axisProxy.
  54189. axisModel.__dzAxisProxy = new AxisProxy(
  54190. dimNames.name, axisIndex, this, ecModel
  54191. )
  54192. );
  54193. // FIXME
  54194. // dispose __dzAxisProxy
  54195. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  54196. }, this);
  54197. },
  54198. /**
  54199. * @private
  54200. */
  54201. _resetTarget: function () {
  54202. var thisOption = this.option;
  54203. var autoMode = this._judgeAutoMode();
  54204. eachAxisDim(function (dimNames) {
  54205. var axisIndexName = dimNames.axisIndex;
  54206. thisOption[axisIndexName] = normalizeToArray(
  54207. thisOption[axisIndexName]
  54208. );
  54209. }, this);
  54210. if (autoMode === 'axisIndex') {
  54211. this._autoSetAxisIndex();
  54212. }
  54213. else if (autoMode === 'orient') {
  54214. this._autoSetOrient();
  54215. }
  54216. },
  54217. /**
  54218. * @private
  54219. */
  54220. _judgeAutoMode: function () {
  54221. // Auto set only works for setOption at the first time.
  54222. // The following is user's reponsibility. So using merged
  54223. // option is OK.
  54224. var thisOption = this.option;
  54225. var hasIndexSpecified = false;
  54226. eachAxisDim(function (dimNames) {
  54227. // When user set axisIndex as a empty array, we think that user specify axisIndex
  54228. // but do not want use auto mode. Because empty array may be encountered when
  54229. // some error occured.
  54230. if (thisOption[dimNames.axisIndex] != null) {
  54231. hasIndexSpecified = true;
  54232. }
  54233. }, this);
  54234. var orient = thisOption.orient;
  54235. if (orient == null && hasIndexSpecified) {
  54236. return 'orient';
  54237. }
  54238. else if (!hasIndexSpecified) {
  54239. if (orient == null) {
  54240. thisOption.orient = 'horizontal';
  54241. }
  54242. return 'axisIndex';
  54243. }
  54244. },
  54245. /**
  54246. * @private
  54247. */
  54248. _autoSetAxisIndex: function () {
  54249. var autoAxisIndex = true;
  54250. var orient = this.get('orient', true);
  54251. var thisOption = this.option;
  54252. var dependentModels = this.dependentModels;
  54253. if (autoAxisIndex) {
  54254. // Find axis that parallel to dataZoom as default.
  54255. var dimName = orient === 'vertical' ? 'y' : 'x';
  54256. if (dependentModels[dimName + 'Axis'].length) {
  54257. thisOption[dimName + 'AxisIndex'] = [0];
  54258. autoAxisIndex = false;
  54259. }
  54260. else {
  54261. each$24(dependentModels.singleAxis, function (singleAxisModel) {
  54262. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  54263. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  54264. autoAxisIndex = false;
  54265. }
  54266. });
  54267. }
  54268. }
  54269. if (autoAxisIndex) {
  54270. // Find the first category axis as default. (consider polar)
  54271. eachAxisDim(function (dimNames) {
  54272. if (!autoAxisIndex) {
  54273. return;
  54274. }
  54275. var axisIndices = [];
  54276. var axisModels = this.dependentModels[dimNames.axis];
  54277. if (axisModels.length && !axisIndices.length) {
  54278. for (var i = 0, len = axisModels.length; i < len; i++) {
  54279. if (axisModels[i].get('type') === 'category') {
  54280. axisIndices.push(i);
  54281. }
  54282. }
  54283. }
  54284. thisOption[dimNames.axisIndex] = axisIndices;
  54285. if (axisIndices.length) {
  54286. autoAxisIndex = false;
  54287. }
  54288. }, this);
  54289. }
  54290. if (autoAxisIndex) {
  54291. // FIXME
  54292. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  54293. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  54294. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  54295. // dataZoom component auto adopts series that reference to
  54296. // both xAxis and yAxis which type is 'value'.
  54297. this.ecModel.eachSeries(function (seriesModel) {
  54298. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  54299. eachAxisDim(function (dimNames) {
  54300. var axisIndices = thisOption[dimNames.axisIndex];
  54301. var axisIndex = seriesModel.get(dimNames.axisIndex);
  54302. var axisId = seriesModel.get(dimNames.axisId);
  54303. var axisModel = seriesModel.ecModel.queryComponents({
  54304. mainType: dimNames.axis,
  54305. index: axisIndex,
  54306. id: axisId
  54307. })[0];
  54308. if (__DEV__) {
  54309. if (!axisModel) {
  54310. throw new Error(
  54311. dimNames.axis + ' "' + retrieve(
  54312. axisIndex,
  54313. axisId,
  54314. 0
  54315. ) + '" not found'
  54316. );
  54317. }
  54318. }
  54319. axisIndex = axisModel.componentIndex;
  54320. if (indexOf(axisIndices, axisIndex) < 0) {
  54321. axisIndices.push(axisIndex);
  54322. }
  54323. });
  54324. }
  54325. }, this);
  54326. }
  54327. },
  54328. /**
  54329. * @private
  54330. */
  54331. _autoSetOrient: function () {
  54332. var dim;
  54333. // Find the first axis
  54334. this.eachTargetAxis(function (dimNames) {
  54335. !dim && (dim = dimNames.name);
  54336. }, this);
  54337. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  54338. },
  54339. /**
  54340. * @private
  54341. */
  54342. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  54343. // FIXME
  54344. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  54345. // 例如series.type === scatter时。
  54346. var is = true;
  54347. eachAxisDim(function (dimNames) {
  54348. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  54349. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  54350. if (!axisModel || axisModel.get('type') !== axisType) {
  54351. is = false;
  54352. }
  54353. }, this);
  54354. return is;
  54355. },
  54356. /**
  54357. * @private
  54358. */
  54359. _setDefaultThrottle: function (rawOption) {
  54360. // When first time user set throttle, auto throttle ends.
  54361. if (rawOption.hasOwnProperty('throttle')) {
  54362. this._autoThrottle = false;
  54363. }
  54364. if (this._autoThrottle) {
  54365. var globalOption = this.ecModel.option;
  54366. this.option.throttle =
  54367. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  54368. ? 100 : 20;
  54369. }
  54370. },
  54371. /**
  54372. * @public
  54373. */
  54374. getFirstTargetAxisModel: function () {
  54375. var firstAxisModel;
  54376. eachAxisDim(function (dimNames) {
  54377. if (firstAxisModel == null) {
  54378. var indices = this.get(dimNames.axisIndex);
  54379. if (indices.length) {
  54380. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  54381. }
  54382. }
  54383. }, this);
  54384. return firstAxisModel;
  54385. },
  54386. /**
  54387. * @public
  54388. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  54389. */
  54390. eachTargetAxis: function (callback, context) {
  54391. var ecModel = this.ecModel;
  54392. eachAxisDim(function (dimNames) {
  54393. each$24(
  54394. this.get(dimNames.axisIndex),
  54395. function (axisIndex) {
  54396. callback.call(context, dimNames, axisIndex, this, ecModel);
  54397. },
  54398. this
  54399. );
  54400. }, this);
  54401. },
  54402. /**
  54403. * @param {string} dimName
  54404. * @param {number} axisIndex
  54405. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  54406. */
  54407. getAxisProxy: function (dimName, axisIndex) {
  54408. return this._axisProxies[dimName + '_' + axisIndex];
  54409. },
  54410. /**
  54411. * @param {string} dimName
  54412. * @param {number} axisIndex
  54413. * @return {module:echarts/model/Model} If not found, return null/undefined.
  54414. */
  54415. getAxisModel: function (dimName, axisIndex) {
  54416. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  54417. return axisProxy && axisProxy.getAxisModel();
  54418. },
  54419. /**
  54420. * If not specified, set to undefined.
  54421. *
  54422. * @public
  54423. * @param {Object} opt
  54424. * @param {number} [opt.start]
  54425. * @param {number} [opt.end]
  54426. * @param {number} [opt.startValue]
  54427. * @param {number} [opt.endValue]
  54428. * @param {boolean} [ignoreUpdateRangeUsg=false]
  54429. */
  54430. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  54431. var option = this.option;
  54432. each$24([['start', 'startValue'], ['end', 'endValue']], function (names) {
  54433. // If only one of 'start' and 'startValue' is not null/undefined, the other
  54434. // should be cleared, which enable clear the option.
  54435. // If both of them are not set, keep option with the original value, which
  54436. // enable use only set start but not set end when calling `dispatchAction`.
  54437. // The same as 'end' and 'endValue'.
  54438. if (opt[names[0]] != null || opt[names[1]] != null) {
  54439. option[names[0]] = opt[names[0]];
  54440. option[names[1]] = opt[names[1]];
  54441. }
  54442. }, this);
  54443. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  54444. },
  54445. /**
  54446. * @public
  54447. * @return {Array.<number>} [startPercent, endPercent]
  54448. */
  54449. getPercentRange: function () {
  54450. var axisProxy = this.findRepresentativeAxisProxy();
  54451. if (axisProxy) {
  54452. return axisProxy.getDataPercentWindow();
  54453. }
  54454. },
  54455. /**
  54456. * @public
  54457. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  54458. *
  54459. * @param {string} [axisDimName]
  54460. * @param {number} [axisIndex]
  54461. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  54462. */
  54463. getValueRange: function (axisDimName, axisIndex) {
  54464. if (axisDimName == null && axisIndex == null) {
  54465. var axisProxy = this.findRepresentativeAxisProxy();
  54466. if (axisProxy) {
  54467. return axisProxy.getDataValueWindow();
  54468. }
  54469. }
  54470. else {
  54471. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  54472. }
  54473. },
  54474. /**
  54475. * @public
  54476. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  54477. * corresponding to the axisModel
  54478. * @return {module:echarts/component/dataZoom/AxisProxy}
  54479. */
  54480. findRepresentativeAxisProxy: function (axisModel) {
  54481. if (axisModel) {
  54482. return axisModel.__dzAxisProxy;
  54483. }
  54484. // Find the first hosted axisProxy
  54485. var axisProxies = this._axisProxies;
  54486. for (var key in axisProxies) {
  54487. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  54488. return axisProxies[key];
  54489. }
  54490. }
  54491. // If no hosted axis find not hosted axisProxy.
  54492. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  54493. // and the option.start or option.end settings are different. The percentRange
  54494. // should follow axisProxy.
  54495. // (We encounter this problem in toolbox data zoom.)
  54496. for (var key in axisProxies) {
  54497. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  54498. return axisProxies[key];
  54499. }
  54500. }
  54501. },
  54502. /**
  54503. * @return {Array.<string>}
  54504. */
  54505. getRangePropMode: function () {
  54506. return this._rangePropMode.slice();
  54507. }
  54508. });
  54509. function retrieveRaw(option) {
  54510. var ret = {};
  54511. each$24(
  54512. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  54513. function (name) {
  54514. option.hasOwnProperty(name) && (ret[name] = option[name]);
  54515. }
  54516. );
  54517. return ret;
  54518. }
  54519. function updateRangeUse(dataZoomModel, rawOption) {
  54520. var rangePropMode = dataZoomModel._rangePropMode;
  54521. var rangeModeInOption = dataZoomModel.get('rangeMode');
  54522. each$24([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  54523. var percentSpecified = rawOption[names[0]] != null;
  54524. var valueSpecified = rawOption[names[1]] != null;
  54525. if (percentSpecified && !valueSpecified) {
  54526. rangePropMode[index] = 'percent';
  54527. }
  54528. else if (!percentSpecified && valueSpecified) {
  54529. rangePropMode[index] = 'value';
  54530. }
  54531. else if (rangeModeInOption) {
  54532. rangePropMode[index] = rangeModeInOption[index];
  54533. }
  54534. else if (percentSpecified) { // percentSpecified && valueSpecified
  54535. rangePropMode[index] = 'percent';
  54536. }
  54537. // else remain its original setting.
  54538. });
  54539. }
  54540. var DataZoomView = Component.extend({
  54541. type: 'dataZoom',
  54542. render: function (dataZoomModel, ecModel, api, payload) {
  54543. this.dataZoomModel = dataZoomModel;
  54544. this.ecModel = ecModel;
  54545. this.api = api;
  54546. },
  54547. /**
  54548. * Find the first target coordinate system.
  54549. *
  54550. * @protected
  54551. * @return {Object} {
  54552. * grid: [
  54553. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  54554. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  54555. * ...
  54556. * ], // cartesians must not be null/undefined.
  54557. * polar: [
  54558. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  54559. * ...
  54560. * ], // polars must not be null/undefined.
  54561. * singleAxis: [
  54562. * {model: coord0, axisModels: [], coordIndex: 0}
  54563. * ]
  54564. */
  54565. getTargetCoordInfo: function () {
  54566. var dataZoomModel = this.dataZoomModel;
  54567. var ecModel = this.ecModel;
  54568. var coordSysLists = {};
  54569. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  54570. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  54571. if (axisModel) {
  54572. var coordModel = axisModel.getCoordSysModel();
  54573. coordModel && save(
  54574. coordModel,
  54575. axisModel,
  54576. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  54577. coordModel.componentIndex
  54578. );
  54579. }
  54580. }, this);
  54581. function save(coordModel, axisModel, store, coordIndex) {
  54582. var item;
  54583. for (var i = 0; i < store.length; i++) {
  54584. if (store[i].model === coordModel) {
  54585. item = store[i];
  54586. break;
  54587. }
  54588. }
  54589. if (!item) {
  54590. store.push(item = {
  54591. model: coordModel, axisModels: [], coordIndex: coordIndex
  54592. });
  54593. }
  54594. item.axisModels.push(axisModel);
  54595. }
  54596. return coordSysLists;
  54597. }
  54598. });
  54599. var SliderZoomModel = DataZoomModel.extend({
  54600. type: 'dataZoom.slider',
  54601. layoutMode: 'box',
  54602. /**
  54603. * @protected
  54604. */
  54605. defaultOption: {
  54606. show: true,
  54607. // ph => placeholder. Using placehoder here because
  54608. // deault value can only be drived in view stage.
  54609. right: 'ph', // Default align to grid rect.
  54610. top: 'ph', // Default align to grid rect.
  54611. width: 'ph', // Default align to grid rect.
  54612. height: 'ph', // Default align to grid rect.
  54613. left: null, // Default align to grid rect.
  54614. bottom: null, // Default align to grid rect.
  54615. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  54616. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  54617. // highest priority, remain for compatibility of
  54618. // previous version, but not recommended any more.
  54619. dataBackground: {
  54620. lineStyle: {
  54621. color: '#2f4554',
  54622. width: 0.5,
  54623. opacity: 0.3
  54624. },
  54625. areaStyle: {
  54626. color: 'rgba(47,69,84,0.3)',
  54627. opacity: 0.3
  54628. }
  54629. },
  54630. borderColor: '#ddd', // border color of the box. For compatibility,
  54631. // if dataBackgroundColor is set, borderColor
  54632. // is ignored.
  54633. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  54634. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  54635. // 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',
  54636. 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',
  54637. // Percent of the slider height
  54638. handleSize: '100%',
  54639. handleStyle: {
  54640. color: '#a7b7cc'
  54641. },
  54642. labelPrecision: null,
  54643. labelFormatter: null,
  54644. showDetail: true,
  54645. showDataShadow: 'auto', // Default auto decision.
  54646. realtime: true,
  54647. zoomLock: false, // Whether disable zoom.
  54648. textStyle: {
  54649. color: '#333'
  54650. }
  54651. }
  54652. });
  54653. var Rect$2 = Rect;
  54654. var linearMap$2 = linearMap;
  54655. var asc$2 = asc;
  54656. var bind$4 = bind;
  54657. var each$26 = each$1;
  54658. // Constants
  54659. var DEFAULT_LOCATION_EDGE_GAP = 7;
  54660. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  54661. var DEFAULT_FILLER_SIZE = 30;
  54662. var HORIZONTAL = 'horizontal';
  54663. var VERTICAL = 'vertical';
  54664. var LABEL_GAP = 5;
  54665. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  54666. var SliderZoomView = DataZoomView.extend({
  54667. type: 'dataZoom.slider',
  54668. init: function (ecModel, api) {
  54669. /**
  54670. * @private
  54671. * @type {Object}
  54672. */
  54673. this._displayables = {};
  54674. /**
  54675. * @private
  54676. * @type {string}
  54677. */
  54678. this._orient;
  54679. /**
  54680. * [0, 100]
  54681. * @private
  54682. */
  54683. this._range;
  54684. /**
  54685. * [coord of the first handle, coord of the second handle]
  54686. * @private
  54687. */
  54688. this._handleEnds;
  54689. /**
  54690. * [length, thick]
  54691. * @private
  54692. * @type {Array.<number>}
  54693. */
  54694. this._size;
  54695. /**
  54696. * @private
  54697. * @type {number}
  54698. */
  54699. this._handleWidth;
  54700. /**
  54701. * @private
  54702. * @type {number}
  54703. */
  54704. this._handleHeight;
  54705. /**
  54706. * @private
  54707. */
  54708. this._location;
  54709. /**
  54710. * @private
  54711. */
  54712. this._dragging;
  54713. /**
  54714. * @private
  54715. */
  54716. this._dataShadowInfo;
  54717. this.api = api;
  54718. },
  54719. /**
  54720. * @override
  54721. */
  54722. render: function (dataZoomModel, ecModel, api, payload) {
  54723. SliderZoomView.superApply(this, 'render', arguments);
  54724. createOrUpdate(
  54725. this,
  54726. '_dispatchZoomAction',
  54727. this.dataZoomModel.get('throttle'),
  54728. 'fixRate'
  54729. );
  54730. this._orient = dataZoomModel.get('orient');
  54731. if (this.dataZoomModel.get('show') === false) {
  54732. this.group.removeAll();
  54733. return;
  54734. }
  54735. // Notice: this._resetInterval() should not be executed when payload.type
  54736. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  54737. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  54738. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  54739. this._buildView();
  54740. }
  54741. this._updateView();
  54742. },
  54743. /**
  54744. * @override
  54745. */
  54746. remove: function () {
  54747. SliderZoomView.superApply(this, 'remove', arguments);
  54748. clear(this, '_dispatchZoomAction');
  54749. },
  54750. /**
  54751. * @override
  54752. */
  54753. dispose: function () {
  54754. SliderZoomView.superApply(this, 'dispose', arguments);
  54755. clear(this, '_dispatchZoomAction');
  54756. },
  54757. _buildView: function () {
  54758. var thisGroup = this.group;
  54759. thisGroup.removeAll();
  54760. this._resetLocation();
  54761. this._resetInterval();
  54762. var barGroup = this._displayables.barGroup = new Group();
  54763. this._renderBackground();
  54764. this._renderHandle();
  54765. this._renderDataShadow();
  54766. thisGroup.add(barGroup);
  54767. this._positionGroup();
  54768. },
  54769. /**
  54770. * @private
  54771. */
  54772. _resetLocation: function () {
  54773. var dataZoomModel = this.dataZoomModel;
  54774. var api = this.api;
  54775. // If some of x/y/width/height are not specified,
  54776. // auto-adapt according to target grid.
  54777. var coordRect = this._findCoordRect();
  54778. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  54779. // Default align by coordinate system rect.
  54780. var positionInfo = this._orient === HORIZONTAL
  54781. ? {
  54782. // Why using 'right', because right should be used in vertical,
  54783. // and it is better to be consistent for dealing with position param merge.
  54784. right: ecSize.width - coordRect.x - coordRect.width,
  54785. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  54786. width: coordRect.width,
  54787. height: DEFAULT_FILLER_SIZE
  54788. }
  54789. : { // vertical
  54790. right: DEFAULT_LOCATION_EDGE_GAP,
  54791. top: coordRect.y,
  54792. width: DEFAULT_FILLER_SIZE,
  54793. height: coordRect.height
  54794. };
  54795. // Do not write back to option and replace value 'ph', because
  54796. // the 'ph' value should be recalculated when resize.
  54797. var layoutParams = getLayoutParams(dataZoomModel.option);
  54798. // Replace the placeholder value.
  54799. each$1(['right', 'top', 'width', 'height'], function (name) {
  54800. if (layoutParams[name] === 'ph') {
  54801. layoutParams[name] = positionInfo[name];
  54802. }
  54803. });
  54804. var layoutRect = getLayoutRect(
  54805. layoutParams,
  54806. ecSize,
  54807. dataZoomModel.padding
  54808. );
  54809. this._location = {x: layoutRect.x, y: layoutRect.y};
  54810. this._size = [layoutRect.width, layoutRect.height];
  54811. this._orient === VERTICAL && this._size.reverse();
  54812. },
  54813. /**
  54814. * @private
  54815. */
  54816. _positionGroup: function () {
  54817. var thisGroup = this.group;
  54818. var location = this._location;
  54819. var orient = this._orient;
  54820. // Just use the first axis to determine mapping.
  54821. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  54822. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  54823. var barGroup = this._displayables.barGroup;
  54824. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  54825. // Transform barGroup.
  54826. barGroup.attr(
  54827. (orient === HORIZONTAL && !inverse)
  54828. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  54829. : (orient === HORIZONTAL && inverse)
  54830. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  54831. : (orient === VERTICAL && !inverse)
  54832. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  54833. // Dont use Math.PI, considering shadow direction.
  54834. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  54835. );
  54836. // Position barGroup
  54837. var rect = thisGroup.getBoundingRect([barGroup]);
  54838. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  54839. },
  54840. /**
  54841. * @private
  54842. */
  54843. _getViewExtent: function () {
  54844. return [0, this._size[0]];
  54845. },
  54846. _renderBackground: function () {
  54847. var dataZoomModel = this.dataZoomModel;
  54848. var size = this._size;
  54849. var barGroup = this._displayables.barGroup;
  54850. barGroup.add(new Rect$2({
  54851. silent: true,
  54852. shape: {
  54853. x: 0, y: 0, width: size[0], height: size[1]
  54854. },
  54855. style: {
  54856. fill: dataZoomModel.get('backgroundColor')
  54857. },
  54858. z2: -40
  54859. }));
  54860. // Click panel, over shadow, below handles.
  54861. barGroup.add(new Rect$2({
  54862. shape: {
  54863. x: 0, y: 0, width: size[0], height: size[1]
  54864. },
  54865. style: {
  54866. fill: 'transparent'
  54867. },
  54868. z2: 0,
  54869. onclick: bind(this._onClickPanelClick, this)
  54870. }));
  54871. },
  54872. _renderDataShadow: function () {
  54873. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  54874. if (!info) {
  54875. return;
  54876. }
  54877. var size = this._size;
  54878. var seriesModel = info.series;
  54879. var data = seriesModel.getRawData();
  54880. var otherDim = seriesModel.getShadowDim
  54881. ? seriesModel.getShadowDim() // @see candlestick
  54882. : info.otherDim;
  54883. if (otherDim == null) {
  54884. return;
  54885. }
  54886. var otherDataExtent = data.getDataExtent(otherDim);
  54887. // Nice extent.
  54888. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  54889. otherDataExtent = [
  54890. otherDataExtent[0] - otherOffset,
  54891. otherDataExtent[1] + otherOffset
  54892. ];
  54893. var otherShadowExtent = [0, size[1]];
  54894. var thisShadowExtent = [0, size[0]];
  54895. var areaPoints = [[size[0], 0], [0, 0]];
  54896. var linePoints = [];
  54897. var step = thisShadowExtent[1] / (data.count() - 1);
  54898. var thisCoord = 0;
  54899. // Optimize for large data shadow
  54900. var stride = Math.round(data.count() / size[0]);
  54901. var lastIsEmpty;
  54902. data.each([otherDim], function (value, index) {
  54903. if (stride > 0 && (index % stride)) {
  54904. thisCoord += step;
  54905. return;
  54906. }
  54907. // FIXME
  54908. // Should consider axis.min/axis.max when drawing dataShadow.
  54909. // FIXME
  54910. // 应该使用统一的空判断?还是在list里进行空判断?
  54911. var isEmpty = value == null || isNaN(value) || value === '';
  54912. // See #4235.
  54913. var otherCoord = isEmpty
  54914. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  54915. // Attempt to draw data shadow precisely when there are empty value.
  54916. if (isEmpty && !lastIsEmpty && index) {
  54917. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  54918. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  54919. }
  54920. else if (!isEmpty && lastIsEmpty) {
  54921. areaPoints.push([thisCoord, 0]);
  54922. linePoints.push([thisCoord, 0]);
  54923. }
  54924. areaPoints.push([thisCoord, otherCoord]);
  54925. linePoints.push([thisCoord, otherCoord]);
  54926. thisCoord += step;
  54927. lastIsEmpty = isEmpty;
  54928. });
  54929. var dataZoomModel = this.dataZoomModel;
  54930. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  54931. this._displayables.barGroup.add(new Polygon({
  54932. shape: {points: areaPoints},
  54933. style: defaults(
  54934. {fill: dataZoomModel.get('dataBackgroundColor')},
  54935. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  54936. ),
  54937. silent: true,
  54938. z2: -20
  54939. }));
  54940. this._displayables.barGroup.add(new Polyline({
  54941. shape: {points: linePoints},
  54942. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  54943. silent: true,
  54944. z2: -19
  54945. }));
  54946. },
  54947. _prepareDataShadowInfo: function () {
  54948. var dataZoomModel = this.dataZoomModel;
  54949. var showDataShadow = dataZoomModel.get('showDataShadow');
  54950. if (showDataShadow === false) {
  54951. return;
  54952. }
  54953. // Find a representative series.
  54954. var result;
  54955. var ecModel = this.ecModel;
  54956. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  54957. var seriesModels = dataZoomModel
  54958. .getAxisProxy(dimNames.name, axisIndex)
  54959. .getTargetSeriesModels();
  54960. each$1(seriesModels, function (seriesModel) {
  54961. if (result) {
  54962. return;
  54963. }
  54964. if (showDataShadow !== true && indexOf(
  54965. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  54966. ) < 0
  54967. ) {
  54968. return;
  54969. }
  54970. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  54971. var otherDim = getOtherDim(dimNames.name);
  54972. var otherAxisInverse;
  54973. var coordSys = seriesModel.coordinateSystem;
  54974. if (otherDim != null && coordSys.getOtherAxis) {
  54975. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  54976. }
  54977. result = {
  54978. thisAxis: thisAxis,
  54979. series: seriesModel,
  54980. thisDim: dimNames.name,
  54981. otherDim: otherDim,
  54982. otherAxisInverse: otherAxisInverse
  54983. };
  54984. }, this);
  54985. }, this);
  54986. return result;
  54987. },
  54988. _renderHandle: function () {
  54989. var displaybles = this._displayables;
  54990. var handles = displaybles.handles = [];
  54991. var handleLabels = displaybles.handleLabels = [];
  54992. var barGroup = this._displayables.barGroup;
  54993. var size = this._size;
  54994. var dataZoomModel = this.dataZoomModel;
  54995. barGroup.add(displaybles.filler = new Rect$2({
  54996. draggable: true,
  54997. cursor: getCursor(this._orient),
  54998. drift: bind$4(this._onDragMove, this, 'all'),
  54999. onmousemove: function (e) {
  55000. // Fot mobile devicem, prevent screen slider on the button.
  55001. stop(e.event);
  55002. },
  55003. ondragstart: bind$4(this._showDataInfo, this, true),
  55004. ondragend: bind$4(this._onDragEnd, this),
  55005. onmouseover: bind$4(this._showDataInfo, this, true),
  55006. onmouseout: bind$4(this._showDataInfo, this, false),
  55007. style: {
  55008. fill: dataZoomModel.get('fillerColor'),
  55009. textPosition : 'inside'
  55010. }
  55011. }));
  55012. // Frame border.
  55013. barGroup.add(new Rect$2(subPixelOptimizeRect({
  55014. silent: true,
  55015. shape: {
  55016. x: 0,
  55017. y: 0,
  55018. width: size[0],
  55019. height: size[1]
  55020. },
  55021. style: {
  55022. stroke: dataZoomModel.get('dataBackgroundColor')
  55023. || dataZoomModel.get('borderColor'),
  55024. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  55025. fill: 'rgba(0,0,0,0)'
  55026. }
  55027. })));
  55028. each$26([0, 1], function (handleIndex) {
  55029. var path = createIcon(
  55030. dataZoomModel.get('handleIcon'),
  55031. {
  55032. cursor: getCursor(this._orient),
  55033. draggable: true,
  55034. drift: bind$4(this._onDragMove, this, handleIndex),
  55035. onmousemove: function (e) {
  55036. // Fot mobile devicem, prevent screen slider on the button.
  55037. stop(e.event);
  55038. },
  55039. ondragend: bind$4(this._onDragEnd, this),
  55040. onmouseover: bind$4(this._showDataInfo, this, true),
  55041. onmouseout: bind$4(this._showDataInfo, this, false)
  55042. },
  55043. {x: -1, y: 0, width: 2, height: 2}
  55044. );
  55045. var bRect = path.getBoundingRect();
  55046. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  55047. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  55048. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  55049. var handleColor = dataZoomModel.get('handleColor');
  55050. // Compatitable with previous version
  55051. if (handleColor != null) {
  55052. path.style.fill = handleColor;
  55053. }
  55054. barGroup.add(handles[handleIndex] = path);
  55055. var textStyleModel = dataZoomModel.textStyleModel;
  55056. this.group.add(
  55057. handleLabels[handleIndex] = new Text({
  55058. silent: true,
  55059. invisible: true,
  55060. style: {
  55061. x: 0, y: 0, text: '',
  55062. textVerticalAlign: 'middle',
  55063. textAlign: 'center',
  55064. textFill: textStyleModel.getTextColor(),
  55065. textFont: textStyleModel.getFont()
  55066. },
  55067. z2: 10
  55068. }));
  55069. }, this);
  55070. },
  55071. /**
  55072. * @private
  55073. */
  55074. _resetInterval: function () {
  55075. var range = this._range = this.dataZoomModel.getPercentRange();
  55076. var viewExtent = this._getViewExtent();
  55077. this._handleEnds = [
  55078. linearMap$2(range[0], [0, 100], viewExtent, true),
  55079. linearMap$2(range[1], [0, 100], viewExtent, true)
  55080. ];
  55081. },
  55082. /**
  55083. * @private
  55084. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  55085. * @param {number} delta
  55086. */
  55087. _updateInterval: function (handleIndex, delta) {
  55088. var dataZoomModel = this.dataZoomModel;
  55089. var handleEnds = this._handleEnds;
  55090. var viewExtend = this._getViewExtent();
  55091. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55092. var percentExtent = [0, 100];
  55093. sliderMove(
  55094. delta,
  55095. handleEnds,
  55096. viewExtend,
  55097. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  55098. minMaxSpan.minSpan != null
  55099. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  55100. minMaxSpan.maxSpan != null
  55101. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  55102. );
  55103. this._range = asc$2([
  55104. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  55105. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  55106. ]);
  55107. },
  55108. /**
  55109. * @private
  55110. */
  55111. _updateView: function (nonRealtime) {
  55112. var displaybles = this._displayables;
  55113. var handleEnds = this._handleEnds;
  55114. var handleInterval = asc$2(handleEnds.slice());
  55115. var size = this._size;
  55116. each$26([0, 1], function (handleIndex) {
  55117. // Handles
  55118. var handle = displaybles.handles[handleIndex];
  55119. var handleHeight = this._handleHeight;
  55120. handle.attr({
  55121. scale: [handleHeight / 2, handleHeight / 2],
  55122. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  55123. });
  55124. }, this);
  55125. // Filler
  55126. displaybles.filler.setShape({
  55127. x: handleInterval[0],
  55128. y: 0,
  55129. width: handleInterval[1] - handleInterval[0],
  55130. height: size[1]
  55131. });
  55132. this._updateDataInfo(nonRealtime);
  55133. },
  55134. /**
  55135. * @private
  55136. */
  55137. _updateDataInfo: function (nonRealtime) {
  55138. var dataZoomModel = this.dataZoomModel;
  55139. var displaybles = this._displayables;
  55140. var handleLabels = displaybles.handleLabels;
  55141. var orient = this._orient;
  55142. var labelTexts = ['', ''];
  55143. // FIXME
  55144. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  55145. if (dataZoomModel.get('showDetail')) {
  55146. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55147. if (axisProxy) {
  55148. var axis = axisProxy.getAxisModel().axis;
  55149. var range = this._range;
  55150. var dataInterval = nonRealtime
  55151. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  55152. ? axisProxy.calculateDataWindow({
  55153. start: range[0], end: range[1]
  55154. }).valueWindow
  55155. : axisProxy.getDataValueWindow();
  55156. labelTexts = [
  55157. this._formatLabel(dataInterval[0], axis),
  55158. this._formatLabel(dataInterval[1], axis)
  55159. ];
  55160. }
  55161. }
  55162. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  55163. setLabel.call(this, 0);
  55164. setLabel.call(this, 1);
  55165. function setLabel(handleIndex) {
  55166. // Label
  55167. // Text should not transform by barGroup.
  55168. // Ignore handlers transform
  55169. var barTransform = getTransform(
  55170. displaybles.handles[handleIndex].parent, this.group
  55171. );
  55172. var direction = transformDirection(
  55173. handleIndex === 0 ? 'right' : 'left', barTransform
  55174. );
  55175. var offset = this._handleWidth / 2 + LABEL_GAP;
  55176. var textPoint = applyTransform$1(
  55177. [
  55178. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  55179. this._size[1] / 2
  55180. ],
  55181. barTransform
  55182. );
  55183. handleLabels[handleIndex].setStyle({
  55184. x: textPoint[0],
  55185. y: textPoint[1],
  55186. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  55187. textAlign: orient === HORIZONTAL ? direction : 'center',
  55188. text: labelTexts[handleIndex]
  55189. });
  55190. }
  55191. },
  55192. /**
  55193. * @private
  55194. */
  55195. _formatLabel: function (value, axis) {
  55196. var dataZoomModel = this.dataZoomModel;
  55197. var labelFormatter = dataZoomModel.get('labelFormatter');
  55198. var labelPrecision = dataZoomModel.get('labelPrecision');
  55199. if (labelPrecision == null || labelPrecision === 'auto') {
  55200. labelPrecision = axis.getPixelPrecision();
  55201. }
  55202. var valueStr = (value == null || isNaN(value))
  55203. ? ''
  55204. // FIXME Glue code
  55205. : (axis.type === 'category' || axis.type === 'time')
  55206. ? axis.scale.getLabel(Math.round(value))
  55207. // param of toFixed should less then 20.
  55208. : value.toFixed(Math.min(labelPrecision, 20));
  55209. return isFunction(labelFormatter)
  55210. ? labelFormatter(value, valueStr)
  55211. : isString(labelFormatter)
  55212. ? labelFormatter.replace('{value}', valueStr)
  55213. : valueStr;
  55214. },
  55215. /**
  55216. * @private
  55217. * @param {boolean} showOrHide true: show, false: hide
  55218. */
  55219. _showDataInfo: function (showOrHide) {
  55220. // Always show when drgging.
  55221. showOrHide = this._dragging || showOrHide;
  55222. var handleLabels = this._displayables.handleLabels;
  55223. handleLabels[0].attr('invisible', !showOrHide);
  55224. handleLabels[1].attr('invisible', !showOrHide);
  55225. },
  55226. _onDragMove: function (handleIndex, dx, dy) {
  55227. this._dragging = true;
  55228. // Transform dx, dy to bar coordination.
  55229. var barTransform = this._displayables.barGroup.getLocalTransform();
  55230. var vertex = applyTransform$1([dx, dy], barTransform, true);
  55231. this._updateInterval(handleIndex, vertex[0]);
  55232. var realtime = this.dataZoomModel.get('realtime');
  55233. this._updateView(!realtime);
  55234. if (realtime) {
  55235. realtime && this._dispatchZoomAction();
  55236. }
  55237. },
  55238. _onDragEnd: function () {
  55239. this._dragging = false;
  55240. this._showDataInfo(false);
  55241. this._dispatchZoomAction();
  55242. },
  55243. _onClickPanelClick: function (e) {
  55244. var size = this._size;
  55245. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  55246. if (localPoint[0] < 0 || localPoint[0] > size[0]
  55247. || localPoint[1] < 0 || localPoint[1] > size[1]
  55248. ) {
  55249. return;
  55250. }
  55251. var handleEnds = this._handleEnds;
  55252. var center = (handleEnds[0] + handleEnds[1]) / 2;
  55253. this._updateInterval('all', localPoint[0] - center);
  55254. this._updateView();
  55255. this._dispatchZoomAction();
  55256. },
  55257. /**
  55258. * This action will be throttled.
  55259. * @private
  55260. */
  55261. _dispatchZoomAction: function () {
  55262. var range = this._range;
  55263. this.api.dispatchAction({
  55264. type: 'dataZoom',
  55265. from: this.uid,
  55266. dataZoomId: this.dataZoomModel.id,
  55267. start: range[0],
  55268. end: range[1]
  55269. });
  55270. },
  55271. /**
  55272. * @private
  55273. */
  55274. _findCoordRect: function () {
  55275. // Find the grid coresponding to the first axis referred by dataZoom.
  55276. var rect;
  55277. each$26(this.getTargetCoordInfo(), function (coordInfoList) {
  55278. if (!rect && coordInfoList.length) {
  55279. var coordSys = coordInfoList[0].model.coordinateSystem;
  55280. rect = coordSys.getRect && coordSys.getRect();
  55281. }
  55282. });
  55283. if (!rect) {
  55284. var width = this.api.getWidth();
  55285. var height = this.api.getHeight();
  55286. rect = {
  55287. x: width * 0.2,
  55288. y: height * 0.2,
  55289. width: width * 0.6,
  55290. height: height * 0.6
  55291. };
  55292. }
  55293. return rect;
  55294. }
  55295. });
  55296. function getOtherDim(thisDim) {
  55297. // FIXME
  55298. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  55299. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  55300. return map$$1[thisDim];
  55301. }
  55302. function getCursor(orient) {
  55303. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  55304. }
  55305. DataZoomModel.extend({
  55306. type: 'dataZoom.inside',
  55307. /**
  55308. * @protected
  55309. */
  55310. defaultOption: {
  55311. disabled: false, // Whether disable this inside zoom.
  55312. zoomLock: false, // Whether disable zoom but only pan.
  55313. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  55314. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  55315. preventDefaultMouseMove: true
  55316. }
  55317. });
  55318. // Only create one roam controller for each coordinate system.
  55319. // one roam controller might be refered by two inside data zoom
  55320. // components (for example, one for x and one for y). When user
  55321. // pan or zoom, only dispatch one action for those data zoom
  55322. // components.
  55323. var curry$6 = curry;
  55324. var ATTR$1 = '\0_ec_dataZoom_roams';
  55325. /**
  55326. * @public
  55327. * @param {module:echarts/ExtensionAPI} api
  55328. * @param {Object} dataZoomInfo
  55329. * @param {string} dataZoomInfo.coordId
  55330. * @param {Function} dataZoomInfo.containsPoint
  55331. * @param {Array.<string>} dataZoomInfo.allCoordIds
  55332. * @param {string} dataZoomInfo.dataZoomId
  55333. * @param {number} dataZoomInfo.throttleRate
  55334. * @param {Function} dataZoomInfo.panGetRange
  55335. * @param {Function} dataZoomInfo.zoomGetRange
  55336. * @param {boolean} [dataZoomInfo.zoomLock]
  55337. * @param {boolean} [dataZoomInfo.disabled]
  55338. */
  55339. function register$2(api, dataZoomInfo) {
  55340. var store = giveStore(api);
  55341. var theDataZoomId = dataZoomInfo.dataZoomId;
  55342. var theCoordId = dataZoomInfo.coordId;
  55343. // Do clean when a dataZoom changes its target coordnate system.
  55344. // Avoid memory leak, dispose all not-used-registered.
  55345. each$1(store, function (record, coordId) {
  55346. var dataZoomInfos = record.dataZoomInfos;
  55347. if (dataZoomInfos[theDataZoomId]
  55348. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  55349. ) {
  55350. delete dataZoomInfos[theDataZoomId];
  55351. record.count--;
  55352. }
  55353. });
  55354. cleanStore(store);
  55355. var record = store[theCoordId];
  55356. // Create if needed.
  55357. if (!record) {
  55358. record = store[theCoordId] = {
  55359. coordId: theCoordId,
  55360. dataZoomInfos: {},
  55361. count: 0
  55362. };
  55363. record.controller = createController(api, record);
  55364. record.dispatchAction = curry(dispatchAction$1, api);
  55365. }
  55366. // Update reference of dataZoom.
  55367. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  55368. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  55369. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  55370. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  55371. // Consider resize, area should be always updated.
  55372. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  55373. // Update throttle.
  55374. createOrUpdate(
  55375. record,
  55376. 'dispatchAction',
  55377. dataZoomInfo.throttleRate,
  55378. 'fixRate'
  55379. );
  55380. }
  55381. /**
  55382. * @public
  55383. * @param {module:echarts/ExtensionAPI} api
  55384. * @param {string} dataZoomId
  55385. */
  55386. function unregister$1(api, dataZoomId) {
  55387. var store = giveStore(api);
  55388. each$1(store, function (record) {
  55389. record.controller.dispose();
  55390. var dataZoomInfos = record.dataZoomInfos;
  55391. if (dataZoomInfos[dataZoomId]) {
  55392. delete dataZoomInfos[dataZoomId];
  55393. record.count--;
  55394. }
  55395. });
  55396. cleanStore(store);
  55397. }
  55398. /**
  55399. * @public
  55400. */
  55401. function shouldRecordRange(payload, dataZoomId) {
  55402. if (payload && payload.type === 'dataZoom' && payload.batch) {
  55403. for (var i = 0, len = payload.batch.length; i < len; i++) {
  55404. if (payload.batch[i].dataZoomId === dataZoomId) {
  55405. return false;
  55406. }
  55407. }
  55408. }
  55409. return true;
  55410. }
  55411. /**
  55412. * @public
  55413. */
  55414. function generateCoordId(coordModel) {
  55415. return coordModel.type + '\0_' + coordModel.id;
  55416. }
  55417. /**
  55418. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  55419. * @type {Array.<Object>}
  55420. */
  55421. function giveStore(api) {
  55422. // Mount store on zrender instance, so that we do not
  55423. // need to worry about dispose.
  55424. var zr = api.getZr();
  55425. return zr[ATTR$1] || (zr[ATTR$1] = {});
  55426. }
  55427. function createController(api, newRecord) {
  55428. var controller = new RoamController(api.getZr());
  55429. controller.on('pan', curry$6(onPan, newRecord));
  55430. controller.on('zoom', curry$6(onZoom, newRecord));
  55431. return controller;
  55432. }
  55433. function cleanStore(store) {
  55434. each$1(store, function (record, coordId) {
  55435. if (!record.count) {
  55436. record.controller.dispose();
  55437. delete store[coordId];
  55438. }
  55439. });
  55440. }
  55441. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  55442. wrapAndDispatch(record, function (info) {
  55443. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  55444. });
  55445. }
  55446. function onZoom(record, scale, mouseX, mouseY) {
  55447. wrapAndDispatch(record, function (info) {
  55448. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  55449. });
  55450. }
  55451. function wrapAndDispatch(record, getRange) {
  55452. var batch = [];
  55453. each$1(record.dataZoomInfos, function (info) {
  55454. var range = getRange(info);
  55455. !info.disabled && range && batch.push({
  55456. dataZoomId: info.dataZoomId,
  55457. start: range[0],
  55458. end: range[1]
  55459. });
  55460. });
  55461. record.dispatchAction(batch);
  55462. }
  55463. /**
  55464. * This action will be throttled.
  55465. */
  55466. function dispatchAction$1(api, batch) {
  55467. api.dispatchAction({
  55468. type: 'dataZoom',
  55469. batch: batch
  55470. });
  55471. }
  55472. /**
  55473. * Merge roamController settings when multiple dataZooms share one roamController.
  55474. */
  55475. function mergeControllerParams(dataZoomInfos) {
  55476. var controlType;
  55477. var opt = {};
  55478. var typePriority = {
  55479. 'true': 2,
  55480. 'move': 1,
  55481. 'false': 0,
  55482. 'undefined': -1
  55483. };
  55484. each$1(dataZoomInfos, function (dataZoomInfo) {
  55485. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  55486. typePriority[oneType] > typePriority[controlType] && (controlType = oneType);
  55487. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  55488. extend(opt, dataZoomInfo.roamControllerOpt);
  55489. });
  55490. return {
  55491. controlType: controlType,
  55492. opt: opt
  55493. };
  55494. }
  55495. var bind$5 = bind;
  55496. var InsideZoomView = DataZoomView.extend({
  55497. type: 'dataZoom.inside',
  55498. /**
  55499. * @override
  55500. */
  55501. init: function (ecModel, api) {
  55502. /**
  55503. * 'throttle' is used in this.dispatchAction, so we save range
  55504. * to avoid missing some 'pan' info.
  55505. * @private
  55506. * @type {Array.<number>}
  55507. */
  55508. this._range;
  55509. },
  55510. /**
  55511. * @override
  55512. */
  55513. render: function (dataZoomModel, ecModel, api, payload) {
  55514. InsideZoomView.superApply(this, 'render', arguments);
  55515. // Notice: origin this._range should be maintained, and should not be re-fetched
  55516. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  55517. // info will be missed because of 'throttle' of this.dispatchAction.
  55518. if (shouldRecordRange(payload, dataZoomModel.id)) {
  55519. this._range = dataZoomModel.getPercentRange();
  55520. }
  55521. // Reset controllers.
  55522. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  55523. var allCoordIds = map(coordInfoList, function (coordInfo) {
  55524. return generateCoordId(coordInfo.model);
  55525. });
  55526. each$1(coordInfoList, function (coordInfo) {
  55527. var coordModel = coordInfo.model;
  55528. var dataZoomOption = dataZoomModel.option;
  55529. register$2(
  55530. api,
  55531. {
  55532. coordId: generateCoordId(coordModel),
  55533. allCoordIds: allCoordIds,
  55534. containsPoint: function (e, x, y) {
  55535. return coordModel.coordinateSystem.containPoint([x, y]);
  55536. },
  55537. dataZoomId: dataZoomModel.id,
  55538. throttleRate: dataZoomModel.get('throttle', true),
  55539. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  55540. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  55541. zoomLock: dataZoomOption.zoomLock,
  55542. disabled: dataZoomOption.disabled,
  55543. roamControllerOpt: {
  55544. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  55545. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  55546. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  55547. }
  55548. }
  55549. );
  55550. }, this);
  55551. }, this);
  55552. },
  55553. /**
  55554. * @override
  55555. */
  55556. dispose: function () {
  55557. unregister$1(this.api, this.dataZoomModel.id);
  55558. InsideZoomView.superApply(this, 'dispose', arguments);
  55559. this._range = null;
  55560. },
  55561. /**
  55562. * @private
  55563. */
  55564. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  55565. var range = this._range.slice();
  55566. // Calculate transform by the first axis.
  55567. var axisModel = coordInfo.axisModels[0];
  55568. if (!axisModel) {
  55569. return;
  55570. }
  55571. var directionInfo = getDirectionInfo[coordSysName](
  55572. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  55573. );
  55574. var percentDelta = directionInfo.signal
  55575. * (range[1] - range[0])
  55576. * directionInfo.pixel / directionInfo.pixelLength;
  55577. sliderMove(percentDelta, range, [0, 100], 'all');
  55578. return (this._range = range);
  55579. },
  55580. /**
  55581. * @private
  55582. */
  55583. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  55584. var range = this._range.slice();
  55585. // Calculate transform by the first axis.
  55586. var axisModel = coordInfo.axisModels[0];
  55587. if (!axisModel) {
  55588. return;
  55589. }
  55590. var directionInfo = getDirectionInfo[coordSysName](
  55591. null, [mouseX, mouseY], axisModel, controller, coordInfo
  55592. );
  55593. var percentPoint = (
  55594. directionInfo.signal > 0
  55595. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  55596. : (directionInfo.pixel - directionInfo.pixelStart)
  55597. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  55598. scale = Math.max(1 / scale, 0);
  55599. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  55600. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  55601. // Restrict range.
  55602. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  55603. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  55604. return (this._range = range);
  55605. }
  55606. });
  55607. var getDirectionInfo = {
  55608. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55609. var axis = axisModel.axis;
  55610. var ret = {};
  55611. var rect = coordInfo.model.coordinateSystem.getRect();
  55612. oldPoint = oldPoint || [0, 0];
  55613. if (axis.dim === 'x') {
  55614. ret.pixel = newPoint[0] - oldPoint[0];
  55615. ret.pixelLength = rect.width;
  55616. ret.pixelStart = rect.x;
  55617. ret.signal = axis.inverse ? 1 : -1;
  55618. }
  55619. else { // axis.dim === 'y'
  55620. ret.pixel = newPoint[1] - oldPoint[1];
  55621. ret.pixelLength = rect.height;
  55622. ret.pixelStart = rect.y;
  55623. ret.signal = axis.inverse ? -1 : 1;
  55624. }
  55625. return ret;
  55626. },
  55627. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55628. var axis = axisModel.axis;
  55629. var ret = {};
  55630. var polar = coordInfo.model.coordinateSystem;
  55631. var radiusExtent = polar.getRadiusAxis().getExtent();
  55632. var angleExtent = polar.getAngleAxis().getExtent();
  55633. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  55634. newPoint = polar.pointToCoord(newPoint);
  55635. if (axisModel.mainType === 'radiusAxis') {
  55636. ret.pixel = newPoint[0] - oldPoint[0];
  55637. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  55638. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  55639. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  55640. ret.pixelStart = radiusExtent[0];
  55641. ret.signal = axis.inverse ? 1 : -1;
  55642. }
  55643. else { // 'angleAxis'
  55644. ret.pixel = newPoint[1] - oldPoint[1];
  55645. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  55646. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  55647. ret.pixelLength = angleExtent[1] - angleExtent[0];
  55648. ret.pixelStart = angleExtent[0];
  55649. ret.signal = axis.inverse ? -1 : 1;
  55650. }
  55651. return ret;
  55652. },
  55653. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  55654. var axis = axisModel.axis;
  55655. var rect = coordInfo.model.coordinateSystem.getRect();
  55656. var ret = {};
  55657. oldPoint = oldPoint || [0, 0];
  55658. if (axis.orient === 'horizontal') {
  55659. ret.pixel = newPoint[0] - oldPoint[0];
  55660. ret.pixelLength = rect.width;
  55661. ret.pixelStart = rect.x;
  55662. ret.signal = axis.inverse ? 1 : -1;
  55663. }
  55664. else { // 'vertical'
  55665. ret.pixel = newPoint[1] - oldPoint[1];
  55666. ret.pixelLength = rect.height;
  55667. ret.pixelStart = rect.y;
  55668. ret.signal = axis.inverse ? -1 : 1;
  55669. }
  55670. return ret;
  55671. }
  55672. };
  55673. registerProcessor(function (ecModel, api) {
  55674. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  55675. // We calculate window and reset axis here but not in model
  55676. // init stage and not after action dispatch handler, because
  55677. // reset should be called after seriesData.restoreData.
  55678. dataZoomModel.eachTargetAxis(resetSingleAxis);
  55679. // Caution: data zoom filtering is order sensitive when using
  55680. // percent range and no min/max/scale set on axis.
  55681. // For example, we have dataZoom definition:
  55682. // [
  55683. // {xAxisIndex: 0, start: 30, end: 70},
  55684. // {yAxisIndex: 0, start: 20, end: 80}
  55685. // ]
  55686. // In this case, [20, 80] of y-dataZoom should be based on data
  55687. // that have filtered by x-dataZoom using range of [30, 70],
  55688. // but should not be based on full raw data. Thus sliding
  55689. // x-dataZoom will change both ranges of xAxis and yAxis,
  55690. // while sliding y-dataZoom will only change the range of yAxis.
  55691. // So we should filter x-axis after reset x-axis immediately,
  55692. // and then reset y-axis and filter y-axis.
  55693. dataZoomModel.eachTargetAxis(filterSingleAxis);
  55694. });
  55695. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  55696. // Fullfill all of the range props so that user
  55697. // is able to get them from chart.getOption().
  55698. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  55699. var percentRange = axisProxy.getDataPercentWindow();
  55700. var valueRange = axisProxy.getDataValueWindow();
  55701. dataZoomModel.setRawRange({
  55702. start: percentRange[0],
  55703. end: percentRange[1],
  55704. startValue: valueRange[0],
  55705. endValue: valueRange[1]
  55706. }, true);
  55707. });
  55708. });
  55709. function resetSingleAxis(dimNames, axisIndex, dataZoomModel) {
  55710. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel);
  55711. }
  55712. function filterSingleAxis(dimNames, axisIndex, dataZoomModel) {
  55713. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel);
  55714. }
  55715. registerAction('dataZoom', function (payload, ecModel) {
  55716. var linkedNodesFinder = createLinkedNodesFinder(
  55717. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  55718. eachAxisDim$1,
  55719. function (model, dimNames) {
  55720. return model.get(dimNames.axisIndex);
  55721. }
  55722. );
  55723. var effectedModels = [];
  55724. ecModel.eachComponent(
  55725. {mainType: 'dataZoom', query: payload},
  55726. function (model, index) {
  55727. effectedModels.push.apply(
  55728. effectedModels, linkedNodesFinder(model).nodes
  55729. );
  55730. }
  55731. );
  55732. each$1(effectedModels, function (dataZoomModel, index) {
  55733. dataZoomModel.setRawRange({
  55734. start: payload.start,
  55735. end: payload.end,
  55736. startValue: payload.startValue,
  55737. endValue: payload.endValue
  55738. });
  55739. });
  55740. });
  55741. /**
  55742. * DataZoom component entry
  55743. */
  55744. var each$27 = each$1;
  55745. var preprocessor$2 = function (option) {
  55746. var visualMap = option && option.visualMap;
  55747. if (!isArray(visualMap)) {
  55748. visualMap = visualMap ? [visualMap] : [];
  55749. }
  55750. each$27(visualMap, function (opt) {
  55751. if (!opt) {
  55752. return;
  55753. }
  55754. // rename splitList to pieces
  55755. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  55756. opt.pieces = opt.splitList;
  55757. delete opt.splitList;
  55758. }
  55759. var pieces = opt.pieces;
  55760. if (pieces && isArray(pieces)) {
  55761. each$27(pieces, function (piece) {
  55762. if (isObject(piece)) {
  55763. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  55764. piece.min = piece.start;
  55765. }
  55766. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  55767. piece.max = piece.end;
  55768. }
  55769. }
  55770. });
  55771. }
  55772. });
  55773. };
  55774. function has$1(obj, name) {
  55775. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  55776. }
  55777. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  55778. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  55779. return (
  55780. !option.categories
  55781. && (
  55782. !(
  55783. option.pieces
  55784. ? option.pieces.length > 0
  55785. : option.splitNumber > 0
  55786. )
  55787. || option.calculable
  55788. )
  55789. )
  55790. ? 'continuous' : 'piecewise';
  55791. });
  55792. registerVisual(PRIORITY.VISUAL.COMPONENT, function (ecModel) {
  55793. ecModel.eachComponent('visualMap', function (visualMapModel) {
  55794. processSingleVisualMap(visualMapModel, ecModel);
  55795. });
  55796. prepareVisualMeta(ecModel);
  55797. });
  55798. function processSingleVisualMap(visualMapModel, ecModel) {
  55799. visualMapModel.eachTargetSeries(function (seriesModel) {
  55800. var data = seriesModel.getData();
  55801. applyVisual(
  55802. visualMapModel.stateList,
  55803. visualMapModel.targetVisuals,
  55804. data,
  55805. visualMapModel.getValueState,
  55806. visualMapModel,
  55807. visualMapModel.getDataDimension(data)
  55808. );
  55809. });
  55810. }
  55811. // Only support color.
  55812. function prepareVisualMeta(ecModel) {
  55813. ecModel.eachSeries(function (seriesModel) {
  55814. var data = seriesModel.getData();
  55815. var visualMetaList = [];
  55816. ecModel.eachComponent('visualMap', function (visualMapModel) {
  55817. if (visualMapModel.isTargetSeries(seriesModel)) {
  55818. var visualMeta = visualMapModel.getVisualMeta(
  55819. bind(getColorVisual, null, seriesModel, visualMapModel)
  55820. ) || {stops: [], outerColors: []};
  55821. visualMeta.dimension = visualMapModel.getDataDimension(data);
  55822. visualMetaList.push(visualMeta);
  55823. }
  55824. });
  55825. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  55826. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  55827. });
  55828. }
  55829. // FIXME
  55830. // performance and export for heatmap?
  55831. // value can be Infinity or -Infinity
  55832. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  55833. var mappings = visualMapModel.targetVisuals[valueState];
  55834. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  55835. var resultVisual = {
  55836. color: seriesModel.getData().getVisual('color') // default color.
  55837. };
  55838. for (var i = 0, len = visualTypes.length; i < len; i++) {
  55839. var type = visualTypes[i];
  55840. var mapping = mappings[
  55841. type === 'opacity' ? '__alphaForOpacity' : type
  55842. ];
  55843. mapping && mapping.applyVisual(value, getVisual, setVisual);
  55844. }
  55845. return resultVisual.color;
  55846. function getVisual(key) {
  55847. return resultVisual[key];
  55848. }
  55849. function setVisual(key, value) {
  55850. resultVisual[key] = value;
  55851. }
  55852. }
  55853. /**
  55854. * @file Visual mapping.
  55855. */
  55856. var visualDefault = {
  55857. /**
  55858. * @public
  55859. */
  55860. get: function (visualType, key, isCategory) {
  55861. var value = clone(
  55862. (defaultOption$3[visualType] || {})[key]
  55863. );
  55864. return isCategory
  55865. ? (isArray(value) ? value[value.length - 1] : value)
  55866. : value;
  55867. }
  55868. };
  55869. var defaultOption$3 = {
  55870. color: {
  55871. active: ['#006edd', '#e0ffff'],
  55872. inactive: ['rgba(0,0,0,0)']
  55873. },
  55874. colorHue: {
  55875. active: [0, 360],
  55876. inactive: [0, 0]
  55877. },
  55878. colorSaturation: {
  55879. active: [0.3, 1],
  55880. inactive: [0, 0]
  55881. },
  55882. colorLightness: {
  55883. active: [0.9, 0.5],
  55884. inactive: [0, 0]
  55885. },
  55886. colorAlpha: {
  55887. active: [0.3, 1],
  55888. inactive: [0, 0]
  55889. },
  55890. opacity: {
  55891. active: [0.3, 1],
  55892. inactive: [0, 0]
  55893. },
  55894. symbol: {
  55895. active: ['circle', 'roundRect', 'diamond'],
  55896. inactive: ['none']
  55897. },
  55898. symbolSize: {
  55899. active: [10, 50],
  55900. inactive: [0, 0]
  55901. }
  55902. };
  55903. var mapVisual$2 = VisualMapping.mapVisual;
  55904. var eachVisual = VisualMapping.eachVisual;
  55905. var isArray$3 = isArray;
  55906. var each$28 = each$1;
  55907. var asc$3 = asc;
  55908. var linearMap$3 = linearMap;
  55909. var noop$2 = noop;
  55910. var DEFAULT_COLOR = ['#f6efa6', '#d88273', '#bf444c'];
  55911. var VisualMapModel = extendComponentModel({
  55912. type: 'visualMap',
  55913. dependencies: ['series'],
  55914. /**
  55915. * @readOnly
  55916. * @type {Array.<string>}
  55917. */
  55918. stateList: ['inRange', 'outOfRange'],
  55919. /**
  55920. * @readOnly
  55921. * @type {Array.<string>}
  55922. */
  55923. replacableOptionKeys: [
  55924. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  55925. ],
  55926. /**
  55927. * [lowerBound, upperBound]
  55928. *
  55929. * @readOnly
  55930. * @type {Array.<number>}
  55931. */
  55932. dataBound: [-Infinity, Infinity],
  55933. /**
  55934. * @readOnly
  55935. * @type {string|Object}
  55936. */
  55937. layoutMode: {type: 'box', ignoreSize: true},
  55938. /**
  55939. * @protected
  55940. */
  55941. defaultOption: {
  55942. show: true,
  55943. zlevel: 0,
  55944. z: 4,
  55945. seriesIndex: 'all', // 'all' or null/undefined: all series.
  55946. // A number or an array of number: the specified series.
  55947. // set min: 0, max: 200, only for campatible with ec2.
  55948. // In fact min max should not have default value.
  55949. min: 0, // min value, must specified if pieces is not specified.
  55950. max: 200, // max value, must specified if pieces is not specified.
  55951. dimension: null,
  55952. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  55953. // 'symbol', 'symbolSize'
  55954. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  55955. // 'colorLightness', 'colorAlpha',
  55956. // 'symbol', 'symbolSize'
  55957. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  55958. right: null, // The same as left.
  55959. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  55960. bottom: 0, // The same as top.
  55961. itemWidth: null,
  55962. itemHeight: null,
  55963. inverse: false,
  55964. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  55965. backgroundColor: 'rgba(0,0,0,0)',
  55966. borderColor: '#ccc', // 值域边框颜色
  55967. contentColor: '#5793f3',
  55968. inactiveColor: '#aaa',
  55969. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  55970. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  55971. // 接受数组分别设定上右下左边距,同css
  55972. textGap: 10, //
  55973. precision: 0, // 小数精度,默认为0,无小数点
  55974. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  55975. formatter: null,
  55976. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  55977. textStyle: {
  55978. color: '#333' // 值域文字颜色
  55979. }
  55980. },
  55981. /**
  55982. * @protected
  55983. */
  55984. init: function (option, parentModel, ecModel) {
  55985. /**
  55986. * @private
  55987. * @type {Array.<number>}
  55988. */
  55989. this._dataExtent;
  55990. /**
  55991. * @readOnly
  55992. */
  55993. this.targetVisuals = {};
  55994. /**
  55995. * @readOnly
  55996. */
  55997. this.controllerVisuals = {};
  55998. /**
  55999. * @readOnly
  56000. */
  56001. this.textStyleModel;
  56002. /**
  56003. * [width, height]
  56004. * @readOnly
  56005. * @type {Array.<number>}
  56006. */
  56007. this.itemSize;
  56008. this.mergeDefaultAndTheme(option, ecModel);
  56009. },
  56010. /**
  56011. * @protected
  56012. */
  56013. optionUpdated: function (newOption, isInit) {
  56014. var thisOption = this.option;
  56015. // FIXME
  56016. // necessary?
  56017. // Disable realtime view update if canvas is not supported.
  56018. if (!env$1.canvasSupported) {
  56019. thisOption.realtime = false;
  56020. }
  56021. !isInit && replaceVisualOption(
  56022. thisOption, newOption, this.replacableOptionKeys
  56023. );
  56024. this.textStyleModel = this.getModel('textStyle');
  56025. this.resetItemSize();
  56026. this.completeVisualOption();
  56027. },
  56028. /**
  56029. * @protected
  56030. */
  56031. resetVisual: function (supplementVisualOption) {
  56032. var stateList = this.stateList;
  56033. supplementVisualOption = bind(supplementVisualOption, this);
  56034. this.controllerVisuals = createVisualMappings(
  56035. this.option.controller, stateList, supplementVisualOption
  56036. );
  56037. this.targetVisuals = createVisualMappings(
  56038. this.option.target, stateList, supplementVisualOption
  56039. );
  56040. },
  56041. /**
  56042. * @protected
  56043. * @return {Array.<number>} An array of series indices.
  56044. */
  56045. getTargetSeriesIndices: function () {
  56046. var optionSeriesIndex = this.option.seriesIndex;
  56047. var seriesIndices = [];
  56048. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  56049. this.ecModel.eachSeries(function (seriesModel, index) {
  56050. seriesIndices.push(index);
  56051. });
  56052. }
  56053. else {
  56054. seriesIndices = normalizeToArray(optionSeriesIndex);
  56055. }
  56056. return seriesIndices;
  56057. },
  56058. /**
  56059. * @public
  56060. */
  56061. eachTargetSeries: function (callback, context) {
  56062. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  56063. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  56064. }, this);
  56065. },
  56066. /**
  56067. * @pubilc
  56068. */
  56069. isTargetSeries: function (seriesModel) {
  56070. var is = false;
  56071. this.eachTargetSeries(function (model) {
  56072. model === seriesModel && (is = true);
  56073. });
  56074. return is;
  56075. },
  56076. /**
  56077. * @example
  56078. * this.formatValueText(someVal); // format single numeric value to text.
  56079. * this.formatValueText(someVal, true); // format single category value to text.
  56080. * this.formatValueText([min, max]); // format numeric min-max to text.
  56081. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  56082. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  56083. *
  56084. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  56085. * @param {boolean} [isCategory=false] Only available when value is number.
  56086. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  56087. * @return {string}
  56088. * @protected
  56089. */
  56090. formatValueText: function(value, isCategory, edgeSymbols) {
  56091. var option = this.option;
  56092. var precision = option.precision;
  56093. var dataBound = this.dataBound;
  56094. var formatter = option.formatter;
  56095. var isMinMax;
  56096. var textValue;
  56097. edgeSymbols = edgeSymbols || ['<', '>'];
  56098. if (isArray(value)) {
  56099. value = value.slice();
  56100. isMinMax = true;
  56101. }
  56102. textValue = isCategory
  56103. ? value
  56104. : (isMinMax
  56105. ? [toFixed(value[0]), toFixed(value[1])]
  56106. : toFixed(value)
  56107. );
  56108. if (isString(formatter)) {
  56109. return formatter
  56110. .replace('{value}', isMinMax ? textValue[0] : textValue)
  56111. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  56112. }
  56113. else if (isFunction(formatter)) {
  56114. return isMinMax
  56115. ? formatter(value[0], value[1])
  56116. : formatter(value);
  56117. }
  56118. if (isMinMax) {
  56119. if (value[0] === dataBound[0]) {
  56120. return edgeSymbols[0] + ' ' + textValue[1];
  56121. }
  56122. else if (value[1] === dataBound[1]) {
  56123. return edgeSymbols[1] + ' ' + textValue[0];
  56124. }
  56125. else {
  56126. return textValue[0] + ' - ' + textValue[1];
  56127. }
  56128. }
  56129. else { // Format single value (includes category case).
  56130. return textValue;
  56131. }
  56132. function toFixed(val) {
  56133. return val === dataBound[0]
  56134. ? 'min'
  56135. : val === dataBound[1]
  56136. ? 'max'
  56137. : (+val).toFixed(Math.min(precision, 20));
  56138. }
  56139. },
  56140. /**
  56141. * @protected
  56142. */
  56143. resetExtent: function () {
  56144. var thisOption = this.option;
  56145. // Can not calculate data extent by data here.
  56146. // Because series and data may be modified in processing stage.
  56147. // So we do not support the feature "auto min/max".
  56148. var extent = asc$3([thisOption.min, thisOption.max]);
  56149. this._dataExtent = extent;
  56150. },
  56151. /**
  56152. * @public
  56153. * @param {module:echarts/data/List} list
  56154. * @return {string} Concrete dimention. If return null/undefined,
  56155. * no dimension used.
  56156. */
  56157. getDataDimension: function (list) {
  56158. var optDim = this.option.dimension;
  56159. return optDim != null
  56160. ? optDim : list.dimensions.length - 1;
  56161. },
  56162. /**
  56163. * @public
  56164. * @override
  56165. */
  56166. getExtent: function () {
  56167. return this._dataExtent.slice();
  56168. },
  56169. /**
  56170. * @protected
  56171. */
  56172. completeVisualOption: function () {
  56173. var thisOption = this.option;
  56174. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  56175. var target = thisOption.target || (thisOption.target = {});
  56176. var controller = thisOption.controller || (thisOption.controller = {});
  56177. merge(target, base); // Do not override
  56178. merge(controller, base); // Do not override
  56179. var isCategory = this.isCategory();
  56180. completeSingle.call(this, target);
  56181. completeSingle.call(this, controller);
  56182. completeInactive.call(this, target, 'inRange', 'outOfRange');
  56183. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  56184. completeController.call(this, controller);
  56185. function completeSingle(base) {
  56186. // Compatible with ec2 dataRange.color.
  56187. // The mapping order of dataRange.color is: [high value, ..., low value]
  56188. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  56189. // Notice: ec2 has no inverse.
  56190. if (isArray$3(thisOption.color)
  56191. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  56192. // So adding color only when no inRange defined.
  56193. && !base.inRange
  56194. ) {
  56195. base.inRange = {color: thisOption.color.slice().reverse()};
  56196. }
  56197. // Compatible with previous logic, always give a defautl color, otherwise
  56198. // simple config with no inRange and outOfRange will not work.
  56199. // Originally we use visualMap.color as the default color, but setOption at
  56200. // the second time the default color will be erased. So we change to use
  56201. // constant DEFAULT_COLOR.
  56202. // If user do not want the defualt color, set inRange: {color: null}.
  56203. base.inRange = base.inRange || {color: DEFAULT_COLOR};
  56204. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  56205. each$28(this.stateList, function (state) {
  56206. var visualType = base[state];
  56207. if (isString(visualType)) {
  56208. var defa = visualDefault.get(visualType, 'active', isCategory);
  56209. if (defa) {
  56210. base[state] = {};
  56211. base[state][visualType] = defa;
  56212. }
  56213. else {
  56214. // Mark as not specified.
  56215. delete base[state];
  56216. }
  56217. }
  56218. }, this);
  56219. }
  56220. function completeInactive(base, stateExist, stateAbsent) {
  56221. var optExist = base[stateExist];
  56222. var optAbsent = base[stateAbsent];
  56223. if (optExist && !optAbsent) {
  56224. optAbsent = base[stateAbsent] = {};
  56225. each$28(optExist, function (visualData, visualType) {
  56226. if (!VisualMapping.isValidType(visualType)) {
  56227. return;
  56228. }
  56229. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  56230. if (defa != null) {
  56231. optAbsent[visualType] = defa;
  56232. // Compatibable with ec2:
  56233. // Only inactive color to rgba(0,0,0,0) can not
  56234. // make label transparent, so use opacity also.
  56235. if (visualType === 'color'
  56236. && !optAbsent.hasOwnProperty('opacity')
  56237. && !optAbsent.hasOwnProperty('colorAlpha')
  56238. ) {
  56239. optAbsent.opacity = [0, 0];
  56240. }
  56241. }
  56242. });
  56243. }
  56244. }
  56245. function completeController(controller) {
  56246. var symbolExists = (controller.inRange || {}).symbol
  56247. || (controller.outOfRange || {}).symbol;
  56248. var symbolSizeExists = (controller.inRange || {}).symbolSize
  56249. || (controller.outOfRange || {}).symbolSize;
  56250. var inactiveColor = this.get('inactiveColor');
  56251. each$28(this.stateList, function (state) {
  56252. var itemSize = this.itemSize;
  56253. var visuals = controller[state];
  56254. // Set inactive color for controller if no other color
  56255. // attr (like colorAlpha) specified.
  56256. if (!visuals) {
  56257. visuals = controller[state] = {
  56258. color: isCategory ? inactiveColor : [inactiveColor]
  56259. };
  56260. }
  56261. // Consistent symbol and symbolSize if not specified.
  56262. if (visuals.symbol == null) {
  56263. visuals.symbol = symbolExists
  56264. && clone(symbolExists)
  56265. || (isCategory ? 'roundRect' : ['roundRect']);
  56266. }
  56267. if (visuals.symbolSize == null) {
  56268. visuals.symbolSize = symbolSizeExists
  56269. && clone(symbolSizeExists)
  56270. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  56271. }
  56272. // Filter square and none.
  56273. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  56274. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  56275. });
  56276. // Normalize symbolSize
  56277. var symbolSize = visuals.symbolSize;
  56278. if (symbolSize != null) {
  56279. var max = -Infinity;
  56280. // symbolSize can be object when categories defined.
  56281. eachVisual(symbolSize, function (value) {
  56282. value > max && (max = value);
  56283. });
  56284. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  56285. return linearMap$3(value, [0, max], [0, itemSize[0]], true);
  56286. });
  56287. }
  56288. }, this);
  56289. }
  56290. },
  56291. /**
  56292. * @protected
  56293. */
  56294. resetItemSize: function () {
  56295. this.itemSize = [
  56296. parseFloat(this.get('itemWidth')),
  56297. parseFloat(this.get('itemHeight'))
  56298. ];
  56299. },
  56300. /**
  56301. * @public
  56302. */
  56303. isCategory: function () {
  56304. return !!this.option.categories;
  56305. },
  56306. /**
  56307. * @public
  56308. * @abstract
  56309. */
  56310. setSelected: noop$2,
  56311. /**
  56312. * @public
  56313. * @abstract
  56314. * @param {*|module:echarts/data/List} valueOrData
  56315. * @param {number} dataIndex
  56316. * @return {string} state See this.stateList
  56317. */
  56318. getValueState: noop$2,
  56319. /**
  56320. * FIXME
  56321. * Do not publish to thirt-part-dev temporarily
  56322. * util the interface is stable. (Should it return
  56323. * a function but not visual meta?)
  56324. *
  56325. * @pubilc
  56326. * @abstract
  56327. * @param {Function} getColorVisual
  56328. * params: value, valueState
  56329. * return: color
  56330. * @return {Object} visualMeta
  56331. * should includes {stops, outerColors}
  56332. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  56333. */
  56334. getVisualMeta: noop$2
  56335. });
  56336. // Constant
  56337. var DEFAULT_BAR_BOUND = [20, 140];
  56338. var ContinuousModel = VisualMapModel.extend({
  56339. type: 'visualMap.continuous',
  56340. /**
  56341. * @protected
  56342. */
  56343. defaultOption: {
  56344. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  56345. calculable: false, // This prop effect default component type determine,
  56346. // See echarts/component/visualMap/typeDefaulter.
  56347. range: null, // selected range. In default case `range` is [min, max]
  56348. // and can auto change along with modification of min max,
  56349. // util use specifid a range.
  56350. realtime: true, // Whether realtime update.
  56351. itemHeight: null, // The length of the range control edge.
  56352. itemWidth: null, // The length of the other side.
  56353. hoverLink: true, // Enable hover highlight.
  56354. hoverLinkDataSize: null,// The size of hovered data.
  56355. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  56356. // If not specified, follow the value of `realtime`.
  56357. },
  56358. /**
  56359. * @override
  56360. */
  56361. optionUpdated: function (newOption, isInit) {
  56362. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  56363. this.resetExtent();
  56364. this.resetVisual(function (mappingOption) {
  56365. mappingOption.mappingMethod = 'linear';
  56366. mappingOption.dataExtent = this.getExtent();
  56367. });
  56368. this._resetRange();
  56369. },
  56370. /**
  56371. * @protected
  56372. * @override
  56373. */
  56374. resetItemSize: function () {
  56375. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  56376. var itemSize = this.itemSize;
  56377. this._orient === 'horizontal' && itemSize.reverse();
  56378. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  56379. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  56380. },
  56381. /**
  56382. * @private
  56383. */
  56384. _resetRange: function () {
  56385. var dataExtent = this.getExtent();
  56386. var range = this.option.range;
  56387. if (!range || range.auto) {
  56388. // `range` should always be array (so we dont use other
  56389. // value like 'auto') for user-friend. (consider getOption).
  56390. dataExtent.auto = 1;
  56391. this.option.range = dataExtent;
  56392. }
  56393. else if (isArray(range)) {
  56394. if (range[0] > range[1]) {
  56395. range.reverse();
  56396. }
  56397. range[0] = Math.max(range[0], dataExtent[0]);
  56398. range[1] = Math.min(range[1], dataExtent[1]);
  56399. }
  56400. },
  56401. /**
  56402. * @protected
  56403. * @override
  56404. */
  56405. completeVisualOption: function () {
  56406. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  56407. each$1(this.stateList, function (state) {
  56408. var symbolSize = this.option.controller[state].symbolSize;
  56409. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  56410. symbolSize[0] = 0; // For good looking.
  56411. }
  56412. }, this);
  56413. },
  56414. /**
  56415. * @override
  56416. */
  56417. setSelected: function (selected) {
  56418. this.option.range = selected.slice();
  56419. this._resetRange();
  56420. },
  56421. /**
  56422. * @public
  56423. */
  56424. getSelected: function () {
  56425. var dataExtent = this.getExtent();
  56426. var dataInterval = asc(
  56427. (this.get('range') || []).slice()
  56428. );
  56429. // Clamp
  56430. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  56431. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  56432. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  56433. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  56434. return dataInterval;
  56435. },
  56436. /**
  56437. * @override
  56438. */
  56439. getValueState: function (value) {
  56440. var range = this.option.range;
  56441. var dataExtent = this.getExtent();
  56442. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  56443. // range[1] is processed likewise.
  56444. return (
  56445. (range[0] <= dataExtent[0] || range[0] <= value)
  56446. && (range[1] >= dataExtent[1] || value <= range[1])
  56447. ) ? 'inRange' : 'outOfRange';
  56448. },
  56449. /**
  56450. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  56451. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  56452. */
  56453. findTargetDataIndices: function (range) {
  56454. var result = [];
  56455. this.eachTargetSeries(function (seriesModel) {
  56456. var dataIndices = [];
  56457. var data = seriesModel.getData();
  56458. data.each(this.getDataDimension(data), function (value, dataIndex) {
  56459. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  56460. }, true, this);
  56461. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  56462. }, this);
  56463. return result;
  56464. },
  56465. /**
  56466. * @implement
  56467. */
  56468. getVisualMeta: function (getColorVisual) {
  56469. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  56470. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  56471. var stops = [];
  56472. function setStop(value, valueState) {
  56473. stops.push({
  56474. value: value,
  56475. color: getColorVisual(value, valueState)
  56476. });
  56477. }
  56478. // Format to: outOfRange -- inRange -- outOfRange.
  56479. var iIdx = 0;
  56480. var oIdx = 0;
  56481. var iLen = iVals.length;
  56482. var oLen = oVals.length;
  56483. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  56484. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  56485. if (oVals[oIdx] < iVals[iIdx]) {
  56486. setStop(oVals[oIdx], 'outOfRange');
  56487. }
  56488. }
  56489. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  56490. // If range is full, value beyond min, max will be clamped.
  56491. // make a singularity
  56492. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  56493. setStop(iVals[iIdx], 'inRange');
  56494. }
  56495. for (var first = 1; oIdx < oLen; oIdx++) {
  56496. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  56497. // make a singularity
  56498. if (first) {
  56499. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  56500. first = 0;
  56501. }
  56502. setStop(oVals[oIdx], 'outOfRange');
  56503. }
  56504. }
  56505. var stopsLen = stops.length;
  56506. return {
  56507. stops: stops,
  56508. outerColors: [
  56509. stopsLen ? stops[0].color : 'transparent',
  56510. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  56511. ]
  56512. };
  56513. }
  56514. });
  56515. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  56516. if (dataExtent[0] === dataExtent[1]) {
  56517. return dataExtent.slice();
  56518. }
  56519. // When using colorHue mapping, it is not linear color any more.
  56520. // Moreover, canvas gradient seems not to be accurate linear.
  56521. // FIXME
  56522. // Should be arbitrary value 100? or based on pixel size?
  56523. var count = 200;
  56524. var step = (dataExtent[1] - dataExtent[0]) / count;
  56525. var value = dataExtent[0];
  56526. var stopValues = [];
  56527. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  56528. stopValues.push(value);
  56529. value += step;
  56530. }
  56531. stopValues.push(dataExtent[1]);
  56532. return stopValues;
  56533. }
  56534. var VisualMapView = extendComponentView({
  56535. type: 'visualMap',
  56536. /**
  56537. * @readOnly
  56538. * @type {Object}
  56539. */
  56540. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  56541. init: function (ecModel, api) {
  56542. /**
  56543. * @readOnly
  56544. * @type {module:echarts/model/Global}
  56545. */
  56546. this.ecModel = ecModel;
  56547. /**
  56548. * @readOnly
  56549. * @type {module:echarts/ExtensionAPI}
  56550. */
  56551. this.api = api;
  56552. /**
  56553. * @readOnly
  56554. * @type {module:echarts/component/visualMap/visualMapModel}
  56555. */
  56556. this.visualMapModel;
  56557. },
  56558. /**
  56559. * @protected
  56560. */
  56561. render: function (visualMapModel, ecModel, api, payload) {
  56562. this.visualMapModel = visualMapModel;
  56563. if (visualMapModel.get('show') === false) {
  56564. this.group.removeAll();
  56565. return;
  56566. }
  56567. this.doRender.apply(this, arguments);
  56568. },
  56569. /**
  56570. * @protected
  56571. */
  56572. renderBackground: function (group) {
  56573. var visualMapModel = this.visualMapModel;
  56574. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  56575. var rect = group.getBoundingRect();
  56576. group.add(new Rect({
  56577. z2: -1, // Lay background rect on the lowest layer.
  56578. silent: true,
  56579. shape: {
  56580. x: rect.x - padding[3],
  56581. y: rect.y - padding[0],
  56582. width: rect.width + padding[3] + padding[1],
  56583. height: rect.height + padding[0] + padding[2]
  56584. },
  56585. style: {
  56586. fill: visualMapModel.get('backgroundColor'),
  56587. stroke: visualMapModel.get('borderColor'),
  56588. lineWidth: visualMapModel.get('borderWidth')
  56589. }
  56590. }));
  56591. },
  56592. /**
  56593. * @protected
  56594. * @param {number} targetValue can be Infinity or -Infinity
  56595. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  56596. * @param {Object} [opts]
  56597. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  56598. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  56599. * @return {*} Visual value.
  56600. */
  56601. getControllerVisual: function (targetValue, visualCluster, opts) {
  56602. opts = opts || {};
  56603. var forceState = opts.forceState;
  56604. var visualMapModel = this.visualMapModel;
  56605. var visualObj = {};
  56606. // Default values.
  56607. if (visualCluster === 'symbol') {
  56608. visualObj.symbol = visualMapModel.get('itemSymbol');
  56609. }
  56610. if (visualCluster === 'color') {
  56611. var defaultColor = visualMapModel.get('contentColor');
  56612. visualObj.color = defaultColor;
  56613. }
  56614. function getter(key) {
  56615. return visualObj[key];
  56616. }
  56617. function setter(key, value) {
  56618. visualObj[key] = value;
  56619. }
  56620. var mappings = visualMapModel.controllerVisuals[
  56621. forceState || visualMapModel.getValueState(targetValue)
  56622. ];
  56623. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  56624. each$1(visualTypes, function (type) {
  56625. var visualMapping = mappings[type];
  56626. if (opts.convertOpacityToAlpha && type === 'opacity') {
  56627. type = 'colorAlpha';
  56628. visualMapping = mappings.__alphaForOpacity;
  56629. }
  56630. if (VisualMapping.dependsOn(type, visualCluster)) {
  56631. visualMapping && visualMapping.applyVisual(
  56632. targetValue, getter, setter
  56633. );
  56634. }
  56635. });
  56636. return visualObj[visualCluster];
  56637. },
  56638. /**
  56639. * @protected
  56640. */
  56641. positionGroup: function (group) {
  56642. var model = this.visualMapModel;
  56643. var api = this.api;
  56644. positionElement(
  56645. group,
  56646. model.getBoxLayoutParams(),
  56647. {width: api.getWidth(), height: api.getHeight()}
  56648. );
  56649. },
  56650. /**
  56651. * @protected
  56652. * @abstract
  56653. */
  56654. doRender: noop
  56655. });
  56656. /**
  56657. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  56658. * @param {module:echarts/ExtensionAPI} api
  56659. * @param {Array.<number>} itemSize always [short, long]
  56660. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  56661. */
  56662. function getItemAlign(visualMapModel, api, itemSize) {
  56663. var modelOption = visualMapModel.option;
  56664. var itemAlign = modelOption.align;
  56665. if (itemAlign != null && itemAlign !== 'auto') {
  56666. return itemAlign;
  56667. }
  56668. // Auto decision align.
  56669. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  56670. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  56671. var paramsSet = [
  56672. ['left', 'right', 'width'],
  56673. ['top', 'bottom', 'height']
  56674. ];
  56675. var reals = paramsSet[realIndex];
  56676. var fakeValue = [0, null, 10];
  56677. var layoutInput = {};
  56678. for (var i = 0; i < 3; i++) {
  56679. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  56680. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  56681. }
  56682. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  56683. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  56684. return reals[
  56685. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  56686. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  56687. ];
  56688. }
  56689. /**
  56690. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  56691. * dataIndexInside means filtered index.
  56692. */
  56693. function convertDataIndex(batch) {
  56694. each$1(batch || [], function (batchItem) {
  56695. if (batch.dataIndex != null) {
  56696. batch.dataIndexInside = batch.dataIndex;
  56697. batch.dataIndex = null;
  56698. }
  56699. });
  56700. return batch;
  56701. }
  56702. var linearMap$4 = linearMap;
  56703. var each$29 = each$1;
  56704. var mathMin$7 = Math.min;
  56705. var mathMax$7 = Math.max;
  56706. // Arbitrary value
  56707. var HOVER_LINK_SIZE = 12;
  56708. var HOVER_LINK_OUT = 6;
  56709. // Notice:
  56710. // Any "interval" should be by the order of [low, high].
  56711. // "handle0" (handleIndex === 0) maps to
  56712. // low data value: this._dataInterval[0] and has low coord.
  56713. // "handle1" (handleIndex === 1) maps to
  56714. // high data value: this._dataInterval[1] and has high coord.
  56715. // The logic of transform is implemented in this._createBarGroup.
  56716. var ContinuousView = VisualMapView.extend({
  56717. type: 'visualMap.continuous',
  56718. /**
  56719. * @override
  56720. */
  56721. init: function () {
  56722. ContinuousView.superApply(this, 'init', arguments);
  56723. /**
  56724. * @private
  56725. */
  56726. this._shapes = {};
  56727. /**
  56728. * @private
  56729. */
  56730. this._dataInterval = [];
  56731. /**
  56732. * @private
  56733. */
  56734. this._handleEnds = [];
  56735. /**
  56736. * @private
  56737. */
  56738. this._orient;
  56739. /**
  56740. * @private
  56741. */
  56742. this._useHandle;
  56743. /**
  56744. * @private
  56745. */
  56746. this._hoverLinkDataIndices = [];
  56747. /**
  56748. * @private
  56749. */
  56750. this._dragging;
  56751. /**
  56752. * @private
  56753. */
  56754. this._hovering;
  56755. },
  56756. /**
  56757. * @protected
  56758. * @override
  56759. */
  56760. doRender: function (visualMapModel, ecModel, api, payload) {
  56761. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  56762. this._buildView();
  56763. }
  56764. },
  56765. /**
  56766. * @private
  56767. */
  56768. _buildView: function () {
  56769. this.group.removeAll();
  56770. var visualMapModel = this.visualMapModel;
  56771. var thisGroup = this.group;
  56772. this._orient = visualMapModel.get('orient');
  56773. this._useHandle = visualMapModel.get('calculable');
  56774. this._resetInterval();
  56775. this._renderBar(thisGroup);
  56776. var dataRangeText = visualMapModel.get('text');
  56777. this._renderEndsText(thisGroup, dataRangeText, 0);
  56778. this._renderEndsText(thisGroup, dataRangeText, 1);
  56779. // Do this for background size calculation.
  56780. this._updateView(true);
  56781. // After updating view, inner shapes is built completely,
  56782. // and then background can be rendered.
  56783. this.renderBackground(thisGroup);
  56784. // Real update view
  56785. this._updateView();
  56786. this._enableHoverLinkToSeries();
  56787. this._enableHoverLinkFromSeries();
  56788. this.positionGroup(thisGroup);
  56789. },
  56790. /**
  56791. * @private
  56792. */
  56793. _renderEndsText: function (group, dataRangeText, endsIndex) {
  56794. if (!dataRangeText) {
  56795. return;
  56796. }
  56797. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  56798. var text = dataRangeText[1 - endsIndex];
  56799. text = text != null ? text + '' : '';
  56800. var visualMapModel = this.visualMapModel;
  56801. var textGap = visualMapModel.get('textGap');
  56802. var itemSize = visualMapModel.itemSize;
  56803. var barGroup = this._shapes.barGroup;
  56804. var position = this._applyTransform(
  56805. [
  56806. itemSize[0] / 2,
  56807. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  56808. ],
  56809. barGroup
  56810. );
  56811. var align = this._applyTransform(
  56812. endsIndex === 0 ? 'bottom' : 'top',
  56813. barGroup
  56814. );
  56815. var orient = this._orient;
  56816. var textStyleModel = this.visualMapModel.textStyleModel;
  56817. this.group.add(new Text({
  56818. style: {
  56819. x: position[0],
  56820. y: position[1],
  56821. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  56822. textAlign: orient === 'horizontal' ? align : 'center',
  56823. text: text,
  56824. textFont: textStyleModel.getFont(),
  56825. textFill: textStyleModel.getTextColor()
  56826. }
  56827. }));
  56828. },
  56829. /**
  56830. * @private
  56831. */
  56832. _renderBar: function (targetGroup) {
  56833. var visualMapModel = this.visualMapModel;
  56834. var shapes = this._shapes;
  56835. var itemSize = visualMapModel.itemSize;
  56836. var orient = this._orient;
  56837. var useHandle = this._useHandle;
  56838. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  56839. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  56840. // Bar
  56841. barGroup.add(shapes.outOfRange = createPolygon());
  56842. barGroup.add(shapes.inRange = createPolygon(
  56843. null,
  56844. useHandle ? getCursor$1(this._orient) : null,
  56845. bind(this._dragHandle, this, 'all', false),
  56846. bind(this._dragHandle, this, 'all', true)
  56847. ));
  56848. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  56849. var textSize = mathMax$7(textRect.width, textRect.height);
  56850. // Handle
  56851. if (useHandle) {
  56852. shapes.handleThumbs = [];
  56853. shapes.handleLabels = [];
  56854. shapes.handleLabelPoints = [];
  56855. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  56856. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  56857. }
  56858. this._createIndicator(barGroup, itemSize, textSize, orient);
  56859. targetGroup.add(barGroup);
  56860. },
  56861. /**
  56862. * @private
  56863. */
  56864. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  56865. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  56866. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  56867. var handleThumb = createPolygon(
  56868. createHandlePoints(handleIndex, textSize),
  56869. getCursor$1(this._orient),
  56870. onDrift,
  56871. onDragEnd
  56872. );
  56873. handleThumb.position[0] = itemSize[0];
  56874. barGroup.add(handleThumb);
  56875. // Text is always horizontal layout but should not be effected by
  56876. // transform (orient/inverse). So label is built separately but not
  56877. // use zrender/graphic/helper/RectText, and is located based on view
  56878. // group (according to handleLabelPoint) but not barGroup.
  56879. var textStyleModel = this.visualMapModel.textStyleModel;
  56880. var handleLabel = new Text({
  56881. draggable: true,
  56882. drift: onDrift,
  56883. onmousemove: function (e) {
  56884. // Fot mobile devicem, prevent screen slider on the button.
  56885. stop(e.event);
  56886. },
  56887. ondragend: onDragEnd,
  56888. style: {
  56889. x: 0, y: 0, text: '',
  56890. textFont: textStyleModel.getFont(),
  56891. textFill: textStyleModel.getTextColor()
  56892. }
  56893. });
  56894. this.group.add(handleLabel);
  56895. var handleLabelPoint = [
  56896. orient === 'horizontal'
  56897. ? textSize / 2
  56898. : textSize * 1.5,
  56899. orient === 'horizontal'
  56900. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  56901. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  56902. ];
  56903. var shapes = this._shapes;
  56904. shapes.handleThumbs[handleIndex] = handleThumb;
  56905. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  56906. shapes.handleLabels[handleIndex] = handleLabel;
  56907. },
  56908. /**
  56909. * @private
  56910. */
  56911. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  56912. var indicator = createPolygon([[0, 0]], 'move');
  56913. indicator.position[0] = itemSize[0];
  56914. indicator.attr({invisible: true, silent: true});
  56915. barGroup.add(indicator);
  56916. var textStyleModel = this.visualMapModel.textStyleModel;
  56917. var indicatorLabel = new Text({
  56918. silent: true,
  56919. invisible: true,
  56920. style: {
  56921. x: 0, y: 0, text: '',
  56922. textFont: textStyleModel.getFont(),
  56923. textFill: textStyleModel.getTextColor()
  56924. }
  56925. });
  56926. this.group.add(indicatorLabel);
  56927. var indicatorLabelPoint = [
  56928. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  56929. 0
  56930. ];
  56931. var shapes = this._shapes;
  56932. shapes.indicator = indicator;
  56933. shapes.indicatorLabel = indicatorLabel;
  56934. shapes.indicatorLabelPoint = indicatorLabelPoint;
  56935. },
  56936. /**
  56937. * @private
  56938. */
  56939. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  56940. if (!this._useHandle) {
  56941. return;
  56942. }
  56943. this._dragging = !isEnd;
  56944. if (!isEnd) {
  56945. // Transform dx, dy to bar coordination.
  56946. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  56947. this._updateInterval(handleIndex, vertex[1]);
  56948. // Considering realtime, update view should be executed
  56949. // before dispatch action.
  56950. this._updateView();
  56951. }
  56952. // dragEnd do not dispatch action when realtime.
  56953. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  56954. this.api.dispatchAction({
  56955. type: 'selectDataRange',
  56956. from: this.uid,
  56957. visualMapId: this.visualMapModel.id,
  56958. selected: this._dataInterval.slice()
  56959. });
  56960. }
  56961. if (isEnd) {
  56962. !this._hovering && this._clearHoverLinkToSeries();
  56963. }
  56964. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  56965. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  56966. }
  56967. },
  56968. /**
  56969. * @private
  56970. */
  56971. _resetInterval: function () {
  56972. var visualMapModel = this.visualMapModel;
  56973. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  56974. var dataExtent = visualMapModel.getExtent();
  56975. var sizeExtent = [0, visualMapModel.itemSize[1]];
  56976. this._handleEnds = [
  56977. linearMap$4(dataInterval[0], dataExtent, sizeExtent, true),
  56978. linearMap$4(dataInterval[1], dataExtent, sizeExtent, true)
  56979. ];
  56980. },
  56981. /**
  56982. * @private
  56983. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  56984. * @param {number} dx
  56985. * @param {number} dy
  56986. */
  56987. _updateInterval: function (handleIndex, delta) {
  56988. delta = delta || 0;
  56989. var visualMapModel = this.visualMapModel;
  56990. var handleEnds = this._handleEnds;
  56991. var sizeExtent = [0, visualMapModel.itemSize[1]];
  56992. sliderMove(
  56993. delta,
  56994. handleEnds,
  56995. sizeExtent,
  56996. handleIndex,
  56997. // cross is forbiden
  56998. 0
  56999. );
  57000. var dataExtent = visualMapModel.getExtent();
  57001. // Update data interval.
  57002. this._dataInterval = [
  57003. linearMap$4(handleEnds[0], sizeExtent, dataExtent, true),
  57004. linearMap$4(handleEnds[1], sizeExtent, dataExtent, true)
  57005. ];
  57006. },
  57007. /**
  57008. * @private
  57009. */
  57010. _updateView: function (forSketch) {
  57011. var visualMapModel = this.visualMapModel;
  57012. var dataExtent = visualMapModel.getExtent();
  57013. var shapes = this._shapes;
  57014. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  57015. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  57016. var visualInRange = this._createBarVisual(
  57017. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  57018. );
  57019. var visualOutOfRange = this._createBarVisual(
  57020. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  57021. );
  57022. shapes.inRange
  57023. .setStyle({
  57024. fill: visualInRange.barColor,
  57025. opacity: visualInRange.opacity
  57026. })
  57027. .setShape('points', visualInRange.barPoints);
  57028. shapes.outOfRange
  57029. .setStyle({
  57030. fill: visualOutOfRange.barColor,
  57031. opacity: visualOutOfRange.opacity
  57032. })
  57033. .setShape('points', visualOutOfRange.barPoints);
  57034. this._updateHandle(inRangeHandleEnds, visualInRange);
  57035. },
  57036. /**
  57037. * @private
  57038. */
  57039. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  57040. var opts = {
  57041. forceState: forceState,
  57042. convertOpacityToAlpha: true
  57043. };
  57044. var colorStops = this._makeColorGradient(dataInterval, opts);
  57045. var symbolSizes = [
  57046. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  57047. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  57048. ];
  57049. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  57050. return {
  57051. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  57052. barPoints: barPoints,
  57053. handlesColor: [
  57054. colorStops[0].color,
  57055. colorStops[colorStops.length - 1].color
  57056. ]
  57057. };
  57058. },
  57059. /**
  57060. * @private
  57061. */
  57062. _makeColorGradient: function (dataInterval, opts) {
  57063. // Considering colorHue, which is not linear, so we have to sample
  57064. // to calculate gradient color stops, but not only caculate head
  57065. // and tail.
  57066. var sampleNumber = 100; // Arbitrary value.
  57067. var colorStops = [];
  57068. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  57069. colorStops.push({
  57070. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  57071. offset: 0
  57072. });
  57073. for (var i = 1; i < sampleNumber; i++) {
  57074. var currValue = dataInterval[0] + step * i;
  57075. if (currValue > dataInterval[1]) {
  57076. break;
  57077. }
  57078. colorStops.push({
  57079. color: this.getControllerVisual(currValue, 'color', opts),
  57080. offset: i / sampleNumber
  57081. });
  57082. }
  57083. colorStops.push({
  57084. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  57085. offset: 1
  57086. });
  57087. return colorStops;
  57088. },
  57089. /**
  57090. * @private
  57091. */
  57092. _createBarPoints: function (handleEnds, symbolSizes) {
  57093. var itemSize = this.visualMapModel.itemSize;
  57094. return [
  57095. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  57096. [itemSize[0], handleEnds[0]],
  57097. [itemSize[0], handleEnds[1]],
  57098. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  57099. ];
  57100. },
  57101. /**
  57102. * @private
  57103. */
  57104. _createBarGroup: function (itemAlign) {
  57105. var orient = this._orient;
  57106. var inverse = this.visualMapModel.get('inverse');
  57107. return new Group(
  57108. (orient === 'horizontal' && !inverse)
  57109. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  57110. : (orient === 'horizontal' && inverse)
  57111. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  57112. : (orient === 'vertical' && !inverse)
  57113. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  57114. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  57115. );
  57116. },
  57117. /**
  57118. * @private
  57119. */
  57120. _updateHandle: function (handleEnds, visualInRange) {
  57121. if (!this._useHandle) {
  57122. return;
  57123. }
  57124. var shapes = this._shapes;
  57125. var visualMapModel = this.visualMapModel;
  57126. var handleThumbs = shapes.handleThumbs;
  57127. var handleLabels = shapes.handleLabels;
  57128. each$29([0, 1], function (handleIndex) {
  57129. var handleThumb = handleThumbs[handleIndex];
  57130. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  57131. handleThumb.position[1] = handleEnds[handleIndex];
  57132. // Update handle label position.
  57133. var textPoint = applyTransform$1(
  57134. shapes.handleLabelPoints[handleIndex],
  57135. getTransform(handleThumb, this.group)
  57136. );
  57137. handleLabels[handleIndex].setStyle({
  57138. x: textPoint[0],
  57139. y: textPoint[1],
  57140. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  57141. textVerticalAlign: 'middle',
  57142. textAlign: this._applyTransform(
  57143. this._orient === 'horizontal'
  57144. ? (handleIndex === 0 ? 'bottom' : 'top')
  57145. : 'left',
  57146. shapes.barGroup
  57147. )
  57148. });
  57149. }, this);
  57150. },
  57151. /**
  57152. * @private
  57153. * @param {number} cursorValue
  57154. * @param {number} textValue
  57155. * @param {string} [rangeSymbol]
  57156. * @param {number} [halfHoverLinkSize]
  57157. */
  57158. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  57159. var visualMapModel = this.visualMapModel;
  57160. var dataExtent = visualMapModel.getExtent();
  57161. var itemSize = visualMapModel.itemSize;
  57162. var sizeExtent = [0, itemSize[1]];
  57163. var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true);
  57164. var shapes = this._shapes;
  57165. var indicator = shapes.indicator;
  57166. if (!indicator) {
  57167. return;
  57168. }
  57169. indicator.position[1] = pos;
  57170. indicator.attr('invisible', false);
  57171. indicator.setShape('points', createIndicatorPoints(
  57172. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  57173. ));
  57174. var opts = {convertOpacityToAlpha: true};
  57175. var color = this.getControllerVisual(cursorValue, 'color', opts);
  57176. indicator.setStyle('fill', color);
  57177. // Update handle label position.
  57178. var textPoint = applyTransform$1(
  57179. shapes.indicatorLabelPoint,
  57180. getTransform(indicator, this.group)
  57181. );
  57182. var indicatorLabel = shapes.indicatorLabel;
  57183. indicatorLabel.attr('invisible', false);
  57184. var align = this._applyTransform('left', shapes.barGroup);
  57185. var orient = this._orient;
  57186. indicatorLabel.setStyle({
  57187. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  57188. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  57189. textAlign: orient === 'horizontal' ? 'center' : align,
  57190. x: textPoint[0],
  57191. y: textPoint[1]
  57192. });
  57193. },
  57194. /**
  57195. * @private
  57196. */
  57197. _enableHoverLinkToSeries: function () {
  57198. var self = this;
  57199. this._shapes.barGroup
  57200. .on('mousemove', function (e) {
  57201. self._hovering = true;
  57202. if (!self._dragging) {
  57203. var itemSize = self.visualMapModel.itemSize;
  57204. var pos = self._applyTransform(
  57205. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  57206. );
  57207. // For hover link show when hover handle, which might be
  57208. // below or upper than sizeExtent.
  57209. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  57210. self._doHoverLinkToSeries(
  57211. pos[1],
  57212. 0 <= pos[0] && pos[0] <= itemSize[0]
  57213. );
  57214. }
  57215. })
  57216. .on('mouseout', function () {
  57217. // When mouse is out of handle, hoverLink still need
  57218. // to be displayed when realtime is set as false.
  57219. self._hovering = false;
  57220. !self._dragging && self._clearHoverLinkToSeries();
  57221. });
  57222. },
  57223. /**
  57224. * @private
  57225. */
  57226. _enableHoverLinkFromSeries: function () {
  57227. var zr = this.api.getZr();
  57228. if (this.visualMapModel.option.hoverLink) {
  57229. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  57230. zr.on('mouseout', this._hideIndicator, this);
  57231. }
  57232. else {
  57233. this._clearHoverLinkFromSeries();
  57234. }
  57235. },
  57236. /**
  57237. * @private
  57238. */
  57239. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  57240. var visualMapModel = this.visualMapModel;
  57241. var itemSize = visualMapModel.itemSize;
  57242. if (!visualMapModel.option.hoverLink) {
  57243. return;
  57244. }
  57245. var sizeExtent = [0, itemSize[1]];
  57246. var dataExtent = visualMapModel.getExtent();
  57247. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  57248. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  57249. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  57250. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  57251. var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true);
  57252. var valueRange = [
  57253. linearMap$4(hoverRange[0], sizeExtent, dataExtent, true),
  57254. linearMap$4(hoverRange[1], sizeExtent, dataExtent, true)
  57255. ];
  57256. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  57257. // where china and india has very large population.
  57258. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  57259. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  57260. // Do not show indicator when mouse is over handle,
  57261. // otherwise labels overlap, especially when dragging.
  57262. if (hoverOnBar) {
  57263. if (valueRange[0] === -Infinity) {
  57264. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  57265. }
  57266. else if (valueRange[1] === Infinity) {
  57267. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  57268. }
  57269. else {
  57270. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  57271. }
  57272. }
  57273. // When realtime is set as false, handles, which are in barGroup,
  57274. // also trigger hoverLink, which help user to realize where they
  57275. // focus on when dragging. (see test/heatmap-large.html)
  57276. // When realtime is set as true, highlight will not show when hover
  57277. // handle, because the label on handle, which displays a exact value
  57278. // but not range, might mislead users.
  57279. var oldBatch = this._hoverLinkDataIndices;
  57280. var newBatch = [];
  57281. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  57282. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  57283. }
  57284. var resultBatches = compressBatches(oldBatch, newBatch);
  57285. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  57286. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  57287. },
  57288. /**
  57289. * @private
  57290. */
  57291. _hoverLinkFromSeriesMouseOver: function (e) {
  57292. var el = e.target;
  57293. var visualMapModel = this.visualMapModel;
  57294. if (!el || el.dataIndex == null) {
  57295. return;
  57296. }
  57297. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  57298. if (!visualMapModel.isTargetSeries(dataModel)) {
  57299. return;
  57300. }
  57301. var data = dataModel.getData(el.dataType);
  57302. var dim = data.getDimension(visualMapModel.getDataDimension(data));
  57303. var value = data.get(dim, el.dataIndex, true);
  57304. if (!isNaN(value)) {
  57305. this._showIndicator(value, value);
  57306. }
  57307. },
  57308. /**
  57309. * @private
  57310. */
  57311. _hideIndicator: function () {
  57312. var shapes = this._shapes;
  57313. shapes.indicator && shapes.indicator.attr('invisible', true);
  57314. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  57315. },
  57316. /**
  57317. * @private
  57318. */
  57319. _clearHoverLinkToSeries: function () {
  57320. this._hideIndicator();
  57321. var indices = this._hoverLinkDataIndices;
  57322. this._dispatchHighDown('downplay', convertDataIndex(indices));
  57323. indices.length = 0;
  57324. },
  57325. /**
  57326. * @private
  57327. */
  57328. _clearHoverLinkFromSeries: function () {
  57329. this._hideIndicator();
  57330. var zr = this.api.getZr();
  57331. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  57332. zr.off('mouseout', this._hideIndicator);
  57333. },
  57334. /**
  57335. * @private
  57336. */
  57337. _applyTransform: function (vertex, element, inverse, global) {
  57338. var transform = getTransform(element, global ? null : this.group);
  57339. return graphic[
  57340. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  57341. ](vertex, transform, inverse);
  57342. },
  57343. /**
  57344. * @private
  57345. */
  57346. _dispatchHighDown: function (type, batch) {
  57347. batch && batch.length && this.api.dispatchAction({
  57348. type: type,
  57349. batch: batch
  57350. });
  57351. },
  57352. /**
  57353. * @override
  57354. */
  57355. dispose: function () {
  57356. this._clearHoverLinkFromSeries();
  57357. this._clearHoverLinkToSeries();
  57358. },
  57359. /**
  57360. * @override
  57361. */
  57362. remove: function () {
  57363. this._clearHoverLinkFromSeries();
  57364. this._clearHoverLinkToSeries();
  57365. }
  57366. });
  57367. function createPolygon(points, cursor, onDrift, onDragEnd) {
  57368. return new Polygon({
  57369. shape: {points: points},
  57370. draggable: !!onDrift,
  57371. cursor: cursor,
  57372. drift: onDrift,
  57373. onmousemove: function (e) {
  57374. // Fot mobile devicem, prevent screen slider on the button.
  57375. stop(e.event);
  57376. },
  57377. ondragend: onDragEnd
  57378. });
  57379. }
  57380. function createHandlePoints(handleIndex, textSize) {
  57381. return handleIndex === 0
  57382. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  57383. : [[0, 0], [textSize, 0], [textSize, textSize]];
  57384. }
  57385. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  57386. return isRange
  57387. ? [ // indicate range
  57388. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  57389. [HOVER_LINK_OUT, 0],
  57390. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  57391. ]
  57392. : [ // indicate single value
  57393. [0, 0], [5, -5], [5, 5]
  57394. ];
  57395. }
  57396. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  57397. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  57398. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  57399. if (hoverLinkDataSize) {
  57400. halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  57401. }
  57402. return halfHoverLinkSize;
  57403. }
  57404. function useHoverLinkOnHandle(visualMapModel) {
  57405. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  57406. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  57407. }
  57408. function getCursor$1(orient) {
  57409. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  57410. }
  57411. var actionInfo$2 = {
  57412. type: 'selectDataRange',
  57413. event: 'dataRangeSelected',
  57414. // FIXME use updateView appears wrong
  57415. update: 'update'
  57416. };
  57417. registerAction(actionInfo$2, function (payload, ecModel) {
  57418. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  57419. model.setSelected(payload.selected);
  57420. });
  57421. });
  57422. /**
  57423. * DataZoom component entry
  57424. */
  57425. registerPreprocessor(preprocessor$2);
  57426. var PiecewiseModel = VisualMapModel.extend({
  57427. type: 'visualMap.piecewise',
  57428. /**
  57429. * Order Rule:
  57430. *
  57431. * option.categories / option.pieces / option.text / option.selected:
  57432. * If !option.inverse,
  57433. * Order when vertical: ['top', ..., 'bottom'].
  57434. * Order when horizontal: ['left', ..., 'right'].
  57435. * If option.inverse, the meaning of
  57436. * the order should be reversed.
  57437. *
  57438. * this._pieceList:
  57439. * The order is always [low, ..., high].
  57440. *
  57441. * Mapping from location to low-high:
  57442. * If !option.inverse
  57443. * When vertical, top is high.
  57444. * When horizontal, right is high.
  57445. * If option.inverse, reverse.
  57446. */
  57447. /**
  57448. * @protected
  57449. */
  57450. defaultOption: {
  57451. selected: null, // Object. If not specified, means selected.
  57452. // When pieces and splitNumber: {'0': true, '5': true}
  57453. // When categories: {'cate1': false, 'cate3': true}
  57454. // When selected === false, means all unselected.
  57455. minOpen: false, // Whether include values that smaller than `min`.
  57456. maxOpen: false, // Whether include values that bigger than `max`.
  57457. align: 'auto', // 'auto', 'left', 'right'
  57458. itemWidth: 20, // When put the controller vertically, it is the length of
  57459. // horizontal side of each item. Otherwise, vertical side.
  57460. itemHeight: 14, // When put the controller vertically, it is the length of
  57461. // vertical side of each item. Otherwise, horizontal side.
  57462. itemSymbol: 'roundRect',
  57463. pieceList: null, // Each item is Object, with some of those attrs:
  57464. // {min, max, lt, gt, lte, gte, value,
  57465. // color, colorSaturation, colorAlpha, opacity,
  57466. // symbol, symbolSize}, which customize the range or visual
  57467. // coding of the certain piece. Besides, see "Order Rule".
  57468. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  57469. // Attr min/max are ignored when categories set. See "Order Rule"
  57470. splitNumber: 5, // If set to 5, auto split five pieces equally.
  57471. // If set to 0 and component type not set, component type will be
  57472. // determined as "continuous". (It is less reasonable but for ec2
  57473. // compatibility, see echarts/component/visualMap/typeDefaulter)
  57474. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  57475. itemGap: 10, // The gap between two items, in px.
  57476. hoverLink: true, // Enable hover highlight.
  57477. showLabel: null // By default, when text is used, label will hide (the logic
  57478. // is remained for compatibility reason)
  57479. },
  57480. /**
  57481. * @override
  57482. */
  57483. optionUpdated: function (newOption, isInit) {
  57484. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  57485. /**
  57486. * The order is always [low, ..., high].
  57487. * [{text: string, interval: Array.<number>}, ...]
  57488. * @private
  57489. * @type {Array.<Object>}
  57490. */
  57491. this._pieceList = [];
  57492. this.resetExtent();
  57493. /**
  57494. * 'pieces', 'categories', 'splitNumber'
  57495. * @type {string}
  57496. */
  57497. var mode = this._mode = this._determineMode();
  57498. resetMethods[this._mode].call(this);
  57499. this._resetSelected(newOption, isInit);
  57500. var categories = this.option.categories;
  57501. this.resetVisual(function (mappingOption, state) {
  57502. if (mode === 'categories') {
  57503. mappingOption.mappingMethod = 'category';
  57504. mappingOption.categories = clone(categories);
  57505. }
  57506. else {
  57507. mappingOption.dataExtent = this.getExtent();
  57508. mappingOption.mappingMethod = 'piecewise';
  57509. mappingOption.pieceList = map(this._pieceList, function (piece) {
  57510. var piece = clone(piece);
  57511. if (state !== 'inRange') {
  57512. // FIXME
  57513. // outOfRange do not support special visual in pieces.
  57514. piece.visual = null;
  57515. }
  57516. return piece;
  57517. });
  57518. }
  57519. });
  57520. },
  57521. /**
  57522. * @protected
  57523. * @override
  57524. */
  57525. completeVisualOption: function () {
  57526. // Consider this case:
  57527. // visualMap: {
  57528. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  57529. // }
  57530. // where no inRange/outOfRange set but only pieces. So we should make
  57531. // default inRange/outOfRange for this case, otherwise visuals that only
  57532. // appear in `pieces` will not be taken into account in visual encoding.
  57533. var option = this.option;
  57534. var visualTypesInPieces = {};
  57535. var visualTypes = VisualMapping.listVisualTypes();
  57536. var isCategory = this.isCategory();
  57537. each$1(option.pieces, function (piece) {
  57538. each$1(visualTypes, function (visualType) {
  57539. if (piece.hasOwnProperty(visualType)) {
  57540. visualTypesInPieces[visualType] = 1;
  57541. }
  57542. });
  57543. });
  57544. each$1(visualTypesInPieces, function (v, visualType) {
  57545. var exists = 0;
  57546. each$1(this.stateList, function (state) {
  57547. exists |= has(option, state, visualType)
  57548. || has(option.target, state, visualType);
  57549. }, this);
  57550. !exists && each$1(this.stateList, function (state) {
  57551. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  57552. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  57553. );
  57554. });
  57555. }, this);
  57556. function has(obj, state, visualType) {
  57557. return obj && obj[state] && (
  57558. isObject(obj[state])
  57559. ? obj[state].hasOwnProperty(visualType)
  57560. : obj[state] === visualType // e.g., inRange: 'symbol'
  57561. );
  57562. }
  57563. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  57564. },
  57565. _resetSelected: function (newOption, isInit) {
  57566. var thisOption = this.option;
  57567. var pieceList = this._pieceList;
  57568. // Selected do not merge but all override.
  57569. var selected = (isInit ? thisOption : newOption).selected || {};
  57570. thisOption.selected = selected;
  57571. // Consider 'not specified' means true.
  57572. each$1(pieceList, function (piece, index) {
  57573. var key = this.getSelectedMapKey(piece);
  57574. if (!selected.hasOwnProperty(key)) {
  57575. selected[key] = true;
  57576. }
  57577. }, this);
  57578. if (thisOption.selectedMode === 'single') {
  57579. // Ensure there is only one selected.
  57580. var hasSel = false;
  57581. each$1(pieceList, function (piece, index) {
  57582. var key = this.getSelectedMapKey(piece);
  57583. if (selected[key]) {
  57584. hasSel
  57585. ? (selected[key] = false)
  57586. : (hasSel = true);
  57587. }
  57588. }, this);
  57589. }
  57590. // thisOption.selectedMode === 'multiple', default: all selected.
  57591. },
  57592. /**
  57593. * @public
  57594. */
  57595. getSelectedMapKey: function (piece) {
  57596. return this._mode === 'categories'
  57597. ? piece.value + '' : piece.index + '';
  57598. },
  57599. /**
  57600. * @public
  57601. */
  57602. getPieceList: function () {
  57603. return this._pieceList;
  57604. },
  57605. /**
  57606. * @private
  57607. * @return {string}
  57608. */
  57609. _determineMode: function () {
  57610. var option = this.option;
  57611. return option.pieces && option.pieces.length > 0
  57612. ? 'pieces'
  57613. : this.option.categories
  57614. ? 'categories'
  57615. : 'splitNumber';
  57616. },
  57617. /**
  57618. * @public
  57619. * @override
  57620. */
  57621. setSelected: function (selected) {
  57622. this.option.selected = clone(selected);
  57623. },
  57624. /**
  57625. * @public
  57626. * @override
  57627. */
  57628. getValueState: function (value) {
  57629. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  57630. return index != null
  57631. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  57632. ? 'inRange' : 'outOfRange'
  57633. )
  57634. : 'outOfRange';
  57635. },
  57636. /**
  57637. * @public
  57638. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  57639. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  57640. */
  57641. findTargetDataIndices: function (pieceIndex) {
  57642. var result = [];
  57643. this.eachTargetSeries(function (seriesModel) {
  57644. var dataIndices = [];
  57645. var data = seriesModel.getData();
  57646. data.each(this.getDataDimension(data), function (value, dataIndex) {
  57647. // Should always base on model pieceList, because it is order sensitive.
  57648. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  57649. pIdx === pieceIndex && dataIndices.push(dataIndex);
  57650. }, true, this);
  57651. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  57652. }, this);
  57653. return result;
  57654. },
  57655. /**
  57656. * @private
  57657. * @param {Object} piece piece.value or piece.interval is required.
  57658. * @return {number} Can be Infinity or -Infinity
  57659. */
  57660. getRepresentValue: function (piece) {
  57661. var representValue;
  57662. if (this.isCategory()) {
  57663. representValue = piece.value;
  57664. }
  57665. else {
  57666. if (piece.value != null) {
  57667. representValue = piece.value;
  57668. }
  57669. else {
  57670. var pieceInterval = piece.interval || [];
  57671. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  57672. ? 0
  57673. : (pieceInterval[0] + pieceInterval[1]) / 2;
  57674. }
  57675. }
  57676. return representValue;
  57677. },
  57678. getVisualMeta: function (getColorVisual) {
  57679. // Do not support category. (category axis is ordinal, numerical)
  57680. if (this.isCategory()) {
  57681. return;
  57682. }
  57683. var stops = [];
  57684. var outerColors = [];
  57685. var visualMapModel = this;
  57686. function setStop(interval, valueState) {
  57687. var representValue = visualMapModel.getRepresentValue({interval: interval});
  57688. if (!valueState) {
  57689. valueState = visualMapModel.getValueState(representValue);
  57690. }
  57691. var color = getColorVisual(representValue, valueState);
  57692. if (interval[0] === -Infinity) {
  57693. outerColors[0] = color;
  57694. }
  57695. else if (interval[1] === Infinity) {
  57696. outerColors[1] = color;
  57697. }
  57698. else {
  57699. stops.push(
  57700. {value: interval[0], color: color},
  57701. {value: interval[1], color: color}
  57702. );
  57703. }
  57704. }
  57705. // Suplement
  57706. var pieceList = this._pieceList.slice();
  57707. if (!pieceList.length) {
  57708. pieceList.push({interval: [-Infinity, Infinity]});
  57709. }
  57710. else {
  57711. var edge = pieceList[0].interval[0];
  57712. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  57713. edge = pieceList[pieceList.length - 1].interval[1];
  57714. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  57715. }
  57716. var curr = -Infinity;
  57717. each$1(pieceList, function (piece) {
  57718. var interval = piece.interval;
  57719. if (interval) {
  57720. // Fulfill gap.
  57721. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  57722. setStop(interval.slice());
  57723. curr = interval[1];
  57724. }
  57725. }, this);
  57726. return {stops: stops, outerColors: outerColors};
  57727. }
  57728. });
  57729. /**
  57730. * Key is this._mode
  57731. * @type {Object}
  57732. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  57733. */
  57734. var resetMethods = {
  57735. splitNumber: function () {
  57736. var thisOption = this.option;
  57737. var pieceList = this._pieceList;
  57738. var precision = Math.min(thisOption.precision, 20);
  57739. var dataExtent = this.getExtent();
  57740. var splitNumber = thisOption.splitNumber;
  57741. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  57742. thisOption.splitNumber = splitNumber;
  57743. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  57744. // Precision auto-adaption
  57745. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  57746. precision++;
  57747. }
  57748. thisOption.precision = precision;
  57749. splitStep = +splitStep.toFixed(precision);
  57750. var index = 0;
  57751. if (thisOption.minOpen) {
  57752. pieceList.push({
  57753. index: index++,
  57754. interval: [-Infinity, dataExtent[0]],
  57755. close: [0, 0]
  57756. });
  57757. }
  57758. for (
  57759. var curr = dataExtent[0], len = index + splitNumber;
  57760. index < len;
  57761. curr += splitStep
  57762. ) {
  57763. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  57764. pieceList.push({
  57765. index: index++,
  57766. interval: [curr, max],
  57767. close: [1, 1]
  57768. });
  57769. }
  57770. if (thisOption.maxOpen) {
  57771. pieceList.push({
  57772. index: index++,
  57773. interval: [dataExtent[1], Infinity],
  57774. close: [0, 0]
  57775. });
  57776. }
  57777. reformIntervals(pieceList);
  57778. each$1(pieceList, function (piece) {
  57779. piece.text = this.formatValueText(piece.interval);
  57780. }, this);
  57781. },
  57782. categories: function () {
  57783. var thisOption = this.option;
  57784. each$1(thisOption.categories, function (cate) {
  57785. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  57786. // 是否改一致。
  57787. this._pieceList.push({
  57788. text: this.formatValueText(cate, true),
  57789. value: cate
  57790. });
  57791. }, this);
  57792. // See "Order Rule".
  57793. normalizeReverse(thisOption, this._pieceList);
  57794. },
  57795. pieces: function () {
  57796. var thisOption = this.option;
  57797. var pieceList = this._pieceList;
  57798. each$1(thisOption.pieces, function (pieceListItem, index) {
  57799. if (!isObject(pieceListItem)) {
  57800. pieceListItem = {value: pieceListItem};
  57801. }
  57802. var item = {text: '', index: index};
  57803. if (pieceListItem.label != null) {
  57804. item.text = pieceListItem.label;
  57805. }
  57806. if (pieceListItem.hasOwnProperty('value')) {
  57807. var value = item.value = pieceListItem.value;
  57808. item.interval = [value, value];
  57809. item.close = [1, 1];
  57810. }
  57811. else {
  57812. // `min` `max` is legacy option.
  57813. // `lt` `gt` `lte` `gte` is recommanded.
  57814. var interval = item.interval = [];
  57815. var close = item.close = [0, 0];
  57816. var closeList = [1, 0, 1];
  57817. var infinityList = [-Infinity, Infinity];
  57818. var useMinMax = [];
  57819. for (var lg = 0; lg < 2; lg++) {
  57820. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  57821. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  57822. interval[lg] = pieceListItem[names[i]];
  57823. close[lg] = closeList[i];
  57824. useMinMax[lg] = i === 2;
  57825. }
  57826. interval[lg] == null && (interval[lg] = infinityList[lg]);
  57827. }
  57828. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  57829. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  57830. if (__DEV__) {
  57831. if (interval[0] > interval[1]) {
  57832. console.warn(
  57833. 'Piece ' + index + 'is illegal: ' + interval
  57834. + ' lower bound should not greater then uppper bound.'
  57835. );
  57836. }
  57837. }
  57838. if (interval[0] === interval[1] && close[0] && close[1]) {
  57839. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  57840. // we use value to lift the priority when min === max
  57841. item.value = interval[0];
  57842. }
  57843. }
  57844. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  57845. pieceList.push(item);
  57846. }, this);
  57847. // See "Order Rule".
  57848. normalizeReverse(thisOption, pieceList);
  57849. // Only pieces
  57850. reformIntervals(pieceList);
  57851. each$1(pieceList, function (piece) {
  57852. var close = piece.close;
  57853. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  57854. piece.text = piece.text || this.formatValueText(
  57855. piece.value != null ? piece.value : piece.interval,
  57856. false,
  57857. edgeSymbols
  57858. );
  57859. }, this);
  57860. }
  57861. };
  57862. function normalizeReverse(thisOption, pieceList) {
  57863. var inverse = thisOption.inverse;
  57864. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  57865. pieceList.reverse();
  57866. }
  57867. }
  57868. var PiecewiseVisualMapView = VisualMapView.extend({
  57869. type: 'visualMap.piecewise',
  57870. /**
  57871. * @protected
  57872. * @override
  57873. */
  57874. doRender: function () {
  57875. var thisGroup = this.group;
  57876. thisGroup.removeAll();
  57877. var visualMapModel = this.visualMapModel;
  57878. var textGap = visualMapModel.get('textGap');
  57879. var textStyleModel = visualMapModel.textStyleModel;
  57880. var textFont = textStyleModel.getFont();
  57881. var textFill = textStyleModel.getTextColor();
  57882. var itemAlign = this._getItemAlign();
  57883. var itemSize = visualMapModel.itemSize;
  57884. var viewData = this._getViewData();
  57885. var endsText = viewData.endsText;
  57886. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  57887. endsText && this._renderEndsText(
  57888. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  57889. );
  57890. each$1(viewData.viewPieceList, renderItem, this);
  57891. endsText && this._renderEndsText(
  57892. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  57893. );
  57894. box(
  57895. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  57896. );
  57897. this.renderBackground(thisGroup);
  57898. this.positionGroup(thisGroup);
  57899. function renderItem(item) {
  57900. var piece = item.piece;
  57901. var itemGroup = new Group();
  57902. itemGroup.onclick = bind(this._onItemClick, this, piece);
  57903. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  57904. var representValue = visualMapModel.getRepresentValue(piece);
  57905. this._createItemSymbol(
  57906. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  57907. );
  57908. if (showLabel) {
  57909. var visualState = this.visualMapModel.getValueState(representValue);
  57910. itemGroup.add(new Text({
  57911. style: {
  57912. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  57913. y: itemSize[1] / 2,
  57914. text: piece.text,
  57915. textVerticalAlign: 'middle',
  57916. textAlign: itemAlign,
  57917. textFont: textFont,
  57918. textFill: textFill,
  57919. opacity: visualState === 'outOfRange' ? 0.5 : 1
  57920. }
  57921. }));
  57922. }
  57923. thisGroup.add(itemGroup);
  57924. }
  57925. },
  57926. /**
  57927. * @private
  57928. */
  57929. _enableHoverLink: function (itemGroup, pieceIndex) {
  57930. itemGroup
  57931. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  57932. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  57933. function onHoverLink(method) {
  57934. var visualMapModel = this.visualMapModel;
  57935. visualMapModel.option.hoverLink && this.api.dispatchAction({
  57936. type: method,
  57937. batch: convertDataIndex(
  57938. visualMapModel.findTargetDataIndices(pieceIndex)
  57939. )
  57940. });
  57941. }
  57942. },
  57943. /**
  57944. * @private
  57945. */
  57946. _getItemAlign: function () {
  57947. var visualMapModel = this.visualMapModel;
  57948. var modelOption = visualMapModel.option;
  57949. if (modelOption.orient === 'vertical') {
  57950. return getItemAlign(
  57951. visualMapModel, this.api, visualMapModel.itemSize
  57952. );
  57953. }
  57954. else { // horizontal, most case left unless specifying right.
  57955. var align = modelOption.align;
  57956. if (!align || align === 'auto') {
  57957. align = 'left';
  57958. }
  57959. return align;
  57960. }
  57961. },
  57962. /**
  57963. * @private
  57964. */
  57965. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  57966. if (!text) {
  57967. return;
  57968. }
  57969. var itemGroup = new Group();
  57970. var textStyleModel = this.visualMapModel.textStyleModel;
  57971. itemGroup.add(new Text({
  57972. style: {
  57973. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  57974. y: itemSize[1] / 2,
  57975. textVerticalAlign: 'middle',
  57976. textAlign: showLabel ? itemAlign : 'center',
  57977. text: text,
  57978. textFont: textStyleModel.getFont(),
  57979. textFill: textStyleModel.getTextColor()
  57980. }
  57981. }));
  57982. group.add(itemGroup);
  57983. },
  57984. /**
  57985. * @private
  57986. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  57987. */
  57988. _getViewData: function () {
  57989. var visualMapModel = this.visualMapModel;
  57990. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  57991. return {piece: piece, indexInModelPieceList: index};
  57992. });
  57993. var endsText = visualMapModel.get('text');
  57994. // Consider orient and inverse.
  57995. var orient = visualMapModel.get('orient');
  57996. var inverse = visualMapModel.get('inverse');
  57997. // Order of model pieceList is always [low, ..., high]
  57998. if (orient === 'horizontal' ? inverse : !inverse) {
  57999. viewPieceList.reverse();
  58000. }
  58001. // Origin order of endsText is [high, low]
  58002. else if (endsText) {
  58003. endsText = endsText.slice().reverse();
  58004. }
  58005. return {viewPieceList: viewPieceList, endsText: endsText};
  58006. },
  58007. /**
  58008. * @private
  58009. */
  58010. _createItemSymbol: function (group, representValue, shapeParam) {
  58011. group.add(createSymbol(
  58012. this.getControllerVisual(representValue, 'symbol'),
  58013. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  58014. this.getControllerVisual(representValue, 'color')
  58015. ));
  58016. },
  58017. /**
  58018. * @private
  58019. */
  58020. _onItemClick: function (piece) {
  58021. var visualMapModel = this.visualMapModel;
  58022. var option = visualMapModel.option;
  58023. var selected = clone(option.selected);
  58024. var newKey = visualMapModel.getSelectedMapKey(piece);
  58025. if (option.selectedMode === 'single') {
  58026. selected[newKey] = true;
  58027. each$1(selected, function (o, key) {
  58028. selected[key] = key === newKey;
  58029. });
  58030. }
  58031. else {
  58032. selected[newKey] = !selected[newKey];
  58033. }
  58034. this.api.dispatchAction({
  58035. type: 'selectDataRange',
  58036. from: this.uid,
  58037. visualMapId: this.visualMapModel.id,
  58038. selected: selected
  58039. });
  58040. }
  58041. });
  58042. /**
  58043. * DataZoom component entry
  58044. */
  58045. registerPreprocessor(preprocessor$2);
  58046. /**
  58047. * visualMap component entry
  58048. */
  58049. var addCommas$1 = addCommas;
  58050. var encodeHTML$1 = encodeHTML;
  58051. function fillLabel(opt) {
  58052. defaultEmphasis(opt.label, ['show']);
  58053. }
  58054. var MarkerModel = extendComponentModel({
  58055. type: 'marker',
  58056. dependencies: ['series', 'grid', 'polar', 'geo'],
  58057. /**
  58058. * @overrite
  58059. */
  58060. init: function (option, parentModel, ecModel, extraOpt) {
  58061. if (__DEV__) {
  58062. if (this.type === 'marker') {
  58063. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  58064. }
  58065. }
  58066. this.mergeDefaultAndTheme(option, ecModel);
  58067. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  58068. },
  58069. /**
  58070. * @return {boolean}
  58071. */
  58072. isAnimationEnabled: function () {
  58073. if (env$1.node) {
  58074. return false;
  58075. }
  58076. var hostSeries = this.__hostSeries;
  58077. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  58078. },
  58079. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  58080. var MarkerModel = this.constructor;
  58081. var modelPropName = this.mainType + 'Model';
  58082. if (!createdBySelf) {
  58083. ecModel.eachSeries(function (seriesModel) {
  58084. var markerOpt = seriesModel.get(this.mainType);
  58085. var markerModel = seriesModel[modelPropName];
  58086. if (!markerOpt || !markerOpt.data) {
  58087. seriesModel[modelPropName] = null;
  58088. return;
  58089. }
  58090. if (!markerModel) {
  58091. if (isInit) {
  58092. // Default label emphasis `position` and `show`
  58093. fillLabel(markerOpt);
  58094. }
  58095. each$1(markerOpt.data, function (item) {
  58096. // FIXME Overwrite fillLabel method ?
  58097. if (item instanceof Array) {
  58098. fillLabel(item[0]);
  58099. fillLabel(item[1]);
  58100. }
  58101. else {
  58102. fillLabel(item);
  58103. }
  58104. });
  58105. markerModel = new MarkerModel(
  58106. markerOpt, this, ecModel
  58107. );
  58108. extend(markerModel, {
  58109. mainType: this.mainType,
  58110. // Use the same series index and name
  58111. seriesIndex: seriesModel.seriesIndex,
  58112. name: seriesModel.name,
  58113. createdBySelf: true
  58114. });
  58115. markerModel.__hostSeries = seriesModel;
  58116. }
  58117. else {
  58118. markerModel.mergeOption(markerOpt, ecModel, true);
  58119. }
  58120. seriesModel[modelPropName] = markerModel;
  58121. }, this);
  58122. }
  58123. },
  58124. formatTooltip: function (dataIndex) {
  58125. var data = this.getData();
  58126. var value = this.getRawValue(dataIndex);
  58127. var formattedValue = isArray(value)
  58128. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  58129. var name = data.getName(dataIndex);
  58130. var html = encodeHTML$1(this.name);
  58131. if (value != null || name) {
  58132. html += '<br />';
  58133. }
  58134. if (name) {
  58135. html += encodeHTML$1(name);
  58136. if (value != null) {
  58137. html += ' : ';
  58138. }
  58139. }
  58140. if (value != null) {
  58141. html += encodeHTML$1(formattedValue);
  58142. }
  58143. return html;
  58144. },
  58145. getData: function () {
  58146. return this._data;
  58147. },
  58148. setData: function (data) {
  58149. this._data = data;
  58150. }
  58151. });
  58152. mixin(MarkerModel, dataFormatMixin);
  58153. MarkerModel.extend({
  58154. type: 'markPoint',
  58155. defaultOption: {
  58156. zlevel: 0,
  58157. z: 5,
  58158. symbol: 'pin',
  58159. symbolSize: 50,
  58160. //symbolRotate: 0,
  58161. //symbolOffset: [0, 0]
  58162. tooltip: {
  58163. trigger: 'item'
  58164. },
  58165. label: {
  58166. normal: {
  58167. show: true,
  58168. position: 'inside'
  58169. },
  58170. emphasis: {
  58171. show: true
  58172. }
  58173. },
  58174. itemStyle: {
  58175. normal: {
  58176. borderWidth: 2
  58177. }
  58178. }
  58179. }
  58180. });
  58181. var indexOf$3 = indexOf;
  58182. function hasXOrY(item) {
  58183. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  58184. }
  58185. function hasXAndY(item) {
  58186. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  58187. }
  58188. function getPrecision$1(data, valueAxisDim, dataIndex) {
  58189. var precision = -1;
  58190. do {
  58191. precision = Math.max(
  58192. getPrecision(data.get(
  58193. valueAxisDim, dataIndex
  58194. )),
  58195. precision
  58196. );
  58197. data = data.stackedOn;
  58198. } while (data);
  58199. return precision;
  58200. }
  58201. function markerTypeCalculatorWithExtent(
  58202. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  58203. ) {
  58204. var coordArr = [];
  58205. var value = numCalculate(data, targetDataDim, mlType);
  58206. var dataIndex = data.indicesOfNearest(targetDataDim, value, true)[0];
  58207. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex, true);
  58208. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex, true);
  58209. var precision = getPrecision$1(data, targetDataDim, dataIndex);
  58210. precision = Math.min(precision, 20);
  58211. if (precision >= 0) {
  58212. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  58213. }
  58214. return coordArr;
  58215. }
  58216. var curry$7 = curry;
  58217. // TODO Specified percent
  58218. var markerTypeCalculator = {
  58219. /**
  58220. * @method
  58221. * @param {module:echarts/data/List} data
  58222. * @param {string} baseAxisDim
  58223. * @param {string} valueAxisDim
  58224. */
  58225. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  58226. /**
  58227. * @method
  58228. * @param {module:echarts/data/List} data
  58229. * @param {string} baseAxisDim
  58230. * @param {string} valueAxisDim
  58231. */
  58232. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  58233. /**
  58234. * @method
  58235. * @param {module:echarts/data/List} data
  58236. * @param {string} baseAxisDim
  58237. * @param {string} valueAxisDim
  58238. */
  58239. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  58240. };
  58241. /**
  58242. * Transform markPoint data item to format used in List by do the following
  58243. * 1. Calculate statistic like `max`, `min`, `average`
  58244. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  58245. * @param {module:echarts/model/Series} seriesModel
  58246. * @param {module:echarts/coord/*} [coordSys]
  58247. * @param {Object} item
  58248. * @return {Object}
  58249. */
  58250. function dataTransform(seriesModel, item) {
  58251. var data = seriesModel.getData();
  58252. var coordSys = seriesModel.coordinateSystem;
  58253. // 1. If not specify the position with pixel directly
  58254. // 2. If `coord` is not a data array. Which uses `xAxis`,
  58255. // `yAxis` to specify the coord on each dimension
  58256. // parseFloat first because item.x and item.y can be percent string like '20%'
  58257. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  58258. var dims = coordSys.dimensions;
  58259. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  58260. // Clone the option
  58261. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  58262. item = clone(item);
  58263. if (item.type
  58264. && markerTypeCalculator[item.type]
  58265. && axisInfo.baseAxis && axisInfo.valueAxis
  58266. ) {
  58267. var otherCoordIndex = indexOf$3(dims, axisInfo.baseAxis.dim);
  58268. var targetCoordIndex = indexOf$3(dims, axisInfo.valueAxis.dim);
  58269. item.coord = markerTypeCalculator[item.type](
  58270. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  58271. otherCoordIndex, targetCoordIndex
  58272. );
  58273. // Force to use the value of calculated value.
  58274. item.value = item.coord[targetCoordIndex];
  58275. }
  58276. else {
  58277. // FIXME Only has one of xAxis and yAxis.
  58278. var coord = [
  58279. item.xAxis != null ? item.xAxis : item.radiusAxis,
  58280. item.yAxis != null ? item.yAxis : item.angleAxis
  58281. ];
  58282. // Each coord support max, min, average
  58283. for (var i = 0; i < 2; i++) {
  58284. if (markerTypeCalculator[coord[i]]) {
  58285. var dataDim = seriesModel.coordDimToDataDim(dims[i])[0];
  58286. coord[i] = numCalculate(data, dataDim, coord[i]);
  58287. }
  58288. }
  58289. item.coord = coord;
  58290. }
  58291. }
  58292. return item;
  58293. }
  58294. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  58295. var ret = {};
  58296. if (item.valueIndex != null || item.valueDim != null) {
  58297. ret.valueDataDim = item.valueIndex != null
  58298. ? data.getDimension(item.valueIndex) : item.valueDim;
  58299. ret.valueAxis = coordSys.getAxis(seriesModel.dataDimToCoordDim(ret.valueDataDim));
  58300. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  58301. ret.baseDataDim = seriesModel.coordDimToDataDim(ret.baseAxis.dim)[0];
  58302. }
  58303. else {
  58304. ret.baseAxis = seriesModel.getBaseAxis();
  58305. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  58306. ret.baseDataDim = seriesModel.coordDimToDataDim(ret.baseAxis.dim)[0];
  58307. ret.valueDataDim = seriesModel.coordDimToDataDim(ret.valueAxis.dim)[0];
  58308. }
  58309. return ret;
  58310. }
  58311. /**
  58312. * Filter data which is out of coordinateSystem range
  58313. * [dataFilter description]
  58314. * @param {module:echarts/coord/*} [coordSys]
  58315. * @param {Object} item
  58316. * @return {boolean}
  58317. */
  58318. function dataFilter$1(coordSys, item) {
  58319. // Alwalys return true if there is no coordSys
  58320. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  58321. ? coordSys.containData(item.coord) : true;
  58322. }
  58323. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  58324. // x, y, radius, angle
  58325. if (dimIndex < 2) {
  58326. return item.coord && item.coord[dimIndex];
  58327. }
  58328. return item.value;
  58329. }
  58330. function numCalculate(data, valueDataDim, type) {
  58331. if (type === 'average') {
  58332. var sum = 0;
  58333. var count = 0;
  58334. data.each(valueDataDim, function (val, idx) {
  58335. if (!isNaN(val)) {
  58336. sum += val;
  58337. count++;
  58338. }
  58339. }, true);
  58340. return sum / count;
  58341. }
  58342. else {
  58343. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  58344. }
  58345. }
  58346. var MarkerView = extendComponentView({
  58347. type: 'marker',
  58348. init: function () {
  58349. /**
  58350. * Markline grouped by series
  58351. * @private
  58352. * @type {module:zrender/core/util.HashMap}
  58353. */
  58354. this.markerGroupMap = createHashMap();
  58355. },
  58356. render: function (markerModel, ecModel, api) {
  58357. var markerGroupMap = this.markerGroupMap;
  58358. markerGroupMap.each(function (item) {
  58359. item.__keep = false;
  58360. });
  58361. var markerModelKey = this.type + 'Model';
  58362. ecModel.eachSeries(function (seriesModel) {
  58363. var markerModel = seriesModel[markerModelKey];
  58364. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  58365. }, this);
  58366. markerGroupMap.each(function (item) {
  58367. !item.__keep && this.group.remove(item.group);
  58368. }, this);
  58369. },
  58370. renderSeries: function () {}
  58371. });
  58372. function updateMarkerLayout(mpData, seriesModel, api) {
  58373. var coordSys = seriesModel.coordinateSystem;
  58374. mpData.each(function (idx) {
  58375. var itemModel = mpData.getItemModel(idx);
  58376. var point;
  58377. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  58378. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  58379. if (!isNaN(xPx) && !isNaN(yPx)) {
  58380. point = [xPx, yPx];
  58381. }
  58382. // Chart like bar may have there own marker positioning logic
  58383. else if (seriesModel.getMarkerPosition) {
  58384. // Use the getMarkerPoisition
  58385. point = seriesModel.getMarkerPosition(
  58386. mpData.getValues(mpData.dimensions, idx)
  58387. );
  58388. }
  58389. else if (coordSys) {
  58390. var x = mpData.get(coordSys.dimensions[0], idx);
  58391. var y = mpData.get(coordSys.dimensions[1], idx);
  58392. point = coordSys.dataToPoint([x, y]);
  58393. }
  58394. // Use x, y if has any
  58395. if (!isNaN(xPx)) {
  58396. point[0] = xPx;
  58397. }
  58398. if (!isNaN(yPx)) {
  58399. point[1] = yPx;
  58400. }
  58401. mpData.setItemLayout(idx, point);
  58402. });
  58403. }
  58404. MarkerView.extend({
  58405. type: 'markPoint',
  58406. updateLayout: function (markPointModel, ecModel, api) {
  58407. ecModel.eachSeries(function (seriesModel) {
  58408. var mpModel = seriesModel.markPointModel;
  58409. if (mpModel) {
  58410. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  58411. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  58412. }
  58413. }, this);
  58414. },
  58415. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  58416. var coordSys = seriesModel.coordinateSystem;
  58417. var seriesId = seriesModel.id;
  58418. var seriesData = seriesModel.getData();
  58419. var symbolDrawMap = this.markerGroupMap;
  58420. var symbolDraw = symbolDrawMap.get(seriesId)
  58421. || symbolDrawMap.set(seriesId, new SymbolDraw());
  58422. var mpData = createList$1(coordSys, seriesModel, mpModel);
  58423. // FIXME
  58424. mpModel.setData(mpData);
  58425. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  58426. mpData.each(function (idx) {
  58427. var itemModel = mpData.getItemModel(idx);
  58428. var symbolSize = itemModel.getShallow('symbolSize');
  58429. if (typeof symbolSize === 'function') {
  58430. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  58431. symbolSize = symbolSize(
  58432. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  58433. );
  58434. }
  58435. mpData.setItemVisual(idx, {
  58436. symbolSize: symbolSize,
  58437. color: itemModel.get('itemStyle.normal.color')
  58438. || seriesData.getVisual('color'),
  58439. symbol: itemModel.getShallow('symbol')
  58440. });
  58441. });
  58442. // TODO Text are wrong
  58443. symbolDraw.updateData(mpData);
  58444. this.group.add(symbolDraw.group);
  58445. // Set host model for tooltip
  58446. // FIXME
  58447. mpData.eachItemGraphicEl(function (el) {
  58448. el.traverse(function (child) {
  58449. child.dataModel = mpModel;
  58450. });
  58451. });
  58452. symbolDraw.__keep = true;
  58453. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  58454. }
  58455. });
  58456. /**
  58457. * @inner
  58458. * @param {module:echarts/coord/*} [coordSys]
  58459. * @param {module:echarts/model/Series} seriesModel
  58460. * @param {module:echarts/model/Model} mpModel
  58461. */
  58462. function createList$1(coordSys, seriesModel, mpModel) {
  58463. var coordDimsInfos;
  58464. if (coordSys) {
  58465. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  58466. var info = seriesModel.getData().getDimensionInfo(
  58467. seriesModel.coordDimToDataDim(coordDim)[0]
  58468. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  58469. info.name = coordDim;
  58470. return info;
  58471. });
  58472. }
  58473. else {
  58474. coordDimsInfos =[{
  58475. name: 'value',
  58476. type: 'float'
  58477. }];
  58478. }
  58479. var mpData = new List(coordDimsInfos, mpModel);
  58480. var dataOpt = map(mpModel.get('data'), curry(
  58481. dataTransform, seriesModel
  58482. ));
  58483. if (coordSys) {
  58484. dataOpt = filter(
  58485. dataOpt, curry(dataFilter$1, coordSys)
  58486. );
  58487. }
  58488. mpData.initData(dataOpt, null,
  58489. coordSys ? dimValueGetter : function (item) {
  58490. return item.value;
  58491. }
  58492. );
  58493. return mpData;
  58494. }
  58495. // HINT Markpoint can't be used too much
  58496. registerPreprocessor(function (opt) {
  58497. // Make sure markPoint component is enabled
  58498. opt.markPoint = opt.markPoint || {};
  58499. });
  58500. MarkerModel.extend({
  58501. type: 'markLine',
  58502. defaultOption: {
  58503. zlevel: 0,
  58504. z: 5,
  58505. symbol: ['circle', 'arrow'],
  58506. symbolSize: [8, 16],
  58507. //symbolRotate: 0,
  58508. precision: 2,
  58509. tooltip: {
  58510. trigger: 'item'
  58511. },
  58512. label: {
  58513. normal: {
  58514. show: true,
  58515. position: 'end'
  58516. },
  58517. emphasis: {
  58518. show: true
  58519. }
  58520. },
  58521. lineStyle: {
  58522. normal: {
  58523. type: 'dashed'
  58524. },
  58525. emphasis: {
  58526. width: 3
  58527. }
  58528. },
  58529. animationEasing: 'linear'
  58530. }
  58531. });
  58532. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  58533. var data = seriesModel.getData();
  58534. // Special type markLine like 'min', 'max', 'average'
  58535. var mlType = item.type;
  58536. if (!isArray(item)
  58537. && (
  58538. mlType === 'min' || mlType === 'max' || mlType === 'average'
  58539. // In case
  58540. // data: [{
  58541. // yAxis: 10
  58542. // }]
  58543. || (item.xAxis != null || item.yAxis != null)
  58544. )
  58545. ) {
  58546. var valueAxis;
  58547. var valueDataDim;
  58548. var value;
  58549. if (item.yAxis != null || item.xAxis != null) {
  58550. valueDataDim = item.yAxis != null ? 'y' : 'x';
  58551. valueAxis = coordSys.getAxis(valueDataDim);
  58552. value = retrieve(item.yAxis, item.xAxis);
  58553. }
  58554. else {
  58555. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  58556. valueDataDim = axisInfo.valueDataDim;
  58557. valueAxis = axisInfo.valueAxis;
  58558. value = numCalculate(data, valueDataDim, mlType);
  58559. }
  58560. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  58561. var baseIndex = 1 - valueIndex;
  58562. var mlFrom = clone(item);
  58563. var mlTo = {};
  58564. mlFrom.type = null;
  58565. mlFrom.coord = [];
  58566. mlTo.coord = [];
  58567. mlFrom.coord[baseIndex] = -Infinity;
  58568. mlTo.coord[baseIndex] = Infinity;
  58569. var precision = mlModel.get('precision');
  58570. if (precision >= 0 && typeof value === 'number') {
  58571. value = +value.toFixed(Math.min(precision, 20));
  58572. }
  58573. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  58574. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  58575. type: mlType,
  58576. valueIndex: item.valueIndex,
  58577. // Force to use the value of calculated value.
  58578. value: value
  58579. }];
  58580. }
  58581. item = [
  58582. dataTransform(seriesModel, item[0]),
  58583. dataTransform(seriesModel, item[1]),
  58584. extend({}, item[2])
  58585. ];
  58586. // Avoid line data type is extended by from(to) data type
  58587. item[2].type = item[2].type || '';
  58588. // Merge from option and to option into line option
  58589. merge(item[2], item[0]);
  58590. merge(item[2], item[1]);
  58591. return item;
  58592. };
  58593. function isInifinity(val) {
  58594. return !isNaN(val) && !isFinite(val);
  58595. }
  58596. // If a markLine has one dim
  58597. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  58598. var otherDimIndex = 1 - dimIndex;
  58599. var dimName = coordSys.dimensions[dimIndex];
  58600. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  58601. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  58602. }
  58603. function markLineFilter(coordSys, item) {
  58604. if (coordSys.type === 'cartesian2d') {
  58605. var fromCoord = item[0].coord;
  58606. var toCoord = item[1].coord;
  58607. // In case
  58608. // {
  58609. // markLine: {
  58610. // data: [{ yAxis: 2 }]
  58611. // }
  58612. // }
  58613. if (
  58614. fromCoord && toCoord &&
  58615. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  58616. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  58617. ) {
  58618. return true;
  58619. }
  58620. }
  58621. return dataFilter$1(coordSys, item[0])
  58622. && dataFilter$1(coordSys, item[1]);
  58623. }
  58624. function updateSingleMarkerEndLayout(
  58625. data, idx, isFrom, seriesModel, api
  58626. ) {
  58627. var coordSys = seriesModel.coordinateSystem;
  58628. var itemModel = data.getItemModel(idx);
  58629. var point;
  58630. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  58631. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  58632. if (!isNaN(xPx) && !isNaN(yPx)) {
  58633. point = [xPx, yPx];
  58634. }
  58635. else {
  58636. // Chart like bar may have there own marker positioning logic
  58637. if (seriesModel.getMarkerPosition) {
  58638. // Use the getMarkerPoisition
  58639. point = seriesModel.getMarkerPosition(
  58640. data.getValues(data.dimensions, idx)
  58641. );
  58642. }
  58643. else {
  58644. var dims = coordSys.dimensions;
  58645. var x = data.get(dims[0], idx);
  58646. var y = data.get(dims[1], idx);
  58647. point = coordSys.dataToPoint([x, y]);
  58648. }
  58649. // Expand line to the edge of grid if value on one axis is Inifnity
  58650. // In case
  58651. // markLine: {
  58652. // data: [{
  58653. // yAxis: 2
  58654. // // or
  58655. // type: 'average'
  58656. // }]
  58657. // }
  58658. if (coordSys.type === 'cartesian2d') {
  58659. var xAxis = coordSys.getAxis('x');
  58660. var yAxis = coordSys.getAxis('y');
  58661. var dims = coordSys.dimensions;
  58662. if (isInifinity(data.get(dims[0], idx))) {
  58663. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  58664. }
  58665. else if (isInifinity(data.get(dims[1], idx))) {
  58666. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  58667. }
  58668. }
  58669. // Use x, y if has any
  58670. if (!isNaN(xPx)) {
  58671. point[0] = xPx;
  58672. }
  58673. if (!isNaN(yPx)) {
  58674. point[1] = yPx;
  58675. }
  58676. }
  58677. data.setItemLayout(idx, point);
  58678. }
  58679. MarkerView.extend({
  58680. type: 'markLine',
  58681. updateLayout: function (markLineModel, ecModel, api) {
  58682. ecModel.eachSeries(function (seriesModel) {
  58683. var mlModel = seriesModel.markLineModel;
  58684. if (mlModel) {
  58685. var mlData = mlModel.getData();
  58686. var fromData = mlModel.__from;
  58687. var toData = mlModel.__to;
  58688. // Update visual and layout of from symbol and to symbol
  58689. fromData.each(function (idx) {
  58690. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  58691. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  58692. });
  58693. // Update layout of line
  58694. mlData.each(function (idx) {
  58695. mlData.setItemLayout(idx, [
  58696. fromData.getItemLayout(idx),
  58697. toData.getItemLayout(idx)
  58698. ]);
  58699. });
  58700. this.markerGroupMap.get(seriesModel.id).updateLayout();
  58701. }
  58702. }, this);
  58703. },
  58704. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  58705. var coordSys = seriesModel.coordinateSystem;
  58706. var seriesId = seriesModel.id;
  58707. var seriesData = seriesModel.getData();
  58708. var lineDrawMap = this.markerGroupMap;
  58709. var lineDraw = lineDrawMap.get(seriesId)
  58710. || lineDrawMap.set(seriesId, new LineDraw());
  58711. this.group.add(lineDraw.group);
  58712. var mlData = createList$2(coordSys, seriesModel, mlModel);
  58713. var fromData = mlData.from;
  58714. var toData = mlData.to;
  58715. var lineData = mlData.line;
  58716. mlModel.__from = fromData;
  58717. mlModel.__to = toData;
  58718. // Line data for tooltip and formatter
  58719. mlModel.setData(lineData);
  58720. var symbolType = mlModel.get('symbol');
  58721. var symbolSize = mlModel.get('symbolSize');
  58722. if (!isArray(symbolType)) {
  58723. symbolType = [symbolType, symbolType];
  58724. }
  58725. if (typeof symbolSize === 'number') {
  58726. symbolSize = [symbolSize, symbolSize];
  58727. }
  58728. // Update visual and layout of from symbol and to symbol
  58729. mlData.from.each(function (idx) {
  58730. updateDataVisualAndLayout(fromData, idx, true);
  58731. updateDataVisualAndLayout(toData, idx, false);
  58732. });
  58733. // Update visual and layout of line
  58734. lineData.each(function (idx) {
  58735. var lineColor = lineData.getItemModel(idx).get('lineStyle.normal.color');
  58736. lineData.setItemVisual(idx, {
  58737. color: lineColor || fromData.getItemVisual(idx, 'color')
  58738. });
  58739. lineData.setItemLayout(idx, [
  58740. fromData.getItemLayout(idx),
  58741. toData.getItemLayout(idx)
  58742. ]);
  58743. lineData.setItemVisual(idx, {
  58744. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  58745. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  58746. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  58747. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  58748. });
  58749. });
  58750. lineDraw.updateData(lineData);
  58751. // Set host model for tooltip
  58752. // FIXME
  58753. mlData.line.eachItemGraphicEl(function (el, idx) {
  58754. el.traverse(function (child) {
  58755. child.dataModel = mlModel;
  58756. });
  58757. });
  58758. function updateDataVisualAndLayout(data, idx, isFrom) {
  58759. var itemModel = data.getItemModel(idx);
  58760. updateSingleMarkerEndLayout(
  58761. data, idx, isFrom, seriesModel, api
  58762. );
  58763. data.setItemVisual(idx, {
  58764. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  58765. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  58766. color: itemModel.get('itemStyle.normal.color') || seriesData.getVisual('color')
  58767. });
  58768. }
  58769. lineDraw.__keep = true;
  58770. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  58771. }
  58772. });
  58773. /**
  58774. * @inner
  58775. * @param {module:echarts/coord/*} coordSys
  58776. * @param {module:echarts/model/Series} seriesModel
  58777. * @param {module:echarts/model/Model} mpModel
  58778. */
  58779. function createList$2(coordSys, seriesModel, mlModel) {
  58780. var coordDimsInfos;
  58781. if (coordSys) {
  58782. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  58783. var info = seriesModel.getData().getDimensionInfo(
  58784. seriesModel.coordDimToDataDim(coordDim)[0]
  58785. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  58786. info.name = coordDim;
  58787. return info;
  58788. });
  58789. }
  58790. else {
  58791. coordDimsInfos =[{
  58792. name: 'value',
  58793. type: 'float'
  58794. }];
  58795. }
  58796. var fromData = new List(coordDimsInfos, mlModel);
  58797. var toData = new List(coordDimsInfos, mlModel);
  58798. // No dimensions
  58799. var lineData = new List([], mlModel);
  58800. var optData = map(mlModel.get('data'), curry(
  58801. markLineTransform, seriesModel, coordSys, mlModel
  58802. ));
  58803. if (coordSys) {
  58804. optData = filter(
  58805. optData, curry(markLineFilter, coordSys)
  58806. );
  58807. }
  58808. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  58809. return item.value;
  58810. };
  58811. fromData.initData(
  58812. map(optData, function (item) { return item[0]; }),
  58813. null, dimValueGetter$$1
  58814. );
  58815. toData.initData(
  58816. map(optData, function (item) { return item[1]; }),
  58817. null, dimValueGetter$$1
  58818. );
  58819. lineData.initData(
  58820. map(optData, function (item) { return item[2]; })
  58821. );
  58822. lineData.hasItemOption = true;
  58823. return {
  58824. from: fromData,
  58825. to: toData,
  58826. line: lineData
  58827. };
  58828. }
  58829. registerPreprocessor(function (opt) {
  58830. // Make sure markLine component is enabled
  58831. opt.markLine = opt.markLine || {};
  58832. });
  58833. MarkerModel.extend({
  58834. type: 'markArea',
  58835. defaultOption: {
  58836. zlevel: 0,
  58837. // PENDING
  58838. z: 1,
  58839. tooltip: {
  58840. trigger: 'item'
  58841. },
  58842. // markArea should fixed on the coordinate system
  58843. animation: false,
  58844. label: {
  58845. normal: {
  58846. show: true,
  58847. position: 'top'
  58848. },
  58849. emphasis: {
  58850. show: true,
  58851. position: 'top'
  58852. }
  58853. },
  58854. itemStyle: {
  58855. normal: {
  58856. // color and borderColor default to use color from series
  58857. // color: 'auto'
  58858. // borderColor: 'auto'
  58859. borderWidth: 0
  58860. }
  58861. }
  58862. }
  58863. });
  58864. // TODO Better on polar
  58865. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  58866. var lt = dataTransform(seriesModel, item[0]);
  58867. var rb = dataTransform(seriesModel, item[1]);
  58868. var retrieve$$1 = retrieve;
  58869. // FIXME make sure lt is less than rb
  58870. var ltCoord = lt.coord;
  58871. var rbCoord = rb.coord;
  58872. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  58873. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  58874. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  58875. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  58876. // Merge option into one
  58877. var result = mergeAll([{}, lt, rb]);
  58878. result.coord = [
  58879. lt.coord, rb.coord
  58880. ];
  58881. result.x0 = lt.x;
  58882. result.y0 = lt.y;
  58883. result.x1 = rb.x;
  58884. result.y1 = rb.y;
  58885. return result;
  58886. };
  58887. function isInifinity$1(val) {
  58888. return !isNaN(val) && !isFinite(val);
  58889. }
  58890. // If a markArea has one dim
  58891. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  58892. var otherDimIndex = 1 - dimIndex;
  58893. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  58894. }
  58895. function markAreaFilter(coordSys, item) {
  58896. var fromCoord = item.coord[0];
  58897. var toCoord = item.coord[1];
  58898. if (coordSys.type === 'cartesian2d') {
  58899. // In case
  58900. // {
  58901. // markArea: {
  58902. // data: [{ yAxis: 2 }]
  58903. // }
  58904. // }
  58905. if (
  58906. fromCoord && toCoord &&
  58907. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  58908. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  58909. ) {
  58910. return true;
  58911. }
  58912. }
  58913. return dataFilter$1(coordSys, {
  58914. coord: fromCoord,
  58915. x: item.x0,
  58916. y: item.y0
  58917. })
  58918. || dataFilter$1(coordSys, {
  58919. coord: toCoord,
  58920. x: item.x1,
  58921. y: item.y1
  58922. });
  58923. }
  58924. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  58925. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  58926. var coordSys = seriesModel.coordinateSystem;
  58927. var itemModel = data.getItemModel(idx);
  58928. var point;
  58929. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  58930. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  58931. if (!isNaN(xPx) && !isNaN(yPx)) {
  58932. point = [xPx, yPx];
  58933. }
  58934. else {
  58935. // Chart like bar may have there own marker positioning logic
  58936. if (seriesModel.getMarkerPosition) {
  58937. // Use the getMarkerPoisition
  58938. point = seriesModel.getMarkerPosition(
  58939. data.getValues(dims, idx)
  58940. );
  58941. }
  58942. else {
  58943. var x = data.get(dims[0], idx);
  58944. var y = data.get(dims[1], idx);
  58945. point = coordSys.dataToPoint([x, y], true);
  58946. }
  58947. if (coordSys.type === 'cartesian2d') {
  58948. var xAxis = coordSys.getAxis('x');
  58949. var yAxis = coordSys.getAxis('y');
  58950. var x = data.get(dims[0], idx);
  58951. var y = data.get(dims[1], idx);
  58952. if (isInifinity$1(x)) {
  58953. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  58954. }
  58955. else if (isInifinity$1(y)) {
  58956. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  58957. }
  58958. }
  58959. // Use x, y if has any
  58960. if (!isNaN(xPx)) {
  58961. point[0] = xPx;
  58962. }
  58963. if (!isNaN(yPx)) {
  58964. point[1] = yPx;
  58965. }
  58966. }
  58967. return point;
  58968. }
  58969. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  58970. MarkerView.extend({
  58971. type: 'markArea',
  58972. updateLayout: function (markAreaModel, ecModel, api) {
  58973. ecModel.eachSeries(function (seriesModel) {
  58974. var maModel = seriesModel.markAreaModel;
  58975. if (maModel) {
  58976. var areaData = maModel.getData();
  58977. areaData.each(function (idx) {
  58978. var points = map(dimPermutations, function (dim) {
  58979. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  58980. });
  58981. // Layout
  58982. areaData.setItemLayout(idx, points);
  58983. var el = areaData.getItemGraphicEl(idx);
  58984. el.setShape('points', points);
  58985. });
  58986. }
  58987. }, this);
  58988. },
  58989. renderSeries: function (seriesModel, maModel, ecModel, api) {
  58990. var coordSys = seriesModel.coordinateSystem;
  58991. var seriesName = seriesModel.name;
  58992. var seriesData = seriesModel.getData();
  58993. var areaGroupMap = this.markerGroupMap;
  58994. var polygonGroup = areaGroupMap.get(seriesName)
  58995. || areaGroupMap.set(seriesName, {group: new Group()});
  58996. this.group.add(polygonGroup.group);
  58997. polygonGroup.__keep = true;
  58998. var areaData = createList$3(coordSys, seriesModel, maModel);
  58999. // Line data for tooltip and formatter
  59000. maModel.setData(areaData);
  59001. // Update visual and layout of line
  59002. areaData.each(function (idx) {
  59003. // Layout
  59004. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  59005. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  59006. }));
  59007. // Visual
  59008. areaData.setItemVisual(idx, {
  59009. color: seriesData.getVisual('color')
  59010. });
  59011. });
  59012. areaData.diff(polygonGroup.__data)
  59013. .add(function (idx) {
  59014. var polygon = new Polygon({
  59015. shape: {
  59016. points: areaData.getItemLayout(idx)
  59017. }
  59018. });
  59019. areaData.setItemGraphicEl(idx, polygon);
  59020. polygonGroup.group.add(polygon);
  59021. })
  59022. .update(function (newIdx, oldIdx) {
  59023. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  59024. updateProps(polygon, {
  59025. shape: {
  59026. points: areaData.getItemLayout(newIdx)
  59027. }
  59028. }, maModel, newIdx);
  59029. polygonGroup.group.add(polygon);
  59030. areaData.setItemGraphicEl(newIdx, polygon);
  59031. })
  59032. .remove(function (idx) {
  59033. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  59034. polygonGroup.group.remove(polygon);
  59035. })
  59036. .execute();
  59037. areaData.eachItemGraphicEl(function (polygon, idx) {
  59038. var itemModel = areaData.getItemModel(idx);
  59039. var labelModel = itemModel.getModel('label.normal');
  59040. var labelHoverModel = itemModel.getModel('label.emphasis');
  59041. var color = areaData.getItemVisual(idx, 'color');
  59042. polygon.useStyle(
  59043. defaults(
  59044. itemModel.getModel('itemStyle.normal').getItemStyle(),
  59045. {
  59046. fill: modifyAlpha(color, 0.4),
  59047. stroke: color
  59048. }
  59049. )
  59050. );
  59051. polygon.hoverStyle = itemModel.getModel('itemStyle.emphasis').getItemStyle();
  59052. setLabelStyle(
  59053. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  59054. {
  59055. labelFetcher: maModel,
  59056. labelDataIndex: idx,
  59057. defaultText: areaData.getName(idx) || '',
  59058. isRectText: true,
  59059. autoColor: color
  59060. }
  59061. );
  59062. setHoverStyle(polygon, {});
  59063. polygon.dataModel = maModel;
  59064. });
  59065. polygonGroup.__data = areaData;
  59066. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  59067. }
  59068. });
  59069. /**
  59070. * @inner
  59071. * @param {module:echarts/coord/*} coordSys
  59072. * @param {module:echarts/model/Series} seriesModel
  59073. * @param {module:echarts/model/Model} mpModel
  59074. */
  59075. function createList$3(coordSys, seriesModel, maModel) {
  59076. var coordDimsInfos;
  59077. var areaData;
  59078. var dims = ['x0', 'y0', 'x1', 'y1'];
  59079. if (coordSys) {
  59080. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  59081. var info = seriesModel.getData().getDimensionInfo(
  59082. seriesModel.coordDimToDataDim(coordDim)[0]
  59083. ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  59084. info.name = coordDim;
  59085. return info;
  59086. });
  59087. areaData = new List(map(dims, function (dim, idx) {
  59088. return {
  59089. name: dim,
  59090. type: coordDimsInfos[idx % 2].type
  59091. };
  59092. }), maModel);
  59093. }
  59094. else {
  59095. coordDimsInfos =[{
  59096. name: 'value',
  59097. type: 'float'
  59098. }];
  59099. areaData = new List(coordDimsInfos, maModel);
  59100. }
  59101. var optData = map(maModel.get('data'), curry(
  59102. markAreaTransform, seriesModel, coordSys, maModel
  59103. ));
  59104. if (coordSys) {
  59105. optData = filter(
  59106. optData, curry(markAreaFilter, coordSys)
  59107. );
  59108. }
  59109. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  59110. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  59111. } : function (item) {
  59112. return item.value;
  59113. };
  59114. areaData.initData(optData, null, dimValueGetter$$1);
  59115. areaData.hasItemOption = true;
  59116. return areaData;
  59117. }
  59118. registerPreprocessor(function (opt) {
  59119. // Make sure markArea component is enabled
  59120. opt.markArea = opt.markArea || {};
  59121. });
  59122. var preprocessor$3 = function (option) {
  59123. var timelineOpt = option && option.timeline;
  59124. if (!isArray(timelineOpt)) {
  59125. timelineOpt = timelineOpt ? [timelineOpt] : [];
  59126. }
  59127. each$1(timelineOpt, function (opt) {
  59128. if (!opt) {
  59129. return;
  59130. }
  59131. compatibleEC2(opt);
  59132. });
  59133. };
  59134. function compatibleEC2(opt) {
  59135. var type = opt.type;
  59136. var ec2Types = {'number': 'value', 'time': 'time'};
  59137. // Compatible with ec2
  59138. if (ec2Types[type]) {
  59139. opt.axisType = ec2Types[type];
  59140. delete opt.type;
  59141. }
  59142. transferItem(opt);
  59143. if (has$2(opt, 'controlPosition')) {
  59144. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  59145. if (!has$2(controlStyle, 'position')) {
  59146. controlStyle.position = opt.controlPosition;
  59147. }
  59148. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  59149. controlStyle.show = false;
  59150. delete controlStyle.position;
  59151. }
  59152. delete opt.controlPosition;
  59153. }
  59154. each$1(opt.data || [], function (dataItem) {
  59155. if (isObject(dataItem) && !isArray(dataItem)) {
  59156. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  59157. // In ec2, using name as value.
  59158. dataItem.value = dataItem.name;
  59159. }
  59160. transferItem(dataItem);
  59161. }
  59162. });
  59163. }
  59164. function transferItem(opt) {
  59165. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  59166. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  59167. // Transfer label out
  59168. var label = opt.label || (opt.label || {});
  59169. var labelNormal = label.normal || (label.normal = {});
  59170. var excludeLabelAttr = {normal: 1, emphasis: 1};
  59171. each$1(label, function (value, name) {
  59172. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  59173. labelNormal[name] = value;
  59174. }
  59175. });
  59176. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  59177. label.emphasis = itemStyleEmphasis.label;
  59178. delete itemStyleEmphasis.label;
  59179. }
  59180. }
  59181. function has$2(obj, attr) {
  59182. return obj.hasOwnProperty(attr);
  59183. }
  59184. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  59185. // Only slider now.
  59186. return 'slider';
  59187. });
  59188. registerAction(
  59189. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  59190. function (payload, ecModel) {
  59191. var timelineModel = ecModel.getComponent('timeline');
  59192. if (timelineModel && payload.currentIndex != null) {
  59193. timelineModel.setCurrentIndex(payload.currentIndex);
  59194. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  59195. timelineModel.setPlayState(false);
  59196. }
  59197. }
  59198. // Set normalized currentIndex to payload.
  59199. ecModel.resetOption('timeline');
  59200. return defaults({
  59201. currentIndex: timelineModel.option.currentIndex
  59202. }, payload);
  59203. }
  59204. );
  59205. registerAction(
  59206. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  59207. function (payload, ecModel) {
  59208. var timelineModel = ecModel.getComponent('timeline');
  59209. if (timelineModel && payload.playState != null) {
  59210. timelineModel.setPlayState(payload.playState);
  59211. }
  59212. }
  59213. );
  59214. var TimelineModel = ComponentModel.extend({
  59215. type: 'timeline',
  59216. layoutMode: 'box',
  59217. /**
  59218. * @protected
  59219. */
  59220. defaultOption: {
  59221. zlevel: 0, // 一级层叠
  59222. z: 4, // 二级层叠
  59223. show: true,
  59224. axisType: 'time', // 模式是时间类型,支持 value, category
  59225. realtime: true,
  59226. left: '20%',
  59227. top: null,
  59228. right: '20%',
  59229. bottom: 0,
  59230. width: null,
  59231. height: 40,
  59232. padding: 5,
  59233. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  59234. autoPlay: false,
  59235. rewind: false, // 反向播放
  59236. loop: true,
  59237. playInterval: 2000, // 播放时间间隔,单位ms
  59238. currentIndex: 0,
  59239. itemStyle: {
  59240. normal: {},
  59241. emphasis: {}
  59242. },
  59243. label: {
  59244. normal: {
  59245. color: '#000'
  59246. },
  59247. emphasis: {}
  59248. },
  59249. data: []
  59250. },
  59251. /**
  59252. * @override
  59253. */
  59254. init: function (option, parentModel, ecModel) {
  59255. /**
  59256. * @private
  59257. * @type {module:echarts/data/List}
  59258. */
  59259. this._data;
  59260. /**
  59261. * @private
  59262. * @type {Array.<string>}
  59263. */
  59264. this._names;
  59265. this.mergeDefaultAndTheme(option, ecModel);
  59266. this._initData();
  59267. },
  59268. /**
  59269. * @override
  59270. */
  59271. mergeOption: function (option) {
  59272. TimelineModel.superApply(this, 'mergeOption', arguments);
  59273. this._initData();
  59274. },
  59275. /**
  59276. * @param {number} [currentIndex]
  59277. */
  59278. setCurrentIndex: function (currentIndex) {
  59279. if (currentIndex == null) {
  59280. currentIndex = this.option.currentIndex;
  59281. }
  59282. var count = this._data.count();
  59283. if (this.option.loop) {
  59284. currentIndex = (currentIndex % count + count) % count;
  59285. }
  59286. else {
  59287. currentIndex >= count && (currentIndex = count - 1);
  59288. currentIndex < 0 && (currentIndex = 0);
  59289. }
  59290. this.option.currentIndex = currentIndex;
  59291. },
  59292. /**
  59293. * @return {number} currentIndex
  59294. */
  59295. getCurrentIndex: function () {
  59296. return this.option.currentIndex;
  59297. },
  59298. /**
  59299. * @return {boolean}
  59300. */
  59301. isIndexMax: function () {
  59302. return this.getCurrentIndex() >= this._data.count() - 1;
  59303. },
  59304. /**
  59305. * @param {boolean} state true: play, false: stop
  59306. */
  59307. setPlayState: function (state) {
  59308. this.option.autoPlay = !!state;
  59309. },
  59310. /**
  59311. * @return {boolean} true: play, false: stop
  59312. */
  59313. getPlayState: function () {
  59314. return !!this.option.autoPlay;
  59315. },
  59316. /**
  59317. * @private
  59318. */
  59319. _initData: function () {
  59320. var thisOption = this.option;
  59321. var dataArr = thisOption.data || [];
  59322. var axisType = thisOption.axisType;
  59323. var names = this._names = [];
  59324. if (axisType === 'category') {
  59325. var idxArr = [];
  59326. each$1(dataArr, function (item, index) {
  59327. var value = getDataItemValue(item);
  59328. var newItem;
  59329. if (isObject(item)) {
  59330. newItem = clone(item);
  59331. newItem.value = index;
  59332. }
  59333. else {
  59334. newItem = index;
  59335. }
  59336. idxArr.push(newItem);
  59337. if (!isString(value) && (value == null || isNaN(value))) {
  59338. value = '';
  59339. }
  59340. names.push(value + '');
  59341. });
  59342. dataArr = idxArr;
  59343. }
  59344. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  59345. var data = this._data = new List([{name: 'value', type: dimType}], this);
  59346. data.initData(dataArr, names);
  59347. },
  59348. getData: function () {
  59349. return this._data;
  59350. },
  59351. /**
  59352. * @public
  59353. * @return {Array.<string>} categoreis
  59354. */
  59355. getCategories: function () {
  59356. if (this.get('axisType') === 'category') {
  59357. return this._names.slice();
  59358. }
  59359. }
  59360. });
  59361. var SliderTimelineModel = TimelineModel.extend({
  59362. type: 'timeline.slider',
  59363. /**
  59364. * @protected
  59365. */
  59366. defaultOption: {
  59367. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  59368. borderColor: '#ccc', // 时间轴边框颜色
  59369. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  59370. orient: 'horizontal', // 'vertical'
  59371. inverse: false,
  59372. tooltip: { // boolean or Object
  59373. trigger: 'item' // data item may also have tootip attr.
  59374. },
  59375. symbol: 'emptyCircle',
  59376. symbolSize: 10,
  59377. lineStyle: {
  59378. show: true,
  59379. width: 2,
  59380. color: '#304654'
  59381. },
  59382. label: { // 文本标签
  59383. position: 'auto', // auto left right top bottom
  59384. // When using number, label position is not
  59385. // restricted by viewRect.
  59386. // positive: right/bottom, negative: left/top
  59387. normal: {
  59388. show: true,
  59389. interval: 'auto',
  59390. rotate: 0,
  59391. // formatter: null,
  59392. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  59393. color: '#304654'
  59394. },
  59395. emphasis: {
  59396. show: true,
  59397. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  59398. color: '#c23531'
  59399. }
  59400. },
  59401. itemStyle: {
  59402. normal: {
  59403. color: '#304654',
  59404. borderWidth: 1
  59405. },
  59406. emphasis: {
  59407. color: '#c23531'
  59408. }
  59409. },
  59410. checkpointStyle: {
  59411. symbol: 'circle',
  59412. symbolSize: 13,
  59413. color: '#c23531',
  59414. borderWidth: 5,
  59415. borderColor: 'rgba(194,53,49, 0.5)',
  59416. animation: true,
  59417. animationDuration: 300,
  59418. animationEasing: 'quinticInOut'
  59419. },
  59420. controlStyle: {
  59421. show: true,
  59422. showPlayBtn: true,
  59423. showPrevBtn: true,
  59424. showNextBtn: true,
  59425. itemSize: 22,
  59426. itemGap: 12,
  59427. position: 'left', // 'left' 'right' 'top' 'bottom'
  59428. 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
  59429. 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
  59430. 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
  59431. 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
  59432. normal: {
  59433. color: '#304654',
  59434. borderColor: '#304654',
  59435. borderWidth: 1
  59436. },
  59437. emphasis: {
  59438. color: '#c23531',
  59439. borderColor: '#c23531',
  59440. borderWidth: 2
  59441. }
  59442. },
  59443. data: []
  59444. }
  59445. });
  59446. mixin(SliderTimelineModel, dataFormatMixin);
  59447. var TimelineView = Component.extend({
  59448. type: 'timeline'
  59449. });
  59450. /**
  59451. * Extend axis 2d
  59452. * @constructor module:echarts/coord/cartesian/Axis2D
  59453. * @extends {module:echarts/coord/cartesian/Axis}
  59454. * @param {string} dim
  59455. * @param {*} scale
  59456. * @param {Array.<number>} coordExtent
  59457. * @param {string} axisType
  59458. * @param {string} position
  59459. */
  59460. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  59461. Axis.call(this, dim, scale, coordExtent);
  59462. /**
  59463. * Axis type
  59464. * - 'category'
  59465. * - 'value'
  59466. * - 'time'
  59467. * - 'log'
  59468. * @type {string}
  59469. */
  59470. this.type = axisType || 'value';
  59471. /**
  59472. * @private
  59473. * @type {number}
  59474. */
  59475. this._autoLabelInterval;
  59476. /**
  59477. * Axis model
  59478. * @param {module:echarts/component/TimelineModel}
  59479. */
  59480. this.model = null;
  59481. };
  59482. TimelineAxis.prototype = {
  59483. constructor: TimelineAxis,
  59484. /**
  59485. * @public
  59486. * @return {number}
  59487. */
  59488. getLabelInterval: function () {
  59489. var timelineModel = this.model;
  59490. var labelModel = timelineModel.getModel('label.normal');
  59491. var labelInterval = labelModel.get('interval');
  59492. if (labelInterval != null && labelInterval != 'auto') {
  59493. return labelInterval;
  59494. }
  59495. var labelInterval = this._autoLabelInterval;
  59496. if (!labelInterval) {
  59497. labelInterval = this._autoLabelInterval = getAxisLabelInterval(
  59498. map(this.scale.getTicks(), this.dataToCoord, this),
  59499. getFormattedLabels(this, labelModel.get('formatter')),
  59500. labelModel.getFont(),
  59501. timelineModel.get('orient') === 'horizontal' ? 0 : 90,
  59502. labelModel.get('rotate')
  59503. );
  59504. }
  59505. return labelInterval;
  59506. },
  59507. /**
  59508. * If label is ignored.
  59509. * Automatically used when axis is category and label can not be all shown
  59510. * @public
  59511. * @param {number} idx
  59512. * @return {boolean}
  59513. */
  59514. isLabelIgnored: function (idx) {
  59515. if (this.type === 'category') {
  59516. var labelInterval = this.getLabelInterval();
  59517. return ((typeof labelInterval === 'function')
  59518. && !labelInterval(idx, this.scale.getLabel(idx)))
  59519. || idx % (labelInterval + 1);
  59520. }
  59521. }
  59522. };
  59523. inherits(TimelineAxis, Axis);
  59524. var bind$6 = bind;
  59525. var each$30 = each$1;
  59526. var PI$4 = Math.PI;
  59527. TimelineView.extend({
  59528. type: 'timeline.slider',
  59529. init: function (ecModel, api) {
  59530. this.api = api;
  59531. /**
  59532. * @private
  59533. * @type {module:echarts/component/timeline/TimelineAxis}
  59534. */
  59535. this._axis;
  59536. /**
  59537. * @private
  59538. * @type {module:zrender/core/BoundingRect}
  59539. */
  59540. this._viewRect;
  59541. /**
  59542. * @type {number}
  59543. */
  59544. this._timer;
  59545. /**
  59546. * @type {module:zrender/Element}
  59547. */
  59548. this._currentPointer;
  59549. /**
  59550. * @type {module:zrender/container/Group}
  59551. */
  59552. this._mainGroup;
  59553. /**
  59554. * @type {module:zrender/container/Group}
  59555. */
  59556. this._labelGroup;
  59557. },
  59558. /**
  59559. * @override
  59560. */
  59561. render: function (timelineModel, ecModel, api, payload) {
  59562. this.model = timelineModel;
  59563. this.api = api;
  59564. this.ecModel = ecModel;
  59565. this.group.removeAll();
  59566. if (timelineModel.get('show', true)) {
  59567. var layoutInfo = this._layout(timelineModel, api);
  59568. var mainGroup = this._createGroup('mainGroup');
  59569. var labelGroup = this._createGroup('labelGroup');
  59570. /**
  59571. * @private
  59572. * @type {module:echarts/component/timeline/TimelineAxis}
  59573. */
  59574. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  59575. timelineModel.formatTooltip = function (dataIndex) {
  59576. return encodeHTML(axis.scale.getLabel(dataIndex));
  59577. };
  59578. each$30(
  59579. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  59580. function (name) {
  59581. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  59582. },
  59583. this
  59584. );
  59585. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  59586. this._position(layoutInfo, timelineModel);
  59587. }
  59588. this._doPlayStop();
  59589. },
  59590. /**
  59591. * @override
  59592. */
  59593. remove: function () {
  59594. this._clearTimer();
  59595. this.group.removeAll();
  59596. },
  59597. /**
  59598. * @override
  59599. */
  59600. dispose: function () {
  59601. this._clearTimer();
  59602. },
  59603. _layout: function (timelineModel, api) {
  59604. var labelPosOpt = timelineModel.get('label.normal.position');
  59605. var orient = timelineModel.get('orient');
  59606. var viewRect = getViewRect$4(timelineModel, api);
  59607. // Auto label offset.
  59608. if (labelPosOpt == null || labelPosOpt === 'auto') {
  59609. labelPosOpt = orient === 'horizontal'
  59610. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  59611. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  59612. }
  59613. else if (isNaN(labelPosOpt)) {
  59614. labelPosOpt = ({
  59615. horizontal: {top: '-', bottom: '+'},
  59616. vertical: {left: '-', right: '+'}
  59617. })[orient][labelPosOpt];
  59618. }
  59619. var labelAlignMap = {
  59620. horizontal: 'center',
  59621. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  59622. };
  59623. var labelBaselineMap = {
  59624. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  59625. vertical: 'middle'
  59626. };
  59627. var rotationMap = {
  59628. horizontal: 0,
  59629. vertical: PI$4 / 2
  59630. };
  59631. // Position
  59632. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  59633. var controlModel = timelineModel.getModel('controlStyle');
  59634. var showControl = controlModel.get('show');
  59635. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  59636. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  59637. var sizePlusGap = controlSize + controlGap;
  59638. // Special label rotate.
  59639. var labelRotation = timelineModel.get('label.normal.rotate') || 0;
  59640. labelRotation = labelRotation * PI$4 / 180; // To radian.
  59641. var playPosition;
  59642. var prevBtnPosition;
  59643. var nextBtnPosition;
  59644. var axisExtent;
  59645. var controlPosition = controlModel.get('position', true);
  59646. var showControl = controlModel.get('show', true);
  59647. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  59648. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  59649. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  59650. var xLeft = 0;
  59651. var xRight = mainLength;
  59652. // position[0] means left, position[1] means middle.
  59653. if (controlPosition === 'left' || controlPosition === 'bottom') {
  59654. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  59655. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  59656. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59657. }
  59658. else { // 'top' 'right'
  59659. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59660. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  59661. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  59662. }
  59663. axisExtent = [xLeft, xRight];
  59664. if (timelineModel.get('inverse')) {
  59665. axisExtent.reverse();
  59666. }
  59667. return {
  59668. viewRect: viewRect,
  59669. mainLength: mainLength,
  59670. orient: orient,
  59671. rotation: rotationMap[orient],
  59672. labelRotation: labelRotation,
  59673. labelPosOpt: labelPosOpt,
  59674. labelAlign: timelineModel.get('label.normal.align') || labelAlignMap[orient],
  59675. labelBaseline: timelineModel.get('label.normal.verticalAlign')
  59676. || timelineModel.get('label.normal.baseline')
  59677. || labelBaselineMap[orient],
  59678. // Based on mainGroup.
  59679. playPosition: playPosition,
  59680. prevBtnPosition: prevBtnPosition,
  59681. nextBtnPosition: nextBtnPosition,
  59682. axisExtent: axisExtent,
  59683. controlSize: controlSize,
  59684. controlGap: controlGap
  59685. };
  59686. },
  59687. _position: function (layoutInfo, timelineModel) {
  59688. // Position is be called finally, because bounding rect is needed for
  59689. // adapt content to fill viewRect (auto adapt offset).
  59690. // Timeline may be not all in the viewRect when 'offset' is specified
  59691. // as a number, because it is more appropriate that label aligns at
  59692. // 'offset' but not the other edge defined by viewRect.
  59693. var mainGroup = this._mainGroup;
  59694. var labelGroup = this._labelGroup;
  59695. var viewRect = layoutInfo.viewRect;
  59696. if (layoutInfo.orient === 'vertical') {
  59697. // transfrom to horizontal, inverse rotate by left-top point.
  59698. var m = create$1();
  59699. var rotateOriginX = viewRect.x;
  59700. var rotateOriginY = viewRect.y + viewRect.height;
  59701. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  59702. rotate(m, m, -PI$4 / 2);
  59703. translate(m, m, [rotateOriginX, rotateOriginY]);
  59704. viewRect = viewRect.clone();
  59705. viewRect.applyTransform(m);
  59706. }
  59707. var viewBound = getBound(viewRect);
  59708. var mainBound = getBound(mainGroup.getBoundingRect());
  59709. var labelBound = getBound(labelGroup.getBoundingRect());
  59710. var mainPosition = mainGroup.position;
  59711. var labelsPosition = labelGroup.position;
  59712. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  59713. var labelPosOpt = layoutInfo.labelPosOpt;
  59714. if (isNaN(labelPosOpt)) { // '+' or '-'
  59715. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  59716. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  59717. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  59718. }
  59719. else {
  59720. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  59721. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  59722. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  59723. }
  59724. mainGroup.attr('position', mainPosition);
  59725. labelGroup.attr('position', labelsPosition);
  59726. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  59727. setOrigin(mainGroup);
  59728. setOrigin(labelGroup);
  59729. function setOrigin(targetGroup) {
  59730. var pos = targetGroup.position;
  59731. targetGroup.origin = [
  59732. viewBound[0][0] - pos[0],
  59733. viewBound[1][0] - pos[1]
  59734. ];
  59735. }
  59736. function getBound(rect) {
  59737. // [[xmin, xmax], [ymin, ymax]]
  59738. return [
  59739. [rect.x, rect.x + rect.width],
  59740. [rect.y, rect.y + rect.height]
  59741. ];
  59742. }
  59743. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  59744. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  59745. }
  59746. },
  59747. _createAxis: function (layoutInfo, timelineModel) {
  59748. var data = timelineModel.getData();
  59749. var axisType = timelineModel.get('axisType');
  59750. var scale = createScaleByModel(timelineModel, axisType);
  59751. var dataExtent = data.getDataExtent('value');
  59752. scale.setExtent(dataExtent[0], dataExtent[1]);
  59753. this._customizeScale(scale, data);
  59754. scale.niceTicks();
  59755. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  59756. axis.model = timelineModel;
  59757. return axis;
  59758. },
  59759. _customizeScale: function (scale, data) {
  59760. scale.getTicks = function () {
  59761. return data.mapArray(['value'], function (value) {
  59762. return value;
  59763. });
  59764. };
  59765. scale.getTicksLabels = function () {
  59766. return map(this.getTicks(), scale.getLabel, scale);
  59767. };
  59768. },
  59769. _createGroup: function (name) {
  59770. var newGroup = this['_' + name] = new Group();
  59771. this.group.add(newGroup);
  59772. return newGroup;
  59773. },
  59774. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  59775. var axisExtent = axis.getExtent();
  59776. if (!timelineModel.get('lineStyle.show')) {
  59777. return;
  59778. }
  59779. group.add(new Line({
  59780. shape: {
  59781. x1: axisExtent[0], y1: 0,
  59782. x2: axisExtent[1], y2: 0
  59783. },
  59784. style: extend(
  59785. {lineCap: 'round'},
  59786. timelineModel.getModel('lineStyle').getLineStyle()
  59787. ),
  59788. silent: true,
  59789. z2: 1
  59790. }));
  59791. },
  59792. /**
  59793. * @private
  59794. */
  59795. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  59796. var data = timelineModel.getData();
  59797. var ticks = axis.scale.getTicks();
  59798. each$30(ticks, function (value, dataIndex) {
  59799. var tickCoord = axis.dataToCoord(value);
  59800. var itemModel = data.getItemModel(dataIndex);
  59801. var itemStyleModel = itemModel.getModel('itemStyle.normal');
  59802. var hoverStyleModel = itemModel.getModel('itemStyle.emphasis');
  59803. var symbolOpt = {
  59804. position: [tickCoord, 0],
  59805. onclick: bind$6(this._changeTimeline, this, dataIndex)
  59806. };
  59807. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  59808. setHoverStyle(el, hoverStyleModel.getItemStyle());
  59809. if (itemModel.get('tooltip')) {
  59810. el.dataIndex = dataIndex;
  59811. el.dataModel = timelineModel;
  59812. }
  59813. else {
  59814. el.dataIndex = el.dataModel = null;
  59815. }
  59816. }, this);
  59817. },
  59818. /**
  59819. * @private
  59820. */
  59821. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  59822. var labelModel = timelineModel.getModel('label.normal');
  59823. if (!labelModel.get('show')) {
  59824. return;
  59825. }
  59826. var data = timelineModel.getData();
  59827. var ticks = axis.scale.getTicks();
  59828. var labels = getFormattedLabels(
  59829. axis, labelModel.get('formatter')
  59830. );
  59831. var labelInterval = axis.getLabelInterval();
  59832. each$30(ticks, function (tick, dataIndex) {
  59833. if (axis.isLabelIgnored(dataIndex, labelInterval)) {
  59834. return;
  59835. }
  59836. var itemModel = data.getItemModel(dataIndex);
  59837. var normalLabelModel = itemModel.getModel('label.normal');
  59838. var hoverLabelModel = itemModel.getModel('label.emphasis');
  59839. var tickCoord = axis.dataToCoord(tick);
  59840. var textEl = new Text({
  59841. position: [tickCoord, 0],
  59842. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  59843. onclick: bind$6(this._changeTimeline, this, dataIndex),
  59844. silent: false
  59845. });
  59846. setTextStyle(textEl.style, normalLabelModel, {
  59847. text: labels[dataIndex],
  59848. textAlign: layoutInfo.labelAlign,
  59849. textVerticalAlign: layoutInfo.labelBaseline
  59850. });
  59851. group.add(textEl);
  59852. setHoverStyle(
  59853. textEl, setTextStyle({}, hoverLabelModel)
  59854. );
  59855. }, this);
  59856. },
  59857. /**
  59858. * @private
  59859. */
  59860. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  59861. var controlSize = layoutInfo.controlSize;
  59862. var rotation = layoutInfo.rotation;
  59863. var itemStyle = timelineModel.getModel('controlStyle.normal').getItemStyle();
  59864. var hoverStyle = timelineModel.getModel('controlStyle.emphasis').getItemStyle();
  59865. var rect = [0, -controlSize / 2, controlSize, controlSize];
  59866. var playState = timelineModel.getPlayState();
  59867. var inverse = timelineModel.get('inverse', true);
  59868. makeBtn(
  59869. layoutInfo.nextBtnPosition,
  59870. 'controlStyle.nextIcon',
  59871. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  59872. );
  59873. makeBtn(
  59874. layoutInfo.prevBtnPosition,
  59875. 'controlStyle.prevIcon',
  59876. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  59877. );
  59878. makeBtn(
  59879. layoutInfo.playPosition,
  59880. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  59881. bind$6(this._handlePlayClick, this, !playState),
  59882. true
  59883. );
  59884. function makeBtn(position, iconPath, onclick, willRotate) {
  59885. if (!position) {
  59886. return;
  59887. }
  59888. var opt = {
  59889. position: position,
  59890. origin: [controlSize / 2, 0],
  59891. rotation: willRotate ? -rotation : 0,
  59892. rectHover: true,
  59893. style: itemStyle,
  59894. onclick: onclick
  59895. };
  59896. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  59897. group.add(btn);
  59898. setHoverStyle(btn, hoverStyle);
  59899. }
  59900. },
  59901. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  59902. var data = timelineModel.getData();
  59903. var currentIndex = timelineModel.getCurrentIndex();
  59904. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  59905. var me = this;
  59906. var callback = {
  59907. onCreate: function (pointer) {
  59908. pointer.draggable = true;
  59909. pointer.drift = bind$6(me._handlePointerDrag, me);
  59910. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  59911. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  59912. },
  59913. onUpdate: function (pointer) {
  59914. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  59915. }
  59916. };
  59917. // Reuse when exists, for animation and drag.
  59918. this._currentPointer = giveSymbol(
  59919. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  59920. );
  59921. },
  59922. _handlePlayClick: function (nextState) {
  59923. this._clearTimer();
  59924. this.api.dispatchAction({
  59925. type: 'timelinePlayChange',
  59926. playState: nextState,
  59927. from: this.uid
  59928. });
  59929. },
  59930. _handlePointerDrag: function (dx, dy, e) {
  59931. this._clearTimer();
  59932. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  59933. },
  59934. _handlePointerDragend: function (e) {
  59935. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  59936. },
  59937. _pointerChangeTimeline: function (mousePos, trigger) {
  59938. var toCoord = this._toAxisCoord(mousePos)[0];
  59939. var axis = this._axis;
  59940. var axisExtent = asc(axis.getExtent().slice());
  59941. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  59942. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  59943. this._currentPointer.position[0] = toCoord;
  59944. this._currentPointer.dirty();
  59945. var targetDataIndex = this._findNearestTick(toCoord);
  59946. var timelineModel = this.model;
  59947. if (trigger || (
  59948. targetDataIndex !== timelineModel.getCurrentIndex()
  59949. && timelineModel.get('realtime')
  59950. )) {
  59951. this._changeTimeline(targetDataIndex);
  59952. }
  59953. },
  59954. _doPlayStop: function () {
  59955. this._clearTimer();
  59956. if (this.model.getPlayState()) {
  59957. this._timer = setTimeout(
  59958. bind$6(handleFrame, this),
  59959. this.model.get('playInterval')
  59960. );
  59961. }
  59962. function handleFrame() {
  59963. // Do not cache
  59964. var timelineModel = this.model;
  59965. this._changeTimeline(
  59966. timelineModel.getCurrentIndex()
  59967. + (timelineModel.get('rewind', true) ? -1 : 1)
  59968. );
  59969. }
  59970. },
  59971. _toAxisCoord: function (vertex) {
  59972. var trans = this._mainGroup.getLocalTransform();
  59973. return applyTransform$1(vertex, trans, true);
  59974. },
  59975. _findNearestTick: function (axisCoord) {
  59976. var data = this.model.getData();
  59977. var dist = Infinity;
  59978. var targetDataIndex;
  59979. var axis = this._axis;
  59980. data.each(['value'], function (value, dataIndex) {
  59981. var coord = axis.dataToCoord(value);
  59982. var d = Math.abs(coord - axisCoord);
  59983. if (d < dist) {
  59984. dist = d;
  59985. targetDataIndex = dataIndex;
  59986. }
  59987. });
  59988. return targetDataIndex;
  59989. },
  59990. _clearTimer: function () {
  59991. if (this._timer) {
  59992. clearTimeout(this._timer);
  59993. this._timer = null;
  59994. }
  59995. },
  59996. _changeTimeline: function (nextIndex) {
  59997. var currentIndex = this.model.getCurrentIndex();
  59998. if (nextIndex === '+') {
  59999. nextIndex = currentIndex + 1;
  60000. }
  60001. else if (nextIndex === '-') {
  60002. nextIndex = currentIndex - 1;
  60003. }
  60004. this.api.dispatchAction({
  60005. type: 'timelineChange',
  60006. currentIndex: nextIndex,
  60007. from: this.uid
  60008. });
  60009. }
  60010. });
  60011. function getViewRect$4(model, api) {
  60012. return getLayoutRect(
  60013. model.getBoxLayoutParams(),
  60014. {
  60015. width: api.getWidth(),
  60016. height: api.getHeight()
  60017. },
  60018. model.get('padding')
  60019. );
  60020. }
  60021. function makeIcon(timelineModel, objPath, rect, opts) {
  60022. var icon = makePath(
  60023. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  60024. clone(opts || {}),
  60025. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  60026. 'center'
  60027. );
  60028. return icon;
  60029. }
  60030. /**
  60031. * Create symbol or update symbol
  60032. * opt: basic position and event handlers
  60033. */
  60034. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  60035. var color = itemStyleModel.get('color');
  60036. if (!symbol) {
  60037. var symbolType = hostModel.get('symbol');
  60038. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  60039. symbol.setStyle('strokeNoScale', true);
  60040. group.add(symbol);
  60041. callback && callback.onCreate(symbol);
  60042. }
  60043. else {
  60044. symbol.setColor(color);
  60045. group.add(symbol); // Group may be new, also need to add.
  60046. callback && callback.onUpdate(symbol);
  60047. }
  60048. // Style
  60049. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  60050. symbol.setStyle(itemStyle);
  60051. // Transform and events.
  60052. opt = merge({
  60053. rectHover: true,
  60054. z2: 100
  60055. }, opt, true);
  60056. var symbolSize = hostModel.get('symbolSize');
  60057. symbolSize = symbolSize instanceof Array
  60058. ? symbolSize.slice()
  60059. : [+symbolSize, +symbolSize];
  60060. symbolSize[0] /= 2;
  60061. symbolSize[1] /= 2;
  60062. opt.scale = symbolSize;
  60063. var symbolOffset = hostModel.get('symbolOffset');
  60064. if (symbolOffset) {
  60065. var pos = opt.position = opt.position || [0, 0];
  60066. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  60067. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  60068. }
  60069. var symbolRotate = hostModel.get('symbolRotate');
  60070. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  60071. symbol.attr(opt);
  60072. // FIXME
  60073. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  60074. // getBoundingRect will return wrong result.
  60075. // (This is supposed to be resolved in zrender, but it is a little difficult to
  60076. // leverage performance and auto updateTransform)
  60077. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  60078. symbol.updateTransform();
  60079. return symbol;
  60080. }
  60081. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  60082. if (pointer.dragging) {
  60083. return;
  60084. }
  60085. var pointerModel = timelineModel.getModel('checkpointStyle');
  60086. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  60087. if (noAnimation || !pointerModel.get('animation', true)) {
  60088. pointer.attr({position: [toCoord, 0]});
  60089. }
  60090. else {
  60091. pointer.stopAnimation(true);
  60092. pointer.animateTo(
  60093. {position: [toCoord, 0]},
  60094. pointerModel.get('animationDuration', true),
  60095. pointerModel.get('animationEasing', true)
  60096. );
  60097. }
  60098. }
  60099. /**
  60100. * DataZoom component entry
  60101. */
  60102. registerPreprocessor(preprocessor$3);
  60103. var ToolboxModel = extendComponentModel({
  60104. type: 'toolbox',
  60105. layoutMode: {
  60106. type: 'box',
  60107. ignoreSize: true
  60108. },
  60109. mergeDefaultAndTheme: function (option) {
  60110. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  60111. each$1(this.option.feature, function (featureOpt, featureName) {
  60112. var Feature = get$5(featureName);
  60113. Feature && merge(featureOpt, Feature.defaultOption);
  60114. });
  60115. },
  60116. defaultOption: {
  60117. show: true,
  60118. z: 6,
  60119. zlevel: 0,
  60120. orient: 'horizontal',
  60121. left: 'right',
  60122. top: 'top',
  60123. // right
  60124. // bottom
  60125. backgroundColor: 'transparent',
  60126. borderColor: '#ccc',
  60127. borderRadius: 0,
  60128. borderWidth: 0,
  60129. padding: 5,
  60130. itemSize: 15,
  60131. itemGap: 8,
  60132. showTitle: true,
  60133. iconStyle: {
  60134. normal: {
  60135. borderColor: '#666',
  60136. color: 'none'
  60137. },
  60138. emphasis: {
  60139. borderColor: '#3E98C5'
  60140. }
  60141. }
  60142. // textStyle: {},
  60143. // feature
  60144. }
  60145. });
  60146. extendComponentView({
  60147. type: 'toolbox',
  60148. render: function (toolboxModel, ecModel, api, payload) {
  60149. var group = this.group;
  60150. group.removeAll();
  60151. if (!toolboxModel.get('show')) {
  60152. return;
  60153. }
  60154. var itemSize = +toolboxModel.get('itemSize');
  60155. var featureOpts = toolboxModel.get('feature') || {};
  60156. var features = this._features || (this._features = {});
  60157. var featureNames = [];
  60158. each$1(featureOpts, function (opt, name) {
  60159. featureNames.push(name);
  60160. });
  60161. (new DataDiffer(this._featureNames || [], featureNames))
  60162. .add(processFeature)
  60163. .update(processFeature)
  60164. .remove(curry(processFeature, null))
  60165. .execute();
  60166. // Keep for diff.
  60167. this._featureNames = featureNames;
  60168. function processFeature(newIndex, oldIndex) {
  60169. var featureName = featureNames[newIndex];
  60170. var oldName = featureNames[oldIndex];
  60171. var featureOpt = featureOpts[featureName];
  60172. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  60173. var feature;
  60174. if (featureName && !oldName) { // Create
  60175. if (isUserFeatureName(featureName)) {
  60176. feature = {
  60177. model: featureModel,
  60178. onclick: featureModel.option.onclick,
  60179. featureName: featureName
  60180. };
  60181. }
  60182. else {
  60183. var Feature = get$5(featureName);
  60184. if (!Feature) {
  60185. return;
  60186. }
  60187. feature = new Feature(featureModel, ecModel, api);
  60188. }
  60189. features[featureName] = feature;
  60190. }
  60191. else {
  60192. feature = features[oldName];
  60193. // If feature does not exsit.
  60194. if (!feature) {
  60195. return;
  60196. }
  60197. feature.model = featureModel;
  60198. feature.ecModel = ecModel;
  60199. feature.api = api;
  60200. }
  60201. if (!featureName && oldName) {
  60202. feature.dispose && feature.dispose(ecModel, api);
  60203. return;
  60204. }
  60205. if (!featureModel.get('show') || feature.unusable) {
  60206. feature.remove && feature.remove(ecModel, api);
  60207. return;
  60208. }
  60209. createIconPaths(featureModel, feature, featureName);
  60210. featureModel.setIconStatus = function (iconName, status) {
  60211. var option = this.option;
  60212. var iconPaths = this.iconPaths;
  60213. option.iconStatus = option.iconStatus || {};
  60214. option.iconStatus[iconName] = status;
  60215. // FIXME
  60216. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  60217. };
  60218. if (feature.render) {
  60219. feature.render(featureModel, ecModel, api, payload);
  60220. }
  60221. }
  60222. function createIconPaths(featureModel, feature, featureName) {
  60223. var iconStyleModel = featureModel.getModel('iconStyle');
  60224. // If one feature has mutiple icon. they are orginaized as
  60225. // {
  60226. // icon: {
  60227. // foo: '',
  60228. // bar: ''
  60229. // },
  60230. // title: {
  60231. // foo: '',
  60232. // bar: ''
  60233. // }
  60234. // }
  60235. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  60236. var titles = featureModel.get('title') || {};
  60237. if (typeof icons === 'string') {
  60238. var icon = icons;
  60239. var title = titles;
  60240. icons = {};
  60241. titles = {};
  60242. icons[featureName] = icon;
  60243. titles[featureName] = title;
  60244. }
  60245. var iconPaths = featureModel.iconPaths = {};
  60246. each$1(icons, function (iconStr, iconName) {
  60247. var path = createIcon(
  60248. iconStr,
  60249. {},
  60250. {
  60251. x: -itemSize / 2,
  60252. y: -itemSize / 2,
  60253. width: itemSize,
  60254. height: itemSize
  60255. }
  60256. );
  60257. path.setStyle(iconStyleModel.getModel('normal').getItemStyle());
  60258. path.hoverStyle = iconStyleModel.getModel('emphasis').getItemStyle();
  60259. setHoverStyle(path);
  60260. if (toolboxModel.get('showTitle')) {
  60261. path.__title = titles[iconName];
  60262. path.on('mouseover', function () {
  60263. // Should not reuse above hoverStyle, which might be modified.
  60264. var hoverStyle = iconStyleModel.getModel('emphasis').getItemStyle();
  60265. path.setStyle({
  60266. text: titles[iconName],
  60267. textPosition: hoverStyle.textPosition || 'bottom',
  60268. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  60269. textAlign: hoverStyle.textAlign || 'center'
  60270. });
  60271. })
  60272. .on('mouseout', function () {
  60273. path.setStyle({
  60274. textFill: null
  60275. });
  60276. });
  60277. }
  60278. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  60279. group.add(path);
  60280. path.on('click', bind(
  60281. feature.onclick, feature, ecModel, api, iconName
  60282. ));
  60283. iconPaths[iconName] = path;
  60284. });
  60285. }
  60286. layout$2(group, toolboxModel, api);
  60287. // Render background after group is layout
  60288. // FIXME
  60289. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  60290. // Adjust icon title positions to avoid them out of screen
  60291. group.eachChild(function (icon) {
  60292. var titleText = icon.__title;
  60293. var hoverStyle = icon.hoverStyle;
  60294. // May be background element
  60295. if (hoverStyle && titleText) {
  60296. var rect = getBoundingRect(
  60297. titleText, makeFont(hoverStyle)
  60298. );
  60299. var offsetX = icon.position[0] + group.position[0];
  60300. var offsetY = icon.position[1] + group.position[1] + itemSize;
  60301. var needPutOnTop = false;
  60302. if (offsetY + rect.height > api.getHeight()) {
  60303. hoverStyle.textPosition = 'top';
  60304. needPutOnTop = true;
  60305. }
  60306. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  60307. if (offsetX + rect.width / 2 > api.getWidth()) {
  60308. hoverStyle.textPosition = ['100%', topOffset];
  60309. hoverStyle.textAlign = 'right';
  60310. }
  60311. else if (offsetX - rect.width / 2 < 0) {
  60312. hoverStyle.textPosition = [0, topOffset];
  60313. hoverStyle.textAlign = 'left';
  60314. }
  60315. }
  60316. });
  60317. },
  60318. updateView: function (toolboxModel, ecModel, api, payload) {
  60319. each$1(this._features, function (feature) {
  60320. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  60321. });
  60322. },
  60323. updateLayout: function (toolboxModel, ecModel, api, payload) {
  60324. each$1(this._features, function (feature) {
  60325. feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  60326. });
  60327. },
  60328. remove: function (ecModel, api) {
  60329. each$1(this._features, function (feature) {
  60330. feature.remove && feature.remove(ecModel, api);
  60331. });
  60332. this.group.removeAll();
  60333. },
  60334. dispose: function (ecModel, api) {
  60335. each$1(this._features, function (feature) {
  60336. feature.dispose && feature.dispose(ecModel, api);
  60337. });
  60338. }
  60339. });
  60340. function isUserFeatureName(featureName) {
  60341. return featureName.indexOf('my') === 0;
  60342. }
  60343. var saveAsImageLang = lang.toolbox.saveAsImage;
  60344. function SaveAsImage(model) {
  60345. this.model = model;
  60346. }
  60347. SaveAsImage.defaultOption = {
  60348. show: true,
  60349. 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',
  60350. title: saveAsImageLang.title,
  60351. type: 'png',
  60352. // Default use option.backgroundColor
  60353. // backgroundColor: '#fff',
  60354. name: '',
  60355. excludeComponents: ['toolbox'],
  60356. pixelRatio: 1,
  60357. lang: saveAsImageLang.lang.slice()
  60358. };
  60359. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  60360. var proto$2 = SaveAsImage.prototype;
  60361. proto$2.onclick = function (ecModel, api) {
  60362. var model = this.model;
  60363. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  60364. var $a = document.createElement('a');
  60365. var type = model.get('type', true) || 'png';
  60366. $a.download = title + '.' + type;
  60367. $a.target = '_blank';
  60368. var url = api.getConnectedDataURL({
  60369. type: type,
  60370. backgroundColor: model.get('backgroundColor', true)
  60371. || ecModel.get('backgroundColor') || '#fff',
  60372. excludeComponents: model.get('excludeComponents'),
  60373. pixelRatio: model.get('pixelRatio')
  60374. });
  60375. $a.href = url;
  60376. // Chrome and Firefox
  60377. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  60378. var evt = new MouseEvent('click', {
  60379. view: window,
  60380. bubbles: true,
  60381. cancelable: false
  60382. });
  60383. $a.dispatchEvent(evt);
  60384. }
  60385. // IE
  60386. else {
  60387. if (window.navigator.msSaveOrOpenBlob) {
  60388. var bstr = atob(url.split(',')[1]);
  60389. var n = bstr.length;
  60390. var u8arr = new Uint8Array(n);
  60391. while(n--) {
  60392. u8arr[n] = bstr.charCodeAt(n);
  60393. }
  60394. var blob = new Blob([u8arr]);
  60395. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  60396. }
  60397. else {
  60398. var lang$$1 = model.get('lang');
  60399. var html = '' +
  60400. '<body style="margin:0;">' +
  60401. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  60402. '</body>';
  60403. var tab = window.open();
  60404. tab.document.write(html);
  60405. }
  60406. }
  60407. };
  60408. register$1(
  60409. 'saveAsImage', SaveAsImage
  60410. );
  60411. var magicTypeLang = lang.toolbox.magicType;
  60412. function MagicType(model) {
  60413. this.model = model;
  60414. }
  60415. MagicType.defaultOption = {
  60416. show: true,
  60417. type: [],
  60418. // Icon group
  60419. icon: {
  60420. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  60421. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  60422. 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
  60423. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  60424. },
  60425. // `line`, `bar`, `stack`, `tiled`
  60426. title: clone(magicTypeLang.title),
  60427. option: {},
  60428. seriesIndex: {}
  60429. };
  60430. var proto$3 = MagicType.prototype;
  60431. proto$3.getIcons = function () {
  60432. var model = this.model;
  60433. var availableIcons = model.get('icon');
  60434. var icons = {};
  60435. each$1(model.get('type'), function (type) {
  60436. if (availableIcons[type]) {
  60437. icons[type] = availableIcons[type];
  60438. }
  60439. });
  60440. return icons;
  60441. };
  60442. var seriesOptGenreator = {
  60443. 'line': function (seriesType, seriesId, seriesModel, model) {
  60444. if (seriesType === 'bar') {
  60445. return merge({
  60446. id: seriesId,
  60447. type: 'line',
  60448. // Preserve data related option
  60449. data: seriesModel.get('data'),
  60450. stack: seriesModel.get('stack'),
  60451. markPoint: seriesModel.get('markPoint'),
  60452. markLine: seriesModel.get('markLine')
  60453. }, model.get('option.line') || {}, true);
  60454. }
  60455. },
  60456. 'bar': function (seriesType, seriesId, seriesModel, model) {
  60457. if (seriesType === 'line') {
  60458. return merge({
  60459. id: seriesId,
  60460. type: 'bar',
  60461. // Preserve data related option
  60462. data: seriesModel.get('data'),
  60463. stack: seriesModel.get('stack'),
  60464. markPoint: seriesModel.get('markPoint'),
  60465. markLine: seriesModel.get('markLine')
  60466. }, model.get('option.bar') || {}, true);
  60467. }
  60468. },
  60469. 'stack': function (seriesType, seriesId, seriesModel, model) {
  60470. if (seriesType === 'line' || seriesType === 'bar') {
  60471. return merge({
  60472. id: seriesId,
  60473. stack: '__ec_magicType_stack__'
  60474. }, model.get('option.stack') || {}, true);
  60475. }
  60476. },
  60477. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  60478. if (seriesType === 'line' || seriesType === 'bar') {
  60479. return merge({
  60480. id: seriesId,
  60481. stack: ''
  60482. }, model.get('option.tiled') || {}, true);
  60483. }
  60484. }
  60485. };
  60486. var radioTypes = [
  60487. ['line', 'bar'],
  60488. ['stack', 'tiled']
  60489. ];
  60490. proto$3.onclick = function (ecModel, api, type) {
  60491. var model = this.model;
  60492. var seriesIndex = model.get('seriesIndex.' + type);
  60493. // Not supported magicType
  60494. if (!seriesOptGenreator[type]) {
  60495. return;
  60496. }
  60497. var newOption = {
  60498. series: []
  60499. };
  60500. var generateNewSeriesTypes = function (seriesModel) {
  60501. var seriesType = seriesModel.subType;
  60502. var seriesId = seriesModel.id;
  60503. var newSeriesOpt = seriesOptGenreator[type](
  60504. seriesType, seriesId, seriesModel, model
  60505. );
  60506. if (newSeriesOpt) {
  60507. // PENDING If merge original option?
  60508. defaults(newSeriesOpt, seriesModel.option);
  60509. newOption.series.push(newSeriesOpt);
  60510. }
  60511. // Modify boundaryGap
  60512. var coordSys = seriesModel.coordinateSystem;
  60513. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  60514. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  60515. if (categoryAxis) {
  60516. var axisDim = categoryAxis.dim;
  60517. var axisType = axisDim + 'Axis';
  60518. var axisModel = ecModel.queryComponents({
  60519. mainType: axisType,
  60520. index: seriesModel.get(name + 'Index'),
  60521. id: seriesModel.get(name + 'Id')
  60522. })[0];
  60523. var axisIndex = axisModel.componentIndex;
  60524. newOption[axisType] = newOption[axisType] || [];
  60525. for (var i = 0; i <= axisIndex; i++) {
  60526. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  60527. }
  60528. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  60529. }
  60530. }
  60531. };
  60532. each$1(radioTypes, function (radio) {
  60533. if (indexOf(radio, type) >= 0) {
  60534. each$1(radio, function (item) {
  60535. model.setIconStatus(item, 'normal');
  60536. });
  60537. }
  60538. });
  60539. model.setIconStatus(type, 'emphasis');
  60540. ecModel.eachComponent(
  60541. {
  60542. mainType: 'series',
  60543. query: seriesIndex == null ? null : {
  60544. seriesIndex: seriesIndex
  60545. }
  60546. }, generateNewSeriesTypes
  60547. );
  60548. api.dispatchAction({
  60549. type: 'changeMagicType',
  60550. currentType: type,
  60551. newOption: newOption
  60552. });
  60553. };
  60554. registerAction({
  60555. type: 'changeMagicType',
  60556. event: 'magicTypeChanged',
  60557. update: 'prepareAndUpdate'
  60558. }, function (payload, ecModel) {
  60559. ecModel.mergeOption(payload.newOption);
  60560. });
  60561. register$1('magicType', MagicType);
  60562. var dataViewLang = lang.toolbox.dataView;
  60563. var BLOCK_SPLITER = new Array(60).join('-');
  60564. var ITEM_SPLITER = '\t';
  60565. /**
  60566. * Group series into two types
  60567. * 1. on category axis, like line, bar
  60568. * 2. others, like scatter, pie
  60569. * @param {module:echarts/model/Global} ecModel
  60570. * @return {Object}
  60571. * @inner
  60572. */
  60573. function groupSeries(ecModel) {
  60574. var seriesGroupByCategoryAxis = {};
  60575. var otherSeries = [];
  60576. var meta = [];
  60577. ecModel.eachRawSeries(function (seriesModel) {
  60578. var coordSys = seriesModel.coordinateSystem;
  60579. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  60580. var baseAxis = coordSys.getBaseAxis();
  60581. if (baseAxis.type === 'category') {
  60582. var key = baseAxis.dim + '_' + baseAxis.index;
  60583. if (!seriesGroupByCategoryAxis[key]) {
  60584. seriesGroupByCategoryAxis[key] = {
  60585. categoryAxis: baseAxis,
  60586. valueAxis: coordSys.getOtherAxis(baseAxis),
  60587. series: []
  60588. };
  60589. meta.push({
  60590. axisDim: baseAxis.dim,
  60591. axisIndex: baseAxis.index
  60592. });
  60593. }
  60594. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  60595. }
  60596. else {
  60597. otherSeries.push(seriesModel);
  60598. }
  60599. }
  60600. else {
  60601. otherSeries.push(seriesModel);
  60602. }
  60603. });
  60604. return {
  60605. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  60606. other: otherSeries,
  60607. meta: meta
  60608. };
  60609. }
  60610. /**
  60611. * Assemble content of series on cateogory axis
  60612. * @param {Array.<module:echarts/model/Series>} series
  60613. * @return {string}
  60614. * @inner
  60615. */
  60616. function assembleSeriesWithCategoryAxis(series) {
  60617. var tables = [];
  60618. each$1(series, function (group, key) {
  60619. var categoryAxis = group.categoryAxis;
  60620. var valueAxis = group.valueAxis;
  60621. var valueAxisDim = valueAxis.dim;
  60622. var headers = [' '].concat(map(group.series, function (series) {
  60623. return series.name;
  60624. }));
  60625. var columns = [categoryAxis.model.getCategories()];
  60626. each$1(group.series, function (series) {
  60627. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  60628. return val;
  60629. }));
  60630. });
  60631. // Assemble table content
  60632. var lines = [headers.join(ITEM_SPLITER)];
  60633. for (var i = 0; i < columns[0].length; i++) {
  60634. var items = [];
  60635. for (var j = 0; j < columns.length; j++) {
  60636. items.push(columns[j][i]);
  60637. }
  60638. lines.push(items.join(ITEM_SPLITER));
  60639. }
  60640. tables.push(lines.join('\n'));
  60641. });
  60642. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  60643. }
  60644. /**
  60645. * Assemble content of other series
  60646. * @param {Array.<module:echarts/model/Series>} series
  60647. * @return {string}
  60648. * @inner
  60649. */
  60650. function assembleOtherSeries(series) {
  60651. return map(series, function (series) {
  60652. var data = series.getRawData();
  60653. var lines = [series.name];
  60654. var vals = [];
  60655. data.each(data.dimensions, function () {
  60656. var argLen = arguments.length;
  60657. var dataIndex = arguments[argLen - 1];
  60658. var name = data.getName(dataIndex);
  60659. for (var i = 0; i < argLen - 1; i++) {
  60660. vals[i] = arguments[i];
  60661. }
  60662. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  60663. });
  60664. return lines.join('\n');
  60665. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  60666. }
  60667. /**
  60668. * @param {module:echarts/model/Global}
  60669. * @return {Object}
  60670. * @inner
  60671. */
  60672. function getContentFromModel(ecModel) {
  60673. var result = groupSeries(ecModel);
  60674. return {
  60675. value: filter([
  60676. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  60677. assembleOtherSeries(result.other)
  60678. ], function (str) {
  60679. return str.replace(/[\n\t\s]/g, '');
  60680. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  60681. meta: result.meta
  60682. };
  60683. }
  60684. function trim(str) {
  60685. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  60686. }
  60687. /**
  60688. * If a block is tsv format
  60689. */
  60690. function isTSVFormat(block) {
  60691. // Simple method to find out if a block is tsv format
  60692. var firstLine = block.slice(0, block.indexOf('\n'));
  60693. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  60694. return true;
  60695. }
  60696. }
  60697. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  60698. /**
  60699. * @param {string} tsv
  60700. * @return {Object}
  60701. */
  60702. function parseTSVContents(tsv) {
  60703. var tsvLines = tsv.split(/\n+/g);
  60704. var headers = trim(tsvLines.shift()).split(itemSplitRegex);
  60705. var categories = [];
  60706. var series = map(headers, function (header) {
  60707. return {
  60708. name: header,
  60709. data: []
  60710. };
  60711. });
  60712. for (var i = 0; i < tsvLines.length; i++) {
  60713. var items = trim(tsvLines[i]).split(itemSplitRegex);
  60714. categories.push(items.shift());
  60715. for (var j = 0; j < items.length; j++) {
  60716. series[j] && (series[j].data[i] = items[j]);
  60717. }
  60718. }
  60719. return {
  60720. series: series,
  60721. categories: categories
  60722. };
  60723. }
  60724. /**
  60725. * @param {string} str
  60726. * @return {Array.<Object>}
  60727. * @inner
  60728. */
  60729. function parseListContents(str) {
  60730. var lines = str.split(/\n+/g);
  60731. var seriesName = trim(lines.shift());
  60732. var data = [];
  60733. for (var i = 0; i < lines.length; i++) {
  60734. var items = trim(lines[i]).split(itemSplitRegex);
  60735. var name = '';
  60736. var value;
  60737. var hasName = false;
  60738. if (isNaN(items[0])) { // First item is name
  60739. hasName = true;
  60740. name = items[0];
  60741. items = items.slice(1);
  60742. data[i] = {
  60743. name: name,
  60744. value: []
  60745. };
  60746. value = data[i].value;
  60747. }
  60748. else {
  60749. value = data[i] = [];
  60750. }
  60751. for (var j = 0; j < items.length; j++) {
  60752. value.push(+items[j]);
  60753. }
  60754. if (value.length === 1) {
  60755. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  60756. }
  60757. }
  60758. return {
  60759. name: seriesName,
  60760. data: data
  60761. };
  60762. }
  60763. /**
  60764. * @param {string} str
  60765. * @param {Array.<Object>} blockMetaList
  60766. * @return {Object}
  60767. * @inner
  60768. */
  60769. function parseContents(str, blockMetaList) {
  60770. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  60771. var newOption = {
  60772. series: []
  60773. };
  60774. each$1(blocks, function (block, idx) {
  60775. if (isTSVFormat(block)) {
  60776. var result = parseTSVContents(block);
  60777. var blockMeta = blockMetaList[idx];
  60778. var axisKey = blockMeta.axisDim + 'Axis';
  60779. if (blockMeta) {
  60780. newOption[axisKey] = newOption[axisKey] || [];
  60781. newOption[axisKey][blockMeta.axisIndex] = {
  60782. data: result.categories
  60783. };
  60784. newOption.series = newOption.series.concat(result.series);
  60785. }
  60786. }
  60787. else {
  60788. var result = parseListContents(block);
  60789. newOption.series.push(result);
  60790. }
  60791. });
  60792. return newOption;
  60793. }
  60794. /**
  60795. * @alias {module:echarts/component/toolbox/feature/DataView}
  60796. * @constructor
  60797. * @param {module:echarts/model/Model} model
  60798. */
  60799. function DataView(model) {
  60800. this._dom = null;
  60801. this.model = model;
  60802. }
  60803. DataView.defaultOption = {
  60804. show: true,
  60805. readOnly: false,
  60806. optionToContent: null,
  60807. contentToOption: null,
  60808. 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',
  60809. title: clone(dataViewLang.title),
  60810. lang: clone(dataViewLang.lang),
  60811. backgroundColor: '#fff',
  60812. textColor: '#000',
  60813. textareaColor: '#fff',
  60814. textareaBorderColor: '#333',
  60815. buttonColor: '#c23531',
  60816. buttonTextColor: '#fff'
  60817. };
  60818. DataView.prototype.onclick = function (ecModel, api) {
  60819. var container = api.getDom();
  60820. var model = this.model;
  60821. if (this._dom) {
  60822. container.removeChild(this._dom);
  60823. }
  60824. var root = document.createElement('div');
  60825. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  60826. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  60827. // Create elements
  60828. var header = document.createElement('h4');
  60829. var lang$$1 = model.get('lang') || [];
  60830. header.innerHTML = lang$$1[0] || model.get('title');
  60831. header.style.cssText = 'margin: 10px 20px;';
  60832. header.style.color = model.get('textColor');
  60833. var viewMain = document.createElement('div');
  60834. var textarea = document.createElement('textarea');
  60835. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  60836. var optionToContent = model.get('optionToContent');
  60837. var contentToOption = model.get('contentToOption');
  60838. var result = getContentFromModel(ecModel);
  60839. if (typeof optionToContent === 'function') {
  60840. var htmlOrDom = optionToContent(api.getOption());
  60841. if (typeof htmlOrDom === 'string') {
  60842. viewMain.innerHTML = htmlOrDom;
  60843. }
  60844. else if (isDom(htmlOrDom)) {
  60845. viewMain.appendChild(htmlOrDom);
  60846. }
  60847. }
  60848. else {
  60849. // Use default textarea
  60850. viewMain.appendChild(textarea);
  60851. textarea.readOnly = model.get('readOnly');
  60852. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  60853. textarea.style.color = model.get('textColor');
  60854. textarea.style.borderColor = model.get('textareaBorderColor');
  60855. textarea.style.backgroundColor = model.get('textareaColor');
  60856. textarea.value = result.value;
  60857. }
  60858. var blockMetaList = result.meta;
  60859. var buttonContainer = document.createElement('div');
  60860. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  60861. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  60862. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  60863. var closeButton = document.createElement('div');
  60864. var refreshButton = document.createElement('div');
  60865. buttonStyle += ';background-color:' + model.get('buttonColor');
  60866. buttonStyle += ';color:' + model.get('buttonTextColor');
  60867. var self = this;
  60868. function close() {
  60869. container.removeChild(root);
  60870. self._dom = null;
  60871. }
  60872. addEventListener(closeButton, 'click', close);
  60873. addEventListener(refreshButton, 'click', function () {
  60874. var newOption;
  60875. try {
  60876. if (typeof contentToOption === 'function') {
  60877. newOption = contentToOption(viewMain, api.getOption());
  60878. }
  60879. else {
  60880. newOption = parseContents(textarea.value, blockMetaList);
  60881. }
  60882. }
  60883. catch (e) {
  60884. close();
  60885. throw new Error('Data view format error ' + e);
  60886. }
  60887. if (newOption) {
  60888. api.dispatchAction({
  60889. type: 'changeDataView',
  60890. newOption: newOption
  60891. });
  60892. }
  60893. close();
  60894. });
  60895. closeButton.innerHTML = lang$$1[1];
  60896. refreshButton.innerHTML = lang$$1[2];
  60897. refreshButton.style.cssText = buttonStyle;
  60898. closeButton.style.cssText = buttonStyle;
  60899. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  60900. buttonContainer.appendChild(closeButton);
  60901. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  60902. addEventListener(textarea, 'keydown', function (e) {
  60903. if ((e.keyCode || e.which) === 9) {
  60904. // get caret position/selection
  60905. var val = this.value;
  60906. var start = this.selectionStart;
  60907. var end = this.selectionEnd;
  60908. // set textarea value to: text before caret + tab + text after caret
  60909. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  60910. // put caret at right position again
  60911. this.selectionStart = this.selectionEnd = start + 1;
  60912. // prevent the focus lose
  60913. stop(e);
  60914. }
  60915. });
  60916. root.appendChild(header);
  60917. root.appendChild(viewMain);
  60918. root.appendChild(buttonContainer);
  60919. viewMain.style.height = (container.clientHeight - 80) + 'px';
  60920. container.appendChild(root);
  60921. this._dom = root;
  60922. };
  60923. DataView.prototype.remove = function (ecModel, api) {
  60924. this._dom && api.getDom().removeChild(this._dom);
  60925. };
  60926. DataView.prototype.dispose = function (ecModel, api) {
  60927. this.remove(ecModel, api);
  60928. };
  60929. /**
  60930. * @inner
  60931. */
  60932. function tryMergeDataOption(newData, originalData) {
  60933. return map(newData, function (newVal, idx) {
  60934. var original = originalData && originalData[idx];
  60935. if (isObject(original) && !isArray(original)) {
  60936. if (isObject(newVal) && !isArray(newVal)) {
  60937. newVal = newVal.value;
  60938. }
  60939. // Original data has option
  60940. return defaults({
  60941. value: newVal
  60942. }, original);
  60943. }
  60944. else {
  60945. return newVal;
  60946. }
  60947. });
  60948. }
  60949. register$1('dataView', DataView);
  60950. registerAction({
  60951. type: 'changeDataView',
  60952. event: 'dataViewChanged',
  60953. update: 'prepareAndUpdate'
  60954. }, function (payload, ecModel) {
  60955. var newSeriesOptList = [];
  60956. each$1(payload.newOption.series, function (seriesOpt) {
  60957. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  60958. if (!seriesModel) {
  60959. // New created series
  60960. // Geuss the series type
  60961. newSeriesOptList.push(extend({
  60962. // Default is scatter
  60963. type: 'scatter'
  60964. }, seriesOpt));
  60965. }
  60966. else {
  60967. var originalData = seriesModel.get('data');
  60968. newSeriesOptList.push({
  60969. name: seriesOpt.name,
  60970. data: tryMergeDataOption(seriesOpt.data, originalData)
  60971. });
  60972. }
  60973. });
  60974. ecModel.mergeOption(defaults({
  60975. series: newSeriesOptList
  60976. }, payload.newOption));
  60977. });
  60978. var each$32 = each$1;
  60979. var ATTR$2 = '\0_ec_hist_store';
  60980. /**
  60981. * @param {module:echarts/model/Global} ecModel
  60982. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  60983. */
  60984. function push(ecModel, newSnapshot) {
  60985. var store = giveStore$1(ecModel);
  60986. // If previous dataZoom can not be found,
  60987. // complete an range with current range.
  60988. each$32(newSnapshot, function (batchItem, dataZoomId) {
  60989. var i = store.length - 1;
  60990. for (; i >= 0; i--) {
  60991. var snapshot = store[i];
  60992. if (snapshot[dataZoomId]) {
  60993. break;
  60994. }
  60995. }
  60996. if (i < 0) {
  60997. // No origin range set, create one by current range.
  60998. var dataZoomModel = ecModel.queryComponents(
  60999. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  61000. )[0];
  61001. if (dataZoomModel) {
  61002. var percentRange = dataZoomModel.getPercentRange();
  61003. store[0][dataZoomId] = {
  61004. dataZoomId: dataZoomId,
  61005. start: percentRange[0],
  61006. end: percentRange[1]
  61007. };
  61008. }
  61009. }
  61010. });
  61011. store.push(newSnapshot);
  61012. }
  61013. /**
  61014. * @param {module:echarts/model/Global} ecModel
  61015. * @return {Object} snapshot
  61016. */
  61017. function pop(ecModel) {
  61018. var store = giveStore$1(ecModel);
  61019. var head = store[store.length - 1];
  61020. store.length > 1 && store.pop();
  61021. // Find top for all dataZoom.
  61022. var snapshot = {};
  61023. each$32(head, function (batchItem, dataZoomId) {
  61024. for (var i = store.length - 1; i >= 0; i--) {
  61025. var batchItem = store[i][dataZoomId];
  61026. if (batchItem) {
  61027. snapshot[dataZoomId] = batchItem;
  61028. break;
  61029. }
  61030. }
  61031. });
  61032. return snapshot;
  61033. }
  61034. /**
  61035. * @param {module:echarts/model/Global} ecModel
  61036. */
  61037. function clear$1(ecModel) {
  61038. ecModel[ATTR$2] = null;
  61039. }
  61040. /**
  61041. * @param {module:echarts/model/Global} ecModel
  61042. * @return {number} records. always >= 1.
  61043. */
  61044. function count(ecModel) {
  61045. return giveStore$1(ecModel).length;
  61046. }
  61047. /**
  61048. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  61049. * History length of each dataZoom may be different.
  61050. * this._history[0] is used to store origin range.
  61051. * @type {Array.<Object>}
  61052. */
  61053. function giveStore$1(ecModel) {
  61054. var store = ecModel[ATTR$2];
  61055. if (!store) {
  61056. store = ecModel[ATTR$2] = [{}];
  61057. }
  61058. return store;
  61059. }
  61060. DataZoomModel.extend({
  61061. type: 'dataZoom.select'
  61062. });
  61063. DataZoomView.extend({
  61064. type: 'dataZoom.select'
  61065. });
  61066. /**
  61067. * DataZoom component entry
  61068. */
  61069. // Use dataZoomSelect
  61070. var dataZoomLang = lang.toolbox.dataZoom;
  61071. var each$31 = each$1;
  61072. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  61073. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  61074. function DataZoom(model, ecModel, api) {
  61075. /**
  61076. * @private
  61077. * @type {module:echarts/component/helper/BrushController}
  61078. */
  61079. (this._brushController = new BrushController(api.getZr()))
  61080. .on('brush', bind(this._onBrush, this))
  61081. .mount();
  61082. /**
  61083. * @private
  61084. * @type {boolean}
  61085. */
  61086. this._isZoomActive;
  61087. }
  61088. DataZoom.defaultOption = {
  61089. show: true,
  61090. // Icon group
  61091. icon: {
  61092. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  61093. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  61094. },
  61095. // `zoom`, `back`
  61096. title: clone(dataZoomLang.title)
  61097. };
  61098. var proto$4 = DataZoom.prototype;
  61099. proto$4.render = function (featureModel, ecModel, api, payload) {
  61100. this.model = featureModel;
  61101. this.ecModel = ecModel;
  61102. this.api = api;
  61103. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  61104. updateBackBtnStatus(featureModel, ecModel);
  61105. };
  61106. proto$4.onclick = function (ecModel, api, type) {
  61107. handlers$1[type].call(this);
  61108. };
  61109. proto$4.remove = function (ecModel, api) {
  61110. this._brushController.unmount();
  61111. };
  61112. proto$4.dispose = function (ecModel, api) {
  61113. this._brushController.dispose();
  61114. };
  61115. /**
  61116. * @private
  61117. */
  61118. var handlers$1 = {
  61119. zoom: function () {
  61120. var nextActive = !this._isZoomActive;
  61121. this.api.dispatchAction({
  61122. type: 'takeGlobalCursor',
  61123. key: 'dataZoomSelect',
  61124. dataZoomSelectActive: nextActive
  61125. });
  61126. },
  61127. back: function () {
  61128. this._dispatchZoomAction(pop(this.ecModel));
  61129. }
  61130. };
  61131. /**
  61132. * @private
  61133. */
  61134. proto$4._onBrush = function (areas, opt) {
  61135. if (!opt.isEnd || !areas.length) {
  61136. return;
  61137. }
  61138. var snapshot = {};
  61139. var ecModel = this.ecModel;
  61140. this._brushController.updateCovers([]); // remove cover
  61141. var brushTargetManager = new BrushTargetManager(
  61142. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  61143. );
  61144. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  61145. if (coordSys.type !== 'cartesian2d') {
  61146. return;
  61147. }
  61148. var brushType = area.brushType;
  61149. if (brushType === 'rect') {
  61150. setBatch('x', coordSys, coordRange[0]);
  61151. setBatch('y', coordSys, coordRange[1]);
  61152. }
  61153. else {
  61154. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  61155. }
  61156. });
  61157. push(ecModel, snapshot);
  61158. this._dispatchZoomAction(snapshot);
  61159. function setBatch(dimName, coordSys, minMax) {
  61160. var axis = coordSys.getAxis(dimName);
  61161. var axisModel = axis.model;
  61162. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  61163. // Restrict range.
  61164. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  61165. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  61166. minMax = sliderMove(
  61167. 0, minMax.slice(), axis.scale.getExtent(), 0,
  61168. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  61169. );
  61170. }
  61171. dataZoomModel && (snapshot[dataZoomModel.id] = {
  61172. dataZoomId: dataZoomModel.id,
  61173. startValue: minMax[0],
  61174. endValue: minMax[1]
  61175. });
  61176. }
  61177. function findDataZoom(dimName, axisModel, ecModel) {
  61178. var found;
  61179. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  61180. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  61181. has && (found = dzModel);
  61182. });
  61183. return found;
  61184. }
  61185. };
  61186. /**
  61187. * @private
  61188. */
  61189. proto$4._dispatchZoomAction = function (snapshot) {
  61190. var batch = [];
  61191. // Convert from hash map to array.
  61192. each$31(snapshot, function (batchItem, dataZoomId) {
  61193. batch.push(clone(batchItem));
  61194. });
  61195. batch.length && this.api.dispatchAction({
  61196. type: 'dataZoom',
  61197. from: this.uid,
  61198. batch: batch
  61199. });
  61200. };
  61201. function retrieveAxisSetting(option) {
  61202. var setting = {};
  61203. // Compatible with previous setting: null => all axis, false => no axis.
  61204. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  61205. setting[name] = option[name];
  61206. setting[name] == null && (setting[name] = 'all');
  61207. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  61208. });
  61209. return setting;
  61210. }
  61211. function updateBackBtnStatus(featureModel, ecModel) {
  61212. featureModel.setIconStatus(
  61213. 'back',
  61214. count(ecModel) > 1 ? 'emphasis' : 'normal'
  61215. );
  61216. }
  61217. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  61218. var zoomActive = view._isZoomActive;
  61219. if (payload && payload.type === 'takeGlobalCursor') {
  61220. zoomActive = payload.key === 'dataZoomSelect'
  61221. ? payload.dataZoomSelectActive : false;
  61222. }
  61223. view._isZoomActive = zoomActive;
  61224. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  61225. var brushTargetManager = new BrushTargetManager(
  61226. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  61227. );
  61228. view._brushController
  61229. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  61230. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  61231. ? 'lineX'
  61232. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  61233. ? 'lineY'
  61234. : 'rect';
  61235. }))
  61236. .enableBrush(
  61237. zoomActive
  61238. ? {
  61239. brushType: 'auto',
  61240. brushStyle: {
  61241. // FIXME user customized?
  61242. lineWidth: 0,
  61243. fill: 'rgba(0,0,0,0.2)'
  61244. }
  61245. }
  61246. : false
  61247. );
  61248. }
  61249. register$1('dataZoom', DataZoom);
  61250. // Create special dataZoom option for select
  61251. registerPreprocessor(function (option) {
  61252. if (!option) {
  61253. return;
  61254. }
  61255. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  61256. if (!isArray(dataZoomOpts)) {
  61257. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  61258. }
  61259. var toolboxOpt = option.toolbox;
  61260. if (toolboxOpt) {
  61261. // Assume there is only one toolbox
  61262. if (isArray(toolboxOpt)) {
  61263. toolboxOpt = toolboxOpt[0];
  61264. }
  61265. if (toolboxOpt && toolboxOpt.feature) {
  61266. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  61267. addForAxis('xAxis', dataZoomOpt);
  61268. addForAxis('yAxis', dataZoomOpt);
  61269. }
  61270. }
  61271. function addForAxis(axisName, dataZoomOpt) {
  61272. if (!dataZoomOpt) {
  61273. return;
  61274. }
  61275. // Try not to modify model, because it is not merged yet.
  61276. var axisIndicesName = axisName + 'Index';
  61277. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  61278. if (givenAxisIndices != null
  61279. && givenAxisIndices != 'all'
  61280. && !isArray(givenAxisIndices)
  61281. ) {
  61282. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  61283. }
  61284. forEachComponent(axisName, function (axisOpt, axisIndex) {
  61285. if (givenAxisIndices != null
  61286. && givenAxisIndices != 'all'
  61287. && indexOf(givenAxisIndices, axisIndex) === -1
  61288. ) {
  61289. return;
  61290. }
  61291. var newOpt = {
  61292. type: 'select',
  61293. $fromToolbox: true,
  61294. // Id for merge mapping.
  61295. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  61296. };
  61297. // FIXME
  61298. // Only support one axis now.
  61299. newOpt[axisIndicesName] = axisIndex;
  61300. dataZoomOpts.push(newOpt);
  61301. });
  61302. }
  61303. function forEachComponent(mainType, cb) {
  61304. var opts = option[mainType];
  61305. if (!isArray(opts)) {
  61306. opts = opts ? [opts] : [];
  61307. }
  61308. each$31(opts, cb);
  61309. }
  61310. });
  61311. var restoreLang = lang.toolbox.restore;
  61312. function Restore(model) {
  61313. this.model = model;
  61314. }
  61315. Restore.defaultOption = {
  61316. show: true,
  61317. 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',
  61318. title: restoreLang.title
  61319. };
  61320. var proto$5 = Restore.prototype;
  61321. proto$5.onclick = function (ecModel, api, type) {
  61322. clear$1(ecModel);
  61323. api.dispatchAction({
  61324. type: 'restore',
  61325. from: this.uid
  61326. });
  61327. };
  61328. register$1('restore', Restore);
  61329. registerAction(
  61330. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  61331. function (payload, ecModel) {
  61332. ecModel.resetOption('recreate');
  61333. }
  61334. );
  61335. var urn = 'urn:schemas-microsoft-com:vml';
  61336. var win = typeof window === 'undefined' ? null : window;
  61337. var vmlInited = false;
  61338. var doc = win && win.document;
  61339. function createNode(tagName) {
  61340. return doCreateNode(tagName);
  61341. }
  61342. // Avoid assign to an exported variable, for transforming to cjs.
  61343. var doCreateNode;
  61344. if (doc && !env$1.canvasSupported) {
  61345. try {
  61346. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  61347. doCreateNode = function (tagName) {
  61348. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  61349. };
  61350. }
  61351. catch (e) {
  61352. doCreateNode = function (tagName) {
  61353. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  61354. };
  61355. }
  61356. }
  61357. // From raphael
  61358. function initVML() {
  61359. if (vmlInited || !doc) {
  61360. return;
  61361. }
  61362. vmlInited = true;
  61363. var styleSheets = doc.styleSheets;
  61364. if (styleSheets.length < 31) {
  61365. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  61366. }
  61367. else {
  61368. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  61369. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  61370. }
  61371. }
  61372. // http://www.w3.org/TR/NOTE-VML
  61373. // TODO Use proxy like svg instead of overwrite brush methods
  61374. var CMD$3 = PathProxy.CMD;
  61375. var round$3 = Math.round;
  61376. var sqrt = Math.sqrt;
  61377. var abs$1 = Math.abs;
  61378. var cos = Math.cos;
  61379. var sin = Math.sin;
  61380. var mathMax$8 = Math.max;
  61381. if (!env$1.canvasSupported) {
  61382. var comma = ',';
  61383. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  61384. var Z = 21600;
  61385. var Z2 = Z / 2;
  61386. var ZLEVEL_BASE = 100000;
  61387. var Z_BASE$1 = 1000;
  61388. var initRootElStyle = function (el) {
  61389. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  61390. el.coordsize = Z + ',' + Z;
  61391. el.coordorigin = '0,0';
  61392. };
  61393. var encodeHtmlAttribute = function (s) {
  61394. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  61395. };
  61396. var rgb2Str = function (r, g, b) {
  61397. return 'rgb(' + [r, g, b].join(',') + ')';
  61398. };
  61399. var append = function (parent, child) {
  61400. if (child && parent && child.parentNode !== parent) {
  61401. parent.appendChild(child);
  61402. }
  61403. };
  61404. var remove = function (parent, child) {
  61405. if (child && parent && child.parentNode === parent) {
  61406. parent.removeChild(child);
  61407. }
  61408. };
  61409. var getZIndex = function (zlevel, z, z2) {
  61410. // z 的取值范围为 [0, 1000]
  61411. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  61412. };
  61413. var parsePercent$3 = function (value, maxValue) {
  61414. if (typeof value === 'string') {
  61415. if (value.lastIndexOf('%') >= 0) {
  61416. return parseFloat(value) / 100 * maxValue;
  61417. }
  61418. return parseFloat(value);
  61419. }
  61420. return value;
  61421. };
  61422. /***************************************************
  61423. * PATH
  61424. **************************************************/
  61425. var setColorAndOpacity = function (el, color, opacity) {
  61426. var colorArr = parse(color);
  61427. opacity = +opacity;
  61428. if (isNaN(opacity)) {
  61429. opacity = 1;
  61430. }
  61431. if (colorArr) {
  61432. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  61433. el.opacity = opacity * colorArr[3];
  61434. }
  61435. };
  61436. var getColorAndAlpha = function (color) {
  61437. var colorArr = parse(color);
  61438. return [
  61439. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  61440. colorArr[3]
  61441. ];
  61442. };
  61443. var updateFillNode = function (el, style, zrEl) {
  61444. // TODO pattern
  61445. var fill = style.fill;
  61446. if (fill != null) {
  61447. // Modified from excanvas
  61448. if (fill instanceof Gradient) {
  61449. var gradientType;
  61450. var angle = 0;
  61451. var focus = [0, 0];
  61452. // additional offset
  61453. var shift = 0;
  61454. // scale factor for offset
  61455. var expansion = 1;
  61456. var rect = zrEl.getBoundingRect();
  61457. var rectWidth = rect.width;
  61458. var rectHeight = rect.height;
  61459. if (fill.type === 'linear') {
  61460. gradientType = 'gradient';
  61461. var transform = zrEl.transform;
  61462. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  61463. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  61464. if (transform) {
  61465. applyTransform(p0, p0, transform);
  61466. applyTransform(p1, p1, transform);
  61467. }
  61468. var dx = p1[0] - p0[0];
  61469. var dy = p1[1] - p0[1];
  61470. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  61471. // The angle should be a non-negative number.
  61472. if (angle < 0) {
  61473. angle += 360;
  61474. }
  61475. // Very small angles produce an unexpected result because they are
  61476. // converted to a scientific notation string.
  61477. if (angle < 1e-6) {
  61478. angle = 0;
  61479. }
  61480. }
  61481. else {
  61482. gradientType = 'gradientradial';
  61483. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  61484. var transform = zrEl.transform;
  61485. var scale$$1 = zrEl.scale;
  61486. var width = rectWidth;
  61487. var height = rectHeight;
  61488. focus = [
  61489. // Percent in bounding rect
  61490. (p0[0] - rect.x) / width,
  61491. (p0[1] - rect.y) / height
  61492. ];
  61493. if (transform) {
  61494. applyTransform(p0, p0, transform);
  61495. }
  61496. width /= scale$$1[0] * Z;
  61497. height /= scale$$1[1] * Z;
  61498. var dimension = mathMax$8(width, height);
  61499. shift = 2 * 0 / dimension;
  61500. expansion = 2 * fill.r / dimension - shift;
  61501. }
  61502. // We need to sort the color stops in ascending order by offset,
  61503. // otherwise IE won't interpret it correctly.
  61504. var stops = fill.colorStops.slice();
  61505. stops.sort(function(cs1, cs2) {
  61506. return cs1.offset - cs2.offset;
  61507. });
  61508. var length$$1 = stops.length;
  61509. // Color and alpha list of first and last stop
  61510. var colorAndAlphaList = [];
  61511. var colors = [];
  61512. for (var i = 0; i < length$$1; i++) {
  61513. var stop = stops[i];
  61514. var colorAndAlpha = getColorAndAlpha(stop.color);
  61515. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  61516. if (i === 0 || i === length$$1 - 1) {
  61517. colorAndAlphaList.push(colorAndAlpha);
  61518. }
  61519. }
  61520. if (length$$1 >= 2) {
  61521. var color1 = colorAndAlphaList[0][0];
  61522. var color2 = colorAndAlphaList[1][0];
  61523. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  61524. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  61525. el.type = gradientType;
  61526. el.method = 'none';
  61527. el.focus = '100%';
  61528. el.angle = angle;
  61529. el.color = color1;
  61530. el.color2 = color2;
  61531. el.colors = colors.join(',');
  61532. // When colors attribute is used, the meanings of opacity and o:opacity2
  61533. // are reversed.
  61534. el.opacity = opacity2;
  61535. // FIXME g_o_:opacity ?
  61536. el.opacity2 = opacity1;
  61537. }
  61538. if (gradientType === 'radial') {
  61539. el.focusposition = focus.join(',');
  61540. }
  61541. }
  61542. else {
  61543. // FIXME Change from Gradient fill to color fill
  61544. setColorAndOpacity(el, fill, style.opacity);
  61545. }
  61546. }
  61547. };
  61548. var updateStrokeNode = function (el, style) {
  61549. // if (style.lineJoin != null) {
  61550. // el.joinstyle = style.lineJoin;
  61551. // }
  61552. // if (style.miterLimit != null) {
  61553. // el.miterlimit = style.miterLimit * Z;
  61554. // }
  61555. // if (style.lineCap != null) {
  61556. // el.endcap = style.lineCap;
  61557. // }
  61558. if (style.lineDash != null) {
  61559. el.dashstyle = style.lineDash.join(' ');
  61560. }
  61561. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  61562. setColorAndOpacity(el, style.stroke, style.opacity);
  61563. }
  61564. };
  61565. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  61566. var isFill = type == 'fill';
  61567. var el = vmlEl.getElementsByTagName(type)[0];
  61568. // Stroke must have lineWidth
  61569. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  61570. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  61571. // FIXME Remove before updating, or set `colors` will throw error
  61572. if (style[type] instanceof Gradient) {
  61573. remove(vmlEl, el);
  61574. }
  61575. if (!el) {
  61576. el = createNode(type);
  61577. }
  61578. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  61579. append(vmlEl, el);
  61580. }
  61581. else {
  61582. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  61583. remove(vmlEl, el);
  61584. }
  61585. };
  61586. var points$3 = [[], [], []];
  61587. var pathDataToString = function (path, m) {
  61588. var M = CMD$3.M;
  61589. var C = CMD$3.C;
  61590. var L = CMD$3.L;
  61591. var A = CMD$3.A;
  61592. var Q = CMD$3.Q;
  61593. var str = [];
  61594. var nPoint;
  61595. var cmdStr;
  61596. var cmd;
  61597. var i;
  61598. var xi;
  61599. var yi;
  61600. var data = path.data;
  61601. var dataLength = path.len();
  61602. for (i = 0; i < dataLength;) {
  61603. cmd = data[i++];
  61604. cmdStr = '';
  61605. nPoint = 0;
  61606. switch (cmd) {
  61607. case M:
  61608. cmdStr = ' m ';
  61609. nPoint = 1;
  61610. xi = data[i++];
  61611. yi = data[i++];
  61612. points$3[0][0] = xi;
  61613. points$3[0][1] = yi;
  61614. break;
  61615. case L:
  61616. cmdStr = ' l ';
  61617. nPoint = 1;
  61618. xi = data[i++];
  61619. yi = data[i++];
  61620. points$3[0][0] = xi;
  61621. points$3[0][1] = yi;
  61622. break;
  61623. case Q:
  61624. case C:
  61625. cmdStr = ' c ';
  61626. nPoint = 3;
  61627. var x1 = data[i++];
  61628. var y1 = data[i++];
  61629. var x2 = data[i++];
  61630. var y2 = data[i++];
  61631. var x3;
  61632. var y3;
  61633. if (cmd === Q) {
  61634. // Convert quadratic to cubic using degree elevation
  61635. x3 = x2;
  61636. y3 = y2;
  61637. x2 = (x2 + 2 * x1) / 3;
  61638. y2 = (y2 + 2 * y1) / 3;
  61639. x1 = (xi + 2 * x1) / 3;
  61640. y1 = (yi + 2 * y1) / 3;
  61641. }
  61642. else {
  61643. x3 = data[i++];
  61644. y3 = data[i++];
  61645. }
  61646. points$3[0][0] = x1;
  61647. points$3[0][1] = y1;
  61648. points$3[1][0] = x2;
  61649. points$3[1][1] = y2;
  61650. points$3[2][0] = x3;
  61651. points$3[2][1] = y3;
  61652. xi = x3;
  61653. yi = y3;
  61654. break;
  61655. case A:
  61656. var x = 0;
  61657. var y = 0;
  61658. var sx = 1;
  61659. var sy = 1;
  61660. var angle = 0;
  61661. if (m) {
  61662. // Extract SRT from matrix
  61663. x = m[4];
  61664. y = m[5];
  61665. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  61666. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  61667. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  61668. }
  61669. var cx = data[i++];
  61670. var cy = data[i++];
  61671. var rx = data[i++];
  61672. var ry = data[i++];
  61673. var startAngle = data[i++] + angle;
  61674. var endAngle = data[i++] + startAngle + angle;
  61675. // FIXME
  61676. // var psi = data[i++];
  61677. i++;
  61678. var clockwise = data[i++];
  61679. var x0 = cx + cos(startAngle) * rx;
  61680. var y0 = cy + sin(startAngle) * ry;
  61681. var x1 = cx + cos(endAngle) * rx;
  61682. var y1 = cy + sin(endAngle) * ry;
  61683. var type = clockwise ? ' wa ' : ' at ';
  61684. if (Math.abs(x0 - x1) < 1e-4) {
  61685. // IE won't render arches drawn counter clockwise if x0 == x1.
  61686. if (Math.abs(endAngle - startAngle) > 1e-2) {
  61687. // Offset x0 by 1/80 of a pixel. Use something
  61688. // that can be represented in binary
  61689. if (clockwise) {
  61690. x0 += 270 / Z;
  61691. }
  61692. }
  61693. else {
  61694. // Avoid case draw full circle
  61695. if (Math.abs(y0 - cy) < 1e-4) {
  61696. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  61697. y1 -= 270 / Z;
  61698. }
  61699. else {
  61700. y1 += 270 / Z;
  61701. }
  61702. }
  61703. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  61704. x1 += 270 / Z;
  61705. }
  61706. else {
  61707. x1 -= 270 / Z;
  61708. }
  61709. }
  61710. }
  61711. str.push(
  61712. type,
  61713. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  61714. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  61715. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  61716. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  61717. round$3((x0 * sx + x) * Z - Z2), comma,
  61718. round$3((y0 * sy + y) * Z - Z2), comma,
  61719. round$3((x1 * sx + x) * Z - Z2), comma,
  61720. round$3((y1 * sy + y) * Z - Z2)
  61721. );
  61722. xi = x1;
  61723. yi = y1;
  61724. break;
  61725. case CMD$3.R:
  61726. var p0 = points$3[0];
  61727. var p1 = points$3[1];
  61728. // x0, y0
  61729. p0[0] = data[i++];
  61730. p0[1] = data[i++];
  61731. // x1, y1
  61732. p1[0] = p0[0] + data[i++];
  61733. p1[1] = p0[1] + data[i++];
  61734. if (m) {
  61735. applyTransform(p0, p0, m);
  61736. applyTransform(p1, p1, m);
  61737. }
  61738. p0[0] = round$3(p0[0] * Z - Z2);
  61739. p1[0] = round$3(p1[0] * Z - Z2);
  61740. p0[1] = round$3(p0[1] * Z - Z2);
  61741. p1[1] = round$3(p1[1] * Z - Z2);
  61742. str.push(
  61743. // x0, y0
  61744. ' m ', p0[0], comma, p0[1],
  61745. // x1, y0
  61746. ' l ', p1[0], comma, p0[1],
  61747. // x1, y1
  61748. ' l ', p1[0], comma, p1[1],
  61749. // x0, y1
  61750. ' l ', p0[0], comma, p1[1]
  61751. );
  61752. break;
  61753. case CMD$3.Z:
  61754. // FIXME Update xi, yi
  61755. str.push(' x ');
  61756. }
  61757. if (nPoint > 0) {
  61758. str.push(cmdStr);
  61759. for (var k = 0; k < nPoint; k++) {
  61760. var p = points$3[k];
  61761. m && applyTransform(p, p, m);
  61762. // 不 round 会非常慢
  61763. str.push(
  61764. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  61765. k < nPoint - 1 ? comma : ''
  61766. );
  61767. }
  61768. }
  61769. }
  61770. return str.join('');
  61771. };
  61772. // Rewrite the original path method
  61773. Path.prototype.brushVML = function (vmlRoot) {
  61774. var style = this.style;
  61775. var vmlEl = this._vmlEl;
  61776. if (!vmlEl) {
  61777. vmlEl = createNode('shape');
  61778. initRootElStyle(vmlEl);
  61779. this._vmlEl = vmlEl;
  61780. }
  61781. updateFillAndStroke(vmlEl, 'fill', style, this);
  61782. updateFillAndStroke(vmlEl, 'stroke', style, this);
  61783. var m = this.transform;
  61784. var needTransform = m != null;
  61785. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  61786. if (strokeEl) {
  61787. var lineWidth = style.lineWidth;
  61788. // Get the line scale.
  61789. // Determinant of this.m_ means how much the area is enlarged by the
  61790. // transformation. So its square root can be used as a scale factor
  61791. // for width.
  61792. if (needTransform && !style.strokeNoScale) {
  61793. var det = m[0] * m[3] - m[1] * m[2];
  61794. lineWidth *= sqrt(abs$1(det));
  61795. }
  61796. strokeEl.weight = lineWidth + 'px';
  61797. }
  61798. var path = this.path || (this.path = new PathProxy());
  61799. if (this.__dirtyPath) {
  61800. path.beginPath();
  61801. this.buildPath(path, this.shape);
  61802. path.toStatic();
  61803. this.__dirtyPath = false;
  61804. }
  61805. vmlEl.path = pathDataToString(path, this.transform);
  61806. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  61807. // Append to root
  61808. append(vmlRoot, vmlEl);
  61809. // Text
  61810. if (style.text != null) {
  61811. this.drawRectText(vmlRoot, this.getBoundingRect());
  61812. }
  61813. else {
  61814. this.removeRectText(vmlRoot);
  61815. }
  61816. };
  61817. Path.prototype.onRemove = function (vmlRoot) {
  61818. remove(vmlRoot, this._vmlEl);
  61819. this.removeRectText(vmlRoot);
  61820. };
  61821. Path.prototype.onAdd = function (vmlRoot) {
  61822. append(vmlRoot, this._vmlEl);
  61823. this.appendRectText(vmlRoot);
  61824. };
  61825. /***************************************************
  61826. * IMAGE
  61827. **************************************************/
  61828. var isImage = function (img) {
  61829. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  61830. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  61831. // return img instanceof Image;
  61832. };
  61833. // Rewrite the original path method
  61834. ZImage.prototype.brushVML = function (vmlRoot) {
  61835. var style = this.style;
  61836. var image = style.image;
  61837. // Image original width, height
  61838. var ow;
  61839. var oh;
  61840. if (isImage(image)) {
  61841. var src = image.src;
  61842. if (src === this._imageSrc) {
  61843. ow = this._imageWidth;
  61844. oh = this._imageHeight;
  61845. }
  61846. else {
  61847. var imageRuntimeStyle = image.runtimeStyle;
  61848. var oldRuntimeWidth = imageRuntimeStyle.width;
  61849. var oldRuntimeHeight = imageRuntimeStyle.height;
  61850. imageRuntimeStyle.width = 'auto';
  61851. imageRuntimeStyle.height = 'auto';
  61852. // get the original size
  61853. ow = image.width;
  61854. oh = image.height;
  61855. // and remove overides
  61856. imageRuntimeStyle.width = oldRuntimeWidth;
  61857. imageRuntimeStyle.height = oldRuntimeHeight;
  61858. // Caching image original width, height and src
  61859. this._imageSrc = src;
  61860. this._imageWidth = ow;
  61861. this._imageHeight = oh;
  61862. }
  61863. image = src;
  61864. }
  61865. else {
  61866. if (image === this._imageSrc) {
  61867. ow = this._imageWidth;
  61868. oh = this._imageHeight;
  61869. }
  61870. }
  61871. if (!image) {
  61872. return;
  61873. }
  61874. var x = style.x || 0;
  61875. var y = style.y || 0;
  61876. var dw = style.width;
  61877. var dh = style.height;
  61878. var sw = style.sWidth;
  61879. var sh = style.sHeight;
  61880. var sx = style.sx || 0;
  61881. var sy = style.sy || 0;
  61882. var hasCrop = sw && sh;
  61883. var vmlEl = this._vmlEl;
  61884. if (!vmlEl) {
  61885. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  61886. // vmlEl = vmlCore.createNode('group');
  61887. vmlEl = doc.createElement('div');
  61888. initRootElStyle(vmlEl);
  61889. this._vmlEl = vmlEl;
  61890. }
  61891. var vmlElStyle = vmlEl.style;
  61892. var hasRotation = false;
  61893. var m;
  61894. var scaleX = 1;
  61895. var scaleY = 1;
  61896. if (this.transform) {
  61897. m = this.transform;
  61898. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  61899. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  61900. hasRotation = m[1] || m[2];
  61901. }
  61902. if (hasRotation) {
  61903. // If filters are necessary (rotation exists), create them
  61904. // filters are bog-slow, so only create them if abbsolutely necessary
  61905. // The following check doesn't account for skews (which don't exist
  61906. // in the canvas spec (yet) anyway.
  61907. // From excanvas
  61908. var p0 = [x, y];
  61909. var p1 = [x + dw, y];
  61910. var p2 = [x, y + dh];
  61911. var p3 = [x + dw, y + dh];
  61912. applyTransform(p0, p0, m);
  61913. applyTransform(p1, p1, m);
  61914. applyTransform(p2, p2, m);
  61915. applyTransform(p3, p3, m);
  61916. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  61917. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  61918. var transformFilter = [];
  61919. transformFilter.push('M11=', m[0] / scaleX, comma,
  61920. 'M12=', m[2] / scaleY, comma,
  61921. 'M21=', m[1] / scaleX, comma,
  61922. 'M22=', m[3] / scaleY, comma,
  61923. 'Dx=', round$3(x * scaleX + m[4]), comma,
  61924. 'Dy=', round$3(y * scaleY + m[5]));
  61925. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  61926. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  61927. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  61928. + transformFilter.join('') + ', SizingMethod=clip)';
  61929. }
  61930. else {
  61931. if (m) {
  61932. x = x * scaleX + m[4];
  61933. y = y * scaleY + m[5];
  61934. }
  61935. vmlElStyle.filter = '';
  61936. vmlElStyle.left = round$3(x) + 'px';
  61937. vmlElStyle.top = round$3(y) + 'px';
  61938. }
  61939. var imageEl = this._imageEl;
  61940. var cropEl = this._cropEl;
  61941. if (!imageEl) {
  61942. imageEl = doc.createElement('div');
  61943. this._imageEl = imageEl;
  61944. }
  61945. var imageELStyle = imageEl.style;
  61946. if (hasCrop) {
  61947. // Needs know image original width and height
  61948. if (! (ow && oh)) {
  61949. var tmpImage = new Image();
  61950. var self = this;
  61951. tmpImage.onload = function () {
  61952. tmpImage.onload = null;
  61953. ow = tmpImage.width;
  61954. oh = tmpImage.height;
  61955. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  61956. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  61957. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  61958. // Caching image original width, height and src
  61959. self._imageWidth = ow;
  61960. self._imageHeight = oh;
  61961. self._imageSrc = image;
  61962. };
  61963. tmpImage.src = image;
  61964. }
  61965. else {
  61966. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  61967. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  61968. }
  61969. if (! cropEl) {
  61970. cropEl = doc.createElement('div');
  61971. cropEl.style.overflow = 'hidden';
  61972. this._cropEl = cropEl;
  61973. }
  61974. var cropElStyle = cropEl.style;
  61975. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  61976. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  61977. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  61978. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  61979. if (! cropEl.parentNode) {
  61980. vmlEl.appendChild(cropEl);
  61981. }
  61982. if (imageEl.parentNode != cropEl) {
  61983. cropEl.appendChild(imageEl);
  61984. }
  61985. }
  61986. else {
  61987. imageELStyle.width = round$3(scaleX * dw) + 'px';
  61988. imageELStyle.height = round$3(scaleY * dh) + 'px';
  61989. vmlEl.appendChild(imageEl);
  61990. if (cropEl && cropEl.parentNode) {
  61991. vmlEl.removeChild(cropEl);
  61992. this._cropEl = null;
  61993. }
  61994. }
  61995. var filterStr = '';
  61996. var alpha = style.opacity;
  61997. if (alpha < 1) {
  61998. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  61999. }
  62000. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  62001. imageELStyle.filter = filterStr;
  62002. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  62003. // Append to root
  62004. append(vmlRoot, vmlEl);
  62005. // Text
  62006. if (style.text != null) {
  62007. this.drawRectText(vmlRoot, this.getBoundingRect());
  62008. }
  62009. };
  62010. ZImage.prototype.onRemove = function (vmlRoot) {
  62011. remove(vmlRoot, this._vmlEl);
  62012. this._vmlEl = null;
  62013. this._cropEl = null;
  62014. this._imageEl = null;
  62015. this.removeRectText(vmlRoot);
  62016. };
  62017. ZImage.prototype.onAdd = function (vmlRoot) {
  62018. append(vmlRoot, this._vmlEl);
  62019. this.appendRectText(vmlRoot);
  62020. };
  62021. /***************************************************
  62022. * TEXT
  62023. **************************************************/
  62024. var DEFAULT_STYLE_NORMAL = 'normal';
  62025. var fontStyleCache = {};
  62026. var fontStyleCacheCount = 0;
  62027. var MAX_FONT_CACHE_SIZE = 100;
  62028. var fontEl = document.createElement('div');
  62029. var getFontStyle = function (fontString) {
  62030. var fontStyle = fontStyleCache[fontString];
  62031. if (!fontStyle) {
  62032. // Clear cache
  62033. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  62034. fontStyleCacheCount = 0;
  62035. fontStyleCache = {};
  62036. }
  62037. var style = fontEl.style;
  62038. var fontFamily;
  62039. try {
  62040. style.font = fontString;
  62041. fontFamily = style.fontFamily.split(',')[0];
  62042. }
  62043. catch (e) {
  62044. }
  62045. fontStyle = {
  62046. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  62047. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  62048. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  62049. size: parseFloat(style.fontSize || 12) | 0,
  62050. family: fontFamily || 'Microsoft YaHei'
  62051. };
  62052. fontStyleCache[fontString] = fontStyle;
  62053. fontStyleCacheCount++;
  62054. }
  62055. return fontStyle;
  62056. };
  62057. var textMeasureEl;
  62058. // Overwrite measure text method
  62059. $override$1('measureText', function (text, textFont) {
  62060. var doc$$1 = doc;
  62061. if (!textMeasureEl) {
  62062. textMeasureEl = doc$$1.createElement('div');
  62063. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  62064. + 'padding:0;margin:0;border:none;white-space:pre;';
  62065. doc.body.appendChild(textMeasureEl);
  62066. }
  62067. try {
  62068. textMeasureEl.style.font = textFont;
  62069. } catch (ex) {
  62070. // Ignore failures to set to invalid font.
  62071. }
  62072. textMeasureEl.innerHTML = '';
  62073. // Don't use innerHTML or innerText because they allow markup/whitespace.
  62074. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  62075. return {
  62076. width: textMeasureEl.offsetWidth
  62077. };
  62078. });
  62079. var tmpRect$2 = new BoundingRect();
  62080. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  62081. var style = this.style;
  62082. // Optimize, avoid normalize every time.
  62083. this.__dirty && normalizeTextStyle(style, true);
  62084. var text = style.text;
  62085. // Convert to string
  62086. text != null && (text += '');
  62087. if (!text) {
  62088. return;
  62089. }
  62090. // Convert rich text to plain text. Rich text is not supported in
  62091. // IE8-, but tags in rich text template will be removed.
  62092. if (style.rich) {
  62093. var contentBlock = parseRichText(text, style);
  62094. text = [];
  62095. for (var i = 0; i < contentBlock.lines.length; i++) {
  62096. var tokens = contentBlock.lines[i].tokens;
  62097. var textLine = [];
  62098. for (var j = 0; j < tokens.length; j++) {
  62099. textLine.push(tokens[j].text);
  62100. }
  62101. text.push(textLine.join(''));
  62102. }
  62103. text = text.join('\n');
  62104. }
  62105. var x;
  62106. var y;
  62107. var align = style.textAlign;
  62108. var verticalAlign = style.textVerticalAlign;
  62109. var fontStyle = getFontStyle(style.font);
  62110. // FIXME encodeHtmlAttribute ?
  62111. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  62112. + fontStyle.size + 'px "' + fontStyle.family + '"';
  62113. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  62114. // Transform rect to view space
  62115. var m = this.transform;
  62116. // Ignore transform for text in other element
  62117. if (m && !fromTextEl) {
  62118. tmpRect$2.copy(rect);
  62119. tmpRect$2.applyTransform(m);
  62120. rect = tmpRect$2;
  62121. }
  62122. if (!fromTextEl) {
  62123. var textPosition = style.textPosition;
  62124. var distance$$1 = style.textDistance;
  62125. // Text position represented by coord
  62126. if (textPosition instanceof Array) {
  62127. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  62128. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  62129. align = align || 'left';
  62130. }
  62131. else {
  62132. var res = adjustTextPositionOnRect(
  62133. textPosition, rect, distance$$1
  62134. );
  62135. x = res.x;
  62136. y = res.y;
  62137. // Default align and baseline when has textPosition
  62138. align = align || res.textAlign;
  62139. verticalAlign = verticalAlign || res.textVerticalAlign;
  62140. }
  62141. }
  62142. else {
  62143. x = rect.x;
  62144. y = rect.y;
  62145. }
  62146. x = adjustTextX(x, textRect.width, align);
  62147. y = adjustTextY(y, textRect.height, verticalAlign);
  62148. // Force baseline 'middle'
  62149. y += textRect.height / 2;
  62150. // var fontSize = fontStyle.size;
  62151. // 1.75 is an arbitrary number, as there is no info about the text baseline
  62152. // switch (baseline) {
  62153. // case 'hanging':
  62154. // case 'top':
  62155. // y += fontSize / 1.75;
  62156. // break;
  62157. // case 'middle':
  62158. // break;
  62159. // default:
  62160. // // case null:
  62161. // // case 'alphabetic':
  62162. // // case 'ideographic':
  62163. // // case 'bottom':
  62164. // y -= fontSize / 2.25;
  62165. // break;
  62166. // }
  62167. // switch (align) {
  62168. // case 'left':
  62169. // break;
  62170. // case 'center':
  62171. // x -= textRect.width / 2;
  62172. // break;
  62173. // case 'right':
  62174. // x -= textRect.width;
  62175. // break;
  62176. // case 'end':
  62177. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  62178. // break;
  62179. // case 'start':
  62180. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  62181. // break;
  62182. // default:
  62183. // align = 'left';
  62184. // }
  62185. var createNode$$1 = createNode;
  62186. var textVmlEl = this._textVmlEl;
  62187. var pathEl;
  62188. var textPathEl;
  62189. var skewEl;
  62190. if (!textVmlEl) {
  62191. textVmlEl = createNode$$1('line');
  62192. pathEl = createNode$$1('path');
  62193. textPathEl = createNode$$1('textpath');
  62194. skewEl = createNode$$1('skew');
  62195. // FIXME Why here is not cammel case
  62196. // Align 'center' seems wrong
  62197. textPathEl.style['v-text-align'] = 'left';
  62198. initRootElStyle(textVmlEl);
  62199. pathEl.textpathok = true;
  62200. textPathEl.on = true;
  62201. textVmlEl.from = '0 0';
  62202. textVmlEl.to = '1000 0.05';
  62203. append(textVmlEl, skewEl);
  62204. append(textVmlEl, pathEl);
  62205. append(textVmlEl, textPathEl);
  62206. this._textVmlEl = textVmlEl;
  62207. }
  62208. else {
  62209. // 这里是在前面 appendChild 保证顺序的前提下
  62210. skewEl = textVmlEl.firstChild;
  62211. pathEl = skewEl.nextSibling;
  62212. textPathEl = pathEl.nextSibling;
  62213. }
  62214. var coords = [x, y];
  62215. var textVmlElStyle = textVmlEl.style;
  62216. // Ignore transform for text in other element
  62217. if (m && fromTextEl) {
  62218. applyTransform(coords, coords, m);
  62219. skewEl.on = true;
  62220. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  62221. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  62222. // Text position
  62223. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  62224. // Left top point as origin
  62225. skewEl.origin = '0 0';
  62226. textVmlElStyle.left = '0px';
  62227. textVmlElStyle.top = '0px';
  62228. }
  62229. else {
  62230. skewEl.on = false;
  62231. textVmlElStyle.left = round$3(x) + 'px';
  62232. textVmlElStyle.top = round$3(y) + 'px';
  62233. }
  62234. textPathEl.string = encodeHtmlAttribute(text);
  62235. // TODO
  62236. try {
  62237. textPathEl.style.font = font;
  62238. }
  62239. // Error font format
  62240. catch (e) {}
  62241. updateFillAndStroke(textVmlEl, 'fill', {
  62242. fill: style.textFill,
  62243. opacity: style.opacity
  62244. }, this);
  62245. updateFillAndStroke(textVmlEl, 'stroke', {
  62246. stroke: style.textStroke,
  62247. opacity: style.opacity,
  62248. lineDash: style.lineDash
  62249. }, this);
  62250. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  62251. // Attached to root
  62252. append(vmlRoot, textVmlEl);
  62253. };
  62254. var removeRectText = function (vmlRoot) {
  62255. remove(vmlRoot, this._textVmlEl);
  62256. this._textVmlEl = null;
  62257. };
  62258. var appendRectText = function (vmlRoot) {
  62259. append(vmlRoot, this._textVmlEl);
  62260. };
  62261. var list = [RectText, Displayable, ZImage, Path, Text];
  62262. // In case Displayable has been mixed in RectText
  62263. for (var i$3 = 0; i$3 < list.length; i$3++) {
  62264. var proto$6 = list[i$3].prototype;
  62265. proto$6.drawRectText = drawRectText;
  62266. proto$6.removeRectText = removeRectText;
  62267. proto$6.appendRectText = appendRectText;
  62268. }
  62269. Text.prototype.brushVML = function (vmlRoot) {
  62270. var style = this.style;
  62271. if (style.text != null) {
  62272. this.drawRectText(vmlRoot, {
  62273. x: style.x || 0, y: style.y || 0,
  62274. width: 0, height: 0
  62275. }, this.getBoundingRect(), true);
  62276. }
  62277. else {
  62278. this.removeRectText(vmlRoot);
  62279. }
  62280. };
  62281. Text.prototype.onRemove = function (vmlRoot) {
  62282. this.removeRectText(vmlRoot);
  62283. };
  62284. Text.prototype.onAdd = function (vmlRoot) {
  62285. this.appendRectText(vmlRoot);
  62286. };
  62287. }
  62288. /**
  62289. * VML Painter.
  62290. *
  62291. * @module zrender/vml/Painter
  62292. */
  62293. function parseInt10$1(val) {
  62294. return parseInt(val, 10);
  62295. }
  62296. /**
  62297. * @alias module:zrender/vml/Painter
  62298. */
  62299. function VMLPainter(root, storage) {
  62300. initVML();
  62301. this.root = root;
  62302. this.storage = storage;
  62303. var vmlViewport = document.createElement('div');
  62304. var vmlRoot = document.createElement('div');
  62305. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  62306. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  62307. root.appendChild(vmlViewport);
  62308. this._vmlRoot = vmlRoot;
  62309. this._vmlViewport = vmlViewport;
  62310. this.resize();
  62311. // Modify storage
  62312. var oldDelFromStorage = storage.delFromStorage;
  62313. var oldAddToStorage = storage.addToStorage;
  62314. storage.delFromStorage = function (el) {
  62315. oldDelFromStorage.call(storage, el);
  62316. if (el) {
  62317. el.onRemove && el.onRemove(vmlRoot);
  62318. }
  62319. };
  62320. storage.addToStorage = function (el) {
  62321. // Displayable already has a vml node
  62322. el.onAdd && el.onAdd(vmlRoot);
  62323. oldAddToStorage.call(storage, el);
  62324. };
  62325. this._firstPaint = true;
  62326. }
  62327. VMLPainter.prototype = {
  62328. constructor: VMLPainter,
  62329. getType: function () {
  62330. return 'vml';
  62331. },
  62332. /**
  62333. * @return {HTMLDivElement}
  62334. */
  62335. getViewportRoot: function () {
  62336. return this._vmlViewport;
  62337. },
  62338. getViewportRootOffset: function () {
  62339. var viewportRoot = this.getViewportRoot();
  62340. if (viewportRoot) {
  62341. return {
  62342. offsetLeft: viewportRoot.offsetLeft || 0,
  62343. offsetTop: viewportRoot.offsetTop || 0
  62344. };
  62345. }
  62346. },
  62347. /**
  62348. * 刷新
  62349. */
  62350. refresh: function () {
  62351. var list = this.storage.getDisplayList(true, true);
  62352. this._paintList(list);
  62353. },
  62354. _paintList: function (list) {
  62355. var vmlRoot = this._vmlRoot;
  62356. for (var i = 0; i < list.length; i++) {
  62357. var el = list[i];
  62358. if (el.invisible || el.ignore) {
  62359. if (!el.__alreadyNotVisible) {
  62360. el.onRemove(vmlRoot);
  62361. }
  62362. // Set as already invisible
  62363. el.__alreadyNotVisible = true;
  62364. }
  62365. else {
  62366. if (el.__alreadyNotVisible) {
  62367. el.onAdd(vmlRoot);
  62368. }
  62369. el.__alreadyNotVisible = false;
  62370. if (el.__dirty) {
  62371. el.beforeBrush && el.beforeBrush();
  62372. (el.brushVML || el.brush).call(el, vmlRoot);
  62373. el.afterBrush && el.afterBrush();
  62374. }
  62375. }
  62376. el.__dirty = false;
  62377. }
  62378. if (this._firstPaint) {
  62379. // Detached from document at first time
  62380. // to avoid page refreshing too many times
  62381. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  62382. this._vmlViewport.appendChild(vmlRoot);
  62383. this._firstPaint = false;
  62384. }
  62385. },
  62386. resize: function (width, height) {
  62387. var width = width == null ? this._getWidth() : width;
  62388. var height = height == null ? this._getHeight() : height;
  62389. if (this._width != width || this._height != height) {
  62390. this._width = width;
  62391. this._height = height;
  62392. var vmlViewportStyle = this._vmlViewport.style;
  62393. vmlViewportStyle.width = width + 'px';
  62394. vmlViewportStyle.height = height + 'px';
  62395. }
  62396. },
  62397. dispose: function () {
  62398. this.root.innerHTML = '';
  62399. this._vmlRoot =
  62400. this._vmlViewport =
  62401. this.storage = null;
  62402. },
  62403. getWidth: function () {
  62404. return this._width;
  62405. },
  62406. getHeight: function () {
  62407. return this._height;
  62408. },
  62409. clear: function () {
  62410. if (this._vmlViewport) {
  62411. this.root.removeChild(this._vmlViewport);
  62412. }
  62413. },
  62414. _getWidth: function () {
  62415. var root = this.root;
  62416. var stl = root.currentStyle;
  62417. return ((root.clientWidth || parseInt10$1(stl.width))
  62418. - parseInt10$1(stl.paddingLeft)
  62419. - parseInt10$1(stl.paddingRight)) | 0;
  62420. },
  62421. _getHeight: function () {
  62422. var root = this.root;
  62423. var stl = root.currentStyle;
  62424. return ((root.clientHeight || parseInt10$1(stl.height))
  62425. - parseInt10$1(stl.paddingTop)
  62426. - parseInt10$1(stl.paddingBottom)) | 0;
  62427. }
  62428. };
  62429. // Not supported methods
  62430. function createMethodNotSupport(method) {
  62431. return function () {
  62432. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  62433. };
  62434. }
  62435. // Unsupported methods
  62436. each$1([
  62437. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  62438. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  62439. ], function (name) {
  62440. VMLPainter.prototype[name] = createMethodNotSupport(name);
  62441. });
  62442. registerPainter('vml', VMLPainter);
  62443. var svgURI = 'http://www.w3.org/2000/svg';
  62444. function createElement(name) {
  62445. return document.createElementNS(svgURI, name);
  62446. }
  62447. // TODO
  62448. // 1. shadow
  62449. // 2. Image: sx, sy, sw, sh
  62450. var CMD$4 = PathProxy.CMD;
  62451. var arrayJoin = Array.prototype.join;
  62452. var NONE = 'none';
  62453. var mathRound = Math.round;
  62454. var mathSin$3 = Math.sin;
  62455. var mathCos$3 = Math.cos;
  62456. var PI$5 = Math.PI;
  62457. var PI2$6 = Math.PI * 2;
  62458. var degree = 180 / PI$5;
  62459. var EPSILON$4 = 1e-4;
  62460. function round4(val) {
  62461. return mathRound(val * 1e4) / 1e4;
  62462. }
  62463. function isAroundZero$1(val) {
  62464. return val < EPSILON$4 && val > -EPSILON$4;
  62465. }
  62466. function pathHasFill(style, isText) {
  62467. var fill = isText ? style.textFill : style.fill;
  62468. return fill != null && fill !== NONE;
  62469. }
  62470. function pathHasStroke(style, isText) {
  62471. var stroke = isText ? style.textStroke : style.stroke;
  62472. return stroke != null && stroke !== NONE;
  62473. }
  62474. function setTransform(svgEl, m) {
  62475. if (m) {
  62476. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  62477. }
  62478. }
  62479. function attr(el, key, val) {
  62480. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  62481. // Don't set attribute for gradient, since it need new dom nodes
  62482. el.setAttribute(key, val);
  62483. }
  62484. }
  62485. function attrXLink(el, key, val) {
  62486. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  62487. }
  62488. function bindStyle(svgEl, style, isText) {
  62489. if (pathHasFill(style, isText)) {
  62490. var fill = isText ? style.textFill : style.fill;
  62491. fill = fill === 'transparent' ? NONE : fill;
  62492. /**
  62493. * FIXME:
  62494. * This is a temporary fix for Chrome's clipping bug
  62495. * that happens when a clip-path is referring another one.
  62496. * This fix should be used before Chrome's bug is fixed.
  62497. * For an element that has clip-path, and fill is none,
  62498. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  62499. * Otherwise, it will show black fill color.
  62500. * 0.002 is used because this won't work for alpha values smaller
  62501. * than 0.002.
  62502. *
  62503. * See
  62504. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  62505. * for more information.
  62506. */
  62507. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  62508. fill = 'rgba(0, 0, 0, 0.002)';
  62509. }
  62510. attr(svgEl, 'fill', fill);
  62511. attr(svgEl, 'fill-opacity', style.opacity);
  62512. }
  62513. else {
  62514. attr(svgEl, 'fill', NONE);
  62515. }
  62516. if (pathHasStroke(style, isText)) {
  62517. var stroke = isText ? style.textStroke : style.stroke;
  62518. stroke = stroke === 'transparent' ? NONE : stroke;
  62519. attr(svgEl, 'stroke', stroke);
  62520. var strokeWidth = isText
  62521. ? style.textStrokeWidth
  62522. : style.lineWidth;
  62523. var strokeScale = style.strokeNoScale
  62524. ? style.host.getLineScale()
  62525. : 1;
  62526. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  62527. attr(svgEl, 'paint-order', 'stroke');
  62528. attr(svgEl, 'stroke-opacity', style.opacity);
  62529. var lineDash = style.lineDash;
  62530. if (lineDash) {
  62531. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  62532. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  62533. }
  62534. else {
  62535. attr(svgEl, 'stroke-dasharray', '');
  62536. }
  62537. // PENDING
  62538. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  62539. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  62540. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  62541. }
  62542. else {
  62543. attr(svgEl, 'stroke', NONE);
  62544. }
  62545. }
  62546. /***************************************************
  62547. * PATH
  62548. **************************************************/
  62549. function pathDataToString$1(path) {
  62550. var str = [];
  62551. var data = path.data;
  62552. var dataLength = path.len();
  62553. for (var i = 0; i < dataLength;) {
  62554. var cmd = data[i++];
  62555. var cmdStr = '';
  62556. var nData = 0;
  62557. switch (cmd) {
  62558. case CMD$4.M:
  62559. cmdStr = 'M';
  62560. nData = 2;
  62561. break;
  62562. case CMD$4.L:
  62563. cmdStr = 'L';
  62564. nData = 2;
  62565. break;
  62566. case CMD$4.Q:
  62567. cmdStr = 'Q';
  62568. nData = 4;
  62569. break;
  62570. case CMD$4.C:
  62571. cmdStr = 'C';
  62572. nData = 6;
  62573. break;
  62574. case CMD$4.A:
  62575. var cx = data[i++];
  62576. var cy = data[i++];
  62577. var rx = data[i++];
  62578. var ry = data[i++];
  62579. var theta = data[i++];
  62580. var dTheta = data[i++];
  62581. var psi = data[i++];
  62582. var clockwise = data[i++];
  62583. var dThetaPositive = Math.abs(dTheta);
  62584. var isCircle = isAroundZero$1(dThetaPositive % PI2$6)
  62585. && !isAroundZero$1(dThetaPositive);
  62586. var large = false;
  62587. if (dThetaPositive >= PI2$6) {
  62588. large = true;
  62589. }
  62590. else if (isAroundZero$1(dThetaPositive)) {
  62591. large = false;
  62592. }
  62593. else {
  62594. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  62595. === !!clockwise;
  62596. }
  62597. var x0 = round4(cx + rx * mathCos$3(theta));
  62598. var y0 = round4(cy + ry * mathSin$3(theta));
  62599. // It will not draw if start point and end point are exactly the same
  62600. // We need to shift the end point with a small value
  62601. // FIXME A better way to draw circle ?
  62602. if (isCircle) {
  62603. if (clockwise) {
  62604. dTheta = PI2$6 - 1e-4;
  62605. }
  62606. else {
  62607. dTheta = -PI2$6 + 1e-4;
  62608. }
  62609. large = true;
  62610. if (i === 9) {
  62611. // Move to (x0, y0) only when CMD.A comes at the
  62612. // first position of a shape.
  62613. // For instance, when drawing a ring, CMD.A comes
  62614. // after CMD.M, so it's unnecessary to move to
  62615. // (x0, y0).
  62616. str.push('M', x0, y0);
  62617. }
  62618. }
  62619. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  62620. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  62621. // FIXME Ellipse
  62622. str.push('A', round4(rx), round4(ry),
  62623. mathRound(psi * degree), +large, +clockwise, x, y);
  62624. break;
  62625. case CMD$4.Z:
  62626. cmdStr = 'Z';
  62627. break;
  62628. case CMD$4.R:
  62629. var x = round4(data[i++]);
  62630. var y = round4(data[i++]);
  62631. var w = round4(data[i++]);
  62632. var h = round4(data[i++]);
  62633. str.push(
  62634. 'M', x, y,
  62635. 'L', x + w, y,
  62636. 'L', x + w, y + h,
  62637. 'L', x, y + h,
  62638. 'L', x, y
  62639. );
  62640. break;
  62641. }
  62642. cmdStr && str.push(cmdStr);
  62643. for (var j = 0; j < nData; j++) {
  62644. // PENDING With scale
  62645. str.push(round4(data[i++]));
  62646. }
  62647. }
  62648. return str.join(' ');
  62649. }
  62650. var svgPath = {};
  62651. svgPath.brush = function (el) {
  62652. var style = el.style;
  62653. var svgEl = el.__svgEl;
  62654. if (!svgEl) {
  62655. svgEl = createElement('path');
  62656. el.__svgEl = svgEl;
  62657. }
  62658. if (!el.path) {
  62659. el.createPathProxy();
  62660. }
  62661. var path = el.path;
  62662. if (el.__dirtyPath) {
  62663. path.beginPath();
  62664. el.buildPath(path, el.shape);
  62665. el.__dirtyPath = false;
  62666. var pathStr = pathDataToString$1(path);
  62667. if (pathStr.indexOf('NaN') < 0) {
  62668. // Ignore illegal path, which may happen such in out-of-range
  62669. // data in Calendar series.
  62670. attr(svgEl, 'd', pathStr);
  62671. }
  62672. }
  62673. bindStyle(svgEl, style);
  62674. setTransform(svgEl, el.transform);
  62675. if (style.text != null) {
  62676. svgTextDrawRectText(el, el.getBoundingRect());
  62677. }
  62678. };
  62679. /***************************************************
  62680. * IMAGE
  62681. **************************************************/
  62682. var svgImage = {};
  62683. svgImage.brush = function (el) {
  62684. var style = el.style;
  62685. var image = style.image;
  62686. if (image instanceof HTMLImageElement) {
  62687. var src = image.src;
  62688. image = src;
  62689. }
  62690. if (! image) {
  62691. return;
  62692. }
  62693. var x = style.x || 0;
  62694. var y = style.y || 0;
  62695. var dw = style.width;
  62696. var dh = style.height;
  62697. var svgEl = el.__svgEl;
  62698. if (! svgEl) {
  62699. svgEl = createElement('image');
  62700. el.__svgEl = svgEl;
  62701. }
  62702. if (image !== el.__imageSrc) {
  62703. attrXLink(svgEl, 'href', image);
  62704. // Caching image src
  62705. el.__imageSrc = image;
  62706. }
  62707. attr(svgEl, 'width', dw);
  62708. attr(svgEl, 'height', dh);
  62709. attr(svgEl, 'x', x);
  62710. attr(svgEl, 'y', y);
  62711. setTransform(svgEl, el.transform);
  62712. if (style.text != null) {
  62713. svgTextDrawRectText(el, el.getBoundingRect());
  62714. }
  62715. };
  62716. /***************************************************
  62717. * TEXT
  62718. **************************************************/
  62719. var svgText = {};
  62720. var tmpRect$3 = new BoundingRect();
  62721. var svgTextDrawRectText = function (el, rect, textRect) {
  62722. var style = el.style;
  62723. el.__dirty && normalizeTextStyle(style, true);
  62724. var text = style.text;
  62725. // Convert to string
  62726. if (text == null) {
  62727. // Draw no text only when text is set to null, but not ''
  62728. return;
  62729. }
  62730. else {
  62731. text += '';
  62732. }
  62733. var textSvgEl = el.__textSvgEl;
  62734. if (! textSvgEl) {
  62735. textSvgEl = createElement('text');
  62736. el.__textSvgEl = textSvgEl;
  62737. }
  62738. bindStyle(textSvgEl, style, true);
  62739. if (el instanceof Text || el.style.transformText) {
  62740. // Transform text with element
  62741. setTransform(textSvgEl, el.transform);
  62742. }
  62743. else {
  62744. if (el.transform) {
  62745. tmpRect$3.copy(rect);
  62746. tmpRect$3.applyTransform(el.transform);
  62747. rect = tmpRect$3;
  62748. }
  62749. else {
  62750. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  62751. rect.x = pos[0];
  62752. rect.y = pos[1];
  62753. }
  62754. }
  62755. var x;
  62756. var y;
  62757. var textPosition = style.textPosition;
  62758. var distance = style.textDistance;
  62759. var align = style.textAlign || 'left';
  62760. if (typeof style.fontSize === 'number') {
  62761. style.fontSize += 'px';
  62762. }
  62763. var font = style.font
  62764. || [
  62765. style.fontStyle || '',
  62766. style.fontWeight || '',
  62767. style.fontSize || '',
  62768. style.fontFamily || ''
  62769. ].join(' ')
  62770. || DEFAULT_FONT;
  62771. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  62772. textRect = getBoundingRect(text, font, align,
  62773. verticalAlign);
  62774. var lineHeight = textRect.lineHeight;
  62775. // Text position represented by coord
  62776. if (textPosition instanceof Array) {
  62777. x = rect.x + textPosition[0];
  62778. y = rect.y + textPosition[1];
  62779. }
  62780. else {
  62781. var newPos = adjustTextPositionOnRect(
  62782. textPosition, rect, distance
  62783. );
  62784. x = newPos.x;
  62785. y = newPos.y;
  62786. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  62787. align = newPos.textAlign;
  62788. }
  62789. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  62790. if (font) {
  62791. textSvgEl.style.font = font;
  62792. }
  62793. var textPadding = style.textPadding;
  62794. // Make baseline top
  62795. attr(textSvgEl, 'x', x);
  62796. attr(textSvgEl, 'y', y);
  62797. var textLines = text.split('\n');
  62798. var nTextLines = textLines.length;
  62799. var textAnchor = align;
  62800. // PENDING
  62801. if (textAnchor === 'left') {
  62802. textAnchor = 'start';
  62803. textPadding && (x += textPadding[3]);
  62804. }
  62805. else if (textAnchor === 'right') {
  62806. textAnchor = 'end';
  62807. textPadding && (x -= textPadding[1]);
  62808. }
  62809. else if (textAnchor === 'center') {
  62810. textAnchor = 'middle';
  62811. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  62812. }
  62813. var dy = 0;
  62814. if (verticalAlign === 'baseline') {
  62815. dy = -textRect.height + lineHeight;
  62816. textPadding && (dy -= textPadding[2]);
  62817. }
  62818. else if (verticalAlign === 'middle') {
  62819. dy = (-textRect.height + lineHeight) / 2;
  62820. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  62821. }
  62822. else {
  62823. textPadding && (dy += textPadding[0]);
  62824. }
  62825. // Font may affect position of each tspan elements
  62826. if (el.__text !== text || el.__textFont !== font) {
  62827. var tspanList = el.__tspanList || [];
  62828. el.__tspanList = tspanList;
  62829. for (var i = 0; i < nTextLines; i++) {
  62830. // Using cached tspan elements
  62831. var tspan = tspanList[i];
  62832. if (! tspan) {
  62833. tspan = tspanList[i] = createElement('tspan');
  62834. textSvgEl.appendChild(tspan);
  62835. attr(tspan, 'alignment-baseline', verticalAlign);
  62836. attr(tspan, 'text-anchor', textAnchor);
  62837. }
  62838. else {
  62839. tspan.innerHTML = '';
  62840. }
  62841. attr(tspan, 'x', x);
  62842. attr(tspan, 'y', y + i * lineHeight + dy);
  62843. tspan.appendChild(document.createTextNode(textLines[i]));
  62844. }
  62845. // Remove unsed tspan elements
  62846. for (; i < tspanList.length; i++) {
  62847. textSvgEl.removeChild(tspanList[i]);
  62848. }
  62849. tspanList.length = nTextLines;
  62850. el.__text = text;
  62851. el.__textFont = font;
  62852. }
  62853. else if (el.__tspanList.length) {
  62854. // Update span x and y
  62855. var len = el.__tspanList.length;
  62856. for (var i = 0; i < len; ++i) {
  62857. var tspan = el.__tspanList[i];
  62858. if (tspan) {
  62859. attr(tspan, 'x', x);
  62860. attr(tspan, 'y', y + i * lineHeight + dy);
  62861. }
  62862. }
  62863. }
  62864. };
  62865. function getVerticalAlignForSvg(verticalAlign) {
  62866. if (verticalAlign === 'middle') {
  62867. return 'middle';
  62868. }
  62869. else if (verticalAlign === 'bottom') {
  62870. return 'baseline';
  62871. }
  62872. else {
  62873. return 'hanging';
  62874. }
  62875. }
  62876. svgText.drawRectText = svgTextDrawRectText;
  62877. svgText.brush = function (el) {
  62878. var style = el.style;
  62879. if (style.text != null) {
  62880. // 强制设置 textPosition
  62881. style.textPosition = [0, 0];
  62882. svgTextDrawRectText(el, {
  62883. x: style.x || 0, y: style.y || 0,
  62884. width: 0, height: 0
  62885. }, el.getBoundingRect());
  62886. }
  62887. };
  62888. // Myers' Diff Algorithm
  62889. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  62890. function Diff() {}
  62891. Diff.prototype = {
  62892. diff: function (oldArr, newArr, equals) {
  62893. if (!equals) {
  62894. equals = function (a, b) {
  62895. return a === b;
  62896. };
  62897. }
  62898. this.equals = equals;
  62899. var self = this;
  62900. oldArr = oldArr.slice();
  62901. newArr = newArr.slice();
  62902. // Allow subclasses to massage the input prior to running
  62903. var newLen = newArr.length;
  62904. var oldLen = oldArr.length;
  62905. var editLength = 1;
  62906. var maxEditLength = newLen + oldLen;
  62907. var bestPath = [{ newPos: -1, components: [] }];
  62908. // Seed editLength = 0, i.e. the content starts with the same values
  62909. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  62910. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  62911. var indices = [];
  62912. for (var i = 0; i < newArr.length; i++) {
  62913. indices.push(i);
  62914. }
  62915. // Identity per the equality and tokenizer
  62916. return [{
  62917. indices: indices, count: newArr.length
  62918. }];
  62919. }
  62920. // Main worker method. checks all permutations of a given edit length for acceptance.
  62921. function execEditLength() {
  62922. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  62923. var basePath;
  62924. var addPath = bestPath[diagonalPath - 1];
  62925. var removePath = bestPath[diagonalPath + 1];
  62926. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  62927. if (addPath) {
  62928. // No one else is going to attempt to use this value, clear it
  62929. bestPath[diagonalPath - 1] = undefined;
  62930. }
  62931. var canAdd = addPath && addPath.newPos + 1 < newLen;
  62932. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  62933. if (!canAdd && !canRemove) {
  62934. // If this path is a terminal then prune
  62935. bestPath[diagonalPath] = undefined;
  62936. continue;
  62937. }
  62938. // Select the diagonal that we want to branch from. We select the prior
  62939. // path whose position in the new string is the farthest from the origin
  62940. // and does not pass the bounds of the diff graph
  62941. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  62942. basePath = clonePath(removePath);
  62943. self.pushComponent(basePath.components, undefined, true);
  62944. }
  62945. else {
  62946. basePath = addPath; // No need to clone, we've pulled it from the list
  62947. basePath.newPos++;
  62948. self.pushComponent(basePath.components, true, undefined);
  62949. }
  62950. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  62951. // If we have hit the end of both strings, then we are done
  62952. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  62953. return buildValues(self, basePath.components, newArr, oldArr);
  62954. }
  62955. else {
  62956. // Otherwise track this path as a potential candidate and continue.
  62957. bestPath[diagonalPath] = basePath;
  62958. }
  62959. }
  62960. editLength++;
  62961. }
  62962. while (editLength <= maxEditLength) {
  62963. var ret = execEditLength();
  62964. if (ret) {
  62965. return ret;
  62966. }
  62967. }
  62968. },
  62969. pushComponent: function (components, added, removed) {
  62970. var last = components[components.length - 1];
  62971. if (last && last.added === added && last.removed === removed) {
  62972. // We need to clone here as the component clone operation is just
  62973. // as shallow array clone
  62974. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  62975. }
  62976. else {
  62977. components.push({count: 1, added: added, removed: removed });
  62978. }
  62979. },
  62980. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  62981. var newLen = newArr.length;
  62982. var oldLen = oldArr.length;
  62983. var newPos = basePath.newPos;
  62984. var oldPos = newPos - diagonalPath;
  62985. var commonCount = 0;
  62986. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  62987. newPos++;
  62988. oldPos++;
  62989. commonCount++;
  62990. }
  62991. if (commonCount) {
  62992. basePath.components.push({count: commonCount});
  62993. }
  62994. basePath.newPos = newPos;
  62995. return oldPos;
  62996. },
  62997. tokenize: function (value) {
  62998. return value.slice();
  62999. },
  63000. join: function (value) {
  63001. return value.slice();
  63002. }
  63003. };
  63004. function buildValues(diff, components, newArr, oldArr) {
  63005. var componentPos = 0;
  63006. var componentLen = components.length;
  63007. var newPos = 0;
  63008. var oldPos = 0;
  63009. for (; componentPos < componentLen; componentPos++) {
  63010. var component = components[componentPos];
  63011. if (!component.removed) {
  63012. var indices = [];
  63013. for (var i = newPos; i < newPos + component.count; i++) {
  63014. indices.push(i);
  63015. }
  63016. component.indices = indices;
  63017. newPos += component.count;
  63018. // Common case
  63019. if (!component.added) {
  63020. oldPos += component.count;
  63021. }
  63022. }
  63023. else {
  63024. var indices = [];
  63025. for (var i = oldPos; i < oldPos + component.count; i++) {
  63026. indices.push(i);
  63027. }
  63028. component.indices = indices;
  63029. oldPos += component.count;
  63030. }
  63031. }
  63032. return components;
  63033. }
  63034. function clonePath(path) {
  63035. return { newPos: path.newPos, components: path.components.slice(0) };
  63036. }
  63037. var arrayDiff = new Diff();
  63038. var arrayDiff$1 = function (oldArr, newArr, callback) {
  63039. return arrayDiff.diff(oldArr, newArr, callback);
  63040. };
  63041. /**
  63042. * @file Manages elements that can be defined in <defs> in SVG,
  63043. * e.g., gradients, clip path, etc.
  63044. * @author Zhang Wenli
  63045. */
  63046. var MARK_UNUSED = '0';
  63047. var MARK_USED = '1';
  63048. /**
  63049. * Manages elements that can be defined in <defs> in SVG,
  63050. * e.g., gradients, clip path, etc.
  63051. *
  63052. * @class
  63053. * @param {SVGElement} svgRoot root of SVG document
  63054. * @param {string|string[]} tagNames possible tag names
  63055. * @param {string} markLabel label name to make if the element
  63056. * is used
  63057. */
  63058. function Definable(
  63059. svgRoot,
  63060. tagNames,
  63061. markLabel
  63062. ) {
  63063. this._svgRoot = svgRoot;
  63064. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  63065. this._markLabel = markLabel;
  63066. this.nextId = 0;
  63067. }
  63068. Definable.prototype.createElement = createElement;
  63069. /**
  63070. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  63071. *
  63072. * @param {boolean} isForceCreating if need to create when not exists
  63073. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  63074. * exist and isForceCreating is false
  63075. */
  63076. Definable.prototype.getDefs = function (isForceCreating) {
  63077. var svgRoot = this._svgRoot;
  63078. var defs = this._svgRoot.getElementsByTagName('defs');
  63079. if (defs.length === 0) {
  63080. // Not exist
  63081. if (isForceCreating) {
  63082. defs = svgRoot.insertBefore(
  63083. this.createElement('defs'), // Create new tag
  63084. svgRoot.firstChild // Insert in the front of svg
  63085. );
  63086. if (!defs.contains) {
  63087. // IE doesn't support contains method
  63088. defs.contains = function (el) {
  63089. var children = defs.children;
  63090. if (!children) {
  63091. return false;
  63092. }
  63093. for (var i = children.length - 1; i >= 0; --i) {
  63094. if (children[i] === el) {
  63095. return true;
  63096. }
  63097. }
  63098. return false;
  63099. };
  63100. }
  63101. return defs;
  63102. }
  63103. else {
  63104. return null;
  63105. }
  63106. }
  63107. else {
  63108. return defs[0];
  63109. }
  63110. };
  63111. /**
  63112. * Update DOM element if necessary.
  63113. *
  63114. * @param {Object|string} element style element. e.g., for gradient,
  63115. * it may be '#ccc' or {type: 'linear', ...}
  63116. * @param {Function|undefined} onUpdate update callback
  63117. */
  63118. Definable.prototype.update = function (element, onUpdate) {
  63119. if (!element) {
  63120. return;
  63121. }
  63122. var defs = this.getDefs(false);
  63123. if (element._dom && defs.contains(element._dom)) {
  63124. // Update DOM
  63125. if (typeof onUpdate === 'function') {
  63126. onUpdate();
  63127. }
  63128. }
  63129. else {
  63130. // No previous dom, create new
  63131. var dom = this.add(element);
  63132. if (dom) {
  63133. element._dom = dom;
  63134. }
  63135. }
  63136. };
  63137. /**
  63138. * Add gradient dom to defs
  63139. *
  63140. * @param {SVGElement} dom DOM to be added to <defs>
  63141. */
  63142. Definable.prototype.addDom = function (dom) {
  63143. var defs = this.getDefs(true);
  63144. defs.appendChild(dom);
  63145. };
  63146. /**
  63147. * Remove DOM of a given element.
  63148. *
  63149. * @param {SVGElement} element element to remove dom
  63150. */
  63151. Definable.prototype.removeDom = function (element) {
  63152. var defs = this.getDefs(false);
  63153. defs.removeChild(element._dom);
  63154. };
  63155. /**
  63156. * Get DOMs of this element.
  63157. *
  63158. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  63159. */
  63160. Definable.prototype.getDoms = function () {
  63161. var defs = this.getDefs(false);
  63162. if (!defs) {
  63163. // No dom when defs is not defined
  63164. return [];
  63165. }
  63166. var doms = [];
  63167. each$1(this._tagNames, function (tagName) {
  63168. var tags = defs.getElementsByTagName(tagName);
  63169. // Note that tags is HTMLCollection, which is array-like
  63170. // rather than real array.
  63171. // So `doms.concat(tags)` add tags as one object.
  63172. doms = doms.concat([].slice.call(tags));
  63173. });
  63174. return doms;
  63175. };
  63176. /**
  63177. * Mark DOMs to be unused before painting, and clear unused ones at the end
  63178. * of the painting.
  63179. */
  63180. Definable.prototype.markAllUnused = function () {
  63181. var doms = this.getDoms();
  63182. var that = this;
  63183. each$1(doms, function (dom) {
  63184. dom[that._markLabel] = MARK_UNUSED;
  63185. });
  63186. };
  63187. /**
  63188. * Mark a single DOM to be used.
  63189. *
  63190. * @param {SVGElement} dom DOM to mark
  63191. */
  63192. Definable.prototype.markUsed = function (dom) {
  63193. if (dom) {
  63194. dom[this._markLabel] = MARK_USED;
  63195. }
  63196. };
  63197. /**
  63198. * Remove unused DOMs defined in <defs>
  63199. */
  63200. Definable.prototype.removeUnused = function () {
  63201. var defs = this.getDefs(false);
  63202. if (!defs) {
  63203. // Nothing to remove
  63204. return;
  63205. }
  63206. var doms = this.getDoms();
  63207. var that = this;
  63208. each$1(doms, function (dom) {
  63209. if (dom[that._markLabel] !== MARK_USED) {
  63210. // Remove gradient
  63211. defs.removeChild(dom);
  63212. }
  63213. });
  63214. };
  63215. /**
  63216. * Get SVG proxy.
  63217. *
  63218. * @param {Displayable} displayable displayable element
  63219. * @return {Path|Image|Text} svg proxy of given element
  63220. */
  63221. Definable.prototype.getSvgProxy = function (displayable) {
  63222. if (displayable instanceof Path) {
  63223. return svgPath;
  63224. }
  63225. else if (displayable instanceof ZImage) {
  63226. return svgImage;
  63227. }
  63228. else if (displayable instanceof Text) {
  63229. return svgText;
  63230. }
  63231. else {
  63232. return svgPath;
  63233. }
  63234. };
  63235. /**
  63236. * Get text SVG element.
  63237. *
  63238. * @param {Displayable} displayable displayable element
  63239. * @return {SVGElement} SVG element of text
  63240. */
  63241. Definable.prototype.getTextSvgElement = function (displayable) {
  63242. return displayable.__textSvgEl;
  63243. };
  63244. /**
  63245. * Get SVG element.
  63246. *
  63247. * @param {Displayable} displayable displayable element
  63248. * @return {SVGElement} SVG element
  63249. */
  63250. Definable.prototype.getSvgElement = function (displayable) {
  63251. return displayable.__svgEl;
  63252. };
  63253. /**
  63254. * @file Manages SVG gradient elements.
  63255. * @author Zhang Wenli
  63256. */
  63257. /**
  63258. * Manages SVG gradient elements.
  63259. *
  63260. * @class
  63261. * @extends Definable
  63262. * @param {SVGElement} svgRoot root of SVG document
  63263. */
  63264. function GradientManager(svgRoot) {
  63265. Definable.call(
  63266. this,
  63267. svgRoot,
  63268. ['linearGradient', 'radialGradient'],
  63269. '__gradient_in_use__'
  63270. );
  63271. }
  63272. inherits(GradientManager, Definable);
  63273. /**
  63274. * Create new gradient DOM for fill or stroke if not exist,
  63275. * but will not update gradient if exists.
  63276. *
  63277. * @param {SvgElement} svgElement SVG element to paint
  63278. * @param {Displayable} displayable zrender displayable element
  63279. */
  63280. GradientManager.prototype.addWithoutUpdate = function (
  63281. svgElement,
  63282. displayable
  63283. ) {
  63284. if (displayable && displayable.style) {
  63285. var that = this;
  63286. each$1(['fill', 'stroke'], function (fillOrStroke) {
  63287. if (displayable.style[fillOrStroke]
  63288. && (displayable.style[fillOrStroke].type === 'linear'
  63289. || displayable.style[fillOrStroke].type === 'radial')
  63290. ) {
  63291. var gradient = displayable.style[fillOrStroke];
  63292. var defs = that.getDefs(true);
  63293. // Create dom in <defs> if not exists
  63294. var dom;
  63295. if (gradient._dom) {
  63296. // Gradient exists
  63297. dom = gradient._dom;
  63298. if (!defs.contains(gradient._dom)) {
  63299. // _dom is no longer in defs, recreate
  63300. that.addDom(dom);
  63301. }
  63302. }
  63303. else {
  63304. // New dom
  63305. dom = that.add(gradient);
  63306. }
  63307. that.markUsed(displayable);
  63308. var id = dom.getAttribute('id');
  63309. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  63310. }
  63311. });
  63312. }
  63313. };
  63314. /**
  63315. * Add a new gradient tag in <defs>
  63316. *
  63317. * @param {Gradient} gradient zr gradient instance
  63318. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  63319. * created DOM
  63320. */
  63321. GradientManager.prototype.add = function (gradient) {
  63322. var dom;
  63323. if (gradient.type === 'linear') {
  63324. dom = this.createElement('linearGradient');
  63325. }
  63326. else if (gradient.type === 'radial') {
  63327. dom = this.createElement('radialGradient');
  63328. }
  63329. else {
  63330. zrLog('Illegal gradient type.');
  63331. return null;
  63332. }
  63333. // Set dom id with gradient id, since each gradient instance
  63334. // will have no more than one dom element.
  63335. // id may exists before for those dirty elements, in which case
  63336. // id should remain the same, and other attributes should be
  63337. // updated.
  63338. gradient.id = gradient.id || this.nextId++;
  63339. dom.setAttribute('id', 'zr-gradient-' + gradient.id);
  63340. this.updateDom(gradient, dom);
  63341. this.addDom(dom);
  63342. return dom;
  63343. };
  63344. /**
  63345. * Update gradient.
  63346. *
  63347. * @param {Gradient} gradient zr gradient instance
  63348. */
  63349. GradientManager.prototype.update = function (gradient) {
  63350. var that = this;
  63351. Definable.prototype.update.call(this, gradient, function () {
  63352. var type = gradient.type;
  63353. var tagName = gradient._dom.tagName;
  63354. if (type === 'linear' && tagName === 'linearGradient'
  63355. || type === 'radial' && tagName === 'radialGradient'
  63356. ) {
  63357. // Gradient type is not changed, update gradient
  63358. that.updateDom(gradient, gradient._dom);
  63359. }
  63360. else {
  63361. // Remove and re-create if type is changed
  63362. that.removeDom(gradient);
  63363. that.add(gradient);
  63364. }
  63365. });
  63366. };
  63367. /**
  63368. * Update gradient dom
  63369. *
  63370. * @param {Gradient} gradient zr gradient instance
  63371. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  63372. * DOM to update
  63373. */
  63374. GradientManager.prototype.updateDom = function (gradient, dom) {
  63375. if (gradient.type === 'linear') {
  63376. dom.setAttribute('x1', gradient.x);
  63377. dom.setAttribute('y1', gradient.y);
  63378. dom.setAttribute('x2', gradient.x2);
  63379. dom.setAttribute('y2', gradient.y2);
  63380. }
  63381. else if (gradient.type === 'radial') {
  63382. dom.setAttribute('cx', gradient.x);
  63383. dom.setAttribute('cy', gradient.y);
  63384. dom.setAttribute('r', gradient.r);
  63385. }
  63386. else {
  63387. zrLog('Illegal gradient type.');
  63388. return;
  63389. }
  63390. if (gradient.global) {
  63391. // x1, x2, y1, y2 in range of 0 to canvas width or height
  63392. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  63393. }
  63394. else {
  63395. // x1, x2, y1, y2 in range of 0 to 1
  63396. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  63397. }
  63398. // Remove color stops if exists
  63399. dom.innerHTML = '';
  63400. // Add color stops
  63401. var colors = gradient.colorStops;
  63402. for (var i = 0, len = colors.length; i < len; ++i) {
  63403. var stop = this.createElement('stop');
  63404. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  63405. stop.setAttribute('stop-color', colors[i].color);
  63406. dom.appendChild(stop);
  63407. }
  63408. // Store dom element in gradient, to avoid creating multiple
  63409. // dom instances for the same gradient element
  63410. gradient._dom = dom;
  63411. };
  63412. /**
  63413. * Mark a single gradient to be used
  63414. *
  63415. * @param {Displayable} displayable displayable element
  63416. */
  63417. GradientManager.prototype.markUsed = function (displayable) {
  63418. if (displayable.style) {
  63419. var gradient = displayable.style.fill;
  63420. if (gradient && gradient._dom) {
  63421. Definable.prototype.markUsed.call(this, gradient._dom);
  63422. }
  63423. gradient = displayable.style.stroke;
  63424. if (gradient && gradient._dom) {
  63425. Definable.prototype.markUsed.call(this, gradient._dom);
  63426. }
  63427. }
  63428. };
  63429. /**
  63430. * @file Manages SVG clipPath elements.
  63431. * @author Zhang Wenli
  63432. */
  63433. /**
  63434. * Manages SVG clipPath elements.
  63435. *
  63436. * @class
  63437. * @extends Definable
  63438. * @param {SVGElement} svgRoot root of SVG document
  63439. */
  63440. function ClippathManager(svgRoot) {
  63441. Definable.call(this, svgRoot, 'clipPath', '__clippath_in_use__');
  63442. }
  63443. inherits(ClippathManager, Definable);
  63444. /**
  63445. * Update clipPath.
  63446. *
  63447. * @param {Displayable} displayable displayable element
  63448. */
  63449. ClippathManager.prototype.update = function (displayable) {
  63450. var svgEl = this.getSvgElement(displayable);
  63451. if (svgEl) {
  63452. this.updateDom(svgEl, displayable.__clipPaths, false);
  63453. }
  63454. var textEl = this.getTextSvgElement(displayable);
  63455. if (textEl) {
  63456. // Make another clipPath for text, since it's transform
  63457. // matrix is not the same with svgElement
  63458. this.updateDom(textEl, displayable.__clipPaths, true);
  63459. }
  63460. this.markUsed(displayable);
  63461. };
  63462. /**
  63463. * Create an SVGElement of displayable and create a <clipPath> of its
  63464. * clipPath
  63465. *
  63466. * @param {Displayable} parentEl parent element
  63467. * @param {ClipPath[]} clipPaths clipPaths of parent element
  63468. * @param {boolean} isText if parent element is Text
  63469. */
  63470. ClippathManager.prototype.updateDom = function (
  63471. parentEl,
  63472. clipPaths,
  63473. isText
  63474. ) {
  63475. if (clipPaths && clipPaths.length > 0) {
  63476. // Has clipPath, create <clipPath> with the first clipPath
  63477. var defs = this.getDefs(true);
  63478. var clipPath = clipPaths[0];
  63479. var clipPathEl;
  63480. var id;
  63481. var dom = isText ? '_textDom' : '_dom';
  63482. if (clipPath[dom]) {
  63483. // Use a dom that is already in <defs>
  63484. id = clipPath[dom].getAttribute('id');
  63485. clipPathEl = clipPath[dom];
  63486. // Use a dom that is already in <defs>
  63487. if (!defs.contains(clipPathEl)) {
  63488. // This happens when set old clipPath that has
  63489. // been previously removed
  63490. defs.appendChild(clipPathEl);
  63491. }
  63492. }
  63493. else {
  63494. // New <clipPath>
  63495. id = 'zr-clip-' + this.nextId;
  63496. ++this.nextId;
  63497. clipPathEl = this.createElement('clipPath');
  63498. clipPathEl.setAttribute('id', id);
  63499. defs.appendChild(clipPathEl);
  63500. clipPath[dom] = clipPathEl;
  63501. }
  63502. // Build path and add to <clipPath>
  63503. var svgProxy = this.getSvgProxy(clipPath);
  63504. if (clipPath.transform
  63505. && clipPath.parent.invTransform
  63506. && !isText
  63507. ) {
  63508. /**
  63509. * If a clipPath has a parent with transform, the transform
  63510. * of parent should not be considered when setting transform
  63511. * of clipPath. So we need to transform back from parent's
  63512. * transform, which is done by multiplying parent's inverse
  63513. * transform.
  63514. */
  63515. // Store old transform
  63516. var transform = Array.prototype.slice.call(
  63517. clipPath.transform
  63518. );
  63519. // Transform back from parent, and brush path
  63520. mul$1(
  63521. clipPath.transform,
  63522. clipPath.parent.invTransform,
  63523. clipPath.transform
  63524. );
  63525. svgProxy.brush(clipPath);
  63526. // Set back transform of clipPath
  63527. clipPath.transform = transform;
  63528. }
  63529. else {
  63530. svgProxy.brush(clipPath);
  63531. }
  63532. var pathEl = this.getSvgElement(clipPath);
  63533. /**
  63534. * Use `cloneNode()` here to appendChild to multiple parents,
  63535. * which may happend when Text and other shapes are using the same
  63536. * clipPath. Since Text will create an extra clipPath DOM due to
  63537. * different transform rules.
  63538. */
  63539. clipPathEl.appendChild(pathEl.cloneNode());
  63540. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  63541. if (clipPaths.length > 1) {
  63542. // Make the other clipPaths recursively
  63543. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  63544. }
  63545. }
  63546. else {
  63547. // No clipPath
  63548. if (parentEl) {
  63549. parentEl.setAttribute('clip-path', 'none');
  63550. }
  63551. }
  63552. };
  63553. /**
  63554. * Mark a single clipPath to be used
  63555. *
  63556. * @param {Displayable} displayable displayable element
  63557. */
  63558. ClippathManager.prototype.markUsed = function (displayable) {
  63559. var that = this;
  63560. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  63561. each$1(displayable.__clipPaths, function (clipPath) {
  63562. if (clipPath._dom) {
  63563. Definable.prototype.markUsed.call(that, clipPath._dom);
  63564. }
  63565. if (clipPath._textDom) {
  63566. Definable.prototype.markUsed.call(that, clipPath._textDom);
  63567. }
  63568. });
  63569. }
  63570. };
  63571. /**
  63572. * SVG Painter
  63573. * @module zrender/svg/Painter
  63574. */
  63575. function parseInt10$2(val) {
  63576. return parseInt(val, 10);
  63577. }
  63578. function getSvgProxy(el) {
  63579. if (el instanceof Path) {
  63580. return svgPath;
  63581. }
  63582. else if (el instanceof ZImage) {
  63583. return svgImage;
  63584. }
  63585. else if (el instanceof Text) {
  63586. return svgText;
  63587. }
  63588. else {
  63589. return svgPath;
  63590. }
  63591. }
  63592. function checkParentAvailable(parent, child) {
  63593. return child && parent && child.parentNode !== parent;
  63594. }
  63595. function insertAfter(parent, child, prevSibling) {
  63596. if (checkParentAvailable(parent, child) && prevSibling) {
  63597. var nextSibling = prevSibling.nextSibling;
  63598. nextSibling ? parent.insertBefore(child, nextSibling)
  63599. : parent.appendChild(child);
  63600. }
  63601. }
  63602. function prepend(parent, child) {
  63603. if (checkParentAvailable(parent, child)) {
  63604. var firstChild = parent.firstChild;
  63605. firstChild ? parent.insertBefore(child, firstChild)
  63606. : parent.appendChild(child);
  63607. }
  63608. }
  63609. function remove$1(parent, child) {
  63610. if (child && parent && child.parentNode === parent) {
  63611. parent.removeChild(child);
  63612. }
  63613. }
  63614. function getTextSvgElement(displayable) {
  63615. return displayable.__textSvgEl;
  63616. }
  63617. function getSvgElement(displayable) {
  63618. return displayable.__svgEl;
  63619. }
  63620. /**
  63621. * @alias module:zrender/svg/Painter
  63622. * @constructor
  63623. * @param {HTMLElement} root 绘图容器
  63624. * @param {module:zrender/Storage} storage
  63625. * @param {Object} opts
  63626. */
  63627. var SVGPainter = function (root, storage, opts) {
  63628. this.root = root;
  63629. this.storage = storage;
  63630. this._opts = opts = extend({}, opts || {});
  63631. var svgRoot = createElement('svg');
  63632. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  63633. svgRoot.setAttribute('version', '1.1');
  63634. svgRoot.setAttribute('baseProfile', 'full');
  63635. svgRoot.style['user-select'] = 'none';
  63636. svgRoot.style.cssText = 'position:absolute;left:0;top:0;';
  63637. this.gradientManager = new GradientManager(svgRoot);
  63638. this.clipPathManager = new ClippathManager(svgRoot);
  63639. var viewport = document.createElement('div');
  63640. viewport.style.cssText = 'overflow:hidden;position:relative';
  63641. this._svgRoot = svgRoot;
  63642. this._viewport = viewport;
  63643. root.appendChild(viewport);
  63644. viewport.appendChild(svgRoot);
  63645. this.resize(opts.width, opts.height);
  63646. this._visibleList = [];
  63647. };
  63648. SVGPainter.prototype = {
  63649. constructor: SVGPainter,
  63650. getType: function () {
  63651. return 'svg';
  63652. },
  63653. getViewportRoot: function () {
  63654. return this._viewport;
  63655. },
  63656. getViewportRootOffset: function () {
  63657. var viewportRoot = this.getViewportRoot();
  63658. if (viewportRoot) {
  63659. return {
  63660. offsetLeft: viewportRoot.offsetLeft || 0,
  63661. offsetTop: viewportRoot.offsetTop || 0
  63662. };
  63663. }
  63664. },
  63665. refresh: function () {
  63666. var list = this.storage.getDisplayList(true);
  63667. this._paintList(list);
  63668. },
  63669. _paintList: function (list) {
  63670. this.gradientManager.markAllUnused();
  63671. this.clipPathManager.markAllUnused();
  63672. var svgRoot = this._svgRoot;
  63673. var visibleList = this._visibleList;
  63674. var listLen = list.length;
  63675. var newVisibleList = [];
  63676. var i;
  63677. for (i = 0; i < listLen; i++) {
  63678. var displayable = list[i];
  63679. var svgProxy = getSvgProxy(displayable);
  63680. if (!displayable.invisible) {
  63681. if (displayable.__dirty) {
  63682. svgProxy && svgProxy.brush(displayable);
  63683. // Update clipPath
  63684. this.clipPathManager.update(displayable);
  63685. // Update gradient
  63686. if (displayable.style) {
  63687. this.gradientManager
  63688. .update(displayable.style.fill);
  63689. this.gradientManager
  63690. .update(displayable.style.stroke);
  63691. }
  63692. displayable.__dirty = false;
  63693. }
  63694. newVisibleList.push(displayable);
  63695. }
  63696. }
  63697. var diff = arrayDiff$1(visibleList, newVisibleList);
  63698. var prevSvgElement;
  63699. // First do remove, in case element moved to the head and do remove
  63700. // after add
  63701. for (i = 0; i < diff.length; i++) {
  63702. var item = diff[i];
  63703. if (item.removed) {
  63704. for (var k = 0; k < item.count; k++) {
  63705. var displayable = visibleList[item.indices[k]];
  63706. var svgElement = getSvgElement(displayable);
  63707. var textSvgElement = getTextSvgElement(displayable);
  63708. remove$1(svgRoot, svgElement);
  63709. remove$1(svgRoot, textSvgElement);
  63710. }
  63711. }
  63712. }
  63713. for (i = 0; i < diff.length; i++) {
  63714. var item = diff[i];
  63715. if (item.added) {
  63716. for (var k = 0; k < item.count; k++) {
  63717. var displayable = newVisibleList[item.indices[k]];
  63718. var svgElement = getSvgElement(displayable);
  63719. var textSvgElement = getTextSvgElement(displayable);
  63720. prevSvgElement
  63721. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  63722. : prepend(svgRoot, svgElement);
  63723. if (svgElement) {
  63724. insertAfter(svgRoot, textSvgElement, svgElement);
  63725. }
  63726. else if (prevSvgElement) {
  63727. insertAfter(
  63728. svgRoot, textSvgElement, prevSvgElement
  63729. );
  63730. }
  63731. else {
  63732. prepend(svgRoot, textSvgElement);
  63733. }
  63734. // Insert text
  63735. insertAfter(svgRoot, textSvgElement, svgElement);
  63736. prevSvgElement = textSvgElement || svgElement
  63737. || prevSvgElement;
  63738. this.gradientManager
  63739. .addWithoutUpdate(svgElement, displayable);
  63740. this.clipPathManager.markUsed(displayable);
  63741. }
  63742. }
  63743. else if (!item.removed) {
  63744. for (var k = 0; k < item.count; k++) {
  63745. var displayable = newVisibleList[item.indices[k]];
  63746. prevSvgElement
  63747. = svgElement
  63748. = getTextSvgElement(displayable)
  63749. || getSvgElement(displayable)
  63750. || prevSvgElement;
  63751. this.gradientManager.markUsed(displayable);
  63752. this.gradientManager
  63753. .addWithoutUpdate(svgElement, displayable);
  63754. this.clipPathManager.markUsed(displayable);
  63755. }
  63756. }
  63757. }
  63758. this.gradientManager.removeUnused();
  63759. this.clipPathManager.removeUnused();
  63760. this._visibleList = newVisibleList;
  63761. },
  63762. _getDefs: function (isForceCreating) {
  63763. var svgRoot = this._svgRoot;
  63764. var defs = this._svgRoot.getElementsByTagName('defs');
  63765. if (defs.length === 0) {
  63766. // Not exist
  63767. if (isForceCreating) {
  63768. var defs = svgRoot.insertBefore(
  63769. createElement('defs'), // Create new tag
  63770. svgRoot.firstChild // Insert in the front of svg
  63771. );
  63772. if (!defs.contains) {
  63773. // IE doesn't support contains method
  63774. defs.contains = function (el) {
  63775. var children = defs.children;
  63776. if (!children) {
  63777. return false;
  63778. }
  63779. for (var i = children.length - 1; i >= 0; --i) {
  63780. if (children[i] === el) {
  63781. return true;
  63782. }
  63783. }
  63784. return false;
  63785. };
  63786. }
  63787. return defs;
  63788. }
  63789. else {
  63790. return null;
  63791. }
  63792. }
  63793. else {
  63794. return defs[0];
  63795. }
  63796. },
  63797. resize: function (width, height) {
  63798. var viewport = this._viewport;
  63799. // FIXME Why ?
  63800. viewport.style.display = 'none';
  63801. // Save input w/h
  63802. var opts = this._opts;
  63803. width != null && (opts.width = width);
  63804. height != null && (opts.height = height);
  63805. width = this._getSize(0);
  63806. height = this._getSize(1);
  63807. viewport.style.display = '';
  63808. if (this._width !== width && this._height !== height) {
  63809. this._width = width;
  63810. this._height = height;
  63811. var viewportStyle = viewport.style;
  63812. viewportStyle.width = width + 'px';
  63813. viewportStyle.height = height + 'px';
  63814. var svgRoot = this._svgRoot;
  63815. // Set width by 'svgRoot.width = width' is invalid
  63816. svgRoot.setAttribute('width', width);
  63817. svgRoot.setAttribute('height', height);
  63818. }
  63819. },
  63820. /**
  63821. * 获取绘图区域宽度
  63822. */
  63823. getWidth: function () {
  63824. return this._width;
  63825. },
  63826. /**
  63827. * 获取绘图区域高度
  63828. */
  63829. getHeight: function () {
  63830. return this._height;
  63831. },
  63832. _getSize: function (whIdx) {
  63833. var opts = this._opts;
  63834. var wh = ['width', 'height'][whIdx];
  63835. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  63836. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  63837. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  63838. if (opts[wh] != null && opts[wh] !== 'auto') {
  63839. return parseFloat(opts[wh]);
  63840. }
  63841. var root = this.root;
  63842. // IE8 does not support getComputedStyle, but it use VML.
  63843. var stl = document.defaultView.getComputedStyle(root);
  63844. return (
  63845. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  63846. - (parseInt10$2(stl[plt]) || 0)
  63847. - (parseInt10$2(stl[prb]) || 0)
  63848. ) | 0;
  63849. },
  63850. dispose: function () {
  63851. this.root.innerHTML = '';
  63852. this._svgRoot
  63853. = this._viewport
  63854. = this.storage
  63855. = null;
  63856. },
  63857. clear: function () {
  63858. if (this._viewport) {
  63859. this.root.removeChild(this._viewport);
  63860. }
  63861. },
  63862. pathToSvg: function () {
  63863. this.refresh();
  63864. var html = this._svgRoot.outerHTML;
  63865. return 'data:img/svg+xml;utf-8,' + unescape(html);
  63866. }
  63867. };
  63868. // Not supported methods
  63869. function createMethodNotSupport$1(method) {
  63870. return function () {
  63871. zrLog('In SVG mode painter not support method "' + method + '"');
  63872. };
  63873. }
  63874. // Unsuppoted methods
  63875. each$1([
  63876. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  63877. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  63878. 'toDataURL', 'pathToImage'
  63879. ], function (name) {
  63880. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  63881. });
  63882. registerPainter('svg', SVGPainter);
  63883. // Import all charts and components
  63884. exports.version = version;
  63885. exports.dependencies = dependencies;
  63886. exports.PRIORITY = PRIORITY;
  63887. exports.init = init;
  63888. exports.connect = connect;
  63889. exports.disConnect = disConnect;
  63890. exports.disconnect = disconnect;
  63891. exports.dispose = dispose;
  63892. exports.getInstanceByDom = getInstanceByDom;
  63893. exports.getInstanceById = getInstanceById;
  63894. exports.registerTheme = registerTheme;
  63895. exports.registerPreprocessor = registerPreprocessor;
  63896. exports.registerProcessor = registerProcessor;
  63897. exports.registerPostUpdate = registerPostUpdate;
  63898. exports.registerAction = registerAction;
  63899. exports.registerCoordinateSystem = registerCoordinateSystem;
  63900. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  63901. exports.registerLayout = registerLayout;
  63902. exports.registerVisual = registerVisual;
  63903. exports.registerLoading = registerLoading;
  63904. exports.extendComponentModel = extendComponentModel;
  63905. exports.extendComponentView = extendComponentView;
  63906. exports.extendSeriesModel = extendSeriesModel;
  63907. exports.extendChartView = extendChartView;
  63908. exports.setCanvasCreator = setCanvasCreator;
  63909. exports.registerMap = registerMap;
  63910. exports.getMap = getMap;
  63911. exports.dataTool = dataTool;
  63912. exports.zrender = zrender;
  63913. exports.graphic = graphic;
  63914. exports.number = number;
  63915. exports.format = format;
  63916. exports.throttle = throttle;
  63917. exports.helper = helper;
  63918. exports.matrix = matrix;
  63919. exports.vector = vector;
  63920. exports.color = color;
  63921. exports.util = ecUtil;
  63922. exports.List = List;
  63923. exports.Model = Model;
  63924. exports.Axis = Axis;
  63925. exports.env = env$1;
  63926. exports.parseGeoJson = parseGeoJson;
  63927. })));
  63928. //# sourceMappingURL=echarts.js.map