echarts.js 2.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. var env = {};
  59. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  60. // In Weixin Application
  61. env = {
  62. browser: {},
  63. os: {},
  64. node: false,
  65. wxa: true, // Weixin Application
  66. canvasSupported: true,
  67. svgSupported: false,
  68. touchEventsSupported: true,
  69. domSupported: false
  70. };
  71. }
  72. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  73. // In worker
  74. env = {
  75. browser: {},
  76. os: {},
  77. node: false,
  78. worker: true,
  79. canvasSupported: true,
  80. domSupported: false
  81. };
  82. }
  83. else if (typeof navigator === 'undefined') {
  84. // In node
  85. env = {
  86. browser: {},
  87. os: {},
  88. node: true,
  89. worker: false,
  90. // Assume canvas is supported
  91. canvasSupported: true,
  92. svgSupported: true,
  93. domSupported: false
  94. };
  95. }
  96. else {
  97. env = detect(navigator.userAgent);
  98. }
  99. var env$1 = env;
  100. // Zepto.js
  101. // (c) 2010-2013 Thomas Fuchs
  102. // Zepto.js may be freely distributed under the MIT license.
  103. function detect(ua) {
  104. var os = {};
  105. var browser = {};
  106. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  107. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  108. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  109. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  110. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  111. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  112. // var touchpad = webos && ua.match(/TouchPad/);
  113. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  114. // var silk = ua.match(/Silk\/([\d._]+)/);
  115. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  116. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  117. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  118. // var playbook = ua.match(/PlayBook/);
  119. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  120. var firefox = ua.match(/Firefox\/([\d.]+)/);
  121. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  122. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  123. var ie = ua.match(/MSIE\s([\d.]+)/)
  124. // IE 11 Trident/7.0; rv:11.0
  125. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  126. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  127. var weChat = (/micromessenger/i).test(ua);
  128. // Todo: clean this up with a better OS/browser seperation:
  129. // - discern (more) between multiple browsers on android
  130. // - decide if kindle fire in silk mode is android or not
  131. // - Firefox on Android doesn't specify the Android version
  132. // - possibly devide in os, device and browser hashes
  133. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  134. // if (android) os.android = true, os.version = android[2];
  135. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  136. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  137. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  138. // if (webos) os.webos = true, os.version = webos[2];
  139. // if (touchpad) os.touchpad = true;
  140. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  141. // if (bb10) os.bb10 = true, os.version = bb10[2];
  142. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  143. // if (playbook) browser.playbook = true;
  144. // if (kindle) os.kindle = true, os.version = kindle[1];
  145. // if (silk) browser.silk = true, browser.version = silk[1];
  146. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  147. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  148. if (firefox) {
  149. browser.firefox = true;
  150. browser.version = firefox[1];
  151. }
  152. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  153. // if (webview) browser.webview = true;
  154. if (ie) {
  155. browser.ie = true;
  156. browser.version = ie[1];
  157. }
  158. if (edge) {
  159. browser.edge = true;
  160. browser.version = edge[1];
  161. }
  162. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  163. // not be set on win phone. So we do not consider Win Phone.
  164. if (weChat) {
  165. browser.weChat = true;
  166. }
  167. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  168. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  169. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  170. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  171. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  172. return {
  173. browser: browser,
  174. os: os,
  175. node: false,
  176. // 原生canvas支持,改极端点了
  177. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  178. canvasSupported: !!document.createElement('canvas').getContext,
  179. svgSupported: typeof SVGRect !== 'undefined',
  180. // works on most browsers
  181. // IE10/11 does not support touch event, and MS Edge supports them but not by
  182. // default, so we dont check navigator.maxTouchPoints for them here.
  183. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  184. // <http://caniuse.com/#search=pointer%20event>.
  185. pointerEventsSupported: 'onpointerdown' in window
  186. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  187. // events currently. So we dont use that on other browsers unless tested sufficiently.
  188. // Although IE 10 supports pointer event, it use old style and is different from the
  189. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  190. && (browser.edge || (browser.ie && browser.version >= 11)),
  191. // passiveSupported: detectPassiveSupport()
  192. domSupported: typeof document !== 'undefined'
  193. };
  194. }
  195. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  196. // function detectPassiveSupport() {
  197. // // Test via a getter in the options object to see if the passive property is accessed
  198. // var supportsPassive = false;
  199. // try {
  200. // var opts = Object.defineProperty({}, 'passive', {
  201. // get: function() {
  202. // supportsPassive = true;
  203. // }
  204. // });
  205. // window.addEventListener('testPassive', function() {}, opts);
  206. // } catch (e) {
  207. // }
  208. // return supportsPassive;
  209. // }
  210. /**
  211. * @module zrender/core/util
  212. */
  213. // 用于处理merge时无法遍历Date等对象的问题
  214. var BUILTIN_OBJECT = {
  215. '[object Function]': 1,
  216. '[object RegExp]': 1,
  217. '[object Date]': 1,
  218. '[object Error]': 1,
  219. '[object CanvasGradient]': 1,
  220. '[object CanvasPattern]': 1,
  221. // For node-canvas
  222. '[object Image]': 1,
  223. '[object Canvas]': 1
  224. };
  225. var TYPED_ARRAY = {
  226. '[object Int8Array]': 1,
  227. '[object Uint8Array]': 1,
  228. '[object Uint8ClampedArray]': 1,
  229. '[object Int16Array]': 1,
  230. '[object Uint16Array]': 1,
  231. '[object Int32Array]': 1,
  232. '[object Uint32Array]': 1,
  233. '[object Float32Array]': 1,
  234. '[object Float64Array]': 1
  235. };
  236. var objToString = Object.prototype.toString;
  237. var arrayProto = Array.prototype;
  238. var nativeForEach = arrayProto.forEach;
  239. var nativeFilter = arrayProto.filter;
  240. var nativeSlice = arrayProto.slice;
  241. var nativeMap = arrayProto.map;
  242. var nativeReduce = arrayProto.reduce;
  243. // Avoid assign to an exported variable, for transforming to cjs.
  244. var methods = {};
  245. function $override(name, fn) {
  246. // Clear ctx instance for different environment
  247. if (name === 'createCanvas') {
  248. _ctx = null;
  249. }
  250. methods[name] = fn;
  251. }
  252. /**
  253. * Those data types can be cloned:
  254. * Plain object, Array, TypedArray, number, string, null, undefined.
  255. * Those data types will be assgined using the orginal data:
  256. * BUILTIN_OBJECT
  257. * Instance of user defined class will be cloned to a plain object, without
  258. * properties in prototype.
  259. * Other data types is not supported (not sure what will happen).
  260. *
  261. * Caution: do not support clone Date, for performance consideration.
  262. * (There might be a large number of date in `series.data`).
  263. * So date should not be modified in and out of echarts.
  264. *
  265. * @param {*} source
  266. * @return {*} new
  267. */
  268. function clone(source) {
  269. if (source == null || typeof source !== 'object') {
  270. return source;
  271. }
  272. var result = source;
  273. var typeStr = objToString.call(source);
  274. if (typeStr === '[object Array]') {
  275. if (!isPrimitive(source)) {
  276. result = [];
  277. for (var i = 0, len = source.length; i < len; i++) {
  278. result[i] = clone(source[i]);
  279. }
  280. }
  281. }
  282. else if (TYPED_ARRAY[typeStr]) {
  283. if (!isPrimitive(source)) {
  284. var Ctor = source.constructor;
  285. if (source.constructor.from) {
  286. result = Ctor.from(source);
  287. }
  288. else {
  289. result = new Ctor(source.length);
  290. for (var i = 0, len = source.length; i < len; i++) {
  291. result[i] = clone(source[i]);
  292. }
  293. }
  294. }
  295. }
  296. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  297. result = {};
  298. for (var key in source) {
  299. if (source.hasOwnProperty(key)) {
  300. result[key] = clone(source[key]);
  301. }
  302. }
  303. }
  304. return result;
  305. }
  306. /**
  307. * @memberOf module:zrender/core/util
  308. * @param {*} target
  309. * @param {*} source
  310. * @param {boolean} [overwrite=false]
  311. */
  312. function merge(target, source, overwrite) {
  313. // We should escapse that source is string
  314. // and enter for ... in ...
  315. if (!isObject$1(source) || !isObject$1(target)) {
  316. return overwrite ? clone(source) : target;
  317. }
  318. for (var key in source) {
  319. if (source.hasOwnProperty(key)) {
  320. var targetProp = target[key];
  321. var sourceProp = source[key];
  322. if (isObject$1(sourceProp)
  323. && isObject$1(targetProp)
  324. && !isArray(sourceProp)
  325. && !isArray(targetProp)
  326. && !isDom(sourceProp)
  327. && !isDom(targetProp)
  328. && !isBuiltInObject(sourceProp)
  329. && !isBuiltInObject(targetProp)
  330. && !isPrimitive(sourceProp)
  331. && !isPrimitive(targetProp)
  332. ) {
  333. // 如果需要递归覆盖,就递归调用merge
  334. merge(targetProp, sourceProp, overwrite);
  335. }
  336. else if (overwrite || !(key in target)) {
  337. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  338. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  339. target[key] = clone(source[key], true);
  340. }
  341. }
  342. }
  343. return target;
  344. }
  345. /**
  346. * @param {Array} targetAndSources The first item is target, and the rests are source.
  347. * @param {boolean} [overwrite=false]
  348. * @return {*} target
  349. */
  350. function mergeAll(targetAndSources, overwrite) {
  351. var result = targetAndSources[0];
  352. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  353. result = merge(result, targetAndSources[i], overwrite);
  354. }
  355. return result;
  356. }
  357. /**
  358. * @param {*} target
  359. * @param {*} source
  360. * @memberOf module:zrender/core/util
  361. */
  362. function extend(target, source) {
  363. for (var key in source) {
  364. if (source.hasOwnProperty(key)) {
  365. target[key] = source[key];
  366. }
  367. }
  368. return target;
  369. }
  370. /**
  371. * @param {*} target
  372. * @param {*} source
  373. * @param {boolean} [overlay=false]
  374. * @memberOf module:zrender/core/util
  375. */
  376. function defaults(target, source, overlay) {
  377. for (var key in source) {
  378. if (source.hasOwnProperty(key)
  379. && (overlay ? source[key] != null : target[key] == null)
  380. ) {
  381. target[key] = source[key];
  382. }
  383. }
  384. return target;
  385. }
  386. var createCanvas = function () {
  387. return methods.createCanvas();
  388. };
  389. methods.createCanvas = function () {
  390. return document.createElement('canvas');
  391. };
  392. // FIXME
  393. var _ctx;
  394. function getContext() {
  395. if (!_ctx) {
  396. // Use util.createCanvas instead of createCanvas
  397. // because createCanvas may be overwritten in different environment
  398. _ctx = createCanvas().getContext('2d');
  399. }
  400. return _ctx;
  401. }
  402. /**
  403. * 查询数组中元素的index
  404. * @memberOf module:zrender/core/util
  405. */
  406. function indexOf(array, value) {
  407. if (array) {
  408. if (array.indexOf) {
  409. return array.indexOf(value);
  410. }
  411. for (var i = 0, len = array.length; i < len; i++) {
  412. if (array[i] === value) {
  413. return i;
  414. }
  415. }
  416. }
  417. return -1;
  418. }
  419. /**
  420. * 构造类继承关系
  421. *
  422. * @memberOf module:zrender/core/util
  423. * @param {Function} clazz 源类
  424. * @param {Function} baseClazz 基类
  425. */
  426. function inherits(clazz, baseClazz) {
  427. var clazzPrototype = clazz.prototype;
  428. function F() {}
  429. F.prototype = baseClazz.prototype;
  430. clazz.prototype = new F();
  431. for (var prop in clazzPrototype) {
  432. clazz.prototype[prop] = clazzPrototype[prop];
  433. }
  434. clazz.prototype.constructor = clazz;
  435. clazz.superClass = baseClazz;
  436. }
  437. /**
  438. * @memberOf module:zrender/core/util
  439. * @param {Object|Function} target
  440. * @param {Object|Function} sorce
  441. * @param {boolean} overlay
  442. */
  443. function mixin(target, source, overlay) {
  444. target = 'prototype' in target ? target.prototype : target;
  445. source = 'prototype' in source ? source.prototype : source;
  446. defaults(target, source, overlay);
  447. }
  448. /**
  449. * Consider typed array.
  450. * @param {Array|TypedArray} data
  451. */
  452. function isArrayLike(data) {
  453. if (!data) {
  454. return;
  455. }
  456. if (typeof data === 'string') {
  457. return false;
  458. }
  459. return typeof data.length === 'number';
  460. }
  461. /**
  462. * 数组或对象遍历
  463. * @memberOf module:zrender/core/util
  464. * @param {Object|Array} obj
  465. * @param {Function} cb
  466. * @param {*} [context]
  467. */
  468. function each$1(obj, cb, context) {
  469. if (!(obj && cb)) {
  470. return;
  471. }
  472. if (obj.forEach && obj.forEach === nativeForEach) {
  473. obj.forEach(cb, context);
  474. }
  475. else if (obj.length === +obj.length) {
  476. for (var i = 0, len = obj.length; i < len; i++) {
  477. cb.call(context, obj[i], i, obj);
  478. }
  479. }
  480. else {
  481. for (var key in obj) {
  482. if (obj.hasOwnProperty(key)) {
  483. cb.call(context, obj[key], key, obj);
  484. }
  485. }
  486. }
  487. }
  488. /**
  489. * 数组映射
  490. * @memberOf module:zrender/core/util
  491. * @param {Array} obj
  492. * @param {Function} cb
  493. * @param {*} [context]
  494. * @return {Array}
  495. */
  496. function map(obj, cb, context) {
  497. if (!(obj && cb)) {
  498. return;
  499. }
  500. if (obj.map && obj.map === nativeMap) {
  501. return obj.map(cb, context);
  502. }
  503. else {
  504. var result = [];
  505. for (var i = 0, len = obj.length; i < len; i++) {
  506. result.push(cb.call(context, obj[i], i, obj));
  507. }
  508. return result;
  509. }
  510. }
  511. /**
  512. * @memberOf module:zrender/core/util
  513. * @param {Array} obj
  514. * @param {Function} cb
  515. * @param {Object} [memo]
  516. * @param {*} [context]
  517. * @return {Array}
  518. */
  519. function reduce(obj, cb, memo, context) {
  520. if (!(obj && cb)) {
  521. return;
  522. }
  523. if (obj.reduce && obj.reduce === nativeReduce) {
  524. return obj.reduce(cb, memo, context);
  525. }
  526. else {
  527. for (var i = 0, len = obj.length; i < len; i++) {
  528. memo = cb.call(context, memo, obj[i], i, obj);
  529. }
  530. return memo;
  531. }
  532. }
  533. /**
  534. * 数组过滤
  535. * @memberOf module:zrender/core/util
  536. * @param {Array} obj
  537. * @param {Function} cb
  538. * @param {*} [context]
  539. * @return {Array}
  540. */
  541. function filter(obj, cb, context) {
  542. if (!(obj && cb)) {
  543. return;
  544. }
  545. if (obj.filter && obj.filter === nativeFilter) {
  546. return obj.filter(cb, context);
  547. }
  548. else {
  549. var result = [];
  550. for (var i = 0, len = obj.length; i < len; i++) {
  551. if (cb.call(context, obj[i], i, obj)) {
  552. result.push(obj[i]);
  553. }
  554. }
  555. return result;
  556. }
  557. }
  558. /**
  559. * 数组项查找
  560. * @memberOf module:zrender/core/util
  561. * @param {Array} obj
  562. * @param {Function} cb
  563. * @param {*} [context]
  564. * @return {*}
  565. */
  566. function find(obj, cb, context) {
  567. if (!(obj && cb)) {
  568. return;
  569. }
  570. for (var i = 0, len = obj.length; i < len; i++) {
  571. if (cb.call(context, obj[i], i, obj)) {
  572. return obj[i];
  573. }
  574. }
  575. }
  576. /**
  577. * @memberOf module:zrender/core/util
  578. * @param {Function} func
  579. * @param {*} context
  580. * @return {Function}
  581. */
  582. function bind(func, context) {
  583. var args = nativeSlice.call(arguments, 2);
  584. return function () {
  585. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  586. };
  587. }
  588. /**
  589. * @memberOf module:zrender/core/util
  590. * @param {Function} func
  591. * @return {Function}
  592. */
  593. function curry(func) {
  594. var args = nativeSlice.call(arguments, 1);
  595. return function () {
  596. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  597. };
  598. }
  599. /**
  600. * @memberOf module:zrender/core/util
  601. * @param {*} value
  602. * @return {boolean}
  603. */
  604. function isArray(value) {
  605. return objToString.call(value) === '[object Array]';
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isFunction$1(value) {
  613. return typeof value === 'function';
  614. }
  615. /**
  616. * @memberOf module:zrender/core/util
  617. * @param {*} value
  618. * @return {boolean}
  619. */
  620. function isString(value) {
  621. return objToString.call(value) === '[object String]';
  622. }
  623. /**
  624. * @memberOf module:zrender/core/util
  625. * @param {*} value
  626. * @return {boolean}
  627. */
  628. function isObject$1(value) {
  629. // Avoid a V8 JIT bug in Chrome 19-20.
  630. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  631. var type = typeof value;
  632. return type === 'function' || (!!value && type === 'object');
  633. }
  634. /**
  635. * @memberOf module:zrender/core/util
  636. * @param {*} value
  637. * @return {boolean}
  638. */
  639. function isBuiltInObject(value) {
  640. return !!BUILTIN_OBJECT[objToString.call(value)];
  641. }
  642. /**
  643. * @memberOf module:zrender/core/util
  644. * @param {*} value
  645. * @return {boolean}
  646. */
  647. function isTypedArray(value) {
  648. return !!TYPED_ARRAY[objToString.call(value)];
  649. }
  650. /**
  651. * @memberOf module:zrender/core/util
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function isDom(value) {
  656. return typeof value === 'object'
  657. && typeof value.nodeType === 'number'
  658. && typeof value.ownerDocument === 'object';
  659. }
  660. /**
  661. * Whether is exactly NaN. Notice isNaN('a') returns true.
  662. * @param {*} value
  663. * @return {boolean}
  664. */
  665. function eqNaN(value) {
  666. return value !== value;
  667. }
  668. /**
  669. * If value1 is not null, then return value1, otherwise judget rest of values.
  670. * Low performance.
  671. * @memberOf module:zrender/core/util
  672. * @return {*} Final value
  673. */
  674. function retrieve(values) {
  675. for (var i = 0, len = arguments.length; i < len; i++) {
  676. if (arguments[i] != null) {
  677. return arguments[i];
  678. }
  679. }
  680. }
  681. function retrieve2(value0, value1) {
  682. return value0 != null
  683. ? value0
  684. : value1;
  685. }
  686. function retrieve3(value0, value1, value2) {
  687. return value0 != null
  688. ? value0
  689. : value1 != null
  690. ? value1
  691. : value2;
  692. }
  693. /**
  694. * @memberOf module:zrender/core/util
  695. * @param {Array} arr
  696. * @param {number} startIndex
  697. * @param {number} endIndex
  698. * @return {Array}
  699. */
  700. function slice() {
  701. return Function.call.apply(nativeSlice, arguments);
  702. }
  703. /**
  704. * Normalize css liked array configuration
  705. * e.g.
  706. * 3 => [3, 3, 3, 3]
  707. * [4, 2] => [4, 2, 4, 2]
  708. * [4, 3, 2] => [4, 3, 2, 3]
  709. * @param {number|Array.<number>} val
  710. * @return {Array.<number>}
  711. */
  712. function normalizeCssArray(val) {
  713. if (typeof (val) === 'number') {
  714. return [val, val, val, val];
  715. }
  716. var len = val.length;
  717. if (len === 2) {
  718. // vertical | horizontal
  719. return [val[0], val[1], val[0], val[1]];
  720. }
  721. else if (len === 3) {
  722. // top | horizontal | bottom
  723. return [val[0], val[1], val[2], val[1]];
  724. }
  725. return val;
  726. }
  727. /**
  728. * @memberOf module:zrender/core/util
  729. * @param {boolean} condition
  730. * @param {string} message
  731. */
  732. function assert$1(condition, message) {
  733. if (!condition) {
  734. throw new Error(message);
  735. }
  736. }
  737. /**
  738. * @memberOf module:zrender/core/util
  739. * @param {string} str string to be trimed
  740. * @return {string} trimed string
  741. */
  742. function trim(str) {
  743. if (str == null) {
  744. return null;
  745. }
  746. else if (typeof str.trim === 'function') {
  747. return str.trim();
  748. }
  749. else {
  750. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  751. }
  752. }
  753. var primitiveKey = '__ec_primitive__';
  754. /**
  755. * Set an object as primitive to be ignored traversing children in clone or merge
  756. */
  757. function setAsPrimitive(obj) {
  758. obj[primitiveKey] = true;
  759. }
  760. function isPrimitive(obj) {
  761. return obj[primitiveKey];
  762. }
  763. /**
  764. * @constructor
  765. * @param {Object} obj Only apply `ownProperty`.
  766. */
  767. function HashMap(obj) {
  768. var isArr = isArray(obj);
  769. // Key should not be set on this, otherwise
  770. // methods get/set/... may be overrided.
  771. this.data = {};
  772. var thisMap = this;
  773. (obj instanceof HashMap)
  774. ? obj.each(visit)
  775. : (obj && each$1(obj, visit));
  776. function visit(value, key) {
  777. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  778. }
  779. }
  780. HashMap.prototype = {
  781. constructor: HashMap,
  782. // Do not provide `has` method to avoid defining what is `has`.
  783. // (We usually treat `null` and `undefined` as the same, different
  784. // from ES6 Map).
  785. get: function (key) {
  786. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  787. },
  788. set: function (key, value) {
  789. // Comparing with invocation chaining, `return value` is more commonly
  790. // used in this case: `var someVal = map.set('a', genVal());`
  791. return (this.data[key] = value);
  792. },
  793. // Although util.each can be performed on this hashMap directly, user
  794. // should not use the exposed keys, who are prefixed.
  795. each: function (cb, context) {
  796. context !== void 0 && (cb = bind(cb, context));
  797. for (var key in this.data) {
  798. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  799. }
  800. },
  801. // Do not use this method if performance sensitive.
  802. removeKey: function (key) {
  803. delete this.data[key];
  804. }
  805. };
  806. function createHashMap(obj) {
  807. return new HashMap(obj);
  808. }
  809. function concatArray(a, b) {
  810. var newArray = new a.constructor(a.length + b.length);
  811. for (var i = 0; i < a.length; i++) {
  812. newArray[i] = a[i];
  813. }
  814. var offset = a.length;
  815. for (i = 0; i < b.length; i++) {
  816. newArray[i + offset] = b[i];
  817. }
  818. return newArray;
  819. }
  820. function noop() {}
  821. var zrUtil = (Object.freeze || Object)({
  822. $override: $override,
  823. clone: clone,
  824. merge: merge,
  825. mergeAll: mergeAll,
  826. extend: extend,
  827. defaults: defaults,
  828. createCanvas: createCanvas,
  829. getContext: getContext,
  830. indexOf: indexOf,
  831. inherits: inherits,
  832. mixin: mixin,
  833. isArrayLike: isArrayLike,
  834. each: each$1,
  835. map: map,
  836. reduce: reduce,
  837. filter: filter,
  838. find: find,
  839. bind: bind,
  840. curry: curry,
  841. isArray: isArray,
  842. isFunction: isFunction$1,
  843. isString: isString,
  844. isObject: isObject$1,
  845. isBuiltInObject: isBuiltInObject,
  846. isTypedArray: isTypedArray,
  847. isDom: isDom,
  848. eqNaN: eqNaN,
  849. retrieve: retrieve,
  850. retrieve2: retrieve2,
  851. retrieve3: retrieve3,
  852. slice: slice,
  853. normalizeCssArray: normalizeCssArray,
  854. assert: assert$1,
  855. trim: trim,
  856. setAsPrimitive: setAsPrimitive,
  857. isPrimitive: isPrimitive,
  858. createHashMap: createHashMap,
  859. concatArray: concatArray,
  860. noop: noop
  861. });
  862. var ArrayCtor = typeof Float32Array === 'undefined'
  863. ? Array
  864. : Float32Array;
  865. /**
  866. * 创建一个向量
  867. * @param {number} [x=0]
  868. * @param {number} [y=0]
  869. * @return {Vector2}
  870. */
  871. function create(x, y) {
  872. var out = new ArrayCtor(2);
  873. if (x == null) {
  874. x = 0;
  875. }
  876. if (y == null) {
  877. y = 0;
  878. }
  879. out[0] = x;
  880. out[1] = y;
  881. return out;
  882. }
  883. /**
  884. * 复制向量数据
  885. * @param {Vector2} out
  886. * @param {Vector2} v
  887. * @return {Vector2}
  888. */
  889. function copy(out, v) {
  890. out[0] = v[0];
  891. out[1] = v[1];
  892. return out;
  893. }
  894. /**
  895. * 克隆一个向量
  896. * @param {Vector2} v
  897. * @return {Vector2}
  898. */
  899. function clone$1(v) {
  900. var out = new ArrayCtor(2);
  901. out[0] = v[0];
  902. out[1] = v[1];
  903. return out;
  904. }
  905. /**
  906. * 设置向量的两个项
  907. * @param {Vector2} out
  908. * @param {number} a
  909. * @param {number} b
  910. * @return {Vector2} 结果
  911. */
  912. function set(out, a, b) {
  913. out[0] = a;
  914. out[1] = b;
  915. return out;
  916. }
  917. /**
  918. * 向量相加
  919. * @param {Vector2} out
  920. * @param {Vector2} v1
  921. * @param {Vector2} v2
  922. */
  923. function add(out, v1, v2) {
  924. out[0] = v1[0] + v2[0];
  925. out[1] = v1[1] + v2[1];
  926. return out;
  927. }
  928. /**
  929. * 向量缩放后相加
  930. * @param {Vector2} out
  931. * @param {Vector2} v1
  932. * @param {Vector2} v2
  933. * @param {number} a
  934. */
  935. function scaleAndAdd(out, v1, v2, a) {
  936. out[0] = v1[0] + v2[0] * a;
  937. out[1] = v1[1] + v2[1] * a;
  938. return out;
  939. }
  940. /**
  941. * 向量相减
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. */
  946. function sub(out, v1, v2) {
  947. out[0] = v1[0] - v2[0];
  948. out[1] = v1[1] - v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量长度
  953. * @param {Vector2} v
  954. * @return {number}
  955. */
  956. function len(v) {
  957. return Math.sqrt(lenSquare(v));
  958. }
  959. var length = len; // jshint ignore:line
  960. /**
  961. * 向量长度平方
  962. * @param {Vector2} v
  963. * @return {number}
  964. */
  965. function lenSquare(v) {
  966. return v[0] * v[0] + v[1] * v[1];
  967. }
  968. var lengthSquare = lenSquare;
  969. /**
  970. * 向量乘法
  971. * @param {Vector2} out
  972. * @param {Vector2} v1
  973. * @param {Vector2} v2
  974. */
  975. function mul(out, v1, v2) {
  976. out[0] = v1[0] * v2[0];
  977. out[1] = v1[1] * v2[1];
  978. return out;
  979. }
  980. /**
  981. * 向量除法
  982. * @param {Vector2} out
  983. * @param {Vector2} v1
  984. * @param {Vector2} v2
  985. */
  986. function div(out, v1, v2) {
  987. out[0] = v1[0] / v2[0];
  988. out[1] = v1[1] / v2[1];
  989. return out;
  990. }
  991. /**
  992. * 向量点乘
  993. * @param {Vector2} v1
  994. * @param {Vector2} v2
  995. * @return {number}
  996. */
  997. function dot(v1, v2) {
  998. return v1[0] * v2[0] + v1[1] * v2[1];
  999. }
  1000. /**
  1001. * 向量缩放
  1002. * @param {Vector2} out
  1003. * @param {Vector2} v
  1004. * @param {number} s
  1005. */
  1006. function scale(out, v, s) {
  1007. out[0] = v[0] * s;
  1008. out[1] = v[1] * s;
  1009. return out;
  1010. }
  1011. /**
  1012. * 向量归一化
  1013. * @param {Vector2} out
  1014. * @param {Vector2} v
  1015. */
  1016. function normalize(out, v) {
  1017. var d = len(v);
  1018. if (d === 0) {
  1019. out[0] = 0;
  1020. out[1] = 0;
  1021. }
  1022. else {
  1023. out[0] = v[0] / d;
  1024. out[1] = v[1] / d;
  1025. }
  1026. return out;
  1027. }
  1028. /**
  1029. * 计算向量间距离
  1030. * @param {Vector2} v1
  1031. * @param {Vector2} v2
  1032. * @return {number}
  1033. */
  1034. function distance(v1, v2) {
  1035. return Math.sqrt(
  1036. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1037. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1038. );
  1039. }
  1040. var dist = distance;
  1041. /**
  1042. * 向量距离平方
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. * @return {number}
  1046. */
  1047. function distanceSquare(v1, v2) {
  1048. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1049. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1050. }
  1051. var distSquare = distanceSquare;
  1052. /**
  1053. * 求负向量
  1054. * @param {Vector2} out
  1055. * @param {Vector2} v
  1056. */
  1057. function negate(out, v) {
  1058. out[0] = -v[0];
  1059. out[1] = -v[1];
  1060. return out;
  1061. }
  1062. /**
  1063. * 插值两个点
  1064. * @param {Vector2} out
  1065. * @param {Vector2} v1
  1066. * @param {Vector2} v2
  1067. * @param {number} t
  1068. */
  1069. function lerp(out, v1, v2, t) {
  1070. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1071. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 矩阵左乘向量
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v
  1078. * @param {Vector2} m
  1079. */
  1080. function applyTransform(out, v, m) {
  1081. var x = v[0];
  1082. var y = v[1];
  1083. out[0] = m[0] * x + m[2] * y + m[4];
  1084. out[1] = m[1] * x + m[3] * y + m[5];
  1085. return out;
  1086. }
  1087. /**
  1088. * 求两个向量最小值
  1089. * @param {Vector2} out
  1090. * @param {Vector2} v1
  1091. * @param {Vector2} v2
  1092. */
  1093. function min(out, v1, v2) {
  1094. out[0] = Math.min(v1[0], v2[0]);
  1095. out[1] = Math.min(v1[1], v2[1]);
  1096. return out;
  1097. }
  1098. /**
  1099. * 求两个向量最大值
  1100. * @param {Vector2} out
  1101. * @param {Vector2} v1
  1102. * @param {Vector2} v2
  1103. */
  1104. function max(out, v1, v2) {
  1105. out[0] = Math.max(v1[0], v2[0]);
  1106. out[1] = Math.max(v1[1], v2[1]);
  1107. return out;
  1108. }
  1109. var vector = (Object.freeze || Object)({
  1110. create: create,
  1111. copy: copy,
  1112. clone: clone$1,
  1113. set: set,
  1114. add: add,
  1115. scaleAndAdd: scaleAndAdd,
  1116. sub: sub,
  1117. len: len,
  1118. length: length,
  1119. lenSquare: lenSquare,
  1120. lengthSquare: lengthSquare,
  1121. mul: mul,
  1122. div: div,
  1123. dot: dot,
  1124. scale: scale,
  1125. normalize: normalize,
  1126. distance: distance,
  1127. dist: dist,
  1128. distanceSquare: distanceSquare,
  1129. distSquare: distSquare,
  1130. negate: negate,
  1131. lerp: lerp,
  1132. applyTransform: applyTransform,
  1133. min: min,
  1134. max: max
  1135. });
  1136. // TODO Draggable for group
  1137. // FIXME Draggable on element which has parent rotation or scale
  1138. function Draggable() {
  1139. this.on('mousedown', this._dragStart, this);
  1140. this.on('mousemove', this._drag, this);
  1141. this.on('mouseup', this._dragEnd, this);
  1142. this.on('globalout', this._dragEnd, this);
  1143. // this._dropTarget = null;
  1144. // this._draggingTarget = null;
  1145. // this._x = 0;
  1146. // this._y = 0;
  1147. }
  1148. Draggable.prototype = {
  1149. constructor: Draggable,
  1150. _dragStart: function (e) {
  1151. var draggingTarget = e.target;
  1152. if (draggingTarget && draggingTarget.draggable) {
  1153. this._draggingTarget = draggingTarget;
  1154. draggingTarget.dragging = true;
  1155. this._x = e.offsetX;
  1156. this._y = e.offsetY;
  1157. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1158. }
  1159. },
  1160. _drag: function (e) {
  1161. var draggingTarget = this._draggingTarget;
  1162. if (draggingTarget) {
  1163. var x = e.offsetX;
  1164. var y = e.offsetY;
  1165. var dx = x - this._x;
  1166. var dy = y - this._y;
  1167. this._x = x;
  1168. this._y = y;
  1169. draggingTarget.drift(dx, dy, e);
  1170. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1171. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1172. var lastDropTarget = this._dropTarget;
  1173. this._dropTarget = dropTarget;
  1174. if (draggingTarget !== dropTarget) {
  1175. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1176. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1177. }
  1178. if (dropTarget && dropTarget !== lastDropTarget) {
  1179. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1180. }
  1181. }
  1182. }
  1183. },
  1184. _dragEnd: function (e) {
  1185. var draggingTarget = this._draggingTarget;
  1186. if (draggingTarget) {
  1187. draggingTarget.dragging = false;
  1188. }
  1189. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1190. if (this._dropTarget) {
  1191. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1192. }
  1193. this._draggingTarget = null;
  1194. this._dropTarget = null;
  1195. }
  1196. };
  1197. function param(target, e) {
  1198. return {target: target, topTarget: e && e.topTarget};
  1199. }
  1200. /**
  1201. * Event Mixin
  1202. * @module zrender/mixin/Eventful
  1203. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1204. * pissang (https://www.github.com/pissang)
  1205. */
  1206. var arrySlice = Array.prototype.slice;
  1207. /**
  1208. * Event dispatcher.
  1209. *
  1210. * @alias module:zrender/mixin/Eventful
  1211. * @constructor
  1212. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1213. * `eventProcessor.xxx` called.
  1214. * @param {Function} [eventProcessor.normalizeQuery]
  1215. * param: {string|Object} Raw query.
  1216. * return: {string|Object} Normalized query.
  1217. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1218. * if it returns `true`.
  1219. * param: {string} eventType
  1220. * param: {string|Object} query
  1221. * return: {boolean}
  1222. * @param {Function} [eventProcessor.afterTrigger] Call after all handlers called.
  1223. * param: {string} eventType
  1224. */
  1225. var Eventful = function (eventProcessor) {
  1226. this._$handlers = {};
  1227. this._$eventProcessor = eventProcessor;
  1228. };
  1229. Eventful.prototype = {
  1230. constructor: Eventful,
  1231. /**
  1232. * The handler can only be triggered once, then removed.
  1233. *
  1234. * @param {string} event The event name.
  1235. * @param {string|Object} [query] Condition used on event filter.
  1236. * @param {Function} handler The event handler.
  1237. * @param {Object} context
  1238. */
  1239. one: function (event, query, handler, context) {
  1240. return on(this, event, query, handler, context, true);
  1241. },
  1242. /**
  1243. * Bind a handler.
  1244. *
  1245. * @param {string} event The event name.
  1246. * @param {string|Object} [query] Condition used on event filter.
  1247. * @param {Function} handler The event handler.
  1248. * @param {Object} [context]
  1249. */
  1250. on: function (event, query, handler, context) {
  1251. return on(this, event, query, handler, context, false);
  1252. },
  1253. /**
  1254. * Whether any handler has bound.
  1255. *
  1256. * @param {string} event
  1257. * @return {boolean}
  1258. */
  1259. isSilent: function (event) {
  1260. var _h = this._$handlers;
  1261. return !_h[event] || !_h[event].length;
  1262. },
  1263. /**
  1264. * Unbind a event.
  1265. *
  1266. * @param {string} event The event name.
  1267. * @param {Function} [handler] The event handler.
  1268. */
  1269. off: function (event, handler) {
  1270. var _h = this._$handlers;
  1271. if (!event) {
  1272. this._$handlers = {};
  1273. return this;
  1274. }
  1275. if (handler) {
  1276. if (_h[event]) {
  1277. var newList = [];
  1278. for (var i = 0, l = _h[event].length; i < l; i++) {
  1279. if (_h[event][i].h !== handler) {
  1280. newList.push(_h[event][i]);
  1281. }
  1282. }
  1283. _h[event] = newList;
  1284. }
  1285. if (_h[event] && _h[event].length === 0) {
  1286. delete _h[event];
  1287. }
  1288. }
  1289. else {
  1290. delete _h[event];
  1291. }
  1292. return this;
  1293. },
  1294. /**
  1295. * Dispatch a event.
  1296. *
  1297. * @param {string} type The event name.
  1298. */
  1299. trigger: function (type) {
  1300. var _h = this._$handlers[type];
  1301. var eventProcessor = this._$eventProcessor;
  1302. if (_h) {
  1303. var args = arguments;
  1304. var argLen = args.length;
  1305. if (argLen > 3) {
  1306. args = arrySlice.call(args, 1);
  1307. }
  1308. var len = _h.length;
  1309. for (var i = 0; i < len;) {
  1310. var hItem = _h[i];
  1311. if (eventProcessor
  1312. && eventProcessor.filter
  1313. && hItem.query != null
  1314. && !eventProcessor.filter(type, hItem.query)
  1315. ) {
  1316. i++;
  1317. continue;
  1318. }
  1319. // Optimize advise from backbone
  1320. switch (argLen) {
  1321. case 1:
  1322. hItem.h.call(hItem.ctx);
  1323. break;
  1324. case 2:
  1325. hItem.h.call(hItem.ctx, args[1]);
  1326. break;
  1327. case 3:
  1328. hItem.h.call(hItem.ctx, args[1], args[2]);
  1329. break;
  1330. default:
  1331. // have more than 2 given arguments
  1332. hItem.h.apply(hItem.ctx, args);
  1333. break;
  1334. }
  1335. if (hItem.one) {
  1336. _h.splice(i, 1);
  1337. len--;
  1338. }
  1339. else {
  1340. i++;
  1341. }
  1342. }
  1343. }
  1344. eventProcessor && eventProcessor.afterTrigger
  1345. && eventProcessor.afterTrigger(type);
  1346. return this;
  1347. },
  1348. /**
  1349. * Dispatch a event with context, which is specified at the last parameter.
  1350. *
  1351. * @param {string} type The event name.
  1352. */
  1353. triggerWithContext: function (type) {
  1354. var _h = this._$handlers[type];
  1355. var eventProcessor = this._$eventProcessor;
  1356. if (_h) {
  1357. var args = arguments;
  1358. var argLen = args.length;
  1359. if (argLen > 4) {
  1360. args = arrySlice.call(args, 1, args.length - 1);
  1361. }
  1362. var ctx = args[args.length - 1];
  1363. var len = _h.length;
  1364. for (var i = 0; i < len;) {
  1365. var hItem = _h[i];
  1366. if (eventProcessor
  1367. && eventProcessor.filter
  1368. && hItem.query != null
  1369. && !eventProcessor.filter(type, hItem.query)
  1370. ) {
  1371. i++;
  1372. continue;
  1373. }
  1374. // Optimize advise from backbone
  1375. switch (argLen) {
  1376. case 1:
  1377. hItem.h.call(ctx);
  1378. break;
  1379. case 2:
  1380. hItem.h.call(ctx, args[1]);
  1381. break;
  1382. case 3:
  1383. hItem.h.call(ctx, args[1], args[2]);
  1384. break;
  1385. default:
  1386. // have more than 2 given arguments
  1387. hItem.h.apply(ctx, args);
  1388. break;
  1389. }
  1390. if (hItem.one) {
  1391. _h.splice(i, 1);
  1392. len--;
  1393. }
  1394. else {
  1395. i++;
  1396. }
  1397. }
  1398. }
  1399. eventProcessor && eventProcessor.afterTrigger
  1400. && eventProcessor.afterTrigger(type);
  1401. return this;
  1402. }
  1403. };
  1404. function normalizeQuery(host, query) {
  1405. var eventProcessor = host._$eventProcessor;
  1406. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1407. query = eventProcessor.normalizeQuery(query);
  1408. }
  1409. return query;
  1410. }
  1411. function on(eventful, event, query, handler, context, isOnce) {
  1412. var _h = eventful._$handlers;
  1413. if (typeof query === 'function') {
  1414. context = handler;
  1415. handler = query;
  1416. query = null;
  1417. }
  1418. if (!handler || !event) {
  1419. return eventful;
  1420. }
  1421. query = normalizeQuery(eventful, query);
  1422. if (!_h[event]) {
  1423. _h[event] = [];
  1424. }
  1425. for (var i = 0; i < _h[event].length; i++) {
  1426. if (_h[event][i].h === handler) {
  1427. return eventful;
  1428. }
  1429. }
  1430. var wrap = {
  1431. h: handler,
  1432. one: isOnce,
  1433. query: query,
  1434. ctx: context || eventful,
  1435. // FIXME
  1436. // Do not publish this feature util it is proved that it makes sense.
  1437. callAtLast: handler.zrEventfulCallAtLast
  1438. };
  1439. var lastIndex = _h[event].length - 1;
  1440. var lastWrap = _h[event][lastIndex];
  1441. (lastWrap && lastWrap.callAtLast)
  1442. ? _h[event].splice(lastIndex, 0, wrap)
  1443. : _h[event].push(wrap);
  1444. return eventful;
  1445. }
  1446. /**
  1447. * 事件辅助类
  1448. * @module zrender/core/event
  1449. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1450. */
  1451. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1452. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1453. function getBoundingClientRect(el) {
  1454. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  1455. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  1456. }
  1457. // `calculate` is optional, default false
  1458. function clientToLocal(el, e, out, calculate) {
  1459. out = out || {};
  1460. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1461. // to the padding edge of the target element. The only browser using this convention
  1462. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1463. // not support the properties.
  1464. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1465. // In zr painter.dom, padding edge equals to border edge.
  1466. // FIXME
  1467. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  1468. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  1469. // is too complex. So css-transfrom dont support in this case temporarily.
  1470. if (calculate || !env$1.canvasSupported) {
  1471. defaultGetZrXY(el, e, out);
  1472. }
  1473. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1474. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1475. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1476. // zoom-factor, overflow / opacity layers, transforms ...)
  1477. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1478. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1479. // BTW3, In ff, offsetX/offsetY is always 0.
  1480. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1481. out.zrX = e.layerX;
  1482. out.zrY = e.layerY;
  1483. }
  1484. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1485. else if (e.offsetX != null) {
  1486. out.zrX = e.offsetX;
  1487. out.zrY = e.offsetY;
  1488. }
  1489. // For some other device, e.g., IOS safari.
  1490. else {
  1491. defaultGetZrXY(el, e, out);
  1492. }
  1493. return out;
  1494. }
  1495. function defaultGetZrXY(el, e, out) {
  1496. // This well-known method below does not support css transform.
  1497. var box = getBoundingClientRect(el);
  1498. out.zrX = e.clientX - box.left;
  1499. out.zrY = e.clientY - box.top;
  1500. }
  1501. /**
  1502. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  1503. * `calculate` is optional, default false.
  1504. */
  1505. function normalizeEvent(el, e, calculate) {
  1506. e = e || window.event;
  1507. if (e.zrX != null) {
  1508. return e;
  1509. }
  1510. var eventType = e.type;
  1511. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1512. if (!isTouch) {
  1513. clientToLocal(el, e, e, calculate);
  1514. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1515. }
  1516. else {
  1517. var touch = eventType !== 'touchend'
  1518. ? e.targetTouches[0]
  1519. : e.changedTouches[0];
  1520. touch && clientToLocal(el, touch, e, calculate);
  1521. }
  1522. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1523. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1524. // If e.which has been defined, if may be readonly,
  1525. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1526. var button = e.button;
  1527. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1528. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1529. }
  1530. // [Caution]: `e.which` from browser is not always reliable. For example,
  1531. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1532. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1533. // `mousedown (pointerdown)` is the same as Chrome does.
  1534. return e;
  1535. }
  1536. /**
  1537. * @param {HTMLElement} el
  1538. * @param {string} name
  1539. * @param {Function} handler
  1540. */
  1541. function addEventListener(el, name, handler) {
  1542. if (isDomLevel2) {
  1543. // Reproduct the console warning:
  1544. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1545. // Consider marking event handler as 'passive' to make the page more responsive.
  1546. // Just set console log level: verbose in chrome dev tool.
  1547. // then the warning log will be printed when addEventListener called.
  1548. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1549. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1550. // listener delegate all of the upper events of element. Some of those events need
  1551. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1552. // Before passive can be adopted, these issues should be considered:
  1553. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1554. // passive or not.
  1555. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1556. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1557. // compatibility should be handled.
  1558. // var opts = (env.passiveSupported && name === 'mousewheel')
  1559. // ? {passive: true}
  1560. // // By default, the third param of el.addEventListener is `capture: false`.
  1561. // : void 0;
  1562. // el.addEventListener(name, handler /* , opts */);
  1563. el.addEventListener(name, handler);
  1564. }
  1565. else {
  1566. el.attachEvent('on' + name, handler);
  1567. }
  1568. }
  1569. function removeEventListener(el, name, handler) {
  1570. if (isDomLevel2) {
  1571. el.removeEventListener(name, handler);
  1572. }
  1573. else {
  1574. el.detachEvent('on' + name, handler);
  1575. }
  1576. }
  1577. /**
  1578. * preventDefault and stopPropagation.
  1579. * Notice: do not do that in zrender. Upper application
  1580. * do that if necessary.
  1581. *
  1582. * @memberOf module:zrender/core/event
  1583. * @method
  1584. * @param {Event} e : event对象
  1585. */
  1586. var stop = isDomLevel2
  1587. ? function (e) {
  1588. e.preventDefault();
  1589. e.stopPropagation();
  1590. e.cancelBubble = true;
  1591. }
  1592. : function (e) {
  1593. e.returnValue = false;
  1594. e.cancelBubble = true;
  1595. };
  1596. /**
  1597. * This method only works for mouseup and mousedown. The functionality is restricted
  1598. * for fault tolerance, See the `e.which` compatibility above.
  1599. *
  1600. * @param {MouseEvent} e
  1601. * @return {boolean}
  1602. */
  1603. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1604. return e.which === 2 || e.which === 3;
  1605. }
  1606. /**
  1607. * To be removed.
  1608. * @deprecated
  1609. */
  1610. /**
  1611. * Only implements needed gestures for mobile.
  1612. */
  1613. var GestureMgr = function () {
  1614. /**
  1615. * @private
  1616. * @type {Array.<Object>}
  1617. */
  1618. this._track = [];
  1619. };
  1620. GestureMgr.prototype = {
  1621. constructor: GestureMgr,
  1622. recognize: function (event, target, root) {
  1623. this._doTrack(event, target, root);
  1624. return this._recognize(event);
  1625. },
  1626. clear: function () {
  1627. this._track.length = 0;
  1628. return this;
  1629. },
  1630. _doTrack: function (event, target, root) {
  1631. var touches = event.touches;
  1632. if (!touches) {
  1633. return;
  1634. }
  1635. var trackItem = {
  1636. points: [],
  1637. touches: [],
  1638. target: target,
  1639. event: event
  1640. };
  1641. for (var i = 0, len = touches.length; i < len; i++) {
  1642. var touch = touches[i];
  1643. var pos = clientToLocal(root, touch, {});
  1644. trackItem.points.push([pos.zrX, pos.zrY]);
  1645. trackItem.touches.push(touch);
  1646. }
  1647. this._track.push(trackItem);
  1648. },
  1649. _recognize: function (event) {
  1650. for (var eventName in recognizers) {
  1651. if (recognizers.hasOwnProperty(eventName)) {
  1652. var gestureInfo = recognizers[eventName](this._track, event);
  1653. if (gestureInfo) {
  1654. return gestureInfo;
  1655. }
  1656. }
  1657. }
  1658. }
  1659. };
  1660. function dist$1(pointPair) {
  1661. var dx = pointPair[1][0] - pointPair[0][0];
  1662. var dy = pointPair[1][1] - pointPair[0][1];
  1663. return Math.sqrt(dx * dx + dy * dy);
  1664. }
  1665. function center(pointPair) {
  1666. return [
  1667. (pointPair[0][0] + pointPair[1][0]) / 2,
  1668. (pointPair[0][1] + pointPair[1][1]) / 2
  1669. ];
  1670. }
  1671. var recognizers = {
  1672. pinch: function (track, event) {
  1673. var trackLen = track.length;
  1674. if (!trackLen) {
  1675. return;
  1676. }
  1677. var pinchEnd = (track[trackLen - 1] || {}).points;
  1678. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1679. if (pinchPre
  1680. && pinchPre.length > 1
  1681. && pinchEnd
  1682. && pinchEnd.length > 1
  1683. ) {
  1684. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1685. !isFinite(pinchScale) && (pinchScale = 1);
  1686. event.pinchScale = pinchScale;
  1687. var pinchCenter = center(pinchEnd);
  1688. event.pinchX = pinchCenter[0];
  1689. event.pinchY = pinchCenter[1];
  1690. return {
  1691. type: 'pinch',
  1692. target: track[0].target,
  1693. event: event
  1694. };
  1695. }
  1696. }
  1697. // Only pinch currently.
  1698. };
  1699. var SILENT = 'silent';
  1700. function makeEventPacket(eveType, targetInfo, event) {
  1701. return {
  1702. type: eveType,
  1703. event: event,
  1704. // target can only be an element that is not silent.
  1705. target: targetInfo.target,
  1706. // topTarget can be a silent element.
  1707. topTarget: targetInfo.topTarget,
  1708. cancelBubble: false,
  1709. offsetX: event.zrX,
  1710. offsetY: event.zrY,
  1711. gestureEvent: event.gestureEvent,
  1712. pinchX: event.pinchX,
  1713. pinchY: event.pinchY,
  1714. pinchScale: event.pinchScale,
  1715. wheelDelta: event.zrDelta,
  1716. zrByTouch: event.zrByTouch,
  1717. which: event.which,
  1718. stop: stopEvent
  1719. };
  1720. }
  1721. function stopEvent(event) {
  1722. stop(this.event);
  1723. }
  1724. function EmptyProxy() {}
  1725. EmptyProxy.prototype.dispose = function () {};
  1726. var handlerNames = [
  1727. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1728. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1729. ];
  1730. /**
  1731. * @alias module:zrender/Handler
  1732. * @constructor
  1733. * @extends module:zrender/mixin/Eventful
  1734. * @param {module:zrender/Storage} storage Storage instance.
  1735. * @param {module:zrender/Painter} painter Painter instance.
  1736. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1737. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1738. */
  1739. var Handler = function (storage, painter, proxy, painterRoot) {
  1740. Eventful.call(this);
  1741. this.storage = storage;
  1742. this.painter = painter;
  1743. this.painterRoot = painterRoot;
  1744. proxy = proxy || new EmptyProxy();
  1745. /**
  1746. * Proxy of event. can be Dom, WebGLSurface, etc.
  1747. */
  1748. this.proxy = null;
  1749. /**
  1750. * {target, topTarget, x, y}
  1751. * @private
  1752. * @type {Object}
  1753. */
  1754. this._hovered = {};
  1755. /**
  1756. * @private
  1757. * @type {Date}
  1758. */
  1759. this._lastTouchMoment;
  1760. /**
  1761. * @private
  1762. * @type {number}
  1763. */
  1764. this._lastX;
  1765. /**
  1766. * @private
  1767. * @type {number}
  1768. */
  1769. this._lastY;
  1770. /**
  1771. * @private
  1772. * @type {module:zrender/core/GestureMgr}
  1773. */
  1774. this._gestureMgr;
  1775. Draggable.call(this);
  1776. this.setHandlerProxy(proxy);
  1777. };
  1778. Handler.prototype = {
  1779. constructor: Handler,
  1780. setHandlerProxy: function (proxy) {
  1781. if (this.proxy) {
  1782. this.proxy.dispose();
  1783. }
  1784. if (proxy) {
  1785. each$1(handlerNames, function (name) {
  1786. proxy.on && proxy.on(name, this[name], this);
  1787. }, this);
  1788. // Attach handler
  1789. proxy.handler = this;
  1790. }
  1791. this.proxy = proxy;
  1792. },
  1793. mousemove: function (event) {
  1794. var x = event.zrX;
  1795. var y = event.zrY;
  1796. var lastHovered = this._hovered;
  1797. var lastHoveredTarget = lastHovered.target;
  1798. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1799. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1800. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1801. // See #6198.
  1802. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1803. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1804. lastHoveredTarget = lastHovered.target;
  1805. }
  1806. var hovered = this._hovered = this.findHover(x, y);
  1807. var hoveredTarget = hovered.target;
  1808. var proxy = this.proxy;
  1809. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1810. // Mouse out on previous hovered element
  1811. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1812. this.dispatchToElement(lastHovered, 'mouseout', event);
  1813. }
  1814. // Mouse moving on one element
  1815. this.dispatchToElement(hovered, 'mousemove', event);
  1816. // Mouse over on a new element
  1817. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1818. this.dispatchToElement(hovered, 'mouseover', event);
  1819. }
  1820. },
  1821. mouseout: function (event) {
  1822. this.dispatchToElement(this._hovered, 'mouseout', event);
  1823. // There might be some doms created by upper layer application
  1824. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1825. // dom created by echarts), where 'globalout' event should not
  1826. // be triggered when mouse enters these doms. (But 'mouseout'
  1827. // should be triggered at the original hovered element as usual).
  1828. var element = event.toElement || event.relatedTarget;
  1829. var innerDom;
  1830. do {
  1831. element = element && element.parentNode;
  1832. }
  1833. while (element && element.nodeType !== 9 && !(
  1834. innerDom = element === this.painterRoot
  1835. ));
  1836. !innerDom && this.trigger('globalout', {event: event});
  1837. },
  1838. /**
  1839. * Resize
  1840. */
  1841. resize: function (event) {
  1842. this._hovered = {};
  1843. },
  1844. /**
  1845. * Dispatch event
  1846. * @param {string} eventName
  1847. * @param {event=} eventArgs
  1848. */
  1849. dispatch: function (eventName, eventArgs) {
  1850. var handler = this[eventName];
  1851. handler && handler.call(this, eventArgs);
  1852. },
  1853. /**
  1854. * Dispose
  1855. */
  1856. dispose: function () {
  1857. this.proxy.dispose();
  1858. this.storage =
  1859. this.proxy =
  1860. this.painter = null;
  1861. },
  1862. /**
  1863. * 设置默认的cursor style
  1864. * @param {string} [cursorStyle='default'] 例如 crosshair
  1865. */
  1866. setCursorStyle: function (cursorStyle) {
  1867. var proxy = this.proxy;
  1868. proxy.setCursor && proxy.setCursor(cursorStyle);
  1869. },
  1870. /**
  1871. * 事件分发代理
  1872. *
  1873. * @private
  1874. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1875. * @param {string} eventName 事件名称
  1876. * @param {Object} event 事件对象
  1877. */
  1878. dispatchToElement: function (targetInfo, eventName, event) {
  1879. targetInfo = targetInfo || {};
  1880. var el = targetInfo.target;
  1881. if (el && el.silent) {
  1882. return;
  1883. }
  1884. var eventHandler = 'on' + eventName;
  1885. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1886. while (el) {
  1887. el[eventHandler]
  1888. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1889. el.trigger(eventName, eventPacket);
  1890. el = el.parent;
  1891. if (eventPacket.cancelBubble) {
  1892. break;
  1893. }
  1894. }
  1895. if (!eventPacket.cancelBubble) {
  1896. // 冒泡到顶级 zrender 对象
  1897. this.trigger(eventName, eventPacket);
  1898. // 分发事件到用户自定义层
  1899. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1900. this.painter && this.painter.eachOtherLayer(function (layer) {
  1901. if (typeof (layer[eventHandler]) === 'function') {
  1902. layer[eventHandler].call(layer, eventPacket);
  1903. }
  1904. if (layer.trigger) {
  1905. layer.trigger(eventName, eventPacket);
  1906. }
  1907. });
  1908. }
  1909. },
  1910. /**
  1911. * @private
  1912. * @param {number} x
  1913. * @param {number} y
  1914. * @param {module:zrender/graphic/Displayable} exclude
  1915. * @return {model:zrender/Element}
  1916. * @method
  1917. */
  1918. findHover: function (x, y, exclude) {
  1919. var list = this.storage.getDisplayList();
  1920. var out = {x: x, y: y};
  1921. for (var i = list.length - 1; i >= 0; i--) {
  1922. var hoverCheckResult;
  1923. if (list[i] !== exclude
  1924. // getDisplayList may include ignored item in VML mode
  1925. && !list[i].ignore
  1926. && (hoverCheckResult = isHover(list[i], x, y))
  1927. ) {
  1928. !out.topTarget && (out.topTarget = list[i]);
  1929. if (hoverCheckResult !== SILENT) {
  1930. out.target = list[i];
  1931. break;
  1932. }
  1933. }
  1934. }
  1935. return out;
  1936. },
  1937. processGesture: function (event, stage) {
  1938. if (!this._gestureMgr) {
  1939. this._gestureMgr = new GestureMgr();
  1940. }
  1941. var gestureMgr = this._gestureMgr;
  1942. stage === 'start' && gestureMgr.clear();
  1943. var gestureInfo = gestureMgr.recognize(
  1944. event,
  1945. this.findHover(event.zrX, event.zrY, null).target,
  1946. this.proxy.dom
  1947. );
  1948. stage === 'end' && gestureMgr.clear();
  1949. // Do not do any preventDefault here. Upper application do that if necessary.
  1950. if (gestureInfo) {
  1951. var type = gestureInfo.type;
  1952. event.gestureEvent = type;
  1953. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  1954. }
  1955. }
  1956. };
  1957. // Common handlers
  1958. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1959. Handler.prototype[name] = function (event) {
  1960. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1961. var hovered = this.findHover(event.zrX, event.zrY);
  1962. var hoveredTarget = hovered.target;
  1963. if (name === 'mousedown') {
  1964. this._downEl = hoveredTarget;
  1965. this._downPoint = [event.zrX, event.zrY];
  1966. // In case click triggered before mouseup
  1967. this._upEl = hoveredTarget;
  1968. }
  1969. else if (name === 'mouseup') {
  1970. this._upEl = hoveredTarget;
  1971. }
  1972. else if (name === 'click') {
  1973. if (this._downEl !== this._upEl
  1974. // Original click event is triggered on the whole canvas element,
  1975. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1976. // which should be filtered, otherwise it will bring trouble to
  1977. // pan and zoom.
  1978. || !this._downPoint
  1979. // Arbitrary value
  1980. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1981. ) {
  1982. return;
  1983. }
  1984. this._downPoint = null;
  1985. }
  1986. this.dispatchToElement(hovered, name, event);
  1987. };
  1988. });
  1989. function isHover(displayable, x, y) {
  1990. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1991. var el = displayable;
  1992. var isSilent;
  1993. while (el) {
  1994. // If clipped by ancestor.
  1995. // FIXME: If clipPath has neither stroke nor fill,
  1996. // el.clipPath.contain(x, y) will always return false.
  1997. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1998. return false;
  1999. }
  2000. if (el.silent) {
  2001. isSilent = true;
  2002. }
  2003. el = el.parent;
  2004. }
  2005. return isSilent ? SILENT : true;
  2006. }
  2007. return false;
  2008. }
  2009. mixin(Handler, Eventful);
  2010. mixin(Handler, Draggable);
  2011. /**
  2012. * 3x2矩阵操作类
  2013. * @exports zrender/tool/matrix
  2014. */
  2015. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2016. ? Array
  2017. : Float32Array;
  2018. /**
  2019. * Create a identity matrix.
  2020. * @return {Float32Array|Array.<number>}
  2021. */
  2022. function create$1() {
  2023. var out = new ArrayCtor$1(6);
  2024. identity(out);
  2025. return out;
  2026. }
  2027. /**
  2028. * 设置矩阵为单位矩阵
  2029. * @param {Float32Array|Array.<number>} out
  2030. */
  2031. function identity(out) {
  2032. out[0] = 1;
  2033. out[1] = 0;
  2034. out[2] = 0;
  2035. out[3] = 1;
  2036. out[4] = 0;
  2037. out[5] = 0;
  2038. return out;
  2039. }
  2040. /**
  2041. * 复制矩阵
  2042. * @param {Float32Array|Array.<number>} out
  2043. * @param {Float32Array|Array.<number>} m
  2044. */
  2045. function copy$1(out, m) {
  2046. out[0] = m[0];
  2047. out[1] = m[1];
  2048. out[2] = m[2];
  2049. out[3] = m[3];
  2050. out[4] = m[4];
  2051. out[5] = m[5];
  2052. return out;
  2053. }
  2054. /**
  2055. * 矩阵相乘
  2056. * @param {Float32Array|Array.<number>} out
  2057. * @param {Float32Array|Array.<number>} m1
  2058. * @param {Float32Array|Array.<number>} m2
  2059. */
  2060. function mul$1(out, m1, m2) {
  2061. // Consider matrix.mul(m, m2, m);
  2062. // where out is the same as m2.
  2063. // So use temp variable to escape error.
  2064. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2065. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2066. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2067. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2068. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2069. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2070. out[0] = out0;
  2071. out[1] = out1;
  2072. out[2] = out2;
  2073. out[3] = out3;
  2074. out[4] = out4;
  2075. out[5] = out5;
  2076. return out;
  2077. }
  2078. /**
  2079. * 平移变换
  2080. * @param {Float32Array|Array.<number>} out
  2081. * @param {Float32Array|Array.<number>} a
  2082. * @param {Float32Array|Array.<number>} v
  2083. */
  2084. function translate(out, a, v) {
  2085. out[0] = a[0];
  2086. out[1] = a[1];
  2087. out[2] = a[2];
  2088. out[3] = a[3];
  2089. out[4] = a[4] + v[0];
  2090. out[5] = a[5] + v[1];
  2091. return out;
  2092. }
  2093. /**
  2094. * 旋转变换
  2095. * @param {Float32Array|Array.<number>} out
  2096. * @param {Float32Array|Array.<number>} a
  2097. * @param {number} rad
  2098. */
  2099. function rotate(out, a, rad) {
  2100. var aa = a[0];
  2101. var ac = a[2];
  2102. var atx = a[4];
  2103. var ab = a[1];
  2104. var ad = a[3];
  2105. var aty = a[5];
  2106. var st = Math.sin(rad);
  2107. var ct = Math.cos(rad);
  2108. out[0] = aa * ct + ab * st;
  2109. out[1] = -aa * st + ab * ct;
  2110. out[2] = ac * ct + ad * st;
  2111. out[3] = -ac * st + ct * ad;
  2112. out[4] = ct * atx + st * aty;
  2113. out[5] = ct * aty - st * atx;
  2114. return out;
  2115. }
  2116. /**
  2117. * 缩放变换
  2118. * @param {Float32Array|Array.<number>} out
  2119. * @param {Float32Array|Array.<number>} a
  2120. * @param {Float32Array|Array.<number>} v
  2121. */
  2122. function scale$1(out, a, v) {
  2123. var vx = v[0];
  2124. var vy = v[1];
  2125. out[0] = a[0] * vx;
  2126. out[1] = a[1] * vy;
  2127. out[2] = a[2] * vx;
  2128. out[3] = a[3] * vy;
  2129. out[4] = a[4] * vx;
  2130. out[5] = a[5] * vy;
  2131. return out;
  2132. }
  2133. /**
  2134. * 求逆矩阵
  2135. * @param {Float32Array|Array.<number>} out
  2136. * @param {Float32Array|Array.<number>} a
  2137. */
  2138. function invert(out, a) {
  2139. var aa = a[0];
  2140. var ac = a[2];
  2141. var atx = a[4];
  2142. var ab = a[1];
  2143. var ad = a[3];
  2144. var aty = a[5];
  2145. var det = aa * ad - ab * ac;
  2146. if (!det) {
  2147. return null;
  2148. }
  2149. det = 1.0 / det;
  2150. out[0] = ad * det;
  2151. out[1] = -ab * det;
  2152. out[2] = -ac * det;
  2153. out[3] = aa * det;
  2154. out[4] = (ac * aty - ad * atx) * det;
  2155. out[5] = (ab * atx - aa * aty) * det;
  2156. return out;
  2157. }
  2158. /**
  2159. * Clone a new matrix.
  2160. * @param {Float32Array|Array.<number>} a
  2161. */
  2162. function clone$2(a) {
  2163. var b = create$1();
  2164. copy$1(b, a);
  2165. return b;
  2166. }
  2167. var matrix = (Object.freeze || Object)({
  2168. create: create$1,
  2169. identity: identity,
  2170. copy: copy$1,
  2171. mul: mul$1,
  2172. translate: translate,
  2173. rotate: rotate,
  2174. scale: scale$1,
  2175. invert: invert,
  2176. clone: clone$2
  2177. });
  2178. /**
  2179. * 提供变换扩展
  2180. * @module zrender/mixin/Transformable
  2181. * @author pissang (https://www.github.com/pissang)
  2182. */
  2183. var mIdentity = identity;
  2184. var EPSILON = 5e-5;
  2185. function isNotAroundZero(val) {
  2186. return val > EPSILON || val < -EPSILON;
  2187. }
  2188. /**
  2189. * @alias module:zrender/mixin/Transformable
  2190. * @constructor
  2191. */
  2192. var Transformable = function (opts) {
  2193. opts = opts || {};
  2194. // If there are no given position, rotation, scale
  2195. if (!opts.position) {
  2196. /**
  2197. * 平移
  2198. * @type {Array.<number>}
  2199. * @default [0, 0]
  2200. */
  2201. this.position = [0, 0];
  2202. }
  2203. if (opts.rotation == null) {
  2204. /**
  2205. * 旋转
  2206. * @type {Array.<number>}
  2207. * @default 0
  2208. */
  2209. this.rotation = 0;
  2210. }
  2211. if (!opts.scale) {
  2212. /**
  2213. * 缩放
  2214. * @type {Array.<number>}
  2215. * @default [1, 1]
  2216. */
  2217. this.scale = [1, 1];
  2218. }
  2219. /**
  2220. * 旋转和缩放的原点
  2221. * @type {Array.<number>}
  2222. * @default null
  2223. */
  2224. this.origin = this.origin || null;
  2225. };
  2226. var transformableProto = Transformable.prototype;
  2227. transformableProto.transform = null;
  2228. /**
  2229. * 判断是否需要有坐标变换
  2230. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2231. */
  2232. transformableProto.needLocalTransform = function () {
  2233. return isNotAroundZero(this.rotation)
  2234. || isNotAroundZero(this.position[0])
  2235. || isNotAroundZero(this.position[1])
  2236. || isNotAroundZero(this.scale[0] - 1)
  2237. || isNotAroundZero(this.scale[1] - 1);
  2238. };
  2239. var scaleTmp = [];
  2240. transformableProto.updateTransform = function () {
  2241. var parent = this.parent;
  2242. var parentHasTransform = parent && parent.transform;
  2243. var needLocalTransform = this.needLocalTransform();
  2244. var m = this.transform;
  2245. if (!(needLocalTransform || parentHasTransform)) {
  2246. m && mIdentity(m);
  2247. return;
  2248. }
  2249. m = m || create$1();
  2250. if (needLocalTransform) {
  2251. this.getLocalTransform(m);
  2252. }
  2253. else {
  2254. mIdentity(m);
  2255. }
  2256. // 应用父节点变换
  2257. if (parentHasTransform) {
  2258. if (needLocalTransform) {
  2259. mul$1(m, parent.transform, m);
  2260. }
  2261. else {
  2262. copy$1(m, parent.transform);
  2263. }
  2264. }
  2265. // 保存这个变换矩阵
  2266. this.transform = m;
  2267. var globalScaleRatio = this.globalScaleRatio;
  2268. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2269. this.getGlobalScale(scaleTmp);
  2270. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2271. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2272. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2273. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2274. m[0] *= sx;
  2275. m[1] *= sx;
  2276. m[2] *= sy;
  2277. m[3] *= sy;
  2278. }
  2279. this.invTransform = this.invTransform || create$1();
  2280. invert(this.invTransform, m);
  2281. };
  2282. transformableProto.getLocalTransform = function (m) {
  2283. return Transformable.getLocalTransform(this, m);
  2284. };
  2285. /**
  2286. * 将自己的transform应用到context上
  2287. * @param {CanvasRenderingContext2D} ctx
  2288. */
  2289. transformableProto.setTransform = function (ctx) {
  2290. var m = this.transform;
  2291. var dpr = ctx.dpr || 1;
  2292. if (m) {
  2293. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2294. }
  2295. else {
  2296. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2297. }
  2298. };
  2299. transformableProto.restoreTransform = function (ctx) {
  2300. var dpr = ctx.dpr || 1;
  2301. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2302. };
  2303. var tmpTransform = [];
  2304. var originTransform = create$1();
  2305. transformableProto.setLocalTransform = function (m) {
  2306. if (!m) {
  2307. // TODO return or set identity?
  2308. return;
  2309. }
  2310. var sx = m[0] * m[0] + m[1] * m[1];
  2311. var sy = m[2] * m[2] + m[3] * m[3];
  2312. var position = this.position;
  2313. var scale$$1 = this.scale;
  2314. if (isNotAroundZero(sx - 1)) {
  2315. sx = Math.sqrt(sx);
  2316. }
  2317. if (isNotAroundZero(sy - 1)) {
  2318. sy = Math.sqrt(sy);
  2319. }
  2320. if (m[0] < 0) {
  2321. sx = -sx;
  2322. }
  2323. if (m[3] < 0) {
  2324. sy = -sy;
  2325. }
  2326. position[0] = m[4];
  2327. position[1] = m[5];
  2328. scale$$1[0] = sx;
  2329. scale$$1[1] = sy;
  2330. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2331. };
  2332. /**
  2333. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2334. */
  2335. transformableProto.decomposeTransform = function () {
  2336. if (!this.transform) {
  2337. return;
  2338. }
  2339. var parent = this.parent;
  2340. var m = this.transform;
  2341. if (parent && parent.transform) {
  2342. // Get local transform and decompose them to position, scale, rotation
  2343. mul$1(tmpTransform, parent.invTransform, m);
  2344. m = tmpTransform;
  2345. }
  2346. var origin = this.origin;
  2347. if (origin && (origin[0] || origin[1])) {
  2348. originTransform[4] = origin[0];
  2349. originTransform[5] = origin[1];
  2350. mul$1(tmpTransform, m, originTransform);
  2351. tmpTransform[4] -= origin[0];
  2352. tmpTransform[5] -= origin[1];
  2353. m = tmpTransform;
  2354. }
  2355. this.setLocalTransform(m);
  2356. };
  2357. /**
  2358. * Get global scale
  2359. * @return {Array.<number>}
  2360. */
  2361. transformableProto.getGlobalScale = function (out) {
  2362. var m = this.transform;
  2363. out = out || [];
  2364. if (!m) {
  2365. out[0] = 1;
  2366. out[1] = 1;
  2367. return out;
  2368. }
  2369. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2370. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2371. if (m[0] < 0) {
  2372. out[0] = -out[0];
  2373. }
  2374. if (m[3] < 0) {
  2375. out[1] = -out[1];
  2376. }
  2377. return out;
  2378. };
  2379. /**
  2380. * 变换坐标位置到 shape 的局部坐标空间
  2381. * @method
  2382. * @param {number} x
  2383. * @param {number} y
  2384. * @return {Array.<number>}
  2385. */
  2386. transformableProto.transformCoordToLocal = function (x, y) {
  2387. var v2 = [x, y];
  2388. var invTransform = this.invTransform;
  2389. if (invTransform) {
  2390. applyTransform(v2, v2, invTransform);
  2391. }
  2392. return v2;
  2393. };
  2394. /**
  2395. * 变换局部坐标位置到全局坐标空间
  2396. * @method
  2397. * @param {number} x
  2398. * @param {number} y
  2399. * @return {Array.<number>}
  2400. */
  2401. transformableProto.transformCoordToGlobal = function (x, y) {
  2402. var v2 = [x, y];
  2403. var transform = this.transform;
  2404. if (transform) {
  2405. applyTransform(v2, v2, transform);
  2406. }
  2407. return v2;
  2408. };
  2409. /**
  2410. * @static
  2411. * @param {Object} target
  2412. * @param {Array.<number>} target.origin
  2413. * @param {number} target.rotation
  2414. * @param {Array.<number>} target.position
  2415. * @param {Array.<number>} [m]
  2416. */
  2417. Transformable.getLocalTransform = function (target, m) {
  2418. m = m || [];
  2419. mIdentity(m);
  2420. var origin = target.origin;
  2421. var scale$$1 = target.scale || [1, 1];
  2422. var rotation = target.rotation || 0;
  2423. var position = target.position || [0, 0];
  2424. if (origin) {
  2425. // Translate to origin
  2426. m[4] -= origin[0];
  2427. m[5] -= origin[1];
  2428. }
  2429. scale$1(m, m, scale$$1);
  2430. if (rotation) {
  2431. rotate(m, m, rotation);
  2432. }
  2433. if (origin) {
  2434. // Translate back from origin
  2435. m[4] += origin[0];
  2436. m[5] += origin[1];
  2437. }
  2438. m[4] += position[0];
  2439. m[5] += position[1];
  2440. return m;
  2441. };
  2442. /**
  2443. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2444. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2445. * @exports zrender/animation/easing
  2446. */
  2447. var easing = {
  2448. /**
  2449. * @param {number} k
  2450. * @return {number}
  2451. */
  2452. linear: function (k) {
  2453. return k;
  2454. },
  2455. /**
  2456. * @param {number} k
  2457. * @return {number}
  2458. */
  2459. quadraticIn: function (k) {
  2460. return k * k;
  2461. },
  2462. /**
  2463. * @param {number} k
  2464. * @return {number}
  2465. */
  2466. quadraticOut: function (k) {
  2467. return k * (2 - k);
  2468. },
  2469. /**
  2470. * @param {number} k
  2471. * @return {number}
  2472. */
  2473. quadraticInOut: function (k) {
  2474. if ((k *= 2) < 1) {
  2475. return 0.5 * k * k;
  2476. }
  2477. return -0.5 * (--k * (k - 2) - 1);
  2478. },
  2479. // 三次方的缓动(t^3)
  2480. /**
  2481. * @param {number} k
  2482. * @return {number}
  2483. */
  2484. cubicIn: function (k) {
  2485. return k * k * k;
  2486. },
  2487. /**
  2488. * @param {number} k
  2489. * @return {number}
  2490. */
  2491. cubicOut: function (k) {
  2492. return --k * k * k + 1;
  2493. },
  2494. /**
  2495. * @param {number} k
  2496. * @return {number}
  2497. */
  2498. cubicInOut: function (k) {
  2499. if ((k *= 2) < 1) {
  2500. return 0.5 * k * k * k;
  2501. }
  2502. return 0.5 * ((k -= 2) * k * k + 2);
  2503. },
  2504. // 四次方的缓动(t^4)
  2505. /**
  2506. * @param {number} k
  2507. * @return {number}
  2508. */
  2509. quarticIn: function (k) {
  2510. return k * k * k * k;
  2511. },
  2512. /**
  2513. * @param {number} k
  2514. * @return {number}
  2515. */
  2516. quarticOut: function (k) {
  2517. return 1 - (--k * k * k * k);
  2518. },
  2519. /**
  2520. * @param {number} k
  2521. * @return {number}
  2522. */
  2523. quarticInOut: function (k) {
  2524. if ((k *= 2) < 1) {
  2525. return 0.5 * k * k * k * k;
  2526. }
  2527. return -0.5 * ((k -= 2) * k * k * k - 2);
  2528. },
  2529. // 五次方的缓动(t^5)
  2530. /**
  2531. * @param {number} k
  2532. * @return {number}
  2533. */
  2534. quinticIn: function (k) {
  2535. return k * k * k * k * k;
  2536. },
  2537. /**
  2538. * @param {number} k
  2539. * @return {number}
  2540. */
  2541. quinticOut: function (k) {
  2542. return --k * k * k * k * k + 1;
  2543. },
  2544. /**
  2545. * @param {number} k
  2546. * @return {number}
  2547. */
  2548. quinticInOut: function (k) {
  2549. if ((k *= 2) < 1) {
  2550. return 0.5 * k * k * k * k * k;
  2551. }
  2552. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2553. },
  2554. // 正弦曲线的缓动(sin(t))
  2555. /**
  2556. * @param {number} k
  2557. * @return {number}
  2558. */
  2559. sinusoidalIn: function (k) {
  2560. return 1 - Math.cos(k * Math.PI / 2);
  2561. },
  2562. /**
  2563. * @param {number} k
  2564. * @return {number}
  2565. */
  2566. sinusoidalOut: function (k) {
  2567. return Math.sin(k * Math.PI / 2);
  2568. },
  2569. /**
  2570. * @param {number} k
  2571. * @return {number}
  2572. */
  2573. sinusoidalInOut: function (k) {
  2574. return 0.5 * (1 - Math.cos(Math.PI * k));
  2575. },
  2576. // 指数曲线的缓动(2^t)
  2577. /**
  2578. * @param {number} k
  2579. * @return {number}
  2580. */
  2581. exponentialIn: function (k) {
  2582. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2583. },
  2584. /**
  2585. * @param {number} k
  2586. * @return {number}
  2587. */
  2588. exponentialOut: function (k) {
  2589. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2590. },
  2591. /**
  2592. * @param {number} k
  2593. * @return {number}
  2594. */
  2595. exponentialInOut: function (k) {
  2596. if (k === 0) {
  2597. return 0;
  2598. }
  2599. if (k === 1) {
  2600. return 1;
  2601. }
  2602. if ((k *= 2) < 1) {
  2603. return 0.5 * Math.pow(1024, k - 1);
  2604. }
  2605. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2606. },
  2607. // 圆形曲线的缓动(sqrt(1-t^2))
  2608. /**
  2609. * @param {number} k
  2610. * @return {number}
  2611. */
  2612. circularIn: function (k) {
  2613. return 1 - Math.sqrt(1 - k * k);
  2614. },
  2615. /**
  2616. * @param {number} k
  2617. * @return {number}
  2618. */
  2619. circularOut: function (k) {
  2620. return Math.sqrt(1 - (--k * k));
  2621. },
  2622. /**
  2623. * @param {number} k
  2624. * @return {number}
  2625. */
  2626. circularInOut: function (k) {
  2627. if ((k *= 2) < 1) {
  2628. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2629. }
  2630. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2631. },
  2632. // 创建类似于弹簧在停止前来回振荡的动画
  2633. /**
  2634. * @param {number} k
  2635. * @return {number}
  2636. */
  2637. elasticIn: function (k) {
  2638. var s;
  2639. var a = 0.1;
  2640. var p = 0.4;
  2641. if (k === 0) {
  2642. return 0;
  2643. }
  2644. if (k === 1) {
  2645. return 1;
  2646. }
  2647. if (!a || a < 1) {
  2648. a = 1;
  2649. s = p / 4;
  2650. }
  2651. else {
  2652. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2653. }
  2654. return -(a * Math.pow(2, 10 * (k -= 1))
  2655. * Math.sin((k - s) * (2 * Math.PI) / p));
  2656. },
  2657. /**
  2658. * @param {number} k
  2659. * @return {number}
  2660. */
  2661. elasticOut: function (k) {
  2662. var s;
  2663. var a = 0.1;
  2664. var p = 0.4;
  2665. if (k === 0) {
  2666. return 0;
  2667. }
  2668. if (k === 1) {
  2669. return 1;
  2670. }
  2671. if (!a || a < 1) {
  2672. a = 1;
  2673. s = p / 4;
  2674. }
  2675. else {
  2676. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2677. }
  2678. return (a * Math.pow(2, -10 * k)
  2679. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2680. },
  2681. /**
  2682. * @param {number} k
  2683. * @return {number}
  2684. */
  2685. elasticInOut: function (k) {
  2686. var s;
  2687. var a = 0.1;
  2688. var p = 0.4;
  2689. if (k === 0) {
  2690. return 0;
  2691. }
  2692. if (k === 1) {
  2693. return 1;
  2694. }
  2695. if (!a || a < 1) {
  2696. a = 1;
  2697. s = p / 4;
  2698. }
  2699. else {
  2700. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2701. }
  2702. if ((k *= 2) < 1) {
  2703. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2704. * Math.sin((k - s) * (2 * Math.PI) / p));
  2705. }
  2706. return a * Math.pow(2, -10 * (k -= 1))
  2707. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2708. },
  2709. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2710. /**
  2711. * @param {number} k
  2712. * @return {number}
  2713. */
  2714. backIn: function (k) {
  2715. var s = 1.70158;
  2716. return k * k * ((s + 1) * k - s);
  2717. },
  2718. /**
  2719. * @param {number} k
  2720. * @return {number}
  2721. */
  2722. backOut: function (k) {
  2723. var s = 1.70158;
  2724. return --k * k * ((s + 1) * k + s) + 1;
  2725. },
  2726. /**
  2727. * @param {number} k
  2728. * @return {number}
  2729. */
  2730. backInOut: function (k) {
  2731. var s = 1.70158 * 1.525;
  2732. if ((k *= 2) < 1) {
  2733. return 0.5 * (k * k * ((s + 1) * k - s));
  2734. }
  2735. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2736. },
  2737. // 创建弹跳效果
  2738. /**
  2739. * @param {number} k
  2740. * @return {number}
  2741. */
  2742. bounceIn: function (k) {
  2743. return 1 - easing.bounceOut(1 - k);
  2744. },
  2745. /**
  2746. * @param {number} k
  2747. * @return {number}
  2748. */
  2749. bounceOut: function (k) {
  2750. if (k < (1 / 2.75)) {
  2751. return 7.5625 * k * k;
  2752. }
  2753. else if (k < (2 / 2.75)) {
  2754. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2755. }
  2756. else if (k < (2.5 / 2.75)) {
  2757. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2758. }
  2759. else {
  2760. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2761. }
  2762. },
  2763. /**
  2764. * @param {number} k
  2765. * @return {number}
  2766. */
  2767. bounceInOut: function (k) {
  2768. if (k < 0.5) {
  2769. return easing.bounceIn(k * 2) * 0.5;
  2770. }
  2771. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2772. }
  2773. };
  2774. /**
  2775. * 动画主控制器
  2776. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2777. * @config life(1000) 动画时长
  2778. * @config delay(0) 动画延迟时间
  2779. * @config loop(true)
  2780. * @config gap(0) 循环的间隔时间
  2781. * @config onframe
  2782. * @config easing(optional)
  2783. * @config ondestroy(optional)
  2784. * @config onrestart(optional)
  2785. *
  2786. * TODO pause
  2787. */
  2788. function Clip(options) {
  2789. this._target = options.target;
  2790. // 生命周期
  2791. this._life = options.life || 1000;
  2792. // 延时
  2793. this._delay = options.delay || 0;
  2794. // 开始时间
  2795. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2796. this._initialized = false;
  2797. // 是否循环
  2798. this.loop = options.loop == null ? false : options.loop;
  2799. this.gap = options.gap || 0;
  2800. this.easing = options.easing || 'Linear';
  2801. this.onframe = options.onframe;
  2802. this.ondestroy = options.ondestroy;
  2803. this.onrestart = options.onrestart;
  2804. this._pausedTime = 0;
  2805. this._paused = false;
  2806. }
  2807. Clip.prototype = {
  2808. constructor: Clip,
  2809. step: function (globalTime, deltaTime) {
  2810. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2811. // PENDING
  2812. if (!this._initialized) {
  2813. this._startTime = globalTime + this._delay;
  2814. this._initialized = true;
  2815. }
  2816. if (this._paused) {
  2817. this._pausedTime += deltaTime;
  2818. return;
  2819. }
  2820. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2821. // 还没开始
  2822. if (percent < 0) {
  2823. return;
  2824. }
  2825. percent = Math.min(percent, 1);
  2826. var easing$$1 = this.easing;
  2827. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  2828. var schedule = typeof easingFunc === 'function'
  2829. ? easingFunc(percent)
  2830. : percent;
  2831. this.fire('frame', schedule);
  2832. // 结束
  2833. if (percent === 1) {
  2834. if (this.loop) {
  2835. this.restart(globalTime);
  2836. // 重新开始周期
  2837. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2838. return 'restart';
  2839. }
  2840. // 动画完成将这个控制器标识为待删除
  2841. // 在Animation.update中进行批量删除
  2842. this._needsRemove = true;
  2843. return 'destroy';
  2844. }
  2845. return null;
  2846. },
  2847. restart: function (globalTime) {
  2848. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2849. this._startTime = globalTime - remainder + this.gap;
  2850. this._pausedTime = 0;
  2851. this._needsRemove = false;
  2852. },
  2853. fire: function (eventType, arg) {
  2854. eventType = 'on' + eventType;
  2855. if (this[eventType]) {
  2856. this[eventType](this._target, arg);
  2857. }
  2858. },
  2859. pause: function () {
  2860. this._paused = true;
  2861. },
  2862. resume: function () {
  2863. this._paused = false;
  2864. }
  2865. };
  2866. // Simple LRU cache use doubly linked list
  2867. // @module zrender/core/LRU
  2868. /**
  2869. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2870. * @constructor
  2871. */
  2872. var LinkedList = function () {
  2873. /**
  2874. * @type {module:zrender/core/LRU~Entry}
  2875. */
  2876. this.head = null;
  2877. /**
  2878. * @type {module:zrender/core/LRU~Entry}
  2879. */
  2880. this.tail = null;
  2881. this._len = 0;
  2882. };
  2883. var linkedListProto = LinkedList.prototype;
  2884. /**
  2885. * Insert a new value at the tail
  2886. * @param {} val
  2887. * @return {module:zrender/core/LRU~Entry}
  2888. */
  2889. linkedListProto.insert = function (val) {
  2890. var entry = new Entry(val);
  2891. this.insertEntry(entry);
  2892. return entry;
  2893. };
  2894. /**
  2895. * Insert an entry at the tail
  2896. * @param {module:zrender/core/LRU~Entry} entry
  2897. */
  2898. linkedListProto.insertEntry = function (entry) {
  2899. if (!this.head) {
  2900. this.head = this.tail = entry;
  2901. }
  2902. else {
  2903. this.tail.next = entry;
  2904. entry.prev = this.tail;
  2905. entry.next = null;
  2906. this.tail = entry;
  2907. }
  2908. this._len++;
  2909. };
  2910. /**
  2911. * Remove entry.
  2912. * @param {module:zrender/core/LRU~Entry} entry
  2913. */
  2914. linkedListProto.remove = function (entry) {
  2915. var prev = entry.prev;
  2916. var next = entry.next;
  2917. if (prev) {
  2918. prev.next = next;
  2919. }
  2920. else {
  2921. // Is head
  2922. this.head = next;
  2923. }
  2924. if (next) {
  2925. next.prev = prev;
  2926. }
  2927. else {
  2928. // Is tail
  2929. this.tail = prev;
  2930. }
  2931. entry.next = entry.prev = null;
  2932. this._len--;
  2933. };
  2934. /**
  2935. * @return {number}
  2936. */
  2937. linkedListProto.len = function () {
  2938. return this._len;
  2939. };
  2940. /**
  2941. * Clear list
  2942. */
  2943. linkedListProto.clear = function () {
  2944. this.head = this.tail = null;
  2945. this._len = 0;
  2946. };
  2947. /**
  2948. * @constructor
  2949. * @param {} val
  2950. */
  2951. var Entry = function (val) {
  2952. /**
  2953. * @type {}
  2954. */
  2955. this.value = val;
  2956. /**
  2957. * @type {module:zrender/core/LRU~Entry}
  2958. */
  2959. this.next;
  2960. /**
  2961. * @type {module:zrender/core/LRU~Entry}
  2962. */
  2963. this.prev;
  2964. };
  2965. /**
  2966. * LRU Cache
  2967. * @constructor
  2968. * @alias module:zrender/core/LRU
  2969. */
  2970. var LRU = function (maxSize) {
  2971. this._list = new LinkedList();
  2972. this._map = {};
  2973. this._maxSize = maxSize || 10;
  2974. this._lastRemovedEntry = null;
  2975. };
  2976. var LRUProto = LRU.prototype;
  2977. /**
  2978. * @param {string} key
  2979. * @param {} value
  2980. * @return {} Removed value
  2981. */
  2982. LRUProto.put = function (key, value) {
  2983. var list = this._list;
  2984. var map = this._map;
  2985. var removed = null;
  2986. if (map[key] == null) {
  2987. var len = list.len();
  2988. // Reuse last removed entry
  2989. var entry = this._lastRemovedEntry;
  2990. if (len >= this._maxSize && len > 0) {
  2991. // Remove the least recently used
  2992. var leastUsedEntry = list.head;
  2993. list.remove(leastUsedEntry);
  2994. delete map[leastUsedEntry.key];
  2995. removed = leastUsedEntry.value;
  2996. this._lastRemovedEntry = leastUsedEntry;
  2997. }
  2998. if (entry) {
  2999. entry.value = value;
  3000. }
  3001. else {
  3002. entry = new Entry(value);
  3003. }
  3004. entry.key = key;
  3005. list.insertEntry(entry);
  3006. map[key] = entry;
  3007. }
  3008. return removed;
  3009. };
  3010. /**
  3011. * @param {string} key
  3012. * @return {}
  3013. */
  3014. LRUProto.get = function (key) {
  3015. var entry = this._map[key];
  3016. var list = this._list;
  3017. if (entry != null) {
  3018. // Put the latest used entry in the tail
  3019. if (entry !== list.tail) {
  3020. list.remove(entry);
  3021. list.insertEntry(entry);
  3022. }
  3023. return entry.value;
  3024. }
  3025. };
  3026. /**
  3027. * Clear the cache
  3028. */
  3029. LRUProto.clear = function () {
  3030. this._list.clear();
  3031. this._map = {};
  3032. };
  3033. var kCSSColorTable = {
  3034. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3035. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3036. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3037. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3038. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3039. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3040. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3041. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3042. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3043. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3044. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3045. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3046. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3047. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3048. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3049. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3050. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3051. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3052. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3053. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3054. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3055. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3056. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3057. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3058. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3059. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3060. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3061. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3062. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3063. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3064. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3065. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3066. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3067. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3068. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3069. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3070. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3071. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3072. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3073. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3074. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3075. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3076. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3077. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3078. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3079. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3080. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3081. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3082. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3083. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3084. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3085. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3086. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3087. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3088. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3089. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3090. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3091. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3092. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3093. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3094. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3095. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3096. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3097. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3098. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3099. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3100. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3101. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3102. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3103. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3104. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3105. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3106. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3107. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3108. };
  3109. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3110. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3111. return i < 0 ? 0 : i > 255 ? 255 : i;
  3112. }
  3113. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3114. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3115. return i < 0 ? 0 : i > 360 ? 360 : i;
  3116. }
  3117. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3118. return f < 0 ? 0 : f > 1 ? 1 : f;
  3119. }
  3120. function parseCssInt(str) { // int or percentage.
  3121. if (str.length && str.charAt(str.length - 1) === '%') {
  3122. return clampCssByte(parseFloat(str) / 100 * 255);
  3123. }
  3124. return clampCssByte(parseInt(str, 10));
  3125. }
  3126. function parseCssFloat(str) { // float or percentage.
  3127. if (str.length && str.charAt(str.length - 1) === '%') {
  3128. return clampCssFloat(parseFloat(str) / 100);
  3129. }
  3130. return clampCssFloat(parseFloat(str));
  3131. }
  3132. function cssHueToRgb(m1, m2, h) {
  3133. if (h < 0) {
  3134. h += 1;
  3135. }
  3136. else if (h > 1) {
  3137. h -= 1;
  3138. }
  3139. if (h * 6 < 1) {
  3140. return m1 + (m2 - m1) * h * 6;
  3141. }
  3142. if (h * 2 < 1) {
  3143. return m2;
  3144. }
  3145. if (h * 3 < 2) {
  3146. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3147. }
  3148. return m1;
  3149. }
  3150. function lerpNumber(a, b, p) {
  3151. return a + (b - a) * p;
  3152. }
  3153. function setRgba(out, r, g, b, a) {
  3154. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  3155. return out;
  3156. }
  3157. function copyRgba(out, a) {
  3158. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  3159. return out;
  3160. }
  3161. var colorCache = new LRU(20);
  3162. var lastRemovedArr = null;
  3163. function putToCache(colorStr, rgbaArr) {
  3164. // Reuse removed array
  3165. if (lastRemovedArr) {
  3166. copyRgba(lastRemovedArr, rgbaArr);
  3167. }
  3168. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3169. }
  3170. /**
  3171. * @param {string} colorStr
  3172. * @param {Array.<number>} out
  3173. * @return {Array.<number>}
  3174. * @memberOf module:zrender/util/color
  3175. */
  3176. function parse(colorStr, rgbaArr) {
  3177. if (!colorStr) {
  3178. return;
  3179. }
  3180. rgbaArr = rgbaArr || [];
  3181. var cached = colorCache.get(colorStr);
  3182. if (cached) {
  3183. return copyRgba(rgbaArr, cached);
  3184. }
  3185. // colorStr may be not string
  3186. colorStr = colorStr + '';
  3187. // Remove all whitespace, not compliant, but should just be more accepting.
  3188. var str = colorStr.replace(/ /g, '').toLowerCase();
  3189. // Color keywords (and transparent) lookup.
  3190. if (str in kCSSColorTable) {
  3191. copyRgba(rgbaArr, kCSSColorTable[str]);
  3192. putToCache(colorStr, rgbaArr);
  3193. return rgbaArr;
  3194. }
  3195. // #abc and #abc123 syntax.
  3196. if (str.charAt(0) === '#') {
  3197. if (str.length === 4) {
  3198. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3199. if (!(iv >= 0 && iv <= 0xfff)) {
  3200. setRgba(rgbaArr, 0, 0, 0, 1);
  3201. return; // Covers NaN.
  3202. }
  3203. setRgba(rgbaArr,
  3204. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3205. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3206. (iv & 0xf) | ((iv & 0xf) << 4),
  3207. 1
  3208. );
  3209. putToCache(colorStr, rgbaArr);
  3210. return rgbaArr;
  3211. }
  3212. else if (str.length === 7) {
  3213. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3214. if (!(iv >= 0 && iv <= 0xffffff)) {
  3215. setRgba(rgbaArr, 0, 0, 0, 1);
  3216. return; // Covers NaN.
  3217. }
  3218. setRgba(rgbaArr,
  3219. (iv & 0xff0000) >> 16,
  3220. (iv & 0xff00) >> 8,
  3221. iv & 0xff,
  3222. 1
  3223. );
  3224. putToCache(colorStr, rgbaArr);
  3225. return rgbaArr;
  3226. }
  3227. return;
  3228. }
  3229. var op = str.indexOf('(');
  3230. var ep = str.indexOf(')');
  3231. if (op !== -1 && ep + 1 === str.length) {
  3232. var fname = str.substr(0, op);
  3233. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3234. var alpha = 1; // To allow case fallthrough.
  3235. switch (fname) {
  3236. case 'rgba':
  3237. if (params.length !== 4) {
  3238. setRgba(rgbaArr, 0, 0, 0, 1);
  3239. return;
  3240. }
  3241. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3242. // Fall through.
  3243. case 'rgb':
  3244. if (params.length !== 3) {
  3245. setRgba(rgbaArr, 0, 0, 0, 1);
  3246. return;
  3247. }
  3248. setRgba(rgbaArr,
  3249. parseCssInt(params[0]),
  3250. parseCssInt(params[1]),
  3251. parseCssInt(params[2]),
  3252. alpha
  3253. );
  3254. putToCache(colorStr, rgbaArr);
  3255. return rgbaArr;
  3256. case 'hsla':
  3257. if (params.length !== 4) {
  3258. setRgba(rgbaArr, 0, 0, 0, 1);
  3259. return;
  3260. }
  3261. params[3] = parseCssFloat(params[3]);
  3262. hsla2rgba(params, rgbaArr);
  3263. putToCache(colorStr, rgbaArr);
  3264. return rgbaArr;
  3265. case 'hsl':
  3266. if (params.length !== 3) {
  3267. setRgba(rgbaArr, 0, 0, 0, 1);
  3268. return;
  3269. }
  3270. hsla2rgba(params, rgbaArr);
  3271. putToCache(colorStr, rgbaArr);
  3272. return rgbaArr;
  3273. default:
  3274. return;
  3275. }
  3276. }
  3277. setRgba(rgbaArr, 0, 0, 0, 1);
  3278. return;
  3279. }
  3280. /**
  3281. * @param {Array.<number>} hsla
  3282. * @param {Array.<number>} rgba
  3283. * @return {Array.<number>} rgba
  3284. */
  3285. function hsla2rgba(hsla, rgba) {
  3286. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3287. // NOTE(deanm): According to the CSS spec s/l should only be
  3288. // percentages, but we don't bother and let float or percentage.
  3289. var s = parseCssFloat(hsla[1]);
  3290. var l = parseCssFloat(hsla[2]);
  3291. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3292. var m1 = l * 2 - m2;
  3293. rgba = rgba || [];
  3294. setRgba(rgba,
  3295. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3296. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3297. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3298. 1
  3299. );
  3300. if (hsla.length === 4) {
  3301. rgba[3] = hsla[3];
  3302. }
  3303. return rgba;
  3304. }
  3305. /**
  3306. * @param {Array.<number>} rgba
  3307. * @return {Array.<number>} hsla
  3308. */
  3309. function rgba2hsla(rgba) {
  3310. if (!rgba) {
  3311. return;
  3312. }
  3313. // RGB from 0 to 255
  3314. var R = rgba[0] / 255;
  3315. var G = rgba[1] / 255;
  3316. var B = rgba[2] / 255;
  3317. var vMin = Math.min(R, G, B); // Min. value of RGB
  3318. var vMax = Math.max(R, G, B); // Max. value of RGB
  3319. var delta = vMax - vMin; // Delta RGB value
  3320. var L = (vMax + vMin) / 2;
  3321. var H;
  3322. var S;
  3323. // HSL results from 0 to 1
  3324. if (delta === 0) {
  3325. H = 0;
  3326. S = 0;
  3327. }
  3328. else {
  3329. if (L < 0.5) {
  3330. S = delta / (vMax + vMin);
  3331. }
  3332. else {
  3333. S = delta / (2 - vMax - vMin);
  3334. }
  3335. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3336. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3337. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3338. if (R === vMax) {
  3339. H = deltaB - deltaG;
  3340. }
  3341. else if (G === vMax) {
  3342. H = (1 / 3) + deltaR - deltaB;
  3343. }
  3344. else if (B === vMax) {
  3345. H = (2 / 3) + deltaG - deltaR;
  3346. }
  3347. if (H < 0) {
  3348. H += 1;
  3349. }
  3350. if (H > 1) {
  3351. H -= 1;
  3352. }
  3353. }
  3354. var hsla = [H * 360, S, L];
  3355. if (rgba[3] != null) {
  3356. hsla.push(rgba[3]);
  3357. }
  3358. return hsla;
  3359. }
  3360. /**
  3361. * @param {string} color
  3362. * @param {number} level
  3363. * @return {string}
  3364. * @memberOf module:zrender/util/color
  3365. */
  3366. function lift(color, level) {
  3367. var colorArr = parse(color);
  3368. if (colorArr) {
  3369. for (var i = 0; i < 3; i++) {
  3370. if (level < 0) {
  3371. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3372. }
  3373. else {
  3374. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3375. }
  3376. if (colorArr[i] > 255) {
  3377. colorArr[i] = 255;
  3378. }
  3379. else if (color[i] < 0) {
  3380. colorArr[i] = 0;
  3381. }
  3382. }
  3383. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3384. }
  3385. }
  3386. /**
  3387. * @param {string} color
  3388. * @return {string}
  3389. * @memberOf module:zrender/util/color
  3390. */
  3391. function toHex(color) {
  3392. var colorArr = parse(color);
  3393. if (colorArr) {
  3394. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3395. }
  3396. }
  3397. /**
  3398. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3399. * @param {number} normalizedValue A float between 0 and 1.
  3400. * @param {Array.<Array.<number>>} colors List of rgba color array
  3401. * @param {Array.<number>} [out] Mapped gba color array
  3402. * @return {Array.<number>} will be null/undefined if input illegal.
  3403. */
  3404. function fastLerp(normalizedValue, colors, out) {
  3405. if (!(colors && colors.length)
  3406. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3407. ) {
  3408. return;
  3409. }
  3410. out = out || [];
  3411. var value = normalizedValue * (colors.length - 1);
  3412. var leftIndex = Math.floor(value);
  3413. var rightIndex = Math.ceil(value);
  3414. var leftColor = colors[leftIndex];
  3415. var rightColor = colors[rightIndex];
  3416. var dv = value - leftIndex;
  3417. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3418. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3419. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3420. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3421. return out;
  3422. }
  3423. /**
  3424. * @deprecated
  3425. */
  3426. var fastMapToColor = fastLerp;
  3427. /**
  3428. * @param {number} normalizedValue A float between 0 and 1.
  3429. * @param {Array.<string>} colors Color list.
  3430. * @param {boolean=} fullOutput Default false.
  3431. * @return {(string|Object)} Result color. If fullOutput,
  3432. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3433. * @memberOf module:zrender/util/color
  3434. */
  3435. function lerp$1(normalizedValue, colors, fullOutput) {
  3436. if (!(colors && colors.length)
  3437. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3438. ) {
  3439. return;
  3440. }
  3441. var value = normalizedValue * (colors.length - 1);
  3442. var leftIndex = Math.floor(value);
  3443. var rightIndex = Math.ceil(value);
  3444. var leftColor = parse(colors[leftIndex]);
  3445. var rightColor = parse(colors[rightIndex]);
  3446. var dv = value - leftIndex;
  3447. var color = stringify(
  3448. [
  3449. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3450. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3451. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3452. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3453. ],
  3454. 'rgba'
  3455. );
  3456. return fullOutput
  3457. ? {
  3458. color: color,
  3459. leftIndex: leftIndex,
  3460. rightIndex: rightIndex,
  3461. value: value
  3462. }
  3463. : color;
  3464. }
  3465. /**
  3466. * @deprecated
  3467. */
  3468. var mapToColor = lerp$1;
  3469. /**
  3470. * @param {string} color
  3471. * @param {number=} h 0 ~ 360, ignore when null.
  3472. * @param {number=} s 0 ~ 1, ignore when null.
  3473. * @param {number=} l 0 ~ 1, ignore when null.
  3474. * @return {string} Color string in rgba format.
  3475. * @memberOf module:zrender/util/color
  3476. */
  3477. function modifyHSL(color, h, s, l) {
  3478. color = parse(color);
  3479. if (color) {
  3480. color = rgba2hsla(color);
  3481. h != null && (color[0] = clampCssAngle(h));
  3482. s != null && (color[1] = parseCssFloat(s));
  3483. l != null && (color[2] = parseCssFloat(l));
  3484. return stringify(hsla2rgba(color), 'rgba');
  3485. }
  3486. }
  3487. /**
  3488. * @param {string} color
  3489. * @param {number=} alpha 0 ~ 1
  3490. * @return {string} Color string in rgba format.
  3491. * @memberOf module:zrender/util/color
  3492. */
  3493. function modifyAlpha(color, alpha) {
  3494. color = parse(color);
  3495. if (color && alpha != null) {
  3496. color[3] = clampCssFloat(alpha);
  3497. return stringify(color, 'rgba');
  3498. }
  3499. }
  3500. /**
  3501. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3502. * @param {string} type 'rgba', 'hsva', ...
  3503. * @return {string} Result color. (If input illegal, return undefined).
  3504. */
  3505. function stringify(arrColor, type) {
  3506. if (!arrColor || !arrColor.length) {
  3507. return;
  3508. }
  3509. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3510. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3511. colorStr += ',' + arrColor[3];
  3512. }
  3513. return type + '(' + colorStr + ')';
  3514. }
  3515. var color = (Object.freeze || Object)({
  3516. parse: parse,
  3517. lift: lift,
  3518. toHex: toHex,
  3519. fastLerp: fastLerp,
  3520. fastMapToColor: fastMapToColor,
  3521. lerp: lerp$1,
  3522. mapToColor: mapToColor,
  3523. modifyHSL: modifyHSL,
  3524. modifyAlpha: modifyAlpha,
  3525. stringify: stringify
  3526. });
  3527. /**
  3528. * @module echarts/animation/Animator
  3529. */
  3530. var arraySlice = Array.prototype.slice;
  3531. function defaultGetter(target, key) {
  3532. return target[key];
  3533. }
  3534. function defaultSetter(target, key, value) {
  3535. target[key] = value;
  3536. }
  3537. /**
  3538. * @param {number} p0
  3539. * @param {number} p1
  3540. * @param {number} percent
  3541. * @return {number}
  3542. */
  3543. function interpolateNumber(p0, p1, percent) {
  3544. return (p1 - p0) * percent + p0;
  3545. }
  3546. /**
  3547. * @param {string} p0
  3548. * @param {string} p1
  3549. * @param {number} percent
  3550. * @return {string}
  3551. */
  3552. function interpolateString(p0, p1, percent) {
  3553. return percent > 0.5 ? p1 : p0;
  3554. }
  3555. /**
  3556. * @param {Array} p0
  3557. * @param {Array} p1
  3558. * @param {number} percent
  3559. * @param {Array} out
  3560. * @param {number} arrDim
  3561. */
  3562. function interpolateArray(p0, p1, percent, out, arrDim) {
  3563. var len = p0.length;
  3564. if (arrDim === 1) {
  3565. for (var i = 0; i < len; i++) {
  3566. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3567. }
  3568. }
  3569. else {
  3570. var len2 = len && p0[0].length;
  3571. for (var i = 0; i < len; i++) {
  3572. for (var j = 0; j < len2; j++) {
  3573. out[i][j] = interpolateNumber(
  3574. p0[i][j], p1[i][j], percent
  3575. );
  3576. }
  3577. }
  3578. }
  3579. }
  3580. // arr0 is source array, arr1 is target array.
  3581. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3582. function fillArr(arr0, arr1, arrDim) {
  3583. var arr0Len = arr0.length;
  3584. var arr1Len = arr1.length;
  3585. if (arr0Len !== arr1Len) {
  3586. // FIXME Not work for TypedArray
  3587. var isPreviousLarger = arr0Len > arr1Len;
  3588. if (isPreviousLarger) {
  3589. // Cut the previous
  3590. arr0.length = arr1Len;
  3591. }
  3592. else {
  3593. // Fill the previous
  3594. for (var i = arr0Len; i < arr1Len; i++) {
  3595. arr0.push(
  3596. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3597. );
  3598. }
  3599. }
  3600. }
  3601. // Handling NaN value
  3602. var len2 = arr0[0] && arr0[0].length;
  3603. for (var i = 0; i < arr0.length; i++) {
  3604. if (arrDim === 1) {
  3605. if (isNaN(arr0[i])) {
  3606. arr0[i] = arr1[i];
  3607. }
  3608. }
  3609. else {
  3610. for (var j = 0; j < len2; j++) {
  3611. if (isNaN(arr0[i][j])) {
  3612. arr0[i][j] = arr1[i][j];
  3613. }
  3614. }
  3615. }
  3616. }
  3617. }
  3618. /**
  3619. * @param {Array} arr0
  3620. * @param {Array} arr1
  3621. * @param {number} arrDim
  3622. * @return {boolean}
  3623. */
  3624. function isArraySame(arr0, arr1, arrDim) {
  3625. if (arr0 === arr1) {
  3626. return true;
  3627. }
  3628. var len = arr0.length;
  3629. if (len !== arr1.length) {
  3630. return false;
  3631. }
  3632. if (arrDim === 1) {
  3633. for (var i = 0; i < len; i++) {
  3634. if (arr0[i] !== arr1[i]) {
  3635. return false;
  3636. }
  3637. }
  3638. }
  3639. else {
  3640. var len2 = arr0[0].length;
  3641. for (var i = 0; i < len; i++) {
  3642. for (var j = 0; j < len2; j++) {
  3643. if (arr0[i][j] !== arr1[i][j]) {
  3644. return false;
  3645. }
  3646. }
  3647. }
  3648. }
  3649. return true;
  3650. }
  3651. /**
  3652. * Catmull Rom interpolate array
  3653. * @param {Array} p0
  3654. * @param {Array} p1
  3655. * @param {Array} p2
  3656. * @param {Array} p3
  3657. * @param {number} t
  3658. * @param {number} t2
  3659. * @param {number} t3
  3660. * @param {Array} out
  3661. * @param {number} arrDim
  3662. */
  3663. function catmullRomInterpolateArray(
  3664. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3665. ) {
  3666. var len = p0.length;
  3667. if (arrDim === 1) {
  3668. for (var i = 0; i < len; i++) {
  3669. out[i] = catmullRomInterpolate(
  3670. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3671. );
  3672. }
  3673. }
  3674. else {
  3675. var len2 = p0[0].length;
  3676. for (var i = 0; i < len; i++) {
  3677. for (var j = 0; j < len2; j++) {
  3678. out[i][j] = catmullRomInterpolate(
  3679. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3680. t, t2, t3
  3681. );
  3682. }
  3683. }
  3684. }
  3685. }
  3686. /**
  3687. * Catmull Rom interpolate number
  3688. * @param {number} p0
  3689. * @param {number} p1
  3690. * @param {number} p2
  3691. * @param {number} p3
  3692. * @param {number} t
  3693. * @param {number} t2
  3694. * @param {number} t3
  3695. * @return {number}
  3696. */
  3697. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3698. var v0 = (p2 - p0) * 0.5;
  3699. var v1 = (p3 - p1) * 0.5;
  3700. return (2 * (p1 - p2) + v0 + v1) * t3
  3701. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3702. + v0 * t + p1;
  3703. }
  3704. function cloneValue(value) {
  3705. if (isArrayLike(value)) {
  3706. var len = value.length;
  3707. if (isArrayLike(value[0])) {
  3708. var ret = [];
  3709. for (var i = 0; i < len; i++) {
  3710. ret.push(arraySlice.call(value[i]));
  3711. }
  3712. return ret;
  3713. }
  3714. return arraySlice.call(value);
  3715. }
  3716. return value;
  3717. }
  3718. function rgba2String(rgba) {
  3719. rgba[0] = Math.floor(rgba[0]);
  3720. rgba[1] = Math.floor(rgba[1]);
  3721. rgba[2] = Math.floor(rgba[2]);
  3722. return 'rgba(' + rgba.join(',') + ')';
  3723. }
  3724. function getArrayDim(keyframes) {
  3725. var lastValue = keyframes[keyframes.length - 1].value;
  3726. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3727. }
  3728. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3729. var getter = animator._getter;
  3730. var setter = animator._setter;
  3731. var useSpline = easing === 'spline';
  3732. var trackLen = keyframes.length;
  3733. if (!trackLen) {
  3734. return;
  3735. }
  3736. // Guess data type
  3737. var firstVal = keyframes[0].value;
  3738. var isValueArray = isArrayLike(firstVal);
  3739. var isValueColor = false;
  3740. var isValueString = false;
  3741. // For vertices morphing
  3742. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3743. var trackMaxTime;
  3744. // Sort keyframe as ascending
  3745. keyframes.sort(function (a, b) {
  3746. return a.time - b.time;
  3747. });
  3748. trackMaxTime = keyframes[trackLen - 1].time;
  3749. // Percents of each keyframe
  3750. var kfPercents = [];
  3751. // Value of each keyframe
  3752. var kfValues = [];
  3753. var prevValue = keyframes[0].value;
  3754. var isAllValueEqual = true;
  3755. for (var i = 0; i < trackLen; i++) {
  3756. kfPercents.push(keyframes[i].time / trackMaxTime);
  3757. // Assume value is a color when it is a string
  3758. var value = keyframes[i].value;
  3759. // Check if value is equal, deep check if value is array
  3760. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3761. || (!isValueArray && value === prevValue))) {
  3762. isAllValueEqual = false;
  3763. }
  3764. prevValue = value;
  3765. // Try converting a string to a color array
  3766. if (typeof value === 'string') {
  3767. var colorArray = parse(value);
  3768. if (colorArray) {
  3769. value = colorArray;
  3770. isValueColor = true;
  3771. }
  3772. else {
  3773. isValueString = true;
  3774. }
  3775. }
  3776. kfValues.push(value);
  3777. }
  3778. if (!forceAnimate && isAllValueEqual) {
  3779. return;
  3780. }
  3781. var lastValue = kfValues[trackLen - 1];
  3782. // Polyfill array and NaN value
  3783. for (var i = 0; i < trackLen - 1; i++) {
  3784. if (isValueArray) {
  3785. fillArr(kfValues[i], lastValue, arrDim);
  3786. }
  3787. else {
  3788. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3789. kfValues[i] = lastValue;
  3790. }
  3791. }
  3792. }
  3793. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3794. // Cache the key of last frame to speed up when
  3795. // animation playback is sequency
  3796. var lastFrame = 0;
  3797. var lastFramePercent = 0;
  3798. var start;
  3799. var w;
  3800. var p0;
  3801. var p1;
  3802. var p2;
  3803. var p3;
  3804. if (isValueColor) {
  3805. var rgba = [0, 0, 0, 0];
  3806. }
  3807. var onframe = function (target, percent) {
  3808. // Find the range keyframes
  3809. // kf1-----kf2---------current--------kf3
  3810. // find kf2 and kf3 and do interpolation
  3811. var frame;
  3812. // In the easing function like elasticOut, percent may less than 0
  3813. if (percent < 0) {
  3814. frame = 0;
  3815. }
  3816. else if (percent < lastFramePercent) {
  3817. // Start from next key
  3818. // PENDING start from lastFrame ?
  3819. start = Math.min(lastFrame + 1, trackLen - 1);
  3820. for (frame = start; frame >= 0; frame--) {
  3821. if (kfPercents[frame] <= percent) {
  3822. break;
  3823. }
  3824. }
  3825. // PENDING really need to do this ?
  3826. frame = Math.min(frame, trackLen - 2);
  3827. }
  3828. else {
  3829. for (frame = lastFrame; frame < trackLen; frame++) {
  3830. if (kfPercents[frame] > percent) {
  3831. break;
  3832. }
  3833. }
  3834. frame = Math.min(frame - 1, trackLen - 2);
  3835. }
  3836. lastFrame = frame;
  3837. lastFramePercent = percent;
  3838. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3839. if (range === 0) {
  3840. return;
  3841. }
  3842. else {
  3843. w = (percent - kfPercents[frame]) / range;
  3844. }
  3845. if (useSpline) {
  3846. p1 = kfValues[frame];
  3847. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3848. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3849. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3850. if (isValueArray) {
  3851. catmullRomInterpolateArray(
  3852. p0, p1, p2, p3, w, w * w, w * w * w,
  3853. getter(target, propName),
  3854. arrDim
  3855. );
  3856. }
  3857. else {
  3858. var value;
  3859. if (isValueColor) {
  3860. value = catmullRomInterpolateArray(
  3861. p0, p1, p2, p3, w, w * w, w * w * w,
  3862. rgba, 1
  3863. );
  3864. value = rgba2String(rgba);
  3865. }
  3866. else if (isValueString) {
  3867. // String is step(0.5)
  3868. return interpolateString(p1, p2, w);
  3869. }
  3870. else {
  3871. value = catmullRomInterpolate(
  3872. p0, p1, p2, p3, w, w * w, w * w * w
  3873. );
  3874. }
  3875. setter(
  3876. target,
  3877. propName,
  3878. value
  3879. );
  3880. }
  3881. }
  3882. else {
  3883. if (isValueArray) {
  3884. interpolateArray(
  3885. kfValues[frame], kfValues[frame + 1], w,
  3886. getter(target, propName),
  3887. arrDim
  3888. );
  3889. }
  3890. else {
  3891. var value;
  3892. if (isValueColor) {
  3893. interpolateArray(
  3894. kfValues[frame], kfValues[frame + 1], w,
  3895. rgba, 1
  3896. );
  3897. value = rgba2String(rgba);
  3898. }
  3899. else if (isValueString) {
  3900. // String is step(0.5)
  3901. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3902. }
  3903. else {
  3904. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3905. }
  3906. setter(
  3907. target,
  3908. propName,
  3909. value
  3910. );
  3911. }
  3912. }
  3913. };
  3914. var clip = new Clip({
  3915. target: animator._target,
  3916. life: trackMaxTime,
  3917. loop: animator._loop,
  3918. delay: animator._delay,
  3919. onframe: onframe,
  3920. ondestroy: oneTrackDone
  3921. });
  3922. if (easing && easing !== 'spline') {
  3923. clip.easing = easing;
  3924. }
  3925. return clip;
  3926. }
  3927. /**
  3928. * @alias module:zrender/animation/Animator
  3929. * @constructor
  3930. * @param {Object} target
  3931. * @param {boolean} loop
  3932. * @param {Function} getter
  3933. * @param {Function} setter
  3934. */
  3935. var Animator = function (target, loop, getter, setter) {
  3936. this._tracks = {};
  3937. this._target = target;
  3938. this._loop = loop || false;
  3939. this._getter = getter || defaultGetter;
  3940. this._setter = setter || defaultSetter;
  3941. this._clipCount = 0;
  3942. this._delay = 0;
  3943. this._doneList = [];
  3944. this._onframeList = [];
  3945. this._clipList = [];
  3946. };
  3947. Animator.prototype = {
  3948. /**
  3949. * 设置动画关键帧
  3950. * @param {number} time 关键帧时间,单位是ms
  3951. * @param {Object} props 关键帧的属性值,key-value表示
  3952. * @return {module:zrender/animation/Animator}
  3953. */
  3954. when: function (time /* ms */, props) {
  3955. var tracks = this._tracks;
  3956. for (var propName in props) {
  3957. if (!props.hasOwnProperty(propName)) {
  3958. continue;
  3959. }
  3960. if (!tracks[propName]) {
  3961. tracks[propName] = [];
  3962. // Invalid value
  3963. var value = this._getter(this._target, propName);
  3964. if (value == null) {
  3965. // zrLog('Invalid property ' + propName);
  3966. continue;
  3967. }
  3968. // If time is 0
  3969. // Then props is given initialize value
  3970. // Else
  3971. // Initialize value from current prop value
  3972. if (time !== 0) {
  3973. tracks[propName].push({
  3974. time: 0,
  3975. value: cloneValue(value)
  3976. });
  3977. }
  3978. }
  3979. tracks[propName].push({
  3980. time: time,
  3981. value: props[propName]
  3982. });
  3983. }
  3984. return this;
  3985. },
  3986. /**
  3987. * 添加动画每一帧的回调函数
  3988. * @param {Function} callback
  3989. * @return {module:zrender/animation/Animator}
  3990. */
  3991. during: function (callback) {
  3992. this._onframeList.push(callback);
  3993. return this;
  3994. },
  3995. pause: function () {
  3996. for (var i = 0; i < this._clipList.length; i++) {
  3997. this._clipList[i].pause();
  3998. }
  3999. this._paused = true;
  4000. },
  4001. resume: function () {
  4002. for (var i = 0; i < this._clipList.length; i++) {
  4003. this._clipList[i].resume();
  4004. }
  4005. this._paused = false;
  4006. },
  4007. isPaused: function () {
  4008. return !!this._paused;
  4009. },
  4010. _doneCallback: function () {
  4011. // Clear all tracks
  4012. this._tracks = {};
  4013. // Clear all clips
  4014. this._clipList.length = 0;
  4015. var doneList = this._doneList;
  4016. var len = doneList.length;
  4017. for (var i = 0; i < len; i++) {
  4018. doneList[i].call(this);
  4019. }
  4020. },
  4021. /**
  4022. * 开始执行动画
  4023. * @param {string|Function} [easing]
  4024. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4025. * @param {boolean} forceAnimate
  4026. * @return {module:zrender/animation/Animator}
  4027. */
  4028. start: function (easing, forceAnimate) {
  4029. var self = this;
  4030. var clipCount = 0;
  4031. var oneTrackDone = function () {
  4032. clipCount--;
  4033. if (!clipCount) {
  4034. self._doneCallback();
  4035. }
  4036. };
  4037. var lastClip;
  4038. for (var propName in this._tracks) {
  4039. if (!this._tracks.hasOwnProperty(propName)) {
  4040. continue;
  4041. }
  4042. var clip = createTrackClip(
  4043. this, easing, oneTrackDone,
  4044. this._tracks[propName], propName, forceAnimate
  4045. );
  4046. if (clip) {
  4047. this._clipList.push(clip);
  4048. clipCount++;
  4049. // If start after added to animation
  4050. if (this.animation) {
  4051. this.animation.addClip(clip);
  4052. }
  4053. lastClip = clip;
  4054. }
  4055. }
  4056. // Add during callback on the last clip
  4057. if (lastClip) {
  4058. var oldOnFrame = lastClip.onframe;
  4059. lastClip.onframe = function (target, percent) {
  4060. oldOnFrame(target, percent);
  4061. for (var i = 0; i < self._onframeList.length; i++) {
  4062. self._onframeList[i](target, percent);
  4063. }
  4064. };
  4065. }
  4066. // This optimization will help the case that in the upper application
  4067. // the view may be refreshed frequently, where animation will be
  4068. // called repeatly but nothing changed.
  4069. if (!clipCount) {
  4070. this._doneCallback();
  4071. }
  4072. return this;
  4073. },
  4074. /**
  4075. * 停止动画
  4076. * @param {boolean} forwardToLast If move to last frame before stop
  4077. */
  4078. stop: function (forwardToLast) {
  4079. var clipList = this._clipList;
  4080. var animation = this.animation;
  4081. for (var i = 0; i < clipList.length; i++) {
  4082. var clip = clipList[i];
  4083. if (forwardToLast) {
  4084. // Move to last frame before stop
  4085. clip.onframe(this._target, 1);
  4086. }
  4087. animation && animation.removeClip(clip);
  4088. }
  4089. clipList.length = 0;
  4090. },
  4091. /**
  4092. * 设置动画延迟开始的时间
  4093. * @param {number} time 单位ms
  4094. * @return {module:zrender/animation/Animator}
  4095. */
  4096. delay: function (time) {
  4097. this._delay = time;
  4098. return this;
  4099. },
  4100. /**
  4101. * 添加动画结束的回调
  4102. * @param {Function} cb
  4103. * @return {module:zrender/animation/Animator}
  4104. */
  4105. done: function (cb) {
  4106. if (cb) {
  4107. this._doneList.push(cb);
  4108. }
  4109. return this;
  4110. },
  4111. /**
  4112. * @return {Array.<module:zrender/animation/Clip>}
  4113. */
  4114. getClips: function () {
  4115. return this._clipList;
  4116. }
  4117. };
  4118. var dpr = 1;
  4119. // If in browser environment
  4120. if (typeof window !== 'undefined') {
  4121. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4122. }
  4123. /**
  4124. * config默认配置项
  4125. * @exports zrender/config
  4126. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4127. */
  4128. /**
  4129. * debug日志选项:catchBrushException为true下有效
  4130. * 0 : 不生成debug数据,发布用
  4131. * 1 : 异常抛出,调试用
  4132. * 2 : 控制台输出,调试用
  4133. */
  4134. var debugMode = 0;
  4135. // retina 屏幕优化
  4136. var devicePixelRatio = dpr;
  4137. var log = function () {
  4138. };
  4139. if (debugMode === 1) {
  4140. log = function () {
  4141. for (var k in arguments) {
  4142. throw new Error(arguments[k]);
  4143. }
  4144. };
  4145. }
  4146. else if (debugMode > 1) {
  4147. log = function () {
  4148. for (var k in arguments) {
  4149. console.log(arguments[k]);
  4150. }
  4151. };
  4152. }
  4153. var zrLog = log;
  4154. /**
  4155. * @alias modue:zrender/mixin/Animatable
  4156. * @constructor
  4157. */
  4158. var Animatable = function () {
  4159. /**
  4160. * @type {Array.<module:zrender/animation/Animator>}
  4161. * @readOnly
  4162. */
  4163. this.animators = [];
  4164. };
  4165. Animatable.prototype = {
  4166. constructor: Animatable,
  4167. /**
  4168. * 动画
  4169. *
  4170. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4171. * @param {boolean} [loop] Whether to loop animation.
  4172. * @return {module:zrender/animation/Animator}
  4173. * @example:
  4174. * el.animate('style', false)
  4175. * .when(1000, {x: 10} )
  4176. * .done(function(){ // Animation done })
  4177. * .start()
  4178. */
  4179. animate: function (path, loop) {
  4180. var target;
  4181. var animatingShape = false;
  4182. var el = this;
  4183. var zr = this.__zr;
  4184. if (path) {
  4185. var pathSplitted = path.split('.');
  4186. var prop = el;
  4187. // If animating shape
  4188. animatingShape = pathSplitted[0] === 'shape';
  4189. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4190. if (!prop) {
  4191. continue;
  4192. }
  4193. prop = prop[pathSplitted[i]];
  4194. }
  4195. if (prop) {
  4196. target = prop;
  4197. }
  4198. }
  4199. else {
  4200. target = el;
  4201. }
  4202. if (!target) {
  4203. zrLog(
  4204. 'Property "'
  4205. + path
  4206. + '" is not existed in element '
  4207. + el.id
  4208. );
  4209. return;
  4210. }
  4211. var animators = el.animators;
  4212. var animator = new Animator(target, loop);
  4213. animator.during(function (target) {
  4214. el.dirty(animatingShape);
  4215. })
  4216. .done(function () {
  4217. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4218. animators.splice(indexOf(animators, animator), 1);
  4219. });
  4220. animators.push(animator);
  4221. // If animate after added to the zrender
  4222. if (zr) {
  4223. zr.animation.addAnimator(animator);
  4224. }
  4225. return animator;
  4226. },
  4227. /**
  4228. * 停止动画
  4229. * @param {boolean} forwardToLast If move to last frame before stop
  4230. */
  4231. stopAnimation: function (forwardToLast) {
  4232. var animators = this.animators;
  4233. var len = animators.length;
  4234. for (var i = 0; i < len; i++) {
  4235. animators[i].stop(forwardToLast);
  4236. }
  4237. animators.length = 0;
  4238. return this;
  4239. },
  4240. /**
  4241. * Caution: this method will stop previous animation.
  4242. * So do not use this method to one element twice before
  4243. * animation starts, unless you know what you are doing.
  4244. * @param {Object} target
  4245. * @param {number} [time=500] Time in ms
  4246. * @param {string} [easing='linear']
  4247. * @param {number} [delay=0]
  4248. * @param {Function} [callback]
  4249. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4250. * immediently when target values are the same as current values.
  4251. *
  4252. * @example
  4253. * // Animate position
  4254. * el.animateTo({
  4255. * position: [10, 10]
  4256. * }, function () { // done })
  4257. *
  4258. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4259. * el.animateTo({
  4260. * shape: {
  4261. * width: 500
  4262. * },
  4263. * style: {
  4264. * fill: 'red'
  4265. * }
  4266. * position: [10, 10]
  4267. * }, 100, 100, 'cubicOut', function () { // done })
  4268. */
  4269. // TODO Return animation key
  4270. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4271. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4272. },
  4273. /**
  4274. * Animate from the target state to current state.
  4275. * The params and the return value are the same as `this.animateTo`.
  4276. */
  4277. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4278. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4279. }
  4280. };
  4281. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4282. // animateTo(target, time, easing, callback);
  4283. if (isString(delay)) {
  4284. callback = easing;
  4285. easing = delay;
  4286. delay = 0;
  4287. }
  4288. // animateTo(target, time, delay, callback);
  4289. else if (isFunction$1(easing)) {
  4290. callback = easing;
  4291. easing = 'linear';
  4292. delay = 0;
  4293. }
  4294. // animateTo(target, time, callback);
  4295. else if (isFunction$1(delay)) {
  4296. callback = delay;
  4297. delay = 0;
  4298. }
  4299. // animateTo(target, callback)
  4300. else if (isFunction$1(time)) {
  4301. callback = time;
  4302. time = 500;
  4303. }
  4304. // animateTo(target)
  4305. else if (!time) {
  4306. time = 500;
  4307. }
  4308. // Stop all previous animations
  4309. animatable.stopAnimation();
  4310. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4311. // Animators may be removed immediately after start
  4312. // if there is nothing to animate
  4313. var animators = animatable.animators.slice();
  4314. var count = animators.length;
  4315. function done() {
  4316. count--;
  4317. if (!count) {
  4318. callback && callback();
  4319. }
  4320. }
  4321. // No animators. This should be checked before animators[i].start(),
  4322. // because 'done' may be executed immediately if no need to animate.
  4323. if (!count) {
  4324. callback && callback();
  4325. }
  4326. // Start after all animators created
  4327. // Incase any animator is done immediately when all animation properties are not changed
  4328. for (var i = 0; i < animators.length; i++) {
  4329. animators[i]
  4330. .done(done)
  4331. .start(easing, forceAnimate);
  4332. }
  4333. }
  4334. /**
  4335. * @param {string} path=''
  4336. * @param {Object} source=animatable
  4337. * @param {Object} target
  4338. * @param {number} [time=500]
  4339. * @param {number} [delay=0]
  4340. * @param {boolean} [reverse] If `true`, animate
  4341. * from the `target` to current state.
  4342. *
  4343. * @example
  4344. * // Animate position
  4345. * el._animateToShallow({
  4346. * position: [10, 10]
  4347. * })
  4348. *
  4349. * // Animate shape, style and position in 100ms, delayed 100ms
  4350. * el._animateToShallow({
  4351. * shape: {
  4352. * width: 500
  4353. * },
  4354. * style: {
  4355. * fill: 'red'
  4356. * }
  4357. * position: [10, 10]
  4358. * }, 100, 100)
  4359. */
  4360. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4361. var objShallow = {};
  4362. var propertyCount = 0;
  4363. for (var name in target) {
  4364. if (!target.hasOwnProperty(name)) {
  4365. continue;
  4366. }
  4367. if (source[name] != null) {
  4368. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4369. animateToShallow(
  4370. animatable,
  4371. path ? path + '.' + name : name,
  4372. source[name],
  4373. target[name],
  4374. time,
  4375. delay,
  4376. reverse
  4377. );
  4378. }
  4379. else {
  4380. if (reverse) {
  4381. objShallow[name] = source[name];
  4382. setAttrByPath(animatable, path, name, target[name]);
  4383. }
  4384. else {
  4385. objShallow[name] = target[name];
  4386. }
  4387. propertyCount++;
  4388. }
  4389. }
  4390. else if (target[name] != null && !reverse) {
  4391. setAttrByPath(animatable, path, name, target[name]);
  4392. }
  4393. }
  4394. if (propertyCount > 0) {
  4395. animatable.animate(path, false)
  4396. .when(time == null ? 500 : time, objShallow)
  4397. .delay(delay || 0);
  4398. }
  4399. }
  4400. function setAttrByPath(el, path, name, value) {
  4401. // Attr directly if not has property
  4402. // FIXME, if some property not needed for element ?
  4403. if (!path) {
  4404. el.attr(name, value);
  4405. }
  4406. else {
  4407. // Only support set shape or style
  4408. var props = {};
  4409. props[path] = {};
  4410. props[path][name] = value;
  4411. el.attr(props);
  4412. }
  4413. }
  4414. /**
  4415. * @alias module:zrender/Element
  4416. * @constructor
  4417. * @extends {module:zrender/mixin/Animatable}
  4418. * @extends {module:zrender/mixin/Transformable}
  4419. * @extends {module:zrender/mixin/Eventful}
  4420. */
  4421. var Element = function (opts) { // jshint ignore:line
  4422. Transformable.call(this, opts);
  4423. Eventful.call(this, opts);
  4424. Animatable.call(this, opts);
  4425. /**
  4426. * 画布元素ID
  4427. * @type {string}
  4428. */
  4429. this.id = opts.id || guid();
  4430. };
  4431. Element.prototype = {
  4432. /**
  4433. * 元素类型
  4434. * Element type
  4435. * @type {string}
  4436. */
  4437. type: 'element',
  4438. /**
  4439. * 元素名字
  4440. * Element name
  4441. * @type {string}
  4442. */
  4443. name: '',
  4444. /**
  4445. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4446. * ZRender instance will be assigned when element is associated with zrender
  4447. * @name module:/zrender/Element#__zr
  4448. * @type {module:zrender/ZRender}
  4449. */
  4450. __zr: null,
  4451. /**
  4452. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4453. * If ignore drawing and events of the element object
  4454. * @name module:/zrender/Element#ignore
  4455. * @type {boolean}
  4456. * @default false
  4457. */
  4458. ignore: false,
  4459. /**
  4460. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4461. * 该路径会继承被裁减对象的变换
  4462. * @type {module:zrender/graphic/Path}
  4463. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4464. * @readOnly
  4465. */
  4466. clipPath: null,
  4467. /**
  4468. * 是否是 Group
  4469. * @type {boolean}
  4470. */
  4471. isGroup: false,
  4472. /**
  4473. * Drift element
  4474. * @param {number} dx dx on the global space
  4475. * @param {number} dy dy on the global space
  4476. */
  4477. drift: function (dx, dy) {
  4478. switch (this.draggable) {
  4479. case 'horizontal':
  4480. dy = 0;
  4481. break;
  4482. case 'vertical':
  4483. dx = 0;
  4484. break;
  4485. }
  4486. var m = this.transform;
  4487. if (!m) {
  4488. m = this.transform = [1, 0, 0, 1, 0, 0];
  4489. }
  4490. m[4] += dx;
  4491. m[5] += dy;
  4492. this.decomposeTransform();
  4493. this.dirty(false);
  4494. },
  4495. /**
  4496. * Hook before update
  4497. */
  4498. beforeUpdate: function () {},
  4499. /**
  4500. * Hook after update
  4501. */
  4502. afterUpdate: function () {},
  4503. /**
  4504. * Update each frame
  4505. */
  4506. update: function () {
  4507. this.updateTransform();
  4508. },
  4509. /**
  4510. * @param {Function} cb
  4511. * @param {} context
  4512. */
  4513. traverse: function (cb, context) {},
  4514. /**
  4515. * @protected
  4516. */
  4517. attrKV: function (key, value) {
  4518. if (key === 'position' || key === 'scale' || key === 'origin') {
  4519. // Copy the array
  4520. if (value) {
  4521. var target = this[key];
  4522. if (!target) {
  4523. target = this[key] = [];
  4524. }
  4525. target[0] = value[0];
  4526. target[1] = value[1];
  4527. }
  4528. }
  4529. else {
  4530. this[key] = value;
  4531. }
  4532. },
  4533. /**
  4534. * Hide the element
  4535. */
  4536. hide: function () {
  4537. this.ignore = true;
  4538. this.__zr && this.__zr.refresh();
  4539. },
  4540. /**
  4541. * Show the element
  4542. */
  4543. show: function () {
  4544. this.ignore = false;
  4545. this.__zr && this.__zr.refresh();
  4546. },
  4547. /**
  4548. * @param {string|Object} key
  4549. * @param {*} value
  4550. */
  4551. attr: function (key, value) {
  4552. if (typeof key === 'string') {
  4553. this.attrKV(key, value);
  4554. }
  4555. else if (isObject$1(key)) {
  4556. for (var name in key) {
  4557. if (key.hasOwnProperty(name)) {
  4558. this.attrKV(name, key[name]);
  4559. }
  4560. }
  4561. }
  4562. this.dirty(false);
  4563. return this;
  4564. },
  4565. /**
  4566. * @param {module:zrender/graphic/Path} clipPath
  4567. */
  4568. setClipPath: function (clipPath) {
  4569. var zr = this.__zr;
  4570. if (zr) {
  4571. clipPath.addSelfToZr(zr);
  4572. }
  4573. // Remove previous clip path
  4574. if (this.clipPath && this.clipPath !== clipPath) {
  4575. this.removeClipPath();
  4576. }
  4577. this.clipPath = clipPath;
  4578. clipPath.__zr = zr;
  4579. clipPath.__clipTarget = this;
  4580. this.dirty(false);
  4581. },
  4582. /**
  4583. */
  4584. removeClipPath: function () {
  4585. var clipPath = this.clipPath;
  4586. if (clipPath) {
  4587. if (clipPath.__zr) {
  4588. clipPath.removeSelfFromZr(clipPath.__zr);
  4589. }
  4590. clipPath.__zr = null;
  4591. clipPath.__clipTarget = null;
  4592. this.clipPath = null;
  4593. this.dirty(false);
  4594. }
  4595. },
  4596. /**
  4597. * Add self from zrender instance.
  4598. * Not recursively because it will be invoked when element added to storage.
  4599. * @param {module:zrender/ZRender} zr
  4600. */
  4601. addSelfToZr: function (zr) {
  4602. this.__zr = zr;
  4603. // 添加动画
  4604. var animators = this.animators;
  4605. if (animators) {
  4606. for (var i = 0; i < animators.length; i++) {
  4607. zr.animation.addAnimator(animators[i]);
  4608. }
  4609. }
  4610. if (this.clipPath) {
  4611. this.clipPath.addSelfToZr(zr);
  4612. }
  4613. },
  4614. /**
  4615. * Remove self from zrender instance.
  4616. * Not recursively because it will be invoked when element added to storage.
  4617. * @param {module:zrender/ZRender} zr
  4618. */
  4619. removeSelfFromZr: function (zr) {
  4620. this.__zr = null;
  4621. // 移除动画
  4622. var animators = this.animators;
  4623. if (animators) {
  4624. for (var i = 0; i < animators.length; i++) {
  4625. zr.animation.removeAnimator(animators[i]);
  4626. }
  4627. }
  4628. if (this.clipPath) {
  4629. this.clipPath.removeSelfFromZr(zr);
  4630. }
  4631. }
  4632. };
  4633. mixin(Element, Animatable);
  4634. mixin(Element, Transformable);
  4635. mixin(Element, Eventful);
  4636. /**
  4637. * @module echarts/core/BoundingRect
  4638. */
  4639. var v2ApplyTransform = applyTransform;
  4640. var mathMin = Math.min;
  4641. var mathMax = Math.max;
  4642. /**
  4643. * @alias module:echarts/core/BoundingRect
  4644. */
  4645. function BoundingRect(x, y, width, height) {
  4646. if (width < 0) {
  4647. x = x + width;
  4648. width = -width;
  4649. }
  4650. if (height < 0) {
  4651. y = y + height;
  4652. height = -height;
  4653. }
  4654. /**
  4655. * @type {number}
  4656. */
  4657. this.x = x;
  4658. /**
  4659. * @type {number}
  4660. */
  4661. this.y = y;
  4662. /**
  4663. * @type {number}
  4664. */
  4665. this.width = width;
  4666. /**
  4667. * @type {number}
  4668. */
  4669. this.height = height;
  4670. }
  4671. BoundingRect.prototype = {
  4672. constructor: BoundingRect,
  4673. /**
  4674. * @param {module:echarts/core/BoundingRect} other
  4675. */
  4676. union: function (other) {
  4677. var x = mathMin(other.x, this.x);
  4678. var y = mathMin(other.y, this.y);
  4679. this.width = mathMax(
  4680. other.x + other.width,
  4681. this.x + this.width
  4682. ) - x;
  4683. this.height = mathMax(
  4684. other.y + other.height,
  4685. this.y + this.height
  4686. ) - y;
  4687. this.x = x;
  4688. this.y = y;
  4689. },
  4690. /**
  4691. * @param {Array.<number>} m
  4692. * @methods
  4693. */
  4694. applyTransform: (function () {
  4695. var lt = [];
  4696. var rb = [];
  4697. var lb = [];
  4698. var rt = [];
  4699. return function (m) {
  4700. // In case usage like this
  4701. // el.getBoundingRect().applyTransform(el.transform)
  4702. // And element has no transform
  4703. if (!m) {
  4704. return;
  4705. }
  4706. lt[0] = lb[0] = this.x;
  4707. lt[1] = rt[1] = this.y;
  4708. rb[0] = rt[0] = this.x + this.width;
  4709. rb[1] = lb[1] = this.y + this.height;
  4710. v2ApplyTransform(lt, lt, m);
  4711. v2ApplyTransform(rb, rb, m);
  4712. v2ApplyTransform(lb, lb, m);
  4713. v2ApplyTransform(rt, rt, m);
  4714. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4715. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4716. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4717. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4718. this.width = maxX - this.x;
  4719. this.height = maxY - this.y;
  4720. };
  4721. })(),
  4722. /**
  4723. * Calculate matrix of transforming from self to target rect
  4724. * @param {module:zrender/core/BoundingRect} b
  4725. * @return {Array.<number>}
  4726. */
  4727. calculateTransform: function (b) {
  4728. var a = this;
  4729. var sx = b.width / a.width;
  4730. var sy = b.height / a.height;
  4731. var m = create$1();
  4732. // 矩阵右乘
  4733. translate(m, m, [-a.x, -a.y]);
  4734. scale$1(m, m, [sx, sy]);
  4735. translate(m, m, [b.x, b.y]);
  4736. return m;
  4737. },
  4738. /**
  4739. * @param {(module:echarts/core/BoundingRect|Object)} b
  4740. * @return {boolean}
  4741. */
  4742. intersect: function (b) {
  4743. if (!b) {
  4744. return false;
  4745. }
  4746. if (!(b instanceof BoundingRect)) {
  4747. // Normalize negative width/height.
  4748. b = BoundingRect.create(b);
  4749. }
  4750. var a = this;
  4751. var ax0 = a.x;
  4752. var ax1 = a.x + a.width;
  4753. var ay0 = a.y;
  4754. var ay1 = a.y + a.height;
  4755. var bx0 = b.x;
  4756. var bx1 = b.x + b.width;
  4757. var by0 = b.y;
  4758. var by1 = b.y + b.height;
  4759. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4760. },
  4761. contain: function (x, y) {
  4762. var rect = this;
  4763. return x >= rect.x
  4764. && x <= (rect.x + rect.width)
  4765. && y >= rect.y
  4766. && y <= (rect.y + rect.height);
  4767. },
  4768. /**
  4769. * @return {module:echarts/core/BoundingRect}
  4770. */
  4771. clone: function () {
  4772. return new BoundingRect(this.x, this.y, this.width, this.height);
  4773. },
  4774. /**
  4775. * Copy from another rect
  4776. */
  4777. copy: function (other) {
  4778. this.x = other.x;
  4779. this.y = other.y;
  4780. this.width = other.width;
  4781. this.height = other.height;
  4782. },
  4783. plain: function () {
  4784. return {
  4785. x: this.x,
  4786. y: this.y,
  4787. width: this.width,
  4788. height: this.height
  4789. };
  4790. }
  4791. };
  4792. /**
  4793. * @param {Object|module:zrender/core/BoundingRect} rect
  4794. * @param {number} rect.x
  4795. * @param {number} rect.y
  4796. * @param {number} rect.width
  4797. * @param {number} rect.height
  4798. * @return {module:zrender/core/BoundingRect}
  4799. */
  4800. BoundingRect.create = function (rect) {
  4801. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4802. };
  4803. /**
  4804. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4805. * @module zrender/graphic/Group
  4806. * @example
  4807. * var Group = require('zrender/container/Group');
  4808. * var Circle = require('zrender/graphic/shape/Circle');
  4809. * var g = new Group();
  4810. * g.position[0] = 100;
  4811. * g.position[1] = 100;
  4812. * g.add(new Circle({
  4813. * style: {
  4814. * x: 100,
  4815. * y: 100,
  4816. * r: 20,
  4817. * }
  4818. * }));
  4819. * zr.add(g);
  4820. */
  4821. /**
  4822. * @alias module:zrender/graphic/Group
  4823. * @constructor
  4824. * @extends module:zrender/mixin/Transformable
  4825. * @extends module:zrender/mixin/Eventful
  4826. */
  4827. var Group = function (opts) {
  4828. opts = opts || {};
  4829. Element.call(this, opts);
  4830. for (var key in opts) {
  4831. if (opts.hasOwnProperty(key)) {
  4832. this[key] = opts[key];
  4833. }
  4834. }
  4835. this._children = [];
  4836. this.__storage = null;
  4837. this.__dirty = true;
  4838. };
  4839. Group.prototype = {
  4840. constructor: Group,
  4841. isGroup: true,
  4842. /**
  4843. * @type {string}
  4844. */
  4845. type: 'group',
  4846. /**
  4847. * 所有子孙元素是否响应鼠标事件
  4848. * @name module:/zrender/container/Group#silent
  4849. * @type {boolean}
  4850. * @default false
  4851. */
  4852. silent: false,
  4853. /**
  4854. * @return {Array.<module:zrender/Element>}
  4855. */
  4856. children: function () {
  4857. return this._children.slice();
  4858. },
  4859. /**
  4860. * 获取指定 index 的儿子节点
  4861. * @param {number} idx
  4862. * @return {module:zrender/Element}
  4863. */
  4864. childAt: function (idx) {
  4865. return this._children[idx];
  4866. },
  4867. /**
  4868. * 获取指定名字的儿子节点
  4869. * @param {string} name
  4870. * @return {module:zrender/Element}
  4871. */
  4872. childOfName: function (name) {
  4873. var children = this._children;
  4874. for (var i = 0; i < children.length; i++) {
  4875. if (children[i].name === name) {
  4876. return children[i];
  4877. }
  4878. }
  4879. },
  4880. /**
  4881. * @return {number}
  4882. */
  4883. childCount: function () {
  4884. return this._children.length;
  4885. },
  4886. /**
  4887. * 添加子节点到最后
  4888. * @param {module:zrender/Element} child
  4889. */
  4890. add: function (child) {
  4891. if (child && child !== this && child.parent !== this) {
  4892. this._children.push(child);
  4893. this._doAdd(child);
  4894. }
  4895. return this;
  4896. },
  4897. /**
  4898. * 添加子节点在 nextSibling 之前
  4899. * @param {module:zrender/Element} child
  4900. * @param {module:zrender/Element} nextSibling
  4901. */
  4902. addBefore: function (child, nextSibling) {
  4903. if (child && child !== this && child.parent !== this
  4904. && nextSibling && nextSibling.parent === this) {
  4905. var children = this._children;
  4906. var idx = children.indexOf(nextSibling);
  4907. if (idx >= 0) {
  4908. children.splice(idx, 0, child);
  4909. this._doAdd(child);
  4910. }
  4911. }
  4912. return this;
  4913. },
  4914. _doAdd: function (child) {
  4915. if (child.parent) {
  4916. child.parent.remove(child);
  4917. }
  4918. child.parent = this;
  4919. var storage = this.__storage;
  4920. var zr = this.__zr;
  4921. if (storage && storage !== child.__storage) {
  4922. storage.addToStorage(child);
  4923. if (child instanceof Group) {
  4924. child.addChildrenToStorage(storage);
  4925. }
  4926. }
  4927. zr && zr.refresh();
  4928. },
  4929. /**
  4930. * 移除子节点
  4931. * @param {module:zrender/Element} child
  4932. */
  4933. remove: function (child) {
  4934. var zr = this.__zr;
  4935. var storage = this.__storage;
  4936. var children = this._children;
  4937. var idx = indexOf(children, child);
  4938. if (idx < 0) {
  4939. return this;
  4940. }
  4941. children.splice(idx, 1);
  4942. child.parent = null;
  4943. if (storage) {
  4944. storage.delFromStorage(child);
  4945. if (child instanceof Group) {
  4946. child.delChildrenFromStorage(storage);
  4947. }
  4948. }
  4949. zr && zr.refresh();
  4950. return this;
  4951. },
  4952. /**
  4953. * 移除所有子节点
  4954. */
  4955. removeAll: function () {
  4956. var children = this._children;
  4957. var storage = this.__storage;
  4958. var child;
  4959. var i;
  4960. for (i = 0; i < children.length; i++) {
  4961. child = children[i];
  4962. if (storage) {
  4963. storage.delFromStorage(child);
  4964. if (child instanceof Group) {
  4965. child.delChildrenFromStorage(storage);
  4966. }
  4967. }
  4968. child.parent = null;
  4969. }
  4970. children.length = 0;
  4971. return this;
  4972. },
  4973. /**
  4974. * 遍历所有子节点
  4975. * @param {Function} cb
  4976. * @param {} context
  4977. */
  4978. eachChild: function (cb, context) {
  4979. var children = this._children;
  4980. for (var i = 0; i < children.length; i++) {
  4981. var child = children[i];
  4982. cb.call(context, child, i);
  4983. }
  4984. return this;
  4985. },
  4986. /**
  4987. * 深度优先遍历所有子孙节点
  4988. * @param {Function} cb
  4989. * @param {} context
  4990. */
  4991. traverse: function (cb, context) {
  4992. for (var i = 0; i < this._children.length; i++) {
  4993. var child = this._children[i];
  4994. cb.call(context, child);
  4995. if (child.type === 'group') {
  4996. child.traverse(cb, context);
  4997. }
  4998. }
  4999. return this;
  5000. },
  5001. addChildrenToStorage: function (storage) {
  5002. for (var i = 0; i < this._children.length; i++) {
  5003. var child = this._children[i];
  5004. storage.addToStorage(child);
  5005. if (child instanceof Group) {
  5006. child.addChildrenToStorage(storage);
  5007. }
  5008. }
  5009. },
  5010. delChildrenFromStorage: function (storage) {
  5011. for (var i = 0; i < this._children.length; i++) {
  5012. var child = this._children[i];
  5013. storage.delFromStorage(child);
  5014. if (child instanceof Group) {
  5015. child.delChildrenFromStorage(storage);
  5016. }
  5017. }
  5018. },
  5019. dirty: function () {
  5020. this.__dirty = true;
  5021. this.__zr && this.__zr.refresh();
  5022. return this;
  5023. },
  5024. /**
  5025. * @return {module:zrender/core/BoundingRect}
  5026. */
  5027. getBoundingRect: function (includeChildren) {
  5028. // TODO Caching
  5029. var rect = null;
  5030. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5031. var children = includeChildren || this._children;
  5032. var tmpMat = [];
  5033. for (var i = 0; i < children.length; i++) {
  5034. var child = children[i];
  5035. if (child.ignore || child.invisible) {
  5036. continue;
  5037. }
  5038. var childRect = child.getBoundingRect();
  5039. var transform = child.getLocalTransform(tmpMat);
  5040. // TODO
  5041. // The boundingRect cacluated by transforming original
  5042. // rect may be bigger than the actual bundingRect when rotation
  5043. // is used. (Consider a circle rotated aginst its center, where
  5044. // the actual boundingRect should be the same as that not be
  5045. // rotated.) But we can not find better approach to calculate
  5046. // actual boundingRect yet, considering performance.
  5047. if (transform) {
  5048. tmpRect.copy(childRect);
  5049. tmpRect.applyTransform(transform);
  5050. rect = rect || tmpRect.clone();
  5051. rect.union(tmpRect);
  5052. }
  5053. else {
  5054. rect = rect || childRect.clone();
  5055. rect.union(childRect);
  5056. }
  5057. }
  5058. return rect || tmpRect;
  5059. }
  5060. };
  5061. inherits(Group, Element);
  5062. // https://github.com/mziccard/node-timsort
  5063. var DEFAULT_MIN_MERGE = 32;
  5064. var DEFAULT_MIN_GALLOPING = 7;
  5065. function minRunLength(n) {
  5066. var r = 0;
  5067. while (n >= DEFAULT_MIN_MERGE) {
  5068. r |= n & 1;
  5069. n >>= 1;
  5070. }
  5071. return n + r;
  5072. }
  5073. function makeAscendingRun(array, lo, hi, compare) {
  5074. var runHi = lo + 1;
  5075. if (runHi === hi) {
  5076. return 1;
  5077. }
  5078. if (compare(array[runHi++], array[lo]) < 0) {
  5079. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5080. runHi++;
  5081. }
  5082. reverseRun(array, lo, runHi);
  5083. }
  5084. else {
  5085. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5086. runHi++;
  5087. }
  5088. }
  5089. return runHi - lo;
  5090. }
  5091. function reverseRun(array, lo, hi) {
  5092. hi--;
  5093. while (lo < hi) {
  5094. var t = array[lo];
  5095. array[lo++] = array[hi];
  5096. array[hi--] = t;
  5097. }
  5098. }
  5099. function binaryInsertionSort(array, lo, hi, start, compare) {
  5100. if (start === lo) {
  5101. start++;
  5102. }
  5103. for (; start < hi; start++) {
  5104. var pivot = array[start];
  5105. var left = lo;
  5106. var right = start;
  5107. var mid;
  5108. while (left < right) {
  5109. mid = left + right >>> 1;
  5110. if (compare(pivot, array[mid]) < 0) {
  5111. right = mid;
  5112. }
  5113. else {
  5114. left = mid + 1;
  5115. }
  5116. }
  5117. var n = start - left;
  5118. switch (n) {
  5119. case 3:
  5120. array[left + 3] = array[left + 2];
  5121. case 2:
  5122. array[left + 2] = array[left + 1];
  5123. case 1:
  5124. array[left + 1] = array[left];
  5125. break;
  5126. default:
  5127. while (n > 0) {
  5128. array[left + n] = array[left + n - 1];
  5129. n--;
  5130. }
  5131. }
  5132. array[left] = pivot;
  5133. }
  5134. }
  5135. function gallopLeft(value, array, start, length, hint, compare) {
  5136. var lastOffset = 0;
  5137. var maxOffset = 0;
  5138. var offset = 1;
  5139. if (compare(value, array[start + hint]) > 0) {
  5140. maxOffset = length - hint;
  5141. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5142. lastOffset = offset;
  5143. offset = (offset << 1) + 1;
  5144. if (offset <= 0) {
  5145. offset = maxOffset;
  5146. }
  5147. }
  5148. if (offset > maxOffset) {
  5149. offset = maxOffset;
  5150. }
  5151. lastOffset += hint;
  5152. offset += hint;
  5153. }
  5154. else {
  5155. maxOffset = hint + 1;
  5156. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5157. lastOffset = offset;
  5158. offset = (offset << 1) + 1;
  5159. if (offset <= 0) {
  5160. offset = maxOffset;
  5161. }
  5162. }
  5163. if (offset > maxOffset) {
  5164. offset = maxOffset;
  5165. }
  5166. var tmp = lastOffset;
  5167. lastOffset = hint - offset;
  5168. offset = hint - tmp;
  5169. }
  5170. lastOffset++;
  5171. while (lastOffset < offset) {
  5172. var m = lastOffset + (offset - lastOffset >>> 1);
  5173. if (compare(value, array[start + m]) > 0) {
  5174. lastOffset = m + 1;
  5175. }
  5176. else {
  5177. offset = m;
  5178. }
  5179. }
  5180. return offset;
  5181. }
  5182. function gallopRight(value, array, start, length, hint, compare) {
  5183. var lastOffset = 0;
  5184. var maxOffset = 0;
  5185. var offset = 1;
  5186. if (compare(value, array[start + hint]) < 0) {
  5187. maxOffset = hint + 1;
  5188. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5189. lastOffset = offset;
  5190. offset = (offset << 1) + 1;
  5191. if (offset <= 0) {
  5192. offset = maxOffset;
  5193. }
  5194. }
  5195. if (offset > maxOffset) {
  5196. offset = maxOffset;
  5197. }
  5198. var tmp = lastOffset;
  5199. lastOffset = hint - offset;
  5200. offset = hint - tmp;
  5201. }
  5202. else {
  5203. maxOffset = length - hint;
  5204. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5205. lastOffset = offset;
  5206. offset = (offset << 1) + 1;
  5207. if (offset <= 0) {
  5208. offset = maxOffset;
  5209. }
  5210. }
  5211. if (offset > maxOffset) {
  5212. offset = maxOffset;
  5213. }
  5214. lastOffset += hint;
  5215. offset += hint;
  5216. }
  5217. lastOffset++;
  5218. while (lastOffset < offset) {
  5219. var m = lastOffset + (offset - lastOffset >>> 1);
  5220. if (compare(value, array[start + m]) < 0) {
  5221. offset = m;
  5222. }
  5223. else {
  5224. lastOffset = m + 1;
  5225. }
  5226. }
  5227. return offset;
  5228. }
  5229. function TimSort(array, compare) {
  5230. var minGallop = DEFAULT_MIN_GALLOPING;
  5231. var runStart;
  5232. var runLength;
  5233. var stackSize = 0;
  5234. var tmp = [];
  5235. runStart = [];
  5236. runLength = [];
  5237. function pushRun(_runStart, _runLength) {
  5238. runStart[stackSize] = _runStart;
  5239. runLength[stackSize] = _runLength;
  5240. stackSize += 1;
  5241. }
  5242. function mergeRuns() {
  5243. while (stackSize > 1) {
  5244. var n = stackSize - 2;
  5245. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  5246. if (runLength[n - 1] < runLength[n + 1]) {
  5247. n--;
  5248. }
  5249. }
  5250. else if (runLength[n] > runLength[n + 1]) {
  5251. break;
  5252. }
  5253. mergeAt(n);
  5254. }
  5255. }
  5256. function forceMergeRuns() {
  5257. while (stackSize > 1) {
  5258. var n = stackSize - 2;
  5259. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5260. n--;
  5261. }
  5262. mergeAt(n);
  5263. }
  5264. }
  5265. function mergeAt(i) {
  5266. var start1 = runStart[i];
  5267. var length1 = runLength[i];
  5268. var start2 = runStart[i + 1];
  5269. var length2 = runLength[i + 1];
  5270. runLength[i] = length1 + length2;
  5271. if (i === stackSize - 3) {
  5272. runStart[i + 1] = runStart[i + 2];
  5273. runLength[i + 1] = runLength[i + 2];
  5274. }
  5275. stackSize--;
  5276. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5277. start1 += k;
  5278. length1 -= k;
  5279. if (length1 === 0) {
  5280. return;
  5281. }
  5282. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5283. if (length2 === 0) {
  5284. return;
  5285. }
  5286. if (length1 <= length2) {
  5287. mergeLow(start1, length1, start2, length2);
  5288. }
  5289. else {
  5290. mergeHigh(start1, length1, start2, length2);
  5291. }
  5292. }
  5293. function mergeLow(start1, length1, start2, length2) {
  5294. var i = 0;
  5295. for (i = 0; i < length1; i++) {
  5296. tmp[i] = array[start1 + i];
  5297. }
  5298. var cursor1 = 0;
  5299. var cursor2 = start2;
  5300. var dest = start1;
  5301. array[dest++] = array[cursor2++];
  5302. if (--length2 === 0) {
  5303. for (i = 0; i < length1; i++) {
  5304. array[dest + i] = tmp[cursor1 + i];
  5305. }
  5306. return;
  5307. }
  5308. if (length1 === 1) {
  5309. for (i = 0; i < length2; i++) {
  5310. array[dest + i] = array[cursor2 + i];
  5311. }
  5312. array[dest + length2] = tmp[cursor1];
  5313. return;
  5314. }
  5315. var _minGallop = minGallop;
  5316. var count1, count2, exit;
  5317. while (1) {
  5318. count1 = 0;
  5319. count2 = 0;
  5320. exit = false;
  5321. do {
  5322. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5323. array[dest++] = array[cursor2++];
  5324. count2++;
  5325. count1 = 0;
  5326. if (--length2 === 0) {
  5327. exit = true;
  5328. break;
  5329. }
  5330. }
  5331. else {
  5332. array[dest++] = tmp[cursor1++];
  5333. count1++;
  5334. count2 = 0;
  5335. if (--length1 === 1) {
  5336. exit = true;
  5337. break;
  5338. }
  5339. }
  5340. } while ((count1 | count2) < _minGallop);
  5341. if (exit) {
  5342. break;
  5343. }
  5344. do {
  5345. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5346. if (count1 !== 0) {
  5347. for (i = 0; i < count1; i++) {
  5348. array[dest + i] = tmp[cursor1 + i];
  5349. }
  5350. dest += count1;
  5351. cursor1 += count1;
  5352. length1 -= count1;
  5353. if (length1 <= 1) {
  5354. exit = true;
  5355. break;
  5356. }
  5357. }
  5358. array[dest++] = array[cursor2++];
  5359. if (--length2 === 0) {
  5360. exit = true;
  5361. break;
  5362. }
  5363. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5364. if (count2 !== 0) {
  5365. for (i = 0; i < count2; i++) {
  5366. array[dest + i] = array[cursor2 + i];
  5367. }
  5368. dest += count2;
  5369. cursor2 += count2;
  5370. length2 -= count2;
  5371. if (length2 === 0) {
  5372. exit = true;
  5373. break;
  5374. }
  5375. }
  5376. array[dest++] = tmp[cursor1++];
  5377. if (--length1 === 1) {
  5378. exit = true;
  5379. break;
  5380. }
  5381. _minGallop--;
  5382. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5383. if (exit) {
  5384. break;
  5385. }
  5386. if (_minGallop < 0) {
  5387. _minGallop = 0;
  5388. }
  5389. _minGallop += 2;
  5390. }
  5391. minGallop = _minGallop;
  5392. minGallop < 1 && (minGallop = 1);
  5393. if (length1 === 1) {
  5394. for (i = 0; i < length2; i++) {
  5395. array[dest + i] = array[cursor2 + i];
  5396. }
  5397. array[dest + length2] = tmp[cursor1];
  5398. }
  5399. else if (length1 === 0) {
  5400. throw new Error();
  5401. // throw new Error('mergeLow preconditions were not respected');
  5402. }
  5403. else {
  5404. for (i = 0; i < length1; i++) {
  5405. array[dest + i] = tmp[cursor1 + i];
  5406. }
  5407. }
  5408. }
  5409. function mergeHigh(start1, length1, start2, length2) {
  5410. var i = 0;
  5411. for (i = 0; i < length2; i++) {
  5412. tmp[i] = array[start2 + i];
  5413. }
  5414. var cursor1 = start1 + length1 - 1;
  5415. var cursor2 = length2 - 1;
  5416. var dest = start2 + length2 - 1;
  5417. var customCursor = 0;
  5418. var customDest = 0;
  5419. array[dest--] = array[cursor1--];
  5420. if (--length1 === 0) {
  5421. customCursor = dest - (length2 - 1);
  5422. for (i = 0; i < length2; i++) {
  5423. array[customCursor + i] = tmp[i];
  5424. }
  5425. return;
  5426. }
  5427. if (length2 === 1) {
  5428. dest -= length1;
  5429. cursor1 -= length1;
  5430. customDest = dest + 1;
  5431. customCursor = cursor1 + 1;
  5432. for (i = length1 - 1; i >= 0; i--) {
  5433. array[customDest + i] = array[customCursor + i];
  5434. }
  5435. array[dest] = tmp[cursor2];
  5436. return;
  5437. }
  5438. var _minGallop = minGallop;
  5439. while (true) {
  5440. var count1 = 0;
  5441. var count2 = 0;
  5442. var exit = false;
  5443. do {
  5444. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5445. array[dest--] = array[cursor1--];
  5446. count1++;
  5447. count2 = 0;
  5448. if (--length1 === 0) {
  5449. exit = true;
  5450. break;
  5451. }
  5452. }
  5453. else {
  5454. array[dest--] = tmp[cursor2--];
  5455. count2++;
  5456. count1 = 0;
  5457. if (--length2 === 1) {
  5458. exit = true;
  5459. break;
  5460. }
  5461. }
  5462. } while ((count1 | count2) < _minGallop);
  5463. if (exit) {
  5464. break;
  5465. }
  5466. do {
  5467. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5468. if (count1 !== 0) {
  5469. dest -= count1;
  5470. cursor1 -= count1;
  5471. length1 -= count1;
  5472. customDest = dest + 1;
  5473. customCursor = cursor1 + 1;
  5474. for (i = count1 - 1; i >= 0; i--) {
  5475. array[customDest + i] = array[customCursor + i];
  5476. }
  5477. if (length1 === 0) {
  5478. exit = true;
  5479. break;
  5480. }
  5481. }
  5482. array[dest--] = tmp[cursor2--];
  5483. if (--length2 === 1) {
  5484. exit = true;
  5485. break;
  5486. }
  5487. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5488. if (count2 !== 0) {
  5489. dest -= count2;
  5490. cursor2 -= count2;
  5491. length2 -= count2;
  5492. customDest = dest + 1;
  5493. customCursor = cursor2 + 1;
  5494. for (i = 0; i < count2; i++) {
  5495. array[customDest + i] = tmp[customCursor + i];
  5496. }
  5497. if (length2 <= 1) {
  5498. exit = true;
  5499. break;
  5500. }
  5501. }
  5502. array[dest--] = array[cursor1--];
  5503. if (--length1 === 0) {
  5504. exit = true;
  5505. break;
  5506. }
  5507. _minGallop--;
  5508. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5509. if (exit) {
  5510. break;
  5511. }
  5512. if (_minGallop < 0) {
  5513. _minGallop = 0;
  5514. }
  5515. _minGallop += 2;
  5516. }
  5517. minGallop = _minGallop;
  5518. if (minGallop < 1) {
  5519. minGallop = 1;
  5520. }
  5521. if (length2 === 1) {
  5522. dest -= length1;
  5523. cursor1 -= length1;
  5524. customDest = dest + 1;
  5525. customCursor = cursor1 + 1;
  5526. for (i = length1 - 1; i >= 0; i--) {
  5527. array[customDest + i] = array[customCursor + i];
  5528. }
  5529. array[dest] = tmp[cursor2];
  5530. }
  5531. else if (length2 === 0) {
  5532. throw new Error();
  5533. // throw new Error('mergeHigh preconditions were not respected');
  5534. }
  5535. else {
  5536. customCursor = dest - (length2 - 1);
  5537. for (i = 0; i < length2; i++) {
  5538. array[customCursor + i] = tmp[i];
  5539. }
  5540. }
  5541. }
  5542. this.mergeRuns = mergeRuns;
  5543. this.forceMergeRuns = forceMergeRuns;
  5544. this.pushRun = pushRun;
  5545. }
  5546. function sort(array, compare, lo, hi) {
  5547. if (!lo) {
  5548. lo = 0;
  5549. }
  5550. if (!hi) {
  5551. hi = array.length;
  5552. }
  5553. var remaining = hi - lo;
  5554. if (remaining < 2) {
  5555. return;
  5556. }
  5557. var runLength = 0;
  5558. if (remaining < DEFAULT_MIN_MERGE) {
  5559. runLength = makeAscendingRun(array, lo, hi, compare);
  5560. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5561. return;
  5562. }
  5563. var ts = new TimSort(array, compare);
  5564. var minRun = minRunLength(remaining);
  5565. do {
  5566. runLength = makeAscendingRun(array, lo, hi, compare);
  5567. if (runLength < minRun) {
  5568. var force = remaining;
  5569. if (force > minRun) {
  5570. force = minRun;
  5571. }
  5572. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5573. runLength = force;
  5574. }
  5575. ts.pushRun(lo, runLength);
  5576. ts.mergeRuns();
  5577. remaining -= runLength;
  5578. lo += runLength;
  5579. } while (remaining !== 0);
  5580. ts.forceMergeRuns();
  5581. }
  5582. // Use timsort because in most case elements are partially sorted
  5583. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5584. function shapeCompareFunc(a, b) {
  5585. if (a.zlevel === b.zlevel) {
  5586. if (a.z === b.z) {
  5587. // if (a.z2 === b.z2) {
  5588. // // FIXME Slow has renderidx compare
  5589. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5590. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5591. // return a.__renderidx - b.__renderidx;
  5592. // }
  5593. return a.z2 - b.z2;
  5594. }
  5595. return a.z - b.z;
  5596. }
  5597. return a.zlevel - b.zlevel;
  5598. }
  5599. /**
  5600. * 内容仓库 (M)
  5601. * @alias module:zrender/Storage
  5602. * @constructor
  5603. */
  5604. var Storage = function () { // jshint ignore:line
  5605. this._roots = [];
  5606. this._displayList = [];
  5607. this._displayListLen = 0;
  5608. };
  5609. Storage.prototype = {
  5610. constructor: Storage,
  5611. /**
  5612. * @param {Function} cb
  5613. *
  5614. */
  5615. traverse: function (cb, context) {
  5616. for (var i = 0; i < this._roots.length; i++) {
  5617. this._roots[i].traverse(cb, context);
  5618. }
  5619. },
  5620. /**
  5621. * 返回所有图形的绘制队列
  5622. * @param {boolean} [update=false] 是否在返回前更新该数组
  5623. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5624. *
  5625. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5626. * @return {Array.<module:zrender/graphic/Displayable>}
  5627. */
  5628. getDisplayList: function (update, includeIgnore) {
  5629. includeIgnore = includeIgnore || false;
  5630. if (update) {
  5631. this.updateDisplayList(includeIgnore);
  5632. }
  5633. return this._displayList;
  5634. },
  5635. /**
  5636. * 更新图形的绘制队列。
  5637. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5638. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5639. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5640. */
  5641. updateDisplayList: function (includeIgnore) {
  5642. this._displayListLen = 0;
  5643. var roots = this._roots;
  5644. var displayList = this._displayList;
  5645. for (var i = 0, len = roots.length; i < len; i++) {
  5646. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5647. }
  5648. displayList.length = this._displayListLen;
  5649. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5650. },
  5651. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5652. if (el.ignore && !includeIgnore) {
  5653. return;
  5654. }
  5655. el.beforeUpdate();
  5656. if (el.__dirty) {
  5657. el.update();
  5658. }
  5659. el.afterUpdate();
  5660. var userSetClipPath = el.clipPath;
  5661. if (userSetClipPath) {
  5662. // FIXME 效率影响
  5663. if (clipPaths) {
  5664. clipPaths = clipPaths.slice();
  5665. }
  5666. else {
  5667. clipPaths = [];
  5668. }
  5669. var currentClipPath = userSetClipPath;
  5670. var parentClipPath = el;
  5671. // Recursively add clip path
  5672. while (currentClipPath) {
  5673. // clipPath 的变换是基于使用这个 clipPath 的元素
  5674. currentClipPath.parent = parentClipPath;
  5675. currentClipPath.updateTransform();
  5676. clipPaths.push(currentClipPath);
  5677. parentClipPath = currentClipPath;
  5678. currentClipPath = currentClipPath.clipPath;
  5679. }
  5680. }
  5681. if (el.isGroup) {
  5682. var children = el._children;
  5683. for (var i = 0; i < children.length; i++) {
  5684. var child = children[i];
  5685. // Force to mark as dirty if group is dirty
  5686. // FIXME __dirtyPath ?
  5687. if (el.__dirty) {
  5688. child.__dirty = true;
  5689. }
  5690. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5691. }
  5692. // Mark group clean here
  5693. el.__dirty = false;
  5694. }
  5695. else {
  5696. el.__clipPaths = clipPaths;
  5697. this._displayList[this._displayListLen++] = el;
  5698. }
  5699. },
  5700. /**
  5701. * 添加图形(Shape)或者组(Group)到根节点
  5702. * @param {module:zrender/Element} el
  5703. */
  5704. addRoot: function (el) {
  5705. if (el.__storage === this) {
  5706. return;
  5707. }
  5708. if (el instanceof Group) {
  5709. el.addChildrenToStorage(this);
  5710. }
  5711. this.addToStorage(el);
  5712. this._roots.push(el);
  5713. },
  5714. /**
  5715. * 删除指定的图形(Shape)或者组(Group)
  5716. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5717. */
  5718. delRoot: function (el) {
  5719. if (el == null) {
  5720. // 不指定el清空
  5721. for (var i = 0; i < this._roots.length; i++) {
  5722. var root = this._roots[i];
  5723. if (root instanceof Group) {
  5724. root.delChildrenFromStorage(this);
  5725. }
  5726. }
  5727. this._roots = [];
  5728. this._displayList = [];
  5729. this._displayListLen = 0;
  5730. return;
  5731. }
  5732. if (el instanceof Array) {
  5733. for (var i = 0, l = el.length; i < l; i++) {
  5734. this.delRoot(el[i]);
  5735. }
  5736. return;
  5737. }
  5738. var idx = indexOf(this._roots, el);
  5739. if (idx >= 0) {
  5740. this.delFromStorage(el);
  5741. this._roots.splice(idx, 1);
  5742. if (el instanceof Group) {
  5743. el.delChildrenFromStorage(this);
  5744. }
  5745. }
  5746. },
  5747. addToStorage: function (el) {
  5748. if (el) {
  5749. el.__storage = this;
  5750. el.dirty(false);
  5751. }
  5752. return this;
  5753. },
  5754. delFromStorage: function (el) {
  5755. if (el) {
  5756. el.__storage = null;
  5757. }
  5758. return this;
  5759. },
  5760. /**
  5761. * 清空并且释放Storage
  5762. */
  5763. dispose: function () {
  5764. this._renderList =
  5765. this._roots = null;
  5766. },
  5767. displayableSortFunc: shapeCompareFunc
  5768. };
  5769. var SHADOW_PROPS = {
  5770. 'shadowBlur': 1,
  5771. 'shadowOffsetX': 1,
  5772. 'shadowOffsetY': 1,
  5773. 'textShadowBlur': 1,
  5774. 'textShadowOffsetX': 1,
  5775. 'textShadowOffsetY': 1,
  5776. 'textBoxShadowBlur': 1,
  5777. 'textBoxShadowOffsetX': 1,
  5778. 'textBoxShadowOffsetY': 1
  5779. };
  5780. var fixShadow = function (ctx, propName, value) {
  5781. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5782. return value *= ctx.dpr;
  5783. }
  5784. return value;
  5785. };
  5786. var ContextCachedBy = {
  5787. NONE: 0,
  5788. STYLE_BIND: 1,
  5789. PLAIN_TEXT: 2
  5790. };
  5791. // Avoid confused with 0/false.
  5792. var WILL_BE_RESTORED = 9;
  5793. var STYLE_COMMON_PROPS = [
  5794. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5795. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5796. ];
  5797. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5798. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5799. var Style = function (opts) {
  5800. this.extendFrom(opts, false);
  5801. };
  5802. function createLinearGradient(ctx, obj, rect) {
  5803. var x = obj.x == null ? 0 : obj.x;
  5804. var x2 = obj.x2 == null ? 1 : obj.x2;
  5805. var y = obj.y == null ? 0 : obj.y;
  5806. var y2 = obj.y2 == null ? 0 : obj.y2;
  5807. if (!obj.global) {
  5808. x = x * rect.width + rect.x;
  5809. x2 = x2 * rect.width + rect.x;
  5810. y = y * rect.height + rect.y;
  5811. y2 = y2 * rect.height + rect.y;
  5812. }
  5813. // Fix NaN when rect is Infinity
  5814. x = isNaN(x) ? 0 : x;
  5815. x2 = isNaN(x2) ? 1 : x2;
  5816. y = isNaN(y) ? 0 : y;
  5817. y2 = isNaN(y2) ? 0 : y2;
  5818. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5819. return canvasGradient;
  5820. }
  5821. function createRadialGradient(ctx, obj, rect) {
  5822. var width = rect.width;
  5823. var height = rect.height;
  5824. var min = Math.min(width, height);
  5825. var x = obj.x == null ? 0.5 : obj.x;
  5826. var y = obj.y == null ? 0.5 : obj.y;
  5827. var r = obj.r == null ? 0.5 : obj.r;
  5828. if (!obj.global) {
  5829. x = x * width + rect.x;
  5830. y = y * height + rect.y;
  5831. r = r * min;
  5832. }
  5833. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5834. return canvasGradient;
  5835. }
  5836. Style.prototype = {
  5837. constructor: Style,
  5838. /**
  5839. * @type {string}
  5840. */
  5841. fill: '#000',
  5842. /**
  5843. * @type {string}
  5844. */
  5845. stroke: null,
  5846. /**
  5847. * @type {number}
  5848. */
  5849. opacity: 1,
  5850. /**
  5851. * @type {number}
  5852. */
  5853. fillOpacity: null,
  5854. /**
  5855. * @type {number}
  5856. */
  5857. strokeOpacity: null,
  5858. /**
  5859. * @type {Array.<number>}
  5860. */
  5861. lineDash: null,
  5862. /**
  5863. * @type {number}
  5864. */
  5865. lineDashOffset: 0,
  5866. /**
  5867. * @type {number}
  5868. */
  5869. shadowBlur: 0,
  5870. /**
  5871. * @type {number}
  5872. */
  5873. shadowOffsetX: 0,
  5874. /**
  5875. * @type {number}
  5876. */
  5877. shadowOffsetY: 0,
  5878. /**
  5879. * @type {number}
  5880. */
  5881. lineWidth: 1,
  5882. /**
  5883. * If stroke ignore scale
  5884. * @type {Boolean}
  5885. */
  5886. strokeNoScale: false,
  5887. // Bounding rect text configuration
  5888. // Not affected by element transform
  5889. /**
  5890. * @type {string}
  5891. */
  5892. text: null,
  5893. /**
  5894. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5895. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5896. * So do not visit it directly in upper application (like echarts),
  5897. * but use `contain/text#makeFont` instead.
  5898. * @type {string}
  5899. */
  5900. font: null,
  5901. /**
  5902. * The same as font. Use font please.
  5903. * @deprecated
  5904. * @type {string}
  5905. */
  5906. textFont: null,
  5907. /**
  5908. * It helps merging respectively, rather than parsing an entire font string.
  5909. * @type {string}
  5910. */
  5911. fontStyle: null,
  5912. /**
  5913. * It helps merging respectively, rather than parsing an entire font string.
  5914. * @type {string}
  5915. */
  5916. fontWeight: null,
  5917. /**
  5918. * It helps merging respectively, rather than parsing an entire font string.
  5919. * Should be 12 but not '12px'.
  5920. * @type {number}
  5921. */
  5922. fontSize: null,
  5923. /**
  5924. * It helps merging respectively, rather than parsing an entire font string.
  5925. * @type {string}
  5926. */
  5927. fontFamily: null,
  5928. /**
  5929. * Reserved for special functinality, like 'hr'.
  5930. * @type {string}
  5931. */
  5932. textTag: null,
  5933. /**
  5934. * @type {string}
  5935. */
  5936. textFill: '#000',
  5937. /**
  5938. * @type {string}
  5939. */
  5940. textStroke: null,
  5941. /**
  5942. * @type {number}
  5943. */
  5944. textWidth: null,
  5945. /**
  5946. * Only for textBackground.
  5947. * @type {number}
  5948. */
  5949. textHeight: null,
  5950. /**
  5951. * textStroke may be set as some color as a default
  5952. * value in upper applicaion, where the default value
  5953. * of textStrokeWidth should be 0 to make sure that
  5954. * user can choose to do not use text stroke.
  5955. * @type {number}
  5956. */
  5957. textStrokeWidth: 0,
  5958. /**
  5959. * @type {number}
  5960. */
  5961. textLineHeight: null,
  5962. /**
  5963. * 'inside', 'left', 'right', 'top', 'bottom'
  5964. * [x, y]
  5965. * Based on x, y of rect.
  5966. * @type {string|Array.<number>}
  5967. * @default 'inside'
  5968. */
  5969. textPosition: 'inside',
  5970. /**
  5971. * If not specified, use the boundingRect of a `displayable`.
  5972. * @type {Object}
  5973. */
  5974. textRect: null,
  5975. /**
  5976. * [x, y]
  5977. * @type {Array.<number>}
  5978. */
  5979. textOffset: null,
  5980. /**
  5981. * @type {string}
  5982. */
  5983. textAlign: null,
  5984. /**
  5985. * @type {string}
  5986. */
  5987. textVerticalAlign: null,
  5988. /**
  5989. * @type {number}
  5990. */
  5991. textDistance: 5,
  5992. /**
  5993. * @type {string}
  5994. */
  5995. textShadowColor: 'transparent',
  5996. /**
  5997. * @type {number}
  5998. */
  5999. textShadowBlur: 0,
  6000. /**
  6001. * @type {number}
  6002. */
  6003. textShadowOffsetX: 0,
  6004. /**
  6005. * @type {number}
  6006. */
  6007. textShadowOffsetY: 0,
  6008. /**
  6009. * @type {string}
  6010. */
  6011. textBoxShadowColor: 'transparent',
  6012. /**
  6013. * @type {number}
  6014. */
  6015. textBoxShadowBlur: 0,
  6016. /**
  6017. * @type {number}
  6018. */
  6019. textBoxShadowOffsetX: 0,
  6020. /**
  6021. * @type {number}
  6022. */
  6023. textBoxShadowOffsetY: 0,
  6024. /**
  6025. * Whether transform text.
  6026. * Only useful in Path and Image element
  6027. * @type {boolean}
  6028. */
  6029. transformText: false,
  6030. /**
  6031. * Text rotate around position of Path or Image
  6032. * Only useful in Path and Image element and transformText is false.
  6033. */
  6034. textRotation: 0,
  6035. /**
  6036. * Text origin of text rotation, like [10, 40].
  6037. * Based on x, y of rect.
  6038. * Useful in label rotation of circular symbol.
  6039. * By default, this origin is textPosition.
  6040. * Can be 'center'.
  6041. * @type {string|Array.<number>}
  6042. */
  6043. textOrigin: null,
  6044. /**
  6045. * @type {string}
  6046. */
  6047. textBackgroundColor: null,
  6048. /**
  6049. * @type {string}
  6050. */
  6051. textBorderColor: null,
  6052. /**
  6053. * @type {number}
  6054. */
  6055. textBorderWidth: 0,
  6056. /**
  6057. * @type {number}
  6058. */
  6059. textBorderRadius: 0,
  6060. /**
  6061. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6062. * @type {number|Array.<number>}
  6063. */
  6064. textPadding: null,
  6065. /**
  6066. * Text styles for rich text.
  6067. * @type {Object}
  6068. */
  6069. rich: null,
  6070. /**
  6071. * {outerWidth, outerHeight, ellipsis, placeholder}
  6072. * @type {Object}
  6073. */
  6074. truncate: null,
  6075. /**
  6076. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6077. * @type {string}
  6078. */
  6079. blend: null,
  6080. /**
  6081. * @param {CanvasRenderingContext2D} ctx
  6082. */
  6083. bind: function (ctx, el, prevEl) {
  6084. var style = this;
  6085. var prevStyle = prevEl && prevEl.style;
  6086. // If no prevStyle, it means first draw.
  6087. // Only apply cache if the last time cachced by this function.
  6088. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6089. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6090. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6091. var prop = STYLE_COMMON_PROPS[i];
  6092. var styleName = prop[0];
  6093. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6094. // FIXME Invalid property value will cause style leak from previous element.
  6095. ctx[styleName] =
  6096. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6097. }
  6098. }
  6099. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6100. ctx.fillStyle = style.fill;
  6101. }
  6102. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6103. ctx.strokeStyle = style.stroke;
  6104. }
  6105. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6106. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6107. }
  6108. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6109. ctx.globalCompositeOperation = style.blend || 'source-over';
  6110. }
  6111. if (this.hasStroke()) {
  6112. var lineWidth = style.lineWidth;
  6113. ctx.lineWidth = lineWidth / (
  6114. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6115. );
  6116. }
  6117. },
  6118. hasFill: function () {
  6119. var fill = this.fill;
  6120. return fill != null && fill !== 'none';
  6121. },
  6122. hasStroke: function () {
  6123. var stroke = this.stroke;
  6124. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6125. },
  6126. /**
  6127. * Extend from other style
  6128. * @param {zrender/graphic/Style} otherStyle
  6129. * @param {boolean} overwrite true: overwrirte any way.
  6130. * false: overwrite only when !target.hasOwnProperty
  6131. * others: overwrite when property is not null/undefined.
  6132. */
  6133. extendFrom: function (otherStyle, overwrite) {
  6134. if (otherStyle) {
  6135. for (var name in otherStyle) {
  6136. if (otherStyle.hasOwnProperty(name)
  6137. && (overwrite === true
  6138. || (
  6139. overwrite === false
  6140. ? !this.hasOwnProperty(name)
  6141. : otherStyle[name] != null
  6142. )
  6143. )
  6144. ) {
  6145. this[name] = otherStyle[name];
  6146. }
  6147. }
  6148. }
  6149. },
  6150. /**
  6151. * Batch setting style with a given object
  6152. * @param {Object|string} obj
  6153. * @param {*} [obj]
  6154. */
  6155. set: function (obj, value) {
  6156. if (typeof obj === 'string') {
  6157. this[obj] = value;
  6158. }
  6159. else {
  6160. this.extendFrom(obj, true);
  6161. }
  6162. },
  6163. /**
  6164. * Clone
  6165. * @return {zrender/graphic/Style} [description]
  6166. */
  6167. clone: function () {
  6168. var newStyle = new this.constructor();
  6169. newStyle.extendFrom(this, true);
  6170. return newStyle;
  6171. },
  6172. getGradient: function (ctx, obj, rect) {
  6173. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6174. var canvasGradient = method(ctx, obj, rect);
  6175. var colorStops = obj.colorStops;
  6176. for (var i = 0; i < colorStops.length; i++) {
  6177. canvasGradient.addColorStop(
  6178. colorStops[i].offset, colorStops[i].color
  6179. );
  6180. }
  6181. return canvasGradient;
  6182. }
  6183. };
  6184. var styleProto = Style.prototype;
  6185. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6186. var prop = STYLE_COMMON_PROPS[i];
  6187. if (!(prop[0] in styleProto)) {
  6188. styleProto[prop[0]] = prop[1];
  6189. }
  6190. }
  6191. // Provide for others
  6192. Style.getGradient = styleProto.getGradient;
  6193. var Pattern = function (image, repeat) {
  6194. // Should do nothing more in this constructor. Because gradient can be
  6195. // declard by `color: {image: ...}`, where this constructor will not be called.
  6196. this.image = image;
  6197. this.repeat = repeat;
  6198. // Can be cloned
  6199. this.type = 'pattern';
  6200. };
  6201. Pattern.prototype.getCanvasPattern = function (ctx) {
  6202. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6203. };
  6204. /**
  6205. * @module zrender/Layer
  6206. * @author pissang(https://www.github.com/pissang)
  6207. */
  6208. function returnFalse() {
  6209. return false;
  6210. }
  6211. /**
  6212. * 创建dom
  6213. *
  6214. * @inner
  6215. * @param {string} id dom id 待用
  6216. * @param {Painter} painter painter instance
  6217. * @param {number} number
  6218. */
  6219. function createDom(id, painter, dpr) {
  6220. var newDom = createCanvas();
  6221. var width = painter.getWidth();
  6222. var height = painter.getHeight();
  6223. var newDomStyle = newDom.style;
  6224. if (newDomStyle) { // In node or some other non-browser environment
  6225. newDomStyle.position = 'absolute';
  6226. newDomStyle.left = 0;
  6227. newDomStyle.top = 0;
  6228. newDomStyle.width = width + 'px';
  6229. newDomStyle.height = height + 'px';
  6230. newDom.setAttribute('data-zr-dom-id', id);
  6231. }
  6232. newDom.width = width * dpr;
  6233. newDom.height = height * dpr;
  6234. return newDom;
  6235. }
  6236. /**
  6237. * @alias module:zrender/Layer
  6238. * @constructor
  6239. * @extends module:zrender/mixin/Transformable
  6240. * @param {string} id
  6241. * @param {module:zrender/Painter} painter
  6242. * @param {number} [dpr]
  6243. */
  6244. var Layer = function (id, painter, dpr) {
  6245. var dom;
  6246. dpr = dpr || devicePixelRatio;
  6247. if (typeof id === 'string') {
  6248. dom = createDom(id, painter, dpr);
  6249. }
  6250. // Not using isDom because in node it will return false
  6251. else if (isObject$1(id)) {
  6252. dom = id;
  6253. id = dom.id;
  6254. }
  6255. this.id = id;
  6256. this.dom = dom;
  6257. var domStyle = dom.style;
  6258. if (domStyle) { // Not in node
  6259. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6260. domStyle['-webkit-user-select'] = 'none';
  6261. domStyle['user-select'] = 'none';
  6262. domStyle['-webkit-touch-callout'] = 'none';
  6263. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6264. domStyle['padding'] = 0;
  6265. domStyle['margin'] = 0;
  6266. domStyle['border-width'] = 0;
  6267. }
  6268. this.domBack = null;
  6269. this.ctxBack = null;
  6270. this.painter = painter;
  6271. this.config = null;
  6272. // Configs
  6273. /**
  6274. * 每次清空画布的颜色
  6275. * @type {string}
  6276. * @default 0
  6277. */
  6278. this.clearColor = 0;
  6279. /**
  6280. * 是否开启动态模糊
  6281. * @type {boolean}
  6282. * @default false
  6283. */
  6284. this.motionBlur = false;
  6285. /**
  6286. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6287. * @type {number}
  6288. * @default 0.7
  6289. */
  6290. this.lastFrameAlpha = 0.7;
  6291. /**
  6292. * Layer dpr
  6293. * @type {number}
  6294. */
  6295. this.dpr = dpr;
  6296. };
  6297. Layer.prototype = {
  6298. constructor: Layer,
  6299. __dirty: true,
  6300. __used: false,
  6301. __drawIndex: 0,
  6302. __startIndex: 0,
  6303. __endIndex: 0,
  6304. incremental: false,
  6305. getElementCount: function () {
  6306. return this.__endIndex - this.__startIndex;
  6307. },
  6308. initContext: function () {
  6309. this.ctx = this.dom.getContext('2d');
  6310. this.ctx.dpr = this.dpr;
  6311. },
  6312. createBackBuffer: function () {
  6313. var dpr = this.dpr;
  6314. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6315. this.ctxBack = this.domBack.getContext('2d');
  6316. if (dpr !== 1) {
  6317. this.ctxBack.scale(dpr, dpr);
  6318. }
  6319. },
  6320. /**
  6321. * @param {number} width
  6322. * @param {number} height
  6323. */
  6324. resize: function (width, height) {
  6325. var dpr = this.dpr;
  6326. var dom = this.dom;
  6327. var domStyle = dom.style;
  6328. var domBack = this.domBack;
  6329. if (domStyle) {
  6330. domStyle.width = width + 'px';
  6331. domStyle.height = height + 'px';
  6332. }
  6333. dom.width = width * dpr;
  6334. dom.height = height * dpr;
  6335. if (domBack) {
  6336. domBack.width = width * dpr;
  6337. domBack.height = height * dpr;
  6338. if (dpr !== 1) {
  6339. this.ctxBack.scale(dpr, dpr);
  6340. }
  6341. }
  6342. },
  6343. /**
  6344. * 清空该层画布
  6345. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6346. * @param {Color} [clearColor]
  6347. */
  6348. clear: function (clearAll, clearColor) {
  6349. var dom = this.dom;
  6350. var ctx = this.ctx;
  6351. var width = dom.width;
  6352. var height = dom.height;
  6353. var clearColor = clearColor || this.clearColor;
  6354. var haveMotionBLur = this.motionBlur && !clearAll;
  6355. var lastFrameAlpha = this.lastFrameAlpha;
  6356. var dpr = this.dpr;
  6357. if (haveMotionBLur) {
  6358. if (!this.domBack) {
  6359. this.createBackBuffer();
  6360. }
  6361. this.ctxBack.globalCompositeOperation = 'copy';
  6362. this.ctxBack.drawImage(
  6363. dom, 0, 0,
  6364. width / dpr,
  6365. height / dpr
  6366. );
  6367. }
  6368. ctx.clearRect(0, 0, width, height);
  6369. if (clearColor && clearColor !== 'transparent') {
  6370. var clearColorGradientOrPattern;
  6371. // Gradient
  6372. if (clearColor.colorStops) {
  6373. // Cache canvas gradient
  6374. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6375. x: 0,
  6376. y: 0,
  6377. width: width,
  6378. height: height
  6379. });
  6380. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6381. }
  6382. // Pattern
  6383. else if (clearColor.image) {
  6384. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6385. }
  6386. ctx.save();
  6387. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6388. ctx.fillRect(0, 0, width, height);
  6389. ctx.restore();
  6390. }
  6391. if (haveMotionBLur) {
  6392. var domBack = this.domBack;
  6393. ctx.save();
  6394. ctx.globalAlpha = lastFrameAlpha;
  6395. ctx.drawImage(domBack, 0, 0, width, height);
  6396. ctx.restore();
  6397. }
  6398. }
  6399. };
  6400. var requestAnimationFrame = (
  6401. typeof window !== 'undefined'
  6402. && (
  6403. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6404. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6405. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6406. || window.mozRequestAnimationFrame
  6407. || window.webkitRequestAnimationFrame
  6408. )
  6409. ) || function (func) {
  6410. setTimeout(func, 16);
  6411. };
  6412. var globalImageCache = new LRU(50);
  6413. /**
  6414. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6415. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6416. */
  6417. function findExistImage(newImageOrSrc) {
  6418. if (typeof newImageOrSrc === 'string') {
  6419. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6420. return cachedImgObj && cachedImgObj.image;
  6421. }
  6422. else {
  6423. return newImageOrSrc;
  6424. }
  6425. }
  6426. /**
  6427. * Caution: User should cache loaded images, but not just count on LRU.
  6428. * Consider if required images more than LRU size, will dead loop occur?
  6429. *
  6430. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6431. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6432. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6433. * @param {Function} [cb] params: (image, cbPayload)
  6434. * @param {Object} [cbPayload] Payload on cb calling.
  6435. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6436. */
  6437. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6438. if (!newImageOrSrc) {
  6439. return image;
  6440. }
  6441. else if (typeof newImageOrSrc === 'string') {
  6442. // Image should not be loaded repeatly.
  6443. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6444. return image;
  6445. }
  6446. // Only when there is no existent image or existent image src
  6447. // is different, this method is responsible for load.
  6448. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6449. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6450. if (cachedImgObj) {
  6451. image = cachedImgObj.image;
  6452. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6453. }
  6454. else {
  6455. image = new Image();
  6456. image.onload = image.onerror = imageOnLoad;
  6457. globalImageCache.put(
  6458. newImageOrSrc,
  6459. image.__cachedImgObj = {
  6460. image: image,
  6461. pending: [pendingWrap]
  6462. }
  6463. );
  6464. image.src = image.__zrImageSrc = newImageOrSrc;
  6465. }
  6466. return image;
  6467. }
  6468. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6469. else {
  6470. return newImageOrSrc;
  6471. }
  6472. }
  6473. function imageOnLoad() {
  6474. var cachedImgObj = this.__cachedImgObj;
  6475. this.onload = this.onerror = this.__cachedImgObj = null;
  6476. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6477. var pendingWrap = cachedImgObj.pending[i];
  6478. var cb = pendingWrap.cb;
  6479. cb && cb(this, pendingWrap.cbPayload);
  6480. pendingWrap.hostEl.dirty();
  6481. }
  6482. cachedImgObj.pending.length = 0;
  6483. }
  6484. function isImageReady(image) {
  6485. return image && image.width && image.height;
  6486. }
  6487. var textWidthCache = {};
  6488. var textWidthCacheCounter = 0;
  6489. var TEXT_CACHE_MAX = 5000;
  6490. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6491. var DEFAULT_FONT$1 = '12px sans-serif';
  6492. // Avoid assign to an exported variable, for transforming to cjs.
  6493. var methods$1 = {};
  6494. function $override$1(name, fn) {
  6495. methods$1[name] = fn;
  6496. }
  6497. /**
  6498. * @public
  6499. * @param {string} text
  6500. * @param {string} font
  6501. * @return {number} width
  6502. */
  6503. function getWidth(text, font) {
  6504. font = font || DEFAULT_FONT$1;
  6505. var key = text + ':' + font;
  6506. if (textWidthCache[key]) {
  6507. return textWidthCache[key];
  6508. }
  6509. var textLines = (text + '').split('\n');
  6510. var width = 0;
  6511. for (var i = 0, l = textLines.length; i < l; i++) {
  6512. // textContain.measureText may be overrided in SVG or VML
  6513. width = Math.max(measureText(textLines[i], font).width, width);
  6514. }
  6515. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6516. textWidthCacheCounter = 0;
  6517. textWidthCache = {};
  6518. }
  6519. textWidthCacheCounter++;
  6520. textWidthCache[key] = width;
  6521. return width;
  6522. }
  6523. /**
  6524. * @public
  6525. * @param {string} text
  6526. * @param {string} font
  6527. * @param {string} [textAlign='left']
  6528. * @param {string} [textVerticalAlign='top']
  6529. * @param {Array.<number>} [textPadding]
  6530. * @param {Object} [rich]
  6531. * @param {Object} [truncate]
  6532. * @return {Object} {x, y, width, height, lineHeight}
  6533. */
  6534. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6535. return rich
  6536. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, textLineHeight, truncate)
  6537. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6538. }
  6539. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6540. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6541. var outerWidth = getWidth(text, font);
  6542. if (textPadding) {
  6543. outerWidth += textPadding[1] + textPadding[3];
  6544. }
  6545. var outerHeight = contentBlock.outerHeight;
  6546. var x = adjustTextX(0, outerWidth, textAlign);
  6547. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6548. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6549. rect.lineHeight = contentBlock.lineHeight;
  6550. return rect;
  6551. }
  6552. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6553. var contentBlock = parseRichText(text, {
  6554. rich: rich,
  6555. truncate: truncate,
  6556. font: font,
  6557. textAlign: textAlign,
  6558. textPadding: textPadding,
  6559. textLineHeight: textLineHeight
  6560. });
  6561. var outerWidth = contentBlock.outerWidth;
  6562. var outerHeight = contentBlock.outerHeight;
  6563. var x = adjustTextX(0, outerWidth, textAlign);
  6564. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6565. return new BoundingRect(x, y, outerWidth, outerHeight);
  6566. }
  6567. /**
  6568. * @public
  6569. * @param {number} x
  6570. * @param {number} width
  6571. * @param {string} [textAlign='left']
  6572. * @return {number} Adjusted x.
  6573. */
  6574. function adjustTextX(x, width, textAlign) {
  6575. // FIXME Right to left language
  6576. if (textAlign === 'right') {
  6577. x -= width;
  6578. }
  6579. else if (textAlign === 'center') {
  6580. x -= width / 2;
  6581. }
  6582. return x;
  6583. }
  6584. /**
  6585. * @public
  6586. * @param {number} y
  6587. * @param {number} height
  6588. * @param {string} [textVerticalAlign='top']
  6589. * @return {number} Adjusted y.
  6590. */
  6591. function adjustTextY(y, height, textVerticalAlign) {
  6592. if (textVerticalAlign === 'middle') {
  6593. y -= height / 2;
  6594. }
  6595. else if (textVerticalAlign === 'bottom') {
  6596. y -= height;
  6597. }
  6598. return y;
  6599. }
  6600. /**
  6601. * @public
  6602. * @param {stirng} textPosition
  6603. * @param {Object} rect {x, y, width, height}
  6604. * @param {number} distance
  6605. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6606. */
  6607. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6608. var x = rect.x;
  6609. var y = rect.y;
  6610. var height = rect.height;
  6611. var width = rect.width;
  6612. var halfHeight = height / 2;
  6613. var textAlign = 'left';
  6614. var textVerticalAlign = 'top';
  6615. switch (textPosition) {
  6616. case 'left':
  6617. x -= distance;
  6618. y += halfHeight;
  6619. textAlign = 'right';
  6620. textVerticalAlign = 'middle';
  6621. break;
  6622. case 'right':
  6623. x += distance + width;
  6624. y += halfHeight;
  6625. textVerticalAlign = 'middle';
  6626. break;
  6627. case 'top':
  6628. x += width / 2;
  6629. y -= distance;
  6630. textAlign = 'center';
  6631. textVerticalAlign = 'bottom';
  6632. break;
  6633. case 'bottom':
  6634. x += width / 2;
  6635. y += height + distance;
  6636. textAlign = 'center';
  6637. break;
  6638. case 'inside':
  6639. x += width / 2;
  6640. y += halfHeight;
  6641. textAlign = 'center';
  6642. textVerticalAlign = 'middle';
  6643. break;
  6644. case 'insideLeft':
  6645. x += distance;
  6646. y += halfHeight;
  6647. textVerticalAlign = 'middle';
  6648. break;
  6649. case 'insideRight':
  6650. x += width - distance;
  6651. y += halfHeight;
  6652. textAlign = 'right';
  6653. textVerticalAlign = 'middle';
  6654. break;
  6655. case 'insideTop':
  6656. x += width / 2;
  6657. y += distance;
  6658. textAlign = 'center';
  6659. break;
  6660. case 'insideBottom':
  6661. x += width / 2;
  6662. y += height - distance;
  6663. textAlign = 'center';
  6664. textVerticalAlign = 'bottom';
  6665. break;
  6666. case 'insideTopLeft':
  6667. x += distance;
  6668. y += distance;
  6669. break;
  6670. case 'insideTopRight':
  6671. x += width - distance;
  6672. y += distance;
  6673. textAlign = 'right';
  6674. break;
  6675. case 'insideBottomLeft':
  6676. x += distance;
  6677. y += height - distance;
  6678. textVerticalAlign = 'bottom';
  6679. break;
  6680. case 'insideBottomRight':
  6681. x += width - distance;
  6682. y += height - distance;
  6683. textAlign = 'right';
  6684. textVerticalAlign = 'bottom';
  6685. break;
  6686. }
  6687. return {
  6688. x: x,
  6689. y: y,
  6690. textAlign: textAlign,
  6691. textVerticalAlign: textVerticalAlign
  6692. };
  6693. }
  6694. /**
  6695. * Show ellipsis if overflow.
  6696. *
  6697. * @public
  6698. * @param {string} text
  6699. * @param {string} containerWidth
  6700. * @param {string} font
  6701. * @param {number} [ellipsis='...']
  6702. * @param {Object} [options]
  6703. * @param {number} [options.maxIterations=3]
  6704. * @param {number} [options.minChar=0] If truncate result are less
  6705. * then minChar, ellipsis will not show, which is
  6706. * better for user hint in some cases.
  6707. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6708. * @return {string}
  6709. */
  6710. function truncateText(text, containerWidth, font, ellipsis, options) {
  6711. if (!containerWidth) {
  6712. return '';
  6713. }
  6714. var textLines = (text + '').split('\n');
  6715. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6716. // FIXME
  6717. // It is not appropriate that every line has '...' when truncate multiple lines.
  6718. for (var i = 0, len = textLines.length; i < len; i++) {
  6719. textLines[i] = truncateSingleLine(textLines[i], options);
  6720. }
  6721. return textLines.join('\n');
  6722. }
  6723. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6724. options = extend({}, options);
  6725. options.font = font;
  6726. var ellipsis = retrieve2(ellipsis, '...');
  6727. options.maxIterations = retrieve2(options.maxIterations, 2);
  6728. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6729. // FIXME
  6730. // Other languages?
  6731. options.cnCharWidth = getWidth('国', font);
  6732. // FIXME
  6733. // Consider proportional font?
  6734. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6735. options.placeholder = retrieve2(options.placeholder, '');
  6736. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6737. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6738. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6739. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6740. contentWidth -= ascCharWidth;
  6741. }
  6742. var ellipsisWidth = getWidth(ellipsis, font);
  6743. if (ellipsisWidth > contentWidth) {
  6744. ellipsis = '';
  6745. ellipsisWidth = 0;
  6746. }
  6747. contentWidth = containerWidth - ellipsisWidth;
  6748. options.ellipsis = ellipsis;
  6749. options.ellipsisWidth = ellipsisWidth;
  6750. options.contentWidth = contentWidth;
  6751. options.containerWidth = containerWidth;
  6752. return options;
  6753. }
  6754. function truncateSingleLine(textLine, options) {
  6755. var containerWidth = options.containerWidth;
  6756. var font = options.font;
  6757. var contentWidth = options.contentWidth;
  6758. if (!containerWidth) {
  6759. return '';
  6760. }
  6761. var lineWidth = getWidth(textLine, font);
  6762. if (lineWidth <= containerWidth) {
  6763. return textLine;
  6764. }
  6765. for (var j = 0; ; j++) {
  6766. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6767. textLine += options.ellipsis;
  6768. break;
  6769. }
  6770. var subLength = j === 0
  6771. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6772. : lineWidth > 0
  6773. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6774. : 0;
  6775. textLine = textLine.substr(0, subLength);
  6776. lineWidth = getWidth(textLine, font);
  6777. }
  6778. if (textLine === '') {
  6779. textLine = options.placeholder;
  6780. }
  6781. return textLine;
  6782. }
  6783. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6784. var width = 0;
  6785. var i = 0;
  6786. for (var len = text.length; i < len && width < contentWidth; i++) {
  6787. var charCode = text.charCodeAt(i);
  6788. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6789. }
  6790. return i;
  6791. }
  6792. /**
  6793. * @public
  6794. * @param {string} font
  6795. * @return {number} line height
  6796. */
  6797. function getLineHeight(font) {
  6798. // FIXME A rough approach.
  6799. return getWidth('国', font);
  6800. }
  6801. /**
  6802. * @public
  6803. * @param {string} text
  6804. * @param {string} font
  6805. * @return {Object} width
  6806. */
  6807. function measureText(text, font) {
  6808. return methods$1.measureText(text, font);
  6809. }
  6810. // Avoid assign to an exported variable, for transforming to cjs.
  6811. methods$1.measureText = function (text, font) {
  6812. var ctx = getContext();
  6813. ctx.font = font || DEFAULT_FONT$1;
  6814. return ctx.measureText(text);
  6815. };
  6816. /**
  6817. * @public
  6818. * @param {string} text
  6819. * @param {string} font
  6820. * @param {Object} [truncate]
  6821. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6822. * Notice: for performance, do not calculate outerWidth util needed.
  6823. */
  6824. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6825. text != null && (text += '');
  6826. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6827. var lines = text ? text.split('\n') : [];
  6828. var height = lines.length * lineHeight;
  6829. var outerHeight = height;
  6830. if (padding) {
  6831. outerHeight += padding[0] + padding[2];
  6832. }
  6833. if (text && truncate) {
  6834. var truncOuterHeight = truncate.outerHeight;
  6835. var truncOuterWidth = truncate.outerWidth;
  6836. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6837. text = '';
  6838. lines = [];
  6839. }
  6840. else if (truncOuterWidth != null) {
  6841. var options = prepareTruncateOptions(
  6842. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6843. font,
  6844. truncate.ellipsis,
  6845. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6846. );
  6847. // FIXME
  6848. // It is not appropriate that every line has '...' when truncate multiple lines.
  6849. for (var i = 0, len = lines.length; i < len; i++) {
  6850. lines[i] = truncateSingleLine(lines[i], options);
  6851. }
  6852. }
  6853. }
  6854. return {
  6855. lines: lines,
  6856. height: height,
  6857. outerHeight: outerHeight,
  6858. lineHeight: lineHeight
  6859. };
  6860. }
  6861. /**
  6862. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6863. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6864. *
  6865. * @public
  6866. * @param {string} text
  6867. * @param {Object} style
  6868. * @return {Object} block
  6869. * {
  6870. * width,
  6871. * height,
  6872. * lines: [{
  6873. * lineHeight,
  6874. * width,
  6875. * tokens: [[{
  6876. * styleName,
  6877. * text,
  6878. * width, // include textPadding
  6879. * height, // include textPadding
  6880. * textWidth, // pure text width
  6881. * textHeight, // pure text height
  6882. * lineHeihgt,
  6883. * font,
  6884. * textAlign,
  6885. * textVerticalAlign
  6886. * }], [...], ...]
  6887. * }, ...]
  6888. * }
  6889. * If styleName is undefined, it is plain text.
  6890. */
  6891. function parseRichText(text, style) {
  6892. var contentBlock = {lines: [], width: 0, height: 0};
  6893. text != null && (text += '');
  6894. if (!text) {
  6895. return contentBlock;
  6896. }
  6897. var lastIndex = STYLE_REG.lastIndex = 0;
  6898. var result;
  6899. while ((result = STYLE_REG.exec(text)) != null) {
  6900. var matchedIndex = result.index;
  6901. if (matchedIndex > lastIndex) {
  6902. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6903. }
  6904. pushTokens(contentBlock, result[2], result[1]);
  6905. lastIndex = STYLE_REG.lastIndex;
  6906. }
  6907. if (lastIndex < text.length) {
  6908. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6909. }
  6910. var lines = contentBlock.lines;
  6911. var contentHeight = 0;
  6912. var contentWidth = 0;
  6913. // For `textWidth: 100%`
  6914. var pendingList = [];
  6915. var stlPadding = style.textPadding;
  6916. var truncate = style.truncate;
  6917. var truncateWidth = truncate && truncate.outerWidth;
  6918. var truncateHeight = truncate && truncate.outerHeight;
  6919. if (stlPadding) {
  6920. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6921. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6922. }
  6923. // Calculate layout info of tokens.
  6924. for (var i = 0; i < lines.length; i++) {
  6925. var line = lines[i];
  6926. var lineHeight = 0;
  6927. var lineWidth = 0;
  6928. for (var j = 0; j < line.tokens.length; j++) {
  6929. var token = line.tokens[j];
  6930. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6931. // textPadding should not inherit from style.
  6932. var textPadding = token.textPadding = tokenStyle.textPadding;
  6933. // textFont has been asigned to font by `normalizeStyle`.
  6934. var font = token.font = tokenStyle.font || style.font;
  6935. // textHeight can be used when textVerticalAlign is specified in token.
  6936. var tokenHeight = token.textHeight = retrieve2(
  6937. // textHeight should not be inherited, consider it can be specified
  6938. // as box height of the block.
  6939. tokenStyle.textHeight, getLineHeight(font)
  6940. );
  6941. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6942. token.height = tokenHeight;
  6943. token.lineHeight = retrieve3(
  6944. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6945. );
  6946. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6947. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6948. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6949. return {lines: [], width: 0, height: 0};
  6950. }
  6951. token.textWidth = getWidth(token.text, font);
  6952. var tokenWidth = tokenStyle.textWidth;
  6953. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6954. // Percent width, can be `100%`, can be used in drawing separate
  6955. // line when box width is needed to be auto.
  6956. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6957. token.percentWidth = tokenWidth;
  6958. pendingList.push(token);
  6959. tokenWidth = 0;
  6960. // Do not truncate in this case, because there is no user case
  6961. // and it is too complicated.
  6962. }
  6963. else {
  6964. if (tokenWidthNotSpecified) {
  6965. tokenWidth = token.textWidth;
  6966. // FIXME: If image is not loaded and textWidth is not specified, calling
  6967. // `getBoundingRect()` will not get correct result.
  6968. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6969. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6970. // Use cases:
  6971. // (1) If image is not loaded, it will be loaded at render phase and call
  6972. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6973. // image, and then the right size will be calculated here at the next tick.
  6974. // See `graphic/helper/text.js`.
  6975. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6976. // use `imageHelper.findExistImage` to find cached image.
  6977. // `imageHelper.findExistImage` will always be called here before
  6978. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6979. // which ensures that image will not be rendered before correct size calcualted.
  6980. if (bgImg) {
  6981. bgImg = findExistImage(bgImg);
  6982. if (isImageReady(bgImg)) {
  6983. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6984. }
  6985. }
  6986. }
  6987. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6988. tokenWidth += paddingW;
  6989. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6990. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6991. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6992. token.text = '';
  6993. token.textWidth = tokenWidth = 0;
  6994. }
  6995. else {
  6996. token.text = truncateText(
  6997. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6998. {minChar: truncate.minChar}
  6999. );
  7000. token.textWidth = getWidth(token.text, font);
  7001. tokenWidth = token.textWidth + paddingW;
  7002. }
  7003. }
  7004. }
  7005. lineWidth += (token.width = tokenWidth);
  7006. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7007. }
  7008. line.width = lineWidth;
  7009. line.lineHeight = lineHeight;
  7010. contentHeight += lineHeight;
  7011. contentWidth = Math.max(contentWidth, lineWidth);
  7012. }
  7013. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7014. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7015. if (stlPadding) {
  7016. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7017. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7018. }
  7019. for (var i = 0; i < pendingList.length; i++) {
  7020. var token = pendingList[i];
  7021. var percentWidth = token.percentWidth;
  7022. // Should not base on outerWidth, because token can not be placed out of padding.
  7023. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7024. }
  7025. return contentBlock;
  7026. }
  7027. function pushTokens(block, str, styleName) {
  7028. var isEmptyStr = str === '';
  7029. var strs = str.split('\n');
  7030. var lines = block.lines;
  7031. for (var i = 0; i < strs.length; i++) {
  7032. var text = strs[i];
  7033. var token = {
  7034. styleName: styleName,
  7035. text: text,
  7036. isLineHolder: !text && !isEmptyStr
  7037. };
  7038. // The first token should be appended to the last line.
  7039. if (!i) {
  7040. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7041. // Consider cases:
  7042. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7043. // (which is a placeholder) should be replaced by new token.
  7044. // (2) A image backage, where token likes {a|}.
  7045. // (3) A redundant '' will affect textAlign in line.
  7046. // (4) tokens with the same tplName should not be merged, because
  7047. // they should be displayed in different box (with border and padding).
  7048. var tokensLen = tokens.length;
  7049. (tokensLen === 1 && tokens[0].isLineHolder)
  7050. ? (tokens[0] = token)
  7051. // Consider text is '', only insert when it is the "lineHolder" or
  7052. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7053. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7054. }
  7055. // Other tokens always start a new line.
  7056. else {
  7057. // If there is '', insert it as a placeholder.
  7058. lines.push({tokens: [token]});
  7059. }
  7060. }
  7061. }
  7062. function makeFont(style) {
  7063. // FIXME in node-canvas fontWeight is before fontStyle
  7064. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7065. var font = (style.fontSize || style.fontFamily) && [
  7066. style.fontStyle,
  7067. style.fontWeight,
  7068. (style.fontSize || 12) + 'px',
  7069. // If font properties are defined, `fontFamily` should not be ignored.
  7070. style.fontFamily || 'sans-serif'
  7071. ].join(' ');
  7072. return font && trim(font) || style.textFont || style.font;
  7073. }
  7074. /**
  7075. * @param {Object} ctx
  7076. * @param {Object} shape
  7077. * @param {number} shape.x
  7078. * @param {number} shape.y
  7079. * @param {number} shape.width
  7080. * @param {number} shape.height
  7081. * @param {number} shape.r
  7082. */
  7083. function buildPath(ctx, shape) {
  7084. var x = shape.x;
  7085. var y = shape.y;
  7086. var width = shape.width;
  7087. var height = shape.height;
  7088. var r = shape.r;
  7089. var r1;
  7090. var r2;
  7091. var r3;
  7092. var r4;
  7093. // Convert width and height to positive for better borderRadius
  7094. if (width < 0) {
  7095. x = x + width;
  7096. width = -width;
  7097. }
  7098. if (height < 0) {
  7099. y = y + height;
  7100. height = -height;
  7101. }
  7102. if (typeof r === 'number') {
  7103. r1 = r2 = r3 = r4 = r;
  7104. }
  7105. else if (r instanceof Array) {
  7106. if (r.length === 1) {
  7107. r1 = r2 = r3 = r4 = r[0];
  7108. }
  7109. else if (r.length === 2) {
  7110. r1 = r3 = r[0];
  7111. r2 = r4 = r[1];
  7112. }
  7113. else if (r.length === 3) {
  7114. r1 = r[0];
  7115. r2 = r4 = r[1];
  7116. r3 = r[2];
  7117. }
  7118. else {
  7119. r1 = r[0];
  7120. r2 = r[1];
  7121. r3 = r[2];
  7122. r4 = r[3];
  7123. }
  7124. }
  7125. else {
  7126. r1 = r2 = r3 = r4 = 0;
  7127. }
  7128. var total;
  7129. if (r1 + r2 > width) {
  7130. total = r1 + r2;
  7131. r1 *= width / total;
  7132. r2 *= width / total;
  7133. }
  7134. if (r3 + r4 > width) {
  7135. total = r3 + r4;
  7136. r3 *= width / total;
  7137. r4 *= width / total;
  7138. }
  7139. if (r2 + r3 > height) {
  7140. total = r2 + r3;
  7141. r2 *= height / total;
  7142. r3 *= height / total;
  7143. }
  7144. if (r1 + r4 > height) {
  7145. total = r1 + r4;
  7146. r1 *= height / total;
  7147. r4 *= height / total;
  7148. }
  7149. ctx.moveTo(x + r1, y);
  7150. ctx.lineTo(x + width - r2, y);
  7151. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7152. ctx.lineTo(x + width, y + height - r3);
  7153. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7154. ctx.lineTo(x + r4, y + height);
  7155. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7156. ctx.lineTo(x, y + r1);
  7157. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7158. }
  7159. var DEFAULT_FONT = DEFAULT_FONT$1;
  7160. // TODO: Have not support 'start', 'end' yet.
  7161. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7162. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7163. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7164. // the default value of shadowColor is `'transparent'`.
  7165. var SHADOW_STYLE_COMMON_PROPS = [
  7166. ['textShadowBlur', 'shadowBlur', 0],
  7167. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7168. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7169. ['textShadowColor', 'shadowColor', 'transparent']
  7170. ];
  7171. /**
  7172. * @param {module:zrender/graphic/Style} style
  7173. * @return {module:zrender/graphic/Style} The input style.
  7174. */
  7175. function normalizeTextStyle(style) {
  7176. normalizeStyle(style);
  7177. each$1(style.rich, normalizeStyle);
  7178. return style;
  7179. }
  7180. function normalizeStyle(style) {
  7181. if (style) {
  7182. style.font = makeFont(style);
  7183. var textAlign = style.textAlign;
  7184. textAlign === 'middle' && (textAlign = 'center');
  7185. style.textAlign = (
  7186. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7187. ) ? textAlign : 'left';
  7188. // Compatible with textBaseline.
  7189. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7190. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7191. style.textVerticalAlign = (
  7192. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7193. ) ? textVerticalAlign : 'top';
  7194. var textPadding = style.textPadding;
  7195. if (textPadding) {
  7196. style.textPadding = normalizeCssArray(style.textPadding);
  7197. }
  7198. }
  7199. }
  7200. /**
  7201. * @param {CanvasRenderingContext2D} ctx
  7202. * @param {string} text
  7203. * @param {module:zrender/graphic/Style} style
  7204. * @param {Object|boolean} [rect] {x, y, width, height}
  7205. * If set false, rect text is not used.
  7206. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7207. */
  7208. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7209. style.rich
  7210. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7211. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7212. }
  7213. // Avoid setting to ctx according to prevEl if possible for
  7214. // performance in scenarios of large amount text.
  7215. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7216. 'use strict';
  7217. var needDrawBg = needDrawBackground(style);
  7218. var prevStyle;
  7219. var checkCache = false;
  7220. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7221. // Only take and check cache for `Text` el, but not RectText.
  7222. if (prevEl !== WILL_BE_RESTORED) {
  7223. if (prevEl) {
  7224. prevStyle = prevEl.style;
  7225. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7226. }
  7227. // Prevent from using cache in `Style::bind`, because of the case:
  7228. // ctx property is modified by other properties than `Style::bind`
  7229. // used, and Style::bind is called next.
  7230. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7231. }
  7232. // Since this will be restored, prevent from using these props to check cache in the next
  7233. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7234. else if (cachedByMe) {
  7235. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7236. }
  7237. var styleFont = style.font || DEFAULT_FONT;
  7238. // PENDING
  7239. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7240. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7241. // But layer save/restore needed to be considered.
  7242. // if (styleFont !== ctx.__fontCache) {
  7243. // ctx.font = styleFont;
  7244. // if (prevEl !== WILL_BE_RESTORED) {
  7245. // ctx.__fontCache = styleFont;
  7246. // }
  7247. // }
  7248. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7249. ctx.font = styleFont;
  7250. }
  7251. // Use the final font from context-2d, because the final
  7252. // font might not be the style.font when it is illegal.
  7253. // But get `ctx.font` might be time consuming.
  7254. var computedFont = hostEl.__computedFont;
  7255. if (hostEl.__styleFont !== styleFont) {
  7256. hostEl.__styleFont = styleFont;
  7257. computedFont = hostEl.__computedFont = ctx.font;
  7258. }
  7259. var textPadding = style.textPadding;
  7260. var textLineHeight = style.textLineHeight;
  7261. var contentBlock = hostEl.__textCotentBlock;
  7262. if (!contentBlock || hostEl.__dirtyText) {
  7263. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7264. text, computedFont, textPadding, textLineHeight, style.truncate
  7265. );
  7266. }
  7267. var outerHeight = contentBlock.outerHeight;
  7268. var textLines = contentBlock.lines;
  7269. var lineHeight = contentBlock.lineHeight;
  7270. var boxPos = getBoxPosition(outerHeight, style, rect);
  7271. var baseX = boxPos.baseX;
  7272. var baseY = boxPos.baseY;
  7273. var textAlign = boxPos.textAlign || 'left';
  7274. var textVerticalAlign = boxPos.textVerticalAlign;
  7275. // Origin of textRotation should be the base point of text drawing.
  7276. applyTextRotation(ctx, style, rect, baseX, baseY);
  7277. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7278. var textX = baseX;
  7279. var textY = boxY;
  7280. if (needDrawBg || textPadding) {
  7281. // Consider performance, do not call getTextWidth util necessary.
  7282. var textWidth = getWidth(text, computedFont);
  7283. var outerWidth = textWidth;
  7284. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7285. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7286. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7287. if (textPadding) {
  7288. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7289. textY += textPadding[0];
  7290. }
  7291. }
  7292. // Always set textAlign and textBase line, because it is difficute to calculate
  7293. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7294. // font set happened.
  7295. ctx.textAlign = textAlign;
  7296. // Force baseline to be "middle". Otherwise, if using "top", the
  7297. // text will offset downward a little bit in font "Microsoft YaHei".
  7298. ctx.textBaseline = 'middle';
  7299. // Set text opacity
  7300. ctx.globalAlpha = style.opacity || 1;
  7301. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7302. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7303. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7304. var styleProp = propItem[0];
  7305. var ctxProp = propItem[1];
  7306. var val = style[styleProp];
  7307. if (!checkCache || val !== prevStyle[styleProp]) {
  7308. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7309. }
  7310. }
  7311. // `textBaseline` is set as 'middle'.
  7312. textY += lineHeight / 2;
  7313. var textStrokeWidth = style.textStrokeWidth;
  7314. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7315. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7316. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7317. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7318. var textFill = getFill(style.textFill);
  7319. if (textStroke) {
  7320. if (strokeWidthChanged) {
  7321. ctx.lineWidth = textStrokeWidth;
  7322. }
  7323. if (strokeChanged) {
  7324. ctx.strokeStyle = textStroke;
  7325. }
  7326. }
  7327. if (textFill) {
  7328. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7329. ctx.fillStyle = textFill;
  7330. }
  7331. }
  7332. // Optimize simply, in most cases only one line exists.
  7333. if (textLines.length === 1) {
  7334. // Fill after stroke so the outline will not cover the main part.
  7335. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7336. textFill && ctx.fillText(textLines[0], textX, textY);
  7337. }
  7338. else {
  7339. for (var i = 0; i < textLines.length; i++) {
  7340. // Fill after stroke so the outline will not cover the main part.
  7341. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7342. textFill && ctx.fillText(textLines[i], textX, textY);
  7343. textY += lineHeight;
  7344. }
  7345. }
  7346. }
  7347. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7348. // Do not do cache for rich text because of the complexity.
  7349. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7350. if (prevEl !== WILL_BE_RESTORED) {
  7351. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7352. }
  7353. var contentBlock = hostEl.__textCotentBlock;
  7354. if (!contentBlock || hostEl.__dirtyText) {
  7355. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7356. }
  7357. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7358. }
  7359. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7360. var contentWidth = contentBlock.width;
  7361. var outerWidth = contentBlock.outerWidth;
  7362. var outerHeight = contentBlock.outerHeight;
  7363. var textPadding = style.textPadding;
  7364. var boxPos = getBoxPosition(outerHeight, style, rect);
  7365. var baseX = boxPos.baseX;
  7366. var baseY = boxPos.baseY;
  7367. var textAlign = boxPos.textAlign;
  7368. var textVerticalAlign = boxPos.textVerticalAlign;
  7369. // Origin of textRotation should be the base point of text drawing.
  7370. applyTextRotation(ctx, style, rect, baseX, baseY);
  7371. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7372. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7373. var xLeft = boxX;
  7374. var lineTop = boxY;
  7375. if (textPadding) {
  7376. xLeft += textPadding[3];
  7377. lineTop += textPadding[0];
  7378. }
  7379. var xRight = xLeft + contentWidth;
  7380. needDrawBackground(style) && drawBackground(
  7381. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7382. );
  7383. for (var i = 0; i < contentBlock.lines.length; i++) {
  7384. var line = contentBlock.lines[i];
  7385. var tokens = line.tokens;
  7386. var tokenCount = tokens.length;
  7387. var lineHeight = line.lineHeight;
  7388. var usedWidth = line.width;
  7389. var leftIndex = 0;
  7390. var lineXLeft = xLeft;
  7391. var lineXRight = xRight;
  7392. var rightIndex = tokenCount - 1;
  7393. var token;
  7394. while (
  7395. leftIndex < tokenCount
  7396. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7397. ) {
  7398. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7399. usedWidth -= token.width;
  7400. lineXLeft += token.width;
  7401. leftIndex++;
  7402. }
  7403. while (
  7404. rightIndex >= 0
  7405. && (token = tokens[rightIndex], token.textAlign === 'right')
  7406. ) {
  7407. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7408. usedWidth -= token.width;
  7409. lineXRight -= token.width;
  7410. rightIndex--;
  7411. }
  7412. // The other tokens are placed as textAlign 'center' if there is enough space.
  7413. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7414. while (leftIndex <= rightIndex) {
  7415. token = tokens[leftIndex];
  7416. // Consider width specified by user, use 'center' rather than 'left'.
  7417. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7418. lineXLeft += token.width;
  7419. leftIndex++;
  7420. }
  7421. lineTop += lineHeight;
  7422. }
  7423. }
  7424. function applyTextRotation(ctx, style, rect, x, y) {
  7425. // textRotation only apply in RectText.
  7426. if (rect && style.textRotation) {
  7427. var origin = style.textOrigin;
  7428. if (origin === 'center') {
  7429. x = rect.width / 2 + rect.x;
  7430. y = rect.height / 2 + rect.y;
  7431. }
  7432. else if (origin) {
  7433. x = origin[0] + rect.x;
  7434. y = origin[1] + rect.y;
  7435. }
  7436. ctx.translate(x, y);
  7437. // Positive: anticlockwise
  7438. ctx.rotate(-style.textRotation);
  7439. ctx.translate(-x, -y);
  7440. }
  7441. }
  7442. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7443. var tokenStyle = style.rich[token.styleName] || {};
  7444. tokenStyle.text = token.text;
  7445. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7446. // the bias of "Microsoft YaHei".
  7447. var textVerticalAlign = token.textVerticalAlign;
  7448. var y = lineTop + lineHeight / 2;
  7449. if (textVerticalAlign === 'top') {
  7450. y = lineTop + token.height / 2;
  7451. }
  7452. else if (textVerticalAlign === 'bottom') {
  7453. y = lineTop + lineHeight - token.height / 2;
  7454. }
  7455. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7456. hostEl,
  7457. ctx,
  7458. tokenStyle,
  7459. textAlign === 'right'
  7460. ? x - token.width
  7461. : textAlign === 'center'
  7462. ? x - token.width / 2
  7463. : x,
  7464. y - token.height / 2,
  7465. token.width,
  7466. token.height
  7467. );
  7468. var textPadding = token.textPadding;
  7469. if (textPadding) {
  7470. x = getTextXForPadding(x, textAlign, textPadding);
  7471. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7472. }
  7473. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7474. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7475. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7476. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7477. setCtx(ctx, 'textAlign', textAlign);
  7478. // Force baseline to be "middle". Otherwise, if using "top", the
  7479. // text will offset downward a little bit in font "Microsoft YaHei".
  7480. setCtx(ctx, 'textBaseline', 'middle');
  7481. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7482. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7483. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7484. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7485. // Fill after stroke so the outline will not cover the main part.
  7486. if (textStroke) {
  7487. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7488. setCtx(ctx, 'strokeStyle', textStroke);
  7489. ctx.strokeText(token.text, x, y);
  7490. }
  7491. if (textFill) {
  7492. setCtx(ctx, 'fillStyle', textFill);
  7493. ctx.fillText(token.text, x, y);
  7494. }
  7495. }
  7496. function needDrawBackground(style) {
  7497. return !!(
  7498. style.textBackgroundColor
  7499. || (style.textBorderWidth && style.textBorderColor)
  7500. );
  7501. }
  7502. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7503. // shape: {x, y, width, height}
  7504. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7505. var textBackgroundColor = style.textBackgroundColor;
  7506. var textBorderWidth = style.textBorderWidth;
  7507. var textBorderColor = style.textBorderColor;
  7508. var isPlainBg = isString(textBackgroundColor);
  7509. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7510. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7511. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7512. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7513. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7514. ctx.beginPath();
  7515. var textBorderRadius = style.textBorderRadius;
  7516. if (!textBorderRadius) {
  7517. ctx.rect(x, y, width, height);
  7518. }
  7519. else {
  7520. buildPath(ctx, {
  7521. x: x, y: y, width: width, height: height, r: textBorderRadius
  7522. });
  7523. }
  7524. ctx.closePath();
  7525. }
  7526. if (isPlainBg) {
  7527. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7528. if (style.fillOpacity != null) {
  7529. var originalGlobalAlpha = ctx.globalAlpha;
  7530. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7531. ctx.fill();
  7532. ctx.globalAlpha = originalGlobalAlpha;
  7533. }
  7534. else {
  7535. ctx.fill();
  7536. }
  7537. }
  7538. else if (isObject$1(textBackgroundColor)) {
  7539. var image = textBackgroundColor.image;
  7540. image = createOrUpdateImage(
  7541. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7542. );
  7543. if (image && isImageReady(image)) {
  7544. ctx.drawImage(image, x, y, width, height);
  7545. }
  7546. }
  7547. if (textBorderWidth && textBorderColor) {
  7548. setCtx(ctx, 'lineWidth', textBorderWidth);
  7549. setCtx(ctx, 'strokeStyle', textBorderColor);
  7550. if (style.strokeOpacity != null) {
  7551. var originalGlobalAlpha = ctx.globalAlpha;
  7552. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7553. ctx.stroke();
  7554. ctx.globalAlpha = originalGlobalAlpha;
  7555. }
  7556. else {
  7557. ctx.stroke();
  7558. }
  7559. }
  7560. }
  7561. function onBgImageLoaded(image, textBackgroundColor) {
  7562. // Replace image, so that `contain/text.js#parseRichText`
  7563. // will get correct result in next tick.
  7564. textBackgroundColor.image = image;
  7565. }
  7566. function getBoxPosition(blockHeiht, style, rect) {
  7567. var baseX = style.x || 0;
  7568. var baseY = style.y || 0;
  7569. var textAlign = style.textAlign;
  7570. var textVerticalAlign = style.textVerticalAlign;
  7571. // Text position represented by coord
  7572. if (rect) {
  7573. var textPosition = style.textPosition;
  7574. if (textPosition instanceof Array) {
  7575. // Percent
  7576. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7577. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7578. }
  7579. else {
  7580. var res = adjustTextPositionOnRect(
  7581. textPosition, rect, style.textDistance
  7582. );
  7583. baseX = res.x;
  7584. baseY = res.y;
  7585. // Default align and baseline when has textPosition
  7586. textAlign = textAlign || res.textAlign;
  7587. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7588. }
  7589. // textOffset is only support in RectText, otherwise
  7590. // we have to adjust boundingRect for textOffset.
  7591. var textOffset = style.textOffset;
  7592. if (textOffset) {
  7593. baseX += textOffset[0];
  7594. baseY += textOffset[1];
  7595. }
  7596. }
  7597. return {
  7598. baseX: baseX,
  7599. baseY: baseY,
  7600. textAlign: textAlign,
  7601. textVerticalAlign: textVerticalAlign
  7602. };
  7603. }
  7604. function setCtx(ctx, prop, value) {
  7605. ctx[prop] = fixShadow(ctx, prop, value);
  7606. return ctx[prop];
  7607. }
  7608. /**
  7609. * @param {string} [stroke] If specified, do not check style.textStroke.
  7610. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7611. * @param {number} style
  7612. */
  7613. function getStroke(stroke, lineWidth) {
  7614. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7615. ? null
  7616. // TODO pattern and gradient?
  7617. : (stroke.image || stroke.colorStops)
  7618. ? '#000'
  7619. : stroke;
  7620. }
  7621. function getFill(fill) {
  7622. return (fill == null || fill === 'none')
  7623. ? null
  7624. // TODO pattern and gradient?
  7625. : (fill.image || fill.colorStops)
  7626. ? '#000'
  7627. : fill;
  7628. }
  7629. function parsePercent(value, maxValue) {
  7630. if (typeof value === 'string') {
  7631. if (value.lastIndexOf('%') >= 0) {
  7632. return parseFloat(value) / 100 * maxValue;
  7633. }
  7634. return parseFloat(value);
  7635. }
  7636. return value;
  7637. }
  7638. function getTextXForPadding(x, textAlign, textPadding) {
  7639. return textAlign === 'right'
  7640. ? (x - textPadding[1])
  7641. : textAlign === 'center'
  7642. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7643. : (x + textPadding[3]);
  7644. }
  7645. /**
  7646. * @param {string} text
  7647. * @param {module:zrender/Style} style
  7648. * @return {boolean}
  7649. */
  7650. function needDrawText(text, style) {
  7651. return text != null
  7652. && (text
  7653. || style.textBackgroundColor
  7654. || (style.textBorderWidth && style.textBorderColor)
  7655. || style.textPadding
  7656. );
  7657. }
  7658. /**
  7659. * Mixin for drawing text in a element bounding rect
  7660. * @module zrender/mixin/RectText
  7661. */
  7662. var tmpRect$1 = new BoundingRect();
  7663. var RectText = function () {};
  7664. RectText.prototype = {
  7665. constructor: RectText,
  7666. /**
  7667. * Draw text in a rect with specified position.
  7668. * @param {CanvasRenderingContext2D} ctx
  7669. * @param {Object} rect Displayable rect
  7670. */
  7671. drawRectText: function (ctx, rect) {
  7672. var style = this.style;
  7673. rect = style.textRect || rect;
  7674. // Optimize, avoid normalize every time.
  7675. this.__dirty && normalizeTextStyle(style, true);
  7676. var text = style.text;
  7677. // Convert to string
  7678. text != null && (text += '');
  7679. if (!needDrawText(text, style)) {
  7680. return;
  7681. }
  7682. // FIXME
  7683. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7684. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7685. // text propably break the cache for its host elements.
  7686. ctx.save();
  7687. // Transform rect to view space
  7688. var transform = this.transform;
  7689. if (!style.transformText) {
  7690. if (transform) {
  7691. tmpRect$1.copy(rect);
  7692. tmpRect$1.applyTransform(transform);
  7693. rect = tmpRect$1;
  7694. }
  7695. }
  7696. else {
  7697. this.setTransform(ctx);
  7698. }
  7699. // transformText and textRotation can not be used at the same time.
  7700. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7701. ctx.restore();
  7702. }
  7703. };
  7704. /**
  7705. * 可绘制的图形基类
  7706. * Base class of all displayable graphic objects
  7707. * @module zrender/graphic/Displayable
  7708. */
  7709. /**
  7710. * @alias module:zrender/graphic/Displayable
  7711. * @extends module:zrender/Element
  7712. * @extends module:zrender/graphic/mixin/RectText
  7713. */
  7714. function Displayable(opts) {
  7715. opts = opts || {};
  7716. Element.call(this, opts);
  7717. // Extend properties
  7718. for (var name in opts) {
  7719. if (
  7720. opts.hasOwnProperty(name)
  7721. && name !== 'style'
  7722. ) {
  7723. this[name] = opts[name];
  7724. }
  7725. }
  7726. /**
  7727. * @type {module:zrender/graphic/Style}
  7728. */
  7729. this.style = new Style(opts.style, this);
  7730. this._rect = null;
  7731. // Shapes for cascade clipping.
  7732. this.__clipPaths = [];
  7733. // FIXME Stateful must be mixined after style is setted
  7734. // Stateful.call(this, opts);
  7735. }
  7736. Displayable.prototype = {
  7737. constructor: Displayable,
  7738. type: 'displayable',
  7739. /**
  7740. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7741. * Dirty flag. From which painter will determine if this displayable object needs brush
  7742. * @name module:zrender/graphic/Displayable#__dirty
  7743. * @type {boolean}
  7744. */
  7745. __dirty: true,
  7746. /**
  7747. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7748. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7749. * @name module:/zrender/graphic/Displayable#invisible
  7750. * @type {boolean}
  7751. * @default false
  7752. */
  7753. invisible: false,
  7754. /**
  7755. * @name module:/zrender/graphic/Displayable#z
  7756. * @type {number}
  7757. * @default 0
  7758. */
  7759. z: 0,
  7760. /**
  7761. * @name module:/zrender/graphic/Displayable#z
  7762. * @type {number}
  7763. * @default 0
  7764. */
  7765. z2: 0,
  7766. /**
  7767. * z层level,决定绘画在哪层canvas中
  7768. * @name module:/zrender/graphic/Displayable#zlevel
  7769. * @type {number}
  7770. * @default 0
  7771. */
  7772. zlevel: 0,
  7773. /**
  7774. * 是否可拖拽
  7775. * @name module:/zrender/graphic/Displayable#draggable
  7776. * @type {boolean}
  7777. * @default false
  7778. */
  7779. draggable: false,
  7780. /**
  7781. * 是否正在拖拽
  7782. * @name module:/zrender/graphic/Displayable#draggable
  7783. * @type {boolean}
  7784. * @default false
  7785. */
  7786. dragging: false,
  7787. /**
  7788. * 是否相应鼠标事件
  7789. * @name module:/zrender/graphic/Displayable#silent
  7790. * @type {boolean}
  7791. * @default false
  7792. */
  7793. silent: false,
  7794. /**
  7795. * If enable culling
  7796. * @type {boolean}
  7797. * @default false
  7798. */
  7799. culling: false,
  7800. /**
  7801. * Mouse cursor when hovered
  7802. * @name module:/zrender/graphic/Displayable#cursor
  7803. * @type {string}
  7804. */
  7805. cursor: 'pointer',
  7806. /**
  7807. * If hover area is bounding rect
  7808. * @name module:/zrender/graphic/Displayable#rectHover
  7809. * @type {string}
  7810. */
  7811. rectHover: false,
  7812. /**
  7813. * Render the element progressively when the value >= 0,
  7814. * usefull for large data.
  7815. * @type {boolean}
  7816. */
  7817. progressive: false,
  7818. /**
  7819. * @type {boolean}
  7820. */
  7821. incremental: false,
  7822. /**
  7823. * Scale ratio for global scale.
  7824. * @type {boolean}
  7825. */
  7826. globalScaleRatio: 1,
  7827. beforeBrush: function (ctx) {},
  7828. afterBrush: function (ctx) {},
  7829. /**
  7830. * 图形绘制方法
  7831. * @param {CanvasRenderingContext2D} ctx
  7832. */
  7833. // Interface
  7834. brush: function (ctx, prevEl) {},
  7835. /**
  7836. * 获取最小包围盒
  7837. * @return {module:zrender/core/BoundingRect}
  7838. */
  7839. // Interface
  7840. getBoundingRect: function () {},
  7841. /**
  7842. * 判断坐标 x, y 是否在图形上
  7843. * If displayable element contain coord x, y
  7844. * @param {number} x
  7845. * @param {number} y
  7846. * @return {boolean}
  7847. */
  7848. contain: function (x, y) {
  7849. return this.rectContain(x, y);
  7850. },
  7851. /**
  7852. * @param {Function} cb
  7853. * @param {} context
  7854. */
  7855. traverse: function (cb, context) {
  7856. cb.call(context, this);
  7857. },
  7858. /**
  7859. * 判断坐标 x, y 是否在图形的包围盒上
  7860. * If bounding rect of element contain coord x, y
  7861. * @param {number} x
  7862. * @param {number} y
  7863. * @return {boolean}
  7864. */
  7865. rectContain: function (x, y) {
  7866. var coord = this.transformCoordToLocal(x, y);
  7867. var rect = this.getBoundingRect();
  7868. return rect.contain(coord[0], coord[1]);
  7869. },
  7870. /**
  7871. * 标记图形元素为脏,并且在下一帧重绘
  7872. * Mark displayable element dirty and refresh next frame
  7873. */
  7874. dirty: function () {
  7875. this.__dirty = this.__dirtyText = true;
  7876. this._rect = null;
  7877. this.__zr && this.__zr.refresh();
  7878. },
  7879. /**
  7880. * 图形是否会触发事件
  7881. * If displayable object binded any event
  7882. * @return {boolean}
  7883. */
  7884. // TODO, 通过 bind 绑定的事件
  7885. // isSilent: function () {
  7886. // return !(
  7887. // this.hoverable || this.draggable
  7888. // || this.onmousemove || this.onmouseover || this.onmouseout
  7889. // || this.onmousedown || this.onmouseup || this.onclick
  7890. // || this.ondragenter || this.ondragover || this.ondragleave
  7891. // || this.ondrop
  7892. // );
  7893. // },
  7894. /**
  7895. * Alias for animate('style')
  7896. * @param {boolean} loop
  7897. */
  7898. animateStyle: function (loop) {
  7899. return this.animate('style', loop);
  7900. },
  7901. attrKV: function (key, value) {
  7902. if (key !== 'style') {
  7903. Element.prototype.attrKV.call(this, key, value);
  7904. }
  7905. else {
  7906. this.style.set(value);
  7907. }
  7908. },
  7909. /**
  7910. * @param {Object|string} key
  7911. * @param {*} value
  7912. */
  7913. setStyle: function (key, value) {
  7914. this.style.set(key, value);
  7915. this.dirty(false);
  7916. return this;
  7917. },
  7918. /**
  7919. * Use given style object
  7920. * @param {Object} obj
  7921. */
  7922. useStyle: function (obj) {
  7923. this.style = new Style(obj, this);
  7924. this.dirty(false);
  7925. return this;
  7926. }
  7927. };
  7928. inherits(Displayable, Element);
  7929. mixin(Displayable, RectText);
  7930. /**
  7931. * @alias zrender/graphic/Image
  7932. * @extends module:zrender/graphic/Displayable
  7933. * @constructor
  7934. * @param {Object} opts
  7935. */
  7936. function ZImage(opts) {
  7937. Displayable.call(this, opts);
  7938. }
  7939. ZImage.prototype = {
  7940. constructor: ZImage,
  7941. type: 'image',
  7942. brush: function (ctx, prevEl) {
  7943. var style = this.style;
  7944. var src = style.image;
  7945. // Must bind each time
  7946. style.bind(ctx, this, prevEl);
  7947. var image = this._image = createOrUpdateImage(
  7948. src,
  7949. this._image,
  7950. this,
  7951. this.onload
  7952. );
  7953. if (!image || !isImageReady(image)) {
  7954. return;
  7955. }
  7956. // 图片已经加载完成
  7957. // if (image.nodeName.toUpperCase() == 'IMG') {
  7958. // if (!image.complete) {
  7959. // return;
  7960. // }
  7961. // }
  7962. // Else is canvas
  7963. var x = style.x || 0;
  7964. var y = style.y || 0;
  7965. var width = style.width;
  7966. var height = style.height;
  7967. var aspect = image.width / image.height;
  7968. if (width == null && height != null) {
  7969. // Keep image/height ratio
  7970. width = height * aspect;
  7971. }
  7972. else if (height == null && width != null) {
  7973. height = width / aspect;
  7974. }
  7975. else if (width == null && height == null) {
  7976. width = image.width;
  7977. height = image.height;
  7978. }
  7979. // 设置transform
  7980. this.setTransform(ctx);
  7981. if (style.sWidth && style.sHeight) {
  7982. var sx = style.sx || 0;
  7983. var sy = style.sy || 0;
  7984. ctx.drawImage(
  7985. image,
  7986. sx, sy, style.sWidth, style.sHeight,
  7987. x, y, width, height
  7988. );
  7989. }
  7990. else if (style.sx && style.sy) {
  7991. var sx = style.sx;
  7992. var sy = style.sy;
  7993. var sWidth = width - sx;
  7994. var sHeight = height - sy;
  7995. ctx.drawImage(
  7996. image,
  7997. sx, sy, sWidth, sHeight,
  7998. x, y, width, height
  7999. );
  8000. }
  8001. else {
  8002. ctx.drawImage(image, x, y, width, height);
  8003. }
  8004. // Draw rect text
  8005. if (style.text != null) {
  8006. // Only restore transform when needs draw text.
  8007. this.restoreTransform(ctx);
  8008. this.drawRectText(ctx, this.getBoundingRect());
  8009. }
  8010. },
  8011. getBoundingRect: function () {
  8012. var style = this.style;
  8013. if (!this._rect) {
  8014. this._rect = new BoundingRect(
  8015. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8016. );
  8017. }
  8018. return this._rect;
  8019. }
  8020. };
  8021. inherits(ZImage, Displayable);
  8022. var HOVER_LAYER_ZLEVEL = 1e5;
  8023. var CANVAS_ZLEVEL = 314159;
  8024. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8025. var INCREMENTAL_INC = 0.001;
  8026. function parseInt10(val) {
  8027. return parseInt(val, 10);
  8028. }
  8029. function isLayerValid(layer) {
  8030. if (!layer) {
  8031. return false;
  8032. }
  8033. if (layer.__builtin__) {
  8034. return true;
  8035. }
  8036. if (typeof (layer.resize) !== 'function'
  8037. || typeof (layer.refresh) !== 'function'
  8038. ) {
  8039. return false;
  8040. }
  8041. return true;
  8042. }
  8043. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8044. var viewRect = new BoundingRect(0, 0, 0, 0);
  8045. function isDisplayableCulled(el, width, height) {
  8046. tmpRect.copy(el.getBoundingRect());
  8047. if (el.transform) {
  8048. tmpRect.applyTransform(el.transform);
  8049. }
  8050. viewRect.width = width;
  8051. viewRect.height = height;
  8052. return !tmpRect.intersect(viewRect);
  8053. }
  8054. function isClipPathChanged(clipPaths, prevClipPaths) {
  8055. if (clipPaths === prevClipPaths) { // Can both be null or undefined
  8056. return false;
  8057. }
  8058. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8059. return true;
  8060. }
  8061. for (var i = 0; i < clipPaths.length; i++) {
  8062. if (clipPaths[i] !== prevClipPaths[i]) {
  8063. return true;
  8064. }
  8065. }
  8066. }
  8067. function doClip(clipPaths, ctx) {
  8068. for (var i = 0; i < clipPaths.length; i++) {
  8069. var clipPath = clipPaths[i];
  8070. clipPath.setTransform(ctx);
  8071. ctx.beginPath();
  8072. clipPath.buildPath(ctx, clipPath.shape);
  8073. ctx.clip();
  8074. // Transform back
  8075. clipPath.restoreTransform(ctx);
  8076. }
  8077. }
  8078. function createRoot(width, height) {
  8079. var domRoot = document.createElement('div');
  8080. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  8081. domRoot.style.cssText = [
  8082. 'position:relative',
  8083. 'overflow:hidden',
  8084. 'width:' + width + 'px',
  8085. 'height:' + height + 'px',
  8086. 'padding:0',
  8087. 'margin:0',
  8088. 'border-width:0'
  8089. ].join(';') + ';';
  8090. return domRoot;
  8091. }
  8092. /**
  8093. * @alias module:zrender/Painter
  8094. * @constructor
  8095. * @param {HTMLElement} root 绘图容器
  8096. * @param {module:zrender/Storage} storage
  8097. * @param {Object} opts
  8098. */
  8099. var Painter = function (root, storage, opts) {
  8100. this.type = 'canvas';
  8101. // In node environment using node-canvas
  8102. var singleCanvas = !root.nodeName // In node ?
  8103. || root.nodeName.toUpperCase() === 'CANVAS';
  8104. this._opts = opts = extend({}, opts || {});
  8105. /**
  8106. * @type {number}
  8107. */
  8108. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8109. /**
  8110. * @type {boolean}
  8111. * @private
  8112. */
  8113. this._singleCanvas = singleCanvas;
  8114. /**
  8115. * 绘图容器
  8116. * @type {HTMLElement}
  8117. */
  8118. this.root = root;
  8119. var rootStyle = root.style;
  8120. if (rootStyle) {
  8121. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8122. rootStyle['-webkit-user-select'] =
  8123. rootStyle['user-select'] =
  8124. rootStyle['-webkit-touch-callout'] = 'none';
  8125. root.innerHTML = '';
  8126. }
  8127. /**
  8128. * @type {module:zrender/Storage}
  8129. */
  8130. this.storage = storage;
  8131. /**
  8132. * @type {Array.<number>}
  8133. * @private
  8134. */
  8135. var zlevelList = this._zlevelList = [];
  8136. /**
  8137. * @type {Object.<string, module:zrender/Layer>}
  8138. * @private
  8139. */
  8140. var layers = this._layers = {};
  8141. /**
  8142. * @type {Object.<string, Object>}
  8143. * @private
  8144. */
  8145. this._layerConfig = {};
  8146. /**
  8147. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8148. */
  8149. this._needsManuallyCompositing = false;
  8150. if (!singleCanvas) {
  8151. this._width = this._getSize(0);
  8152. this._height = this._getSize(1);
  8153. var domRoot = this._domRoot = createRoot(
  8154. this._width, this._height
  8155. );
  8156. root.appendChild(domRoot);
  8157. }
  8158. else {
  8159. var width = root.width;
  8160. var height = root.height;
  8161. if (opts.width != null) {
  8162. width = opts.width;
  8163. }
  8164. if (opts.height != null) {
  8165. height = opts.height;
  8166. }
  8167. this.dpr = opts.devicePixelRatio || 1;
  8168. // Use canvas width and height directly
  8169. root.width = width * this.dpr;
  8170. root.height = height * this.dpr;
  8171. this._width = width;
  8172. this._height = height;
  8173. // Create layer if only one given canvas
  8174. // Device can be specified to create a high dpi image.
  8175. var mainLayer = new Layer(root, this, this.dpr);
  8176. mainLayer.__builtin__ = true;
  8177. mainLayer.initContext();
  8178. // FIXME Use canvas width and height
  8179. // mainLayer.resize(width, height);
  8180. layers[CANVAS_ZLEVEL] = mainLayer;
  8181. mainLayer.zlevel = CANVAS_ZLEVEL;
  8182. // Not use common zlevel.
  8183. zlevelList.push(CANVAS_ZLEVEL);
  8184. this._domRoot = root;
  8185. }
  8186. /**
  8187. * @type {module:zrender/Layer}
  8188. * @private
  8189. */
  8190. this._hoverlayer = null;
  8191. this._hoverElements = [];
  8192. };
  8193. Painter.prototype = {
  8194. constructor: Painter,
  8195. getType: function () {
  8196. return 'canvas';
  8197. },
  8198. /**
  8199. * If painter use a single canvas
  8200. * @return {boolean}
  8201. */
  8202. isSingleCanvas: function () {
  8203. return this._singleCanvas;
  8204. },
  8205. /**
  8206. * @return {HTMLDivElement}
  8207. */
  8208. getViewportRoot: function () {
  8209. return this._domRoot;
  8210. },
  8211. getViewportRootOffset: function () {
  8212. var viewportRoot = this.getViewportRoot();
  8213. if (viewportRoot) {
  8214. return {
  8215. offsetLeft: viewportRoot.offsetLeft || 0,
  8216. offsetTop: viewportRoot.offsetTop || 0
  8217. };
  8218. }
  8219. },
  8220. /**
  8221. * 刷新
  8222. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8223. */
  8224. refresh: function (paintAll) {
  8225. var list = this.storage.getDisplayList(true);
  8226. var zlevelList = this._zlevelList;
  8227. this._redrawId = Math.random();
  8228. this._paintList(list, paintAll, this._redrawId);
  8229. // Paint custum layers
  8230. for (var i = 0; i < zlevelList.length; i++) {
  8231. var z = zlevelList[i];
  8232. var layer = this._layers[z];
  8233. if (!layer.__builtin__ && layer.refresh) {
  8234. var clearColor = i === 0 ? this._backgroundColor : null;
  8235. layer.refresh(clearColor);
  8236. }
  8237. }
  8238. this.refreshHover();
  8239. return this;
  8240. },
  8241. addHover: function (el, hoverStyle) {
  8242. if (el.__hoverMir) {
  8243. return;
  8244. }
  8245. var elMirror = new el.constructor({
  8246. style: el.style,
  8247. shape: el.shape,
  8248. z: el.z,
  8249. z2: el.z2,
  8250. silent: el.silent
  8251. });
  8252. elMirror.__from = el;
  8253. el.__hoverMir = elMirror;
  8254. hoverStyle && elMirror.setStyle(hoverStyle);
  8255. this._hoverElements.push(elMirror);
  8256. return elMirror;
  8257. },
  8258. removeHover: function (el) {
  8259. var elMirror = el.__hoverMir;
  8260. var hoverElements = this._hoverElements;
  8261. var idx = indexOf(hoverElements, elMirror);
  8262. if (idx >= 0) {
  8263. hoverElements.splice(idx, 1);
  8264. }
  8265. el.__hoverMir = null;
  8266. },
  8267. clearHover: function (el) {
  8268. var hoverElements = this._hoverElements;
  8269. for (var i = 0; i < hoverElements.length; i++) {
  8270. var from = hoverElements[i].__from;
  8271. if (from) {
  8272. from.__hoverMir = null;
  8273. }
  8274. }
  8275. hoverElements.length = 0;
  8276. },
  8277. refreshHover: function () {
  8278. var hoverElements = this._hoverElements;
  8279. var len = hoverElements.length;
  8280. var hoverLayer = this._hoverlayer;
  8281. hoverLayer && hoverLayer.clear();
  8282. if (!len) {
  8283. return;
  8284. }
  8285. sort(hoverElements, this.storage.displayableSortFunc);
  8286. // Use a extream large zlevel
  8287. // FIXME?
  8288. if (!hoverLayer) {
  8289. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8290. }
  8291. var scope = {};
  8292. hoverLayer.ctx.save();
  8293. for (var i = 0; i < len;) {
  8294. var el = hoverElements[i];
  8295. var originalEl = el.__from;
  8296. // Original el is removed
  8297. // PENDING
  8298. if (!(originalEl && originalEl.__zr)) {
  8299. hoverElements.splice(i, 1);
  8300. originalEl.__hoverMir = null;
  8301. len--;
  8302. continue;
  8303. }
  8304. i++;
  8305. // Use transform
  8306. // FIXME style and shape ?
  8307. if (!originalEl.invisible) {
  8308. el.transform = originalEl.transform;
  8309. el.invTransform = originalEl.invTransform;
  8310. el.__clipPaths = originalEl.__clipPaths;
  8311. // el.
  8312. this._doPaintEl(el, hoverLayer, true, scope);
  8313. }
  8314. }
  8315. hoverLayer.ctx.restore();
  8316. },
  8317. getHoverLayer: function () {
  8318. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8319. },
  8320. _paintList: function (list, paintAll, redrawId) {
  8321. if (this._redrawId !== redrawId) {
  8322. return;
  8323. }
  8324. paintAll = paintAll || false;
  8325. this._updateLayerStatus(list);
  8326. var finished = this._doPaintList(list, paintAll);
  8327. if (this._needsManuallyCompositing) {
  8328. this._compositeManually();
  8329. }
  8330. if (!finished) {
  8331. var self = this;
  8332. requestAnimationFrame(function () {
  8333. self._paintList(list, paintAll, redrawId);
  8334. });
  8335. }
  8336. },
  8337. _compositeManually: function () {
  8338. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8339. var width = this._domRoot.width;
  8340. var height = this._domRoot.height;
  8341. ctx.clearRect(0, 0, width, height);
  8342. // PENDING, If only builtin layer?
  8343. this.eachBuiltinLayer(function (layer) {
  8344. if (layer.virtual) {
  8345. ctx.drawImage(layer.dom, 0, 0, width, height);
  8346. }
  8347. });
  8348. },
  8349. _doPaintList: function (list, paintAll) {
  8350. var layerList = [];
  8351. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8352. var zlevel = this._zlevelList[zi];
  8353. var layer = this._layers[zlevel];
  8354. if (layer.__builtin__
  8355. && layer !== this._hoverlayer
  8356. && (layer.__dirty || paintAll)
  8357. ) {
  8358. layerList.push(layer);
  8359. }
  8360. }
  8361. var finished = true;
  8362. for (var k = 0; k < layerList.length; k++) {
  8363. var layer = layerList[k];
  8364. var ctx = layer.ctx;
  8365. var scope = {};
  8366. ctx.save();
  8367. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8368. var useTimer = !paintAll && layer.incremental && Date.now;
  8369. var startTime = useTimer && Date.now();
  8370. var clearColor = layer.zlevel === this._zlevelList[0]
  8371. ? this._backgroundColor : null;
  8372. // All elements in this layer are cleared.
  8373. if (layer.__startIndex === layer.__endIndex) {
  8374. layer.clear(false, clearColor);
  8375. }
  8376. else if (start === layer.__startIndex) {
  8377. var firstEl = list[start];
  8378. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8379. layer.clear(false, clearColor);
  8380. }
  8381. }
  8382. if (start === -1) {
  8383. console.error('For some unknown reason. drawIndex is -1');
  8384. start = layer.__startIndex;
  8385. }
  8386. for (var i = start; i < layer.__endIndex; i++) {
  8387. var el = list[i];
  8388. this._doPaintEl(el, layer, paintAll, scope);
  8389. el.__dirty = el.__dirtyText = false;
  8390. if (useTimer) {
  8391. // Date.now can be executed in 13,025,305 ops/second.
  8392. var dTime = Date.now() - startTime;
  8393. // Give 15 millisecond to draw.
  8394. // The rest elements will be drawn in the next frame.
  8395. if (dTime > 15) {
  8396. break;
  8397. }
  8398. }
  8399. }
  8400. layer.__drawIndex = i;
  8401. if (layer.__drawIndex < layer.__endIndex) {
  8402. finished = false;
  8403. }
  8404. if (scope.prevElClipPaths) {
  8405. // Needs restore the state. If last drawn element is in the clipping area.
  8406. ctx.restore();
  8407. }
  8408. ctx.restore();
  8409. }
  8410. if (env$1.wxa) {
  8411. // Flush for weixin application
  8412. each$1(this._layers, function (layer) {
  8413. if (layer && layer.ctx && layer.ctx.draw) {
  8414. layer.ctx.draw();
  8415. }
  8416. });
  8417. }
  8418. return finished;
  8419. },
  8420. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8421. var ctx = currentLayer.ctx;
  8422. var m = el.transform;
  8423. if (
  8424. (currentLayer.__dirty || forcePaint)
  8425. // Ignore invisible element
  8426. && !el.invisible
  8427. // Ignore transparent element
  8428. && el.style.opacity !== 0
  8429. // Ignore scale 0 element, in some environment like node-canvas
  8430. // Draw a scale 0 element can cause all following draw wrong
  8431. // And setTransform with scale 0 will cause set back transform failed.
  8432. && !(m && !m[0] && !m[3])
  8433. // Ignore culled element
  8434. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8435. ) {
  8436. var clipPaths = el.__clipPaths;
  8437. // Optimize when clipping on group with several elements
  8438. if (!scope.prevElClipPaths
  8439. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  8440. ) {
  8441. // If has previous clipping state, restore from it
  8442. if (scope.prevElClipPaths) {
  8443. currentLayer.ctx.restore();
  8444. scope.prevElClipPaths = null;
  8445. // Reset prevEl since context has been restored
  8446. scope.prevEl = null;
  8447. }
  8448. // New clipping state
  8449. if (clipPaths) {
  8450. ctx.save();
  8451. doClip(clipPaths, ctx);
  8452. scope.prevElClipPaths = clipPaths;
  8453. }
  8454. }
  8455. el.beforeBrush && el.beforeBrush(ctx);
  8456. el.brush(ctx, scope.prevEl || null);
  8457. scope.prevEl = el;
  8458. el.afterBrush && el.afterBrush(ctx);
  8459. }
  8460. },
  8461. /**
  8462. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8463. * @param {number} zlevel
  8464. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8465. * @return {module:zrender/Layer}
  8466. */
  8467. getLayer: function (zlevel, virtual) {
  8468. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8469. zlevel = CANVAS_ZLEVEL;
  8470. }
  8471. var layer = this._layers[zlevel];
  8472. if (!layer) {
  8473. // Create a new layer
  8474. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8475. layer.zlevel = zlevel;
  8476. layer.__builtin__ = true;
  8477. if (this._layerConfig[zlevel]) {
  8478. merge(layer, this._layerConfig[zlevel], true);
  8479. }
  8480. if (virtual) {
  8481. layer.virtual = virtual;
  8482. }
  8483. this.insertLayer(zlevel, layer);
  8484. // Context is created after dom inserted to document
  8485. // Or excanvas will get 0px clientWidth and clientHeight
  8486. layer.initContext();
  8487. }
  8488. return layer;
  8489. },
  8490. insertLayer: function (zlevel, layer) {
  8491. var layersMap = this._layers;
  8492. var zlevelList = this._zlevelList;
  8493. var len = zlevelList.length;
  8494. var prevLayer = null;
  8495. var i = -1;
  8496. var domRoot = this._domRoot;
  8497. if (layersMap[zlevel]) {
  8498. zrLog('ZLevel ' + zlevel + ' has been used already');
  8499. return;
  8500. }
  8501. // Check if is a valid layer
  8502. if (!isLayerValid(layer)) {
  8503. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  8504. return;
  8505. }
  8506. if (len > 0 && zlevel > zlevelList[0]) {
  8507. for (i = 0; i < len - 1; i++) {
  8508. if (
  8509. zlevelList[i] < zlevel
  8510. && zlevelList[i + 1] > zlevel
  8511. ) {
  8512. break;
  8513. }
  8514. }
  8515. prevLayer = layersMap[zlevelList[i]];
  8516. }
  8517. zlevelList.splice(i + 1, 0, zlevel);
  8518. layersMap[zlevel] = layer;
  8519. // Vitual layer will not directly show on the screen.
  8520. // (It can be a WebGL layer and assigned to a ZImage element)
  8521. // But it still under management of zrender.
  8522. if (!layer.virtual) {
  8523. if (prevLayer) {
  8524. var prevDom = prevLayer.dom;
  8525. if (prevDom.nextSibling) {
  8526. domRoot.insertBefore(
  8527. layer.dom,
  8528. prevDom.nextSibling
  8529. );
  8530. }
  8531. else {
  8532. domRoot.appendChild(layer.dom);
  8533. }
  8534. }
  8535. else {
  8536. if (domRoot.firstChild) {
  8537. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8538. }
  8539. else {
  8540. domRoot.appendChild(layer.dom);
  8541. }
  8542. }
  8543. }
  8544. },
  8545. // Iterate each layer
  8546. eachLayer: function (cb, context) {
  8547. var zlevelList = this._zlevelList;
  8548. var z;
  8549. var i;
  8550. for (i = 0; i < zlevelList.length; i++) {
  8551. z = zlevelList[i];
  8552. cb.call(context, this._layers[z], z);
  8553. }
  8554. },
  8555. // Iterate each buildin layer
  8556. eachBuiltinLayer: function (cb, context) {
  8557. var zlevelList = this._zlevelList;
  8558. var layer;
  8559. var z;
  8560. var i;
  8561. for (i = 0; i < zlevelList.length; i++) {
  8562. z = zlevelList[i];
  8563. layer = this._layers[z];
  8564. if (layer.__builtin__) {
  8565. cb.call(context, layer, z);
  8566. }
  8567. }
  8568. },
  8569. // Iterate each other layer except buildin layer
  8570. eachOtherLayer: function (cb, context) {
  8571. var zlevelList = this._zlevelList;
  8572. var layer;
  8573. var z;
  8574. var i;
  8575. for (i = 0; i < zlevelList.length; i++) {
  8576. z = zlevelList[i];
  8577. layer = this._layers[z];
  8578. if (!layer.__builtin__) {
  8579. cb.call(context, layer, z);
  8580. }
  8581. }
  8582. },
  8583. /**
  8584. * 获取所有已创建的层
  8585. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8586. */
  8587. getLayers: function () {
  8588. return this._layers;
  8589. },
  8590. _updateLayerStatus: function (list) {
  8591. this.eachBuiltinLayer(function (layer, z) {
  8592. layer.__dirty = layer.__used = false;
  8593. });
  8594. function updatePrevLayer(idx) {
  8595. if (prevLayer) {
  8596. if (prevLayer.__endIndex !== idx) {
  8597. prevLayer.__dirty = true;
  8598. }
  8599. prevLayer.__endIndex = idx;
  8600. }
  8601. }
  8602. if (this._singleCanvas) {
  8603. for (var i = 1; i < list.length; i++) {
  8604. var el = list[i];
  8605. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8606. this._needsManuallyCompositing = true;
  8607. break;
  8608. }
  8609. }
  8610. }
  8611. var prevLayer = null;
  8612. var incrementalLayerCount = 0;
  8613. for (var i = 0; i < list.length; i++) {
  8614. var el = list[i];
  8615. var zlevel = el.zlevel;
  8616. var layer;
  8617. // PENDING If change one incremental element style ?
  8618. // TODO Where there are non-incremental elements between incremental elements.
  8619. if (el.incremental) {
  8620. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8621. layer.incremental = true;
  8622. incrementalLayerCount = 1;
  8623. }
  8624. else {
  8625. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8626. }
  8627. if (!layer.__builtin__) {
  8628. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8629. }
  8630. if (layer !== prevLayer) {
  8631. layer.__used = true;
  8632. if (layer.__startIndex !== i) {
  8633. layer.__dirty = true;
  8634. }
  8635. layer.__startIndex = i;
  8636. if (!layer.incremental) {
  8637. layer.__drawIndex = i;
  8638. }
  8639. else {
  8640. // Mark layer draw index needs to update.
  8641. layer.__drawIndex = -1;
  8642. }
  8643. updatePrevLayer(i);
  8644. prevLayer = layer;
  8645. }
  8646. if (el.__dirty) {
  8647. layer.__dirty = true;
  8648. if (layer.incremental && layer.__drawIndex < 0) {
  8649. // Start draw from the first dirty element.
  8650. layer.__drawIndex = i;
  8651. }
  8652. }
  8653. }
  8654. updatePrevLayer(i);
  8655. this.eachBuiltinLayer(function (layer, z) {
  8656. // Used in last frame but not in this frame. Needs clear
  8657. if (!layer.__used && layer.getElementCount() > 0) {
  8658. layer.__dirty = true;
  8659. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8660. }
  8661. // For incremental layer. In case start index changed and no elements are dirty.
  8662. if (layer.__dirty && layer.__drawIndex < 0) {
  8663. layer.__drawIndex = layer.__startIndex;
  8664. }
  8665. });
  8666. },
  8667. /**
  8668. * 清除hover层外所有内容
  8669. */
  8670. clear: function () {
  8671. this.eachBuiltinLayer(this._clearLayer);
  8672. return this;
  8673. },
  8674. _clearLayer: function (layer) {
  8675. layer.clear();
  8676. },
  8677. setBackgroundColor: function (backgroundColor) {
  8678. this._backgroundColor = backgroundColor;
  8679. },
  8680. /**
  8681. * 修改指定zlevel的绘制参数
  8682. *
  8683. * @param {string} zlevel
  8684. * @param {Object} config 配置对象
  8685. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8686. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8687. * @param {number} [config.lastFrameAlpha=0.7]
  8688. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8689. */
  8690. configLayer: function (zlevel, config) {
  8691. if (config) {
  8692. var layerConfig = this._layerConfig;
  8693. if (!layerConfig[zlevel]) {
  8694. layerConfig[zlevel] = config;
  8695. }
  8696. else {
  8697. merge(layerConfig[zlevel], config, true);
  8698. }
  8699. for (var i = 0; i < this._zlevelList.length; i++) {
  8700. var _zlevel = this._zlevelList[i];
  8701. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8702. var layer = this._layers[_zlevel];
  8703. merge(layer, layerConfig[zlevel], true);
  8704. }
  8705. }
  8706. }
  8707. },
  8708. /**
  8709. * 删除指定层
  8710. * @param {number} zlevel 层所在的zlevel
  8711. */
  8712. delLayer: function (zlevel) {
  8713. var layers = this._layers;
  8714. var zlevelList = this._zlevelList;
  8715. var layer = layers[zlevel];
  8716. if (!layer) {
  8717. return;
  8718. }
  8719. layer.dom.parentNode.removeChild(layer.dom);
  8720. delete layers[zlevel];
  8721. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8722. },
  8723. /**
  8724. * 区域大小变化后重绘
  8725. */
  8726. resize: function (width, height) {
  8727. if (!this._domRoot.style) { // Maybe in node or worker
  8728. if (width == null || height == null) {
  8729. return;
  8730. }
  8731. this._width = width;
  8732. this._height = height;
  8733. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8734. }
  8735. else {
  8736. var domRoot = this._domRoot;
  8737. // FIXME Why ?
  8738. domRoot.style.display = 'none';
  8739. // Save input w/h
  8740. var opts = this._opts;
  8741. width != null && (opts.width = width);
  8742. height != null && (opts.height = height);
  8743. width = this._getSize(0);
  8744. height = this._getSize(1);
  8745. domRoot.style.display = '';
  8746. // 优化没有实际改变的resize
  8747. if (this._width !== width || height !== this._height) {
  8748. domRoot.style.width = width + 'px';
  8749. domRoot.style.height = height + 'px';
  8750. for (var id in this._layers) {
  8751. if (this._layers.hasOwnProperty(id)) {
  8752. this._layers[id].resize(width, height);
  8753. }
  8754. }
  8755. each$1(this._progressiveLayers, function (layer) {
  8756. layer.resize(width, height);
  8757. });
  8758. this.refresh(true);
  8759. }
  8760. this._width = width;
  8761. this._height = height;
  8762. }
  8763. return this;
  8764. },
  8765. /**
  8766. * 清除单独的一个层
  8767. * @param {number} zlevel
  8768. */
  8769. clearLayer: function (zlevel) {
  8770. var layer = this._layers[zlevel];
  8771. if (layer) {
  8772. layer.clear();
  8773. }
  8774. },
  8775. /**
  8776. * 释放
  8777. */
  8778. dispose: function () {
  8779. this.root.innerHTML = '';
  8780. this.root =
  8781. this.storage =
  8782. this._domRoot =
  8783. this._layers = null;
  8784. },
  8785. /**
  8786. * Get canvas which has all thing rendered
  8787. * @param {Object} opts
  8788. * @param {string} [opts.backgroundColor]
  8789. * @param {number} [opts.pixelRatio]
  8790. */
  8791. getRenderedCanvas: function (opts) {
  8792. opts = opts || {};
  8793. if (this._singleCanvas && !this._compositeManually) {
  8794. return this._layers[CANVAS_ZLEVEL].dom;
  8795. }
  8796. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8797. imageLayer.initContext();
  8798. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8799. if (opts.pixelRatio <= this.dpr) {
  8800. this.refresh();
  8801. var width = imageLayer.dom.width;
  8802. var height = imageLayer.dom.height;
  8803. var ctx = imageLayer.ctx;
  8804. this.eachLayer(function (layer) {
  8805. if (layer.__builtin__) {
  8806. ctx.drawImage(layer.dom, 0, 0, width, height);
  8807. }
  8808. else if (layer.renderToCanvas) {
  8809. imageLayer.ctx.save();
  8810. layer.renderToCanvas(imageLayer.ctx);
  8811. imageLayer.ctx.restore();
  8812. }
  8813. });
  8814. }
  8815. else {
  8816. // PENDING, echarts-gl and incremental rendering.
  8817. var scope = {};
  8818. var displayList = this.storage.getDisplayList(true);
  8819. for (var i = 0; i < displayList.length; i++) {
  8820. var el = displayList[i];
  8821. this._doPaintEl(el, imageLayer, true, scope);
  8822. }
  8823. }
  8824. return imageLayer.dom;
  8825. },
  8826. /**
  8827. * 获取绘图区域宽度
  8828. */
  8829. getWidth: function () {
  8830. return this._width;
  8831. },
  8832. /**
  8833. * 获取绘图区域高度
  8834. */
  8835. getHeight: function () {
  8836. return this._height;
  8837. },
  8838. _getSize: function (whIdx) {
  8839. var opts = this._opts;
  8840. var wh = ['width', 'height'][whIdx];
  8841. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8842. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8843. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8844. if (opts[wh] != null && opts[wh] !== 'auto') {
  8845. return parseFloat(opts[wh]);
  8846. }
  8847. var root = this.root;
  8848. // IE8 does not support getComputedStyle, but it use VML.
  8849. var stl = document.defaultView.getComputedStyle(root);
  8850. return (
  8851. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8852. - (parseInt10(stl[plt]) || 0)
  8853. - (parseInt10(stl[prb]) || 0)
  8854. ) | 0;
  8855. },
  8856. pathToImage: function (path, dpr) {
  8857. dpr = dpr || this.dpr;
  8858. var canvas = document.createElement('canvas');
  8859. var ctx = canvas.getContext('2d');
  8860. var rect = path.getBoundingRect();
  8861. var style = path.style;
  8862. var shadowBlurSize = style.shadowBlur * dpr;
  8863. var shadowOffsetX = style.shadowOffsetX * dpr;
  8864. var shadowOffsetY = style.shadowOffsetY * dpr;
  8865. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8866. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8867. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8868. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8869. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8870. var width = rect.width + leftMargin + rightMargin;
  8871. var height = rect.height + topMargin + bottomMargin;
  8872. canvas.width = width * dpr;
  8873. canvas.height = height * dpr;
  8874. ctx.scale(dpr, dpr);
  8875. ctx.clearRect(0, 0, width, height);
  8876. ctx.dpr = dpr;
  8877. var pathTransform = {
  8878. position: path.position,
  8879. rotation: path.rotation,
  8880. scale: path.scale
  8881. };
  8882. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8883. path.rotation = 0;
  8884. path.scale = [1, 1];
  8885. path.updateTransform();
  8886. if (path) {
  8887. path.brush(ctx);
  8888. }
  8889. var ImageShape = ZImage;
  8890. var imgShape = new ImageShape({
  8891. style: {
  8892. x: 0,
  8893. y: 0,
  8894. image: canvas
  8895. }
  8896. });
  8897. if (pathTransform.position != null) {
  8898. imgShape.position = path.position = pathTransform.position;
  8899. }
  8900. if (pathTransform.rotation != null) {
  8901. imgShape.rotation = path.rotation = pathTransform.rotation;
  8902. }
  8903. if (pathTransform.scale != null) {
  8904. imgShape.scale = path.scale = pathTransform.scale;
  8905. }
  8906. return imgShape;
  8907. }
  8908. };
  8909. /**
  8910. * 动画主类, 调度和管理所有动画控制器
  8911. *
  8912. * @module zrender/animation/Animation
  8913. * @author pissang(https://github.com/pissang)
  8914. */
  8915. // TODO Additive animation
  8916. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8917. // https://developer.apple.com/videos/wwdc2014/#236
  8918. /**
  8919. * @typedef {Object} IZRenderStage
  8920. * @property {Function} update
  8921. */
  8922. /**
  8923. * @alias module:zrender/animation/Animation
  8924. * @constructor
  8925. * @param {Object} [options]
  8926. * @param {Function} [options.onframe]
  8927. * @param {IZRenderStage} [options.stage]
  8928. * @example
  8929. * var animation = new Animation();
  8930. * var obj = {
  8931. * x: 100,
  8932. * y: 100
  8933. * };
  8934. * animation.animate(node.position)
  8935. * .when(1000, {
  8936. * x: 500,
  8937. * y: 500
  8938. * })
  8939. * .when(2000, {
  8940. * x: 100,
  8941. * y: 100
  8942. * })
  8943. * .start('spline');
  8944. */
  8945. var Animation = function (options) {
  8946. options = options || {};
  8947. this.stage = options.stage || {};
  8948. this.onframe = options.onframe || function () {};
  8949. // private properties
  8950. this._clips = [];
  8951. this._running = false;
  8952. this._time;
  8953. this._pausedTime;
  8954. this._pauseStart;
  8955. this._paused = false;
  8956. Eventful.call(this);
  8957. };
  8958. Animation.prototype = {
  8959. constructor: Animation,
  8960. /**
  8961. * 添加 clip
  8962. * @param {module:zrender/animation/Clip} clip
  8963. */
  8964. addClip: function (clip) {
  8965. this._clips.push(clip);
  8966. },
  8967. /**
  8968. * 添加 animator
  8969. * @param {module:zrender/animation/Animator} animator
  8970. */
  8971. addAnimator: function (animator) {
  8972. animator.animation = this;
  8973. var clips = animator.getClips();
  8974. for (var i = 0; i < clips.length; i++) {
  8975. this.addClip(clips[i]);
  8976. }
  8977. },
  8978. /**
  8979. * 删除动画片段
  8980. * @param {module:zrender/animation/Clip} clip
  8981. */
  8982. removeClip: function (clip) {
  8983. var idx = indexOf(this._clips, clip);
  8984. if (idx >= 0) {
  8985. this._clips.splice(idx, 1);
  8986. }
  8987. },
  8988. /**
  8989. * 删除动画片段
  8990. * @param {module:zrender/animation/Animator} animator
  8991. */
  8992. removeAnimator: function (animator) {
  8993. var clips = animator.getClips();
  8994. for (var i = 0; i < clips.length; i++) {
  8995. this.removeClip(clips[i]);
  8996. }
  8997. animator.animation = null;
  8998. },
  8999. _update: function () {
  9000. var time = new Date().getTime() - this._pausedTime;
  9001. var delta = time - this._time;
  9002. var clips = this._clips;
  9003. var len = clips.length;
  9004. var deferredEvents = [];
  9005. var deferredClips = [];
  9006. for (var i = 0; i < len; i++) {
  9007. var clip = clips[i];
  9008. var e = clip.step(time, delta);
  9009. // Throw out the events need to be called after
  9010. // stage.update, like destroy
  9011. if (e) {
  9012. deferredEvents.push(e);
  9013. deferredClips.push(clip);
  9014. }
  9015. }
  9016. // Remove the finished clip
  9017. for (var i = 0; i < len;) {
  9018. if (clips[i]._needsRemove) {
  9019. clips[i] = clips[len - 1];
  9020. clips.pop();
  9021. len--;
  9022. }
  9023. else {
  9024. i++;
  9025. }
  9026. }
  9027. len = deferredEvents.length;
  9028. for (var i = 0; i < len; i++) {
  9029. deferredClips[i].fire(deferredEvents[i]);
  9030. }
  9031. this._time = time;
  9032. this.onframe(delta);
  9033. // 'frame' should be triggered before stage, because upper application
  9034. // depends on the sequence (e.g., echarts-stream and finish
  9035. // event judge)
  9036. this.trigger('frame', delta);
  9037. if (this.stage.update) {
  9038. this.stage.update();
  9039. }
  9040. },
  9041. _startLoop: function () {
  9042. var self = this;
  9043. this._running = true;
  9044. function step() {
  9045. if (self._running) {
  9046. requestAnimationFrame(step);
  9047. !self._paused && self._update();
  9048. }
  9049. }
  9050. requestAnimationFrame(step);
  9051. },
  9052. /**
  9053. * Start animation.
  9054. */
  9055. start: function () {
  9056. this._time = new Date().getTime();
  9057. this._pausedTime = 0;
  9058. this._startLoop();
  9059. },
  9060. /**
  9061. * Stop animation.
  9062. */
  9063. stop: function () {
  9064. this._running = false;
  9065. },
  9066. /**
  9067. * Pause animation.
  9068. */
  9069. pause: function () {
  9070. if (!this._paused) {
  9071. this._pauseStart = new Date().getTime();
  9072. this._paused = true;
  9073. }
  9074. },
  9075. /**
  9076. * Resume animation.
  9077. */
  9078. resume: function () {
  9079. if (this._paused) {
  9080. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9081. this._paused = false;
  9082. }
  9083. },
  9084. /**
  9085. * Clear animation.
  9086. */
  9087. clear: function () {
  9088. this._clips = [];
  9089. },
  9090. /**
  9091. * Whether animation finished.
  9092. */
  9093. isFinished: function () {
  9094. return !this._clips.length;
  9095. },
  9096. /**
  9097. * Creat animator for a target, whose props can be animated.
  9098. *
  9099. * @param {Object} target
  9100. * @param {Object} options
  9101. * @param {boolean} [options.loop=false] Whether loop animation.
  9102. * @param {Function} [options.getter=null] Get value from target.
  9103. * @param {Function} [options.setter=null] Set value to target.
  9104. * @return {module:zrender/animation/Animation~Animator}
  9105. */
  9106. // TODO Gap
  9107. animate: function (target, options) {
  9108. options = options || {};
  9109. var animator = new Animator(
  9110. target,
  9111. options.loop,
  9112. options.getter,
  9113. options.setter
  9114. );
  9115. this.addAnimator(animator);
  9116. return animator;
  9117. }
  9118. };
  9119. mixin(Animation, Eventful);
  9120. var TOUCH_CLICK_DELAY = 300;
  9121. var mouseHandlerNames = [
  9122. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9123. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9124. ];
  9125. var touchHandlerNames = [
  9126. 'touchstart', 'touchend', 'touchmove'
  9127. ];
  9128. var pointerEventNames = {
  9129. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9130. };
  9131. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9132. var nm = name.replace('mouse', 'pointer');
  9133. return pointerEventNames[nm] ? nm : name;
  9134. });
  9135. function eventNameFix(name) {
  9136. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9137. }
  9138. // function onMSGestureChange(proxy, event) {
  9139. // if (event.translationX || event.translationY) {
  9140. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9141. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9142. // }
  9143. // if (event.scale !== 1) {
  9144. // event.pinchX = event.offsetX;
  9145. // event.pinchY = event.offsetY;
  9146. // event.pinchScale = event.scale;
  9147. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9148. // }
  9149. // }
  9150. /**
  9151. * Prevent mouse event from being dispatched after Touch Events action
  9152. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9153. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9154. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9155. * Result: Blocking Mouse Events for 700ms.
  9156. */
  9157. function setTouchTimer(instance) {
  9158. instance._touching = true;
  9159. clearTimeout(instance._touchTimer);
  9160. instance._touchTimer = setTimeout(function () {
  9161. instance._touching = false;
  9162. }, 700);
  9163. }
  9164. var domHandlers = {
  9165. /**
  9166. * Mouse move handler
  9167. * @inner
  9168. * @param {Event} event
  9169. */
  9170. mousemove: function (event) {
  9171. event = normalizeEvent(this.dom, event);
  9172. this.trigger('mousemove', event);
  9173. },
  9174. /**
  9175. * Mouse out handler
  9176. * @inner
  9177. * @param {Event} event
  9178. */
  9179. mouseout: function (event) {
  9180. event = normalizeEvent(this.dom, event);
  9181. var element = event.toElement || event.relatedTarget;
  9182. if (element !== this.dom) {
  9183. while (element && element.nodeType !== 9) {
  9184. // 忽略包含在root中的dom引起的mouseOut
  9185. if (element === this.dom) {
  9186. return;
  9187. }
  9188. element = element.parentNode;
  9189. }
  9190. }
  9191. this.trigger('mouseout', event);
  9192. },
  9193. /**
  9194. * Touch开始响应函数
  9195. * @inner
  9196. * @param {Event} event
  9197. */
  9198. touchstart: function (event) {
  9199. // Default mouse behaviour should not be disabled here.
  9200. // For example, page may needs to be slided.
  9201. event = normalizeEvent(this.dom, event);
  9202. // Mark touch, which is useful in distinguish touch and
  9203. // mouse event in upper applicatoin.
  9204. event.zrByTouch = true;
  9205. this._lastTouchMoment = new Date();
  9206. this.handler.processGesture(this, event, 'start');
  9207. // In touch device, trigger `mousemove`(`mouseover`) should
  9208. // be triggered, and must before `mousedown` triggered.
  9209. domHandlers.mousemove.call(this, event);
  9210. domHandlers.mousedown.call(this, event);
  9211. setTouchTimer(this);
  9212. },
  9213. /**
  9214. * Touch移动响应函数
  9215. * @inner
  9216. * @param {Event} event
  9217. */
  9218. touchmove: function (event) {
  9219. event = normalizeEvent(this.dom, event);
  9220. // Mark touch, which is useful in distinguish touch and
  9221. // mouse event in upper applicatoin.
  9222. event.zrByTouch = true;
  9223. this.handler.processGesture(this, event, 'change');
  9224. // Mouse move should always be triggered no matter whether
  9225. // there is gestrue event, because mouse move and pinch may
  9226. // be used at the same time.
  9227. domHandlers.mousemove.call(this, event);
  9228. setTouchTimer(this);
  9229. },
  9230. /**
  9231. * Touch结束响应函数
  9232. * @inner
  9233. * @param {Event} event
  9234. */
  9235. touchend: function (event) {
  9236. event = normalizeEvent(this.dom, event);
  9237. // Mark touch, which is useful in distinguish touch and
  9238. // mouse event in upper applicatoin.
  9239. event.zrByTouch = true;
  9240. this.handler.processGesture(this, event, 'end');
  9241. domHandlers.mouseup.call(this, event);
  9242. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9243. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9244. // we can conveniently implement "hover style" in both PC and touch device just
  9245. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9246. // to remove "hover style" on an element, without any additional code for
  9247. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9248. // style" will remain for user view)
  9249. // click event should always be triggered no matter whether
  9250. // there is gestrue event. System click can not be prevented.
  9251. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9252. domHandlers.click.call(this, event);
  9253. }
  9254. setTouchTimer(this);
  9255. },
  9256. pointerdown: function (event) {
  9257. domHandlers.mousedown.call(this, event);
  9258. // if (useMSGuesture(this, event)) {
  9259. // this._msGesture.addPointer(event.pointerId);
  9260. // }
  9261. },
  9262. pointermove: function (event) {
  9263. // FIXME
  9264. // pointermove is so sensitive that it always triggered when
  9265. // tap(click) on touch screen, which affect some judgement in
  9266. // upper application. So, we dont support mousemove on MS touch
  9267. // device yet.
  9268. if (!isPointerFromTouch(event)) {
  9269. domHandlers.mousemove.call(this, event);
  9270. }
  9271. },
  9272. pointerup: function (event) {
  9273. domHandlers.mouseup.call(this, event);
  9274. },
  9275. pointerout: function (event) {
  9276. // pointerout will be triggered when tap on touch screen
  9277. // (IE11+/Edge on MS Surface) after click event triggered,
  9278. // which is inconsistent with the mousout behavior we defined
  9279. // in touchend. So we unify them.
  9280. // (check domHandlers.touchend for detailed explanation)
  9281. if (!isPointerFromTouch(event)) {
  9282. domHandlers.mouseout.call(this, event);
  9283. }
  9284. }
  9285. };
  9286. function isPointerFromTouch(event) {
  9287. var pointerType = event.pointerType;
  9288. return pointerType === 'pen' || pointerType === 'touch';
  9289. }
  9290. // function useMSGuesture(handlerProxy, event) {
  9291. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9292. // }
  9293. // Common handlers
  9294. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9295. domHandlers[name] = function (event) {
  9296. event = normalizeEvent(this.dom, event);
  9297. this.trigger(name, event);
  9298. };
  9299. });
  9300. /**
  9301. * 为控制类实例初始化dom 事件处理函数
  9302. *
  9303. * @inner
  9304. * @param {module:zrender/Handler} instance 控制类实例
  9305. */
  9306. function initDomHandler(instance) {
  9307. each$1(touchHandlerNames, function (name) {
  9308. instance._handlers[name] = bind(domHandlers[name], instance);
  9309. });
  9310. each$1(pointerHandlerNames, function (name) {
  9311. instance._handlers[name] = bind(domHandlers[name], instance);
  9312. });
  9313. each$1(mouseHandlerNames, function (name) {
  9314. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9315. });
  9316. function makeMouseHandler(fn, instance) {
  9317. return function () {
  9318. if (instance._touching) {
  9319. return;
  9320. }
  9321. return fn.apply(instance, arguments);
  9322. };
  9323. }
  9324. }
  9325. function HandlerDomProxy(dom) {
  9326. Eventful.call(this);
  9327. this.dom = dom;
  9328. /**
  9329. * @private
  9330. * @type {boolean}
  9331. */
  9332. this._touching = false;
  9333. /**
  9334. * @private
  9335. * @type {number}
  9336. */
  9337. this._touchTimer;
  9338. this._handlers = {};
  9339. initDomHandler(this);
  9340. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9341. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9342. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9343. // at the same time.
  9344. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9345. // screen, which do not occurs in pointer event.
  9346. // So we use pointer event to both detect touch gesture and mouse behavior.
  9347. mountHandlers(pointerHandlerNames, this);
  9348. // FIXME
  9349. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9350. // which does not prevent defuault behavior occasionally (which may cause view port
  9351. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9352. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9353. // touch screen. And we only support click behavior on MS touch screen now.
  9354. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9355. // We dont support touch on IE on win7.
  9356. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9357. // if (typeof MSGesture === 'function') {
  9358. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9359. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9360. // }
  9361. }
  9362. else {
  9363. if (env$1.touchEventsSupported) {
  9364. mountHandlers(touchHandlerNames, this);
  9365. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9366. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9367. }
  9368. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9369. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9370. // mouse event can not be handle in those devices.
  9371. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9372. // mouseevent after touch event triggered, see `setTouchTimer`.
  9373. mountHandlers(mouseHandlerNames, this);
  9374. }
  9375. function mountHandlers(handlerNames, instance) {
  9376. each$1(handlerNames, function (name) {
  9377. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9378. }, instance);
  9379. }
  9380. }
  9381. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9382. handlerDomProxyProto.dispose = function () {
  9383. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9384. for (var i = 0; i < handlerNames.length; i++) {
  9385. var name = handlerNames[i];
  9386. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9387. }
  9388. };
  9389. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9390. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9391. };
  9392. mixin(HandlerDomProxy, Eventful);
  9393. /*!
  9394. * ZRender, a high performance 2d drawing library.
  9395. *
  9396. * Copyright (c) 2013, Baidu Inc.
  9397. * All rights reserved.
  9398. *
  9399. * LICENSE
  9400. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9401. */
  9402. var useVML = !env$1.canvasSupported;
  9403. var painterCtors = {
  9404. canvas: Painter
  9405. };
  9406. var instances$1 = {}; // ZRender实例map索引
  9407. /**
  9408. * @type {string}
  9409. */
  9410. var version$1 = '4.0.6';
  9411. /**
  9412. * Initializing a zrender instance
  9413. * @param {HTMLElement} dom
  9414. * @param {Object} [opts]
  9415. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9416. * @param {number} [opts.devicePixelRatio]
  9417. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9418. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9419. * @return {module:zrender/ZRender}
  9420. */
  9421. function init$1(dom, opts) {
  9422. var zr = new ZRender(guid(), dom, opts);
  9423. instances$1[zr.id] = zr;
  9424. return zr;
  9425. }
  9426. /**
  9427. * Dispose zrender instance
  9428. * @param {module:zrender/ZRender} zr
  9429. */
  9430. function dispose$1(zr) {
  9431. if (zr) {
  9432. zr.dispose();
  9433. }
  9434. else {
  9435. for (var key in instances$1) {
  9436. if (instances$1.hasOwnProperty(key)) {
  9437. instances$1[key].dispose();
  9438. }
  9439. }
  9440. instances$1 = {};
  9441. }
  9442. return this;
  9443. }
  9444. /**
  9445. * Get zrender instance by id
  9446. * @param {string} id zrender instance id
  9447. * @return {module:zrender/ZRender}
  9448. */
  9449. function getInstance(id) {
  9450. return instances$1[id];
  9451. }
  9452. function registerPainter(name, Ctor) {
  9453. painterCtors[name] = Ctor;
  9454. }
  9455. function delInstance(id) {
  9456. delete instances$1[id];
  9457. }
  9458. /**
  9459. * @module zrender/ZRender
  9460. */
  9461. /**
  9462. * @constructor
  9463. * @alias module:zrender/ZRender
  9464. * @param {string} id
  9465. * @param {HTMLElement} dom
  9466. * @param {Object} opts
  9467. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9468. * @param {number} [opts.devicePixelRatio]
  9469. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9470. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9471. */
  9472. var ZRender = function (id, dom, opts) {
  9473. opts = opts || {};
  9474. /**
  9475. * @type {HTMLDomElement}
  9476. */
  9477. this.dom = dom;
  9478. /**
  9479. * @type {string}
  9480. */
  9481. this.id = id;
  9482. var self = this;
  9483. var storage = new Storage();
  9484. var rendererType = opts.renderer;
  9485. // TODO WebGL
  9486. if (useVML) {
  9487. if (!painterCtors.vml) {
  9488. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9489. }
  9490. rendererType = 'vml';
  9491. }
  9492. else if (!rendererType || !painterCtors[rendererType]) {
  9493. rendererType = 'canvas';
  9494. }
  9495. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9496. this.storage = storage;
  9497. this.painter = painter;
  9498. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9499. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9500. /**
  9501. * @type {module:zrender/animation/Animation}
  9502. */
  9503. this.animation = new Animation({
  9504. stage: {
  9505. update: bind(this.flush, this)
  9506. }
  9507. });
  9508. this.animation.start();
  9509. /**
  9510. * @type {boolean}
  9511. * @private
  9512. */
  9513. this._needsRefresh;
  9514. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9515. // FIXME 有点ugly
  9516. var oldDelFromStorage = storage.delFromStorage;
  9517. var oldAddToStorage = storage.addToStorage;
  9518. storage.delFromStorage = function (el) {
  9519. oldDelFromStorage.call(storage, el);
  9520. el && el.removeSelfFromZr(self);
  9521. };
  9522. storage.addToStorage = function (el) {
  9523. oldAddToStorage.call(storage, el);
  9524. el.addSelfToZr(self);
  9525. };
  9526. };
  9527. ZRender.prototype = {
  9528. constructor: ZRender,
  9529. /**
  9530. * 获取实例唯一标识
  9531. * @return {string}
  9532. */
  9533. getId: function () {
  9534. return this.id;
  9535. },
  9536. /**
  9537. * 添加元素
  9538. * @param {module:zrender/Element} el
  9539. */
  9540. add: function (el) {
  9541. this.storage.addRoot(el);
  9542. this._needsRefresh = true;
  9543. },
  9544. /**
  9545. * 删除元素
  9546. * @param {module:zrender/Element} el
  9547. */
  9548. remove: function (el) {
  9549. this.storage.delRoot(el);
  9550. this._needsRefresh = true;
  9551. },
  9552. /**
  9553. * Change configuration of layer
  9554. * @param {string} zLevel
  9555. * @param {Object} config
  9556. * @param {string} [config.clearColor=0] Clear color
  9557. * @param {string} [config.motionBlur=false] If enable motion blur
  9558. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9559. */
  9560. configLayer: function (zLevel, config) {
  9561. if (this.painter.configLayer) {
  9562. this.painter.configLayer(zLevel, config);
  9563. }
  9564. this._needsRefresh = true;
  9565. },
  9566. /**
  9567. * Set background color
  9568. * @param {string} backgroundColor
  9569. */
  9570. setBackgroundColor: function (backgroundColor) {
  9571. if (this.painter.setBackgroundColor) {
  9572. this.painter.setBackgroundColor(backgroundColor);
  9573. }
  9574. this._needsRefresh = true;
  9575. },
  9576. /**
  9577. * Repaint the canvas immediately
  9578. */
  9579. refreshImmediately: function () {
  9580. // var start = new Date();
  9581. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9582. // Or it will cause zrender refreshes again and again.
  9583. this._needsRefresh = false;
  9584. this.painter.refresh();
  9585. /**
  9586. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9587. */
  9588. this._needsRefresh = false;
  9589. // var end = new Date();
  9590. // var log = document.getElementById('log');
  9591. // if (log) {
  9592. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9593. // }
  9594. },
  9595. /**
  9596. * Mark and repaint the canvas in the next frame of browser
  9597. */
  9598. refresh: function () {
  9599. this._needsRefresh = true;
  9600. },
  9601. /**
  9602. * Perform all refresh
  9603. */
  9604. flush: function () {
  9605. var triggerRendered;
  9606. if (this._needsRefresh) {
  9607. triggerRendered = true;
  9608. this.refreshImmediately();
  9609. }
  9610. if (this._needsRefreshHover) {
  9611. triggerRendered = true;
  9612. this.refreshHoverImmediately();
  9613. }
  9614. triggerRendered && this.trigger('rendered');
  9615. },
  9616. /**
  9617. * Add element to hover layer
  9618. * @param {module:zrender/Element} el
  9619. * @param {Object} style
  9620. */
  9621. addHover: function (el, style) {
  9622. if (this.painter.addHover) {
  9623. var elMirror = this.painter.addHover(el, style);
  9624. this.refreshHover();
  9625. return elMirror;
  9626. }
  9627. },
  9628. /**
  9629. * Add element from hover layer
  9630. * @param {module:zrender/Element} el
  9631. */
  9632. removeHover: function (el) {
  9633. if (this.painter.removeHover) {
  9634. this.painter.removeHover(el);
  9635. this.refreshHover();
  9636. }
  9637. },
  9638. /**
  9639. * Clear all hover elements in hover layer
  9640. * @param {module:zrender/Element} el
  9641. */
  9642. clearHover: function () {
  9643. if (this.painter.clearHover) {
  9644. this.painter.clearHover();
  9645. this.refreshHover();
  9646. }
  9647. },
  9648. /**
  9649. * Refresh hover in next frame
  9650. */
  9651. refreshHover: function () {
  9652. this._needsRefreshHover = true;
  9653. },
  9654. /**
  9655. * Refresh hover immediately
  9656. */
  9657. refreshHoverImmediately: function () {
  9658. this._needsRefreshHover = false;
  9659. this.painter.refreshHover && this.painter.refreshHover();
  9660. },
  9661. /**
  9662. * Resize the canvas.
  9663. * Should be invoked when container size is changed
  9664. * @param {Object} [opts]
  9665. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9666. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9667. */
  9668. resize: function (opts) {
  9669. opts = opts || {};
  9670. this.painter.resize(opts.width, opts.height);
  9671. this.handler.resize();
  9672. },
  9673. /**
  9674. * Stop and clear all animation immediately
  9675. */
  9676. clearAnimation: function () {
  9677. this.animation.clear();
  9678. },
  9679. /**
  9680. * Get container width
  9681. */
  9682. getWidth: function () {
  9683. return this.painter.getWidth();
  9684. },
  9685. /**
  9686. * Get container height
  9687. */
  9688. getHeight: function () {
  9689. return this.painter.getHeight();
  9690. },
  9691. /**
  9692. * Export the canvas as Base64 URL
  9693. * @param {string} type
  9694. * @param {string} [backgroundColor='#fff']
  9695. * @return {string} Base64 URL
  9696. */
  9697. // toDataURL: function(type, backgroundColor) {
  9698. // return this.painter.getRenderedCanvas({
  9699. // backgroundColor: backgroundColor
  9700. // }).toDataURL(type);
  9701. // },
  9702. /**
  9703. * Converting a path to image.
  9704. * It has much better performance of drawing image rather than drawing a vector path.
  9705. * @param {module:zrender/graphic/Path} e
  9706. * @param {number} width
  9707. * @param {number} height
  9708. */
  9709. pathToImage: function (e, dpr) {
  9710. return this.painter.pathToImage(e, dpr);
  9711. },
  9712. /**
  9713. * Set default cursor
  9714. * @param {string} [cursorStyle='default'] 例如 crosshair
  9715. */
  9716. setCursorStyle: function (cursorStyle) {
  9717. this.handler.setCursorStyle(cursorStyle);
  9718. },
  9719. /**
  9720. * Find hovered element
  9721. * @param {number} x
  9722. * @param {number} y
  9723. * @return {Object} {target, topTarget}
  9724. */
  9725. findHover: function (x, y) {
  9726. return this.handler.findHover(x, y);
  9727. },
  9728. /**
  9729. * Bind event
  9730. *
  9731. * @param {string} eventName Event name
  9732. * @param {Function} eventHandler Handler function
  9733. * @param {Object} [context] Context object
  9734. */
  9735. on: function (eventName, eventHandler, context) {
  9736. this.handler.on(eventName, eventHandler, context);
  9737. },
  9738. /**
  9739. * Unbind event
  9740. * @param {string} eventName Event name
  9741. * @param {Function} [eventHandler] Handler function
  9742. */
  9743. off: function (eventName, eventHandler) {
  9744. this.handler.off(eventName, eventHandler);
  9745. },
  9746. /**
  9747. * Trigger event manually
  9748. *
  9749. * @param {string} eventName Event name
  9750. * @param {event=} event Event object
  9751. */
  9752. trigger: function (eventName, event) {
  9753. this.handler.trigger(eventName, event);
  9754. },
  9755. /**
  9756. * Clear all objects and the canvas.
  9757. */
  9758. clear: function () {
  9759. this.storage.delRoot();
  9760. this.painter.clear();
  9761. },
  9762. /**
  9763. * Dispose self.
  9764. */
  9765. dispose: function () {
  9766. this.animation.stop();
  9767. this.clear();
  9768. this.storage.dispose();
  9769. this.painter.dispose();
  9770. this.handler.dispose();
  9771. this.animation =
  9772. this.storage =
  9773. this.painter =
  9774. this.handler = null;
  9775. delInstance(this.id);
  9776. }
  9777. };
  9778. var zrender = (Object.freeze || Object)({
  9779. version: version$1,
  9780. init: init$1,
  9781. dispose: dispose$1,
  9782. getInstance: getInstance,
  9783. registerPainter: registerPainter
  9784. });
  9785. /*
  9786. * Licensed to the Apache Software Foundation (ASF) under one
  9787. * or more contributor license agreements. See the NOTICE file
  9788. * distributed with this work for additional information
  9789. * regarding copyright ownership. The ASF licenses this file
  9790. * to you under the Apache License, Version 2.0 (the
  9791. * "License"); you may not use this file except in compliance
  9792. * with the License. You may obtain a copy of the License at
  9793. *
  9794. * http://www.apache.org/licenses/LICENSE-2.0
  9795. *
  9796. * Unless required by applicable law or agreed to in writing,
  9797. * software distributed under the License is distributed on an
  9798. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9799. * KIND, either express or implied. See the License for the
  9800. * specific language governing permissions and limitations
  9801. * under the License.
  9802. */
  9803. var each$2 = each$1;
  9804. var isObject$2 = isObject$1;
  9805. var isArray$1 = isArray;
  9806. /**
  9807. * Make the name displayable. But we should
  9808. * make sure it is not duplicated with user
  9809. * specified name, so use '\0';
  9810. */
  9811. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9812. /**
  9813. * If value is not array, then translate it to array.
  9814. * @param {*} value
  9815. * @return {Array} [value] or value
  9816. */
  9817. function normalizeToArray(value) {
  9818. return value instanceof Array
  9819. ? value
  9820. : value == null
  9821. ? []
  9822. : [value];
  9823. }
  9824. /**
  9825. * Sync default option between normal and emphasis like `position` and `show`
  9826. * In case some one will write code like
  9827. * label: {
  9828. * show: false,
  9829. * position: 'outside',
  9830. * fontSize: 18
  9831. * },
  9832. * emphasis: {
  9833. * label: { show: true }
  9834. * }
  9835. * @param {Object} opt
  9836. * @param {string} key
  9837. * @param {Array.<string>} subOpts
  9838. */
  9839. function defaultEmphasis(opt, key, subOpts) {
  9840. // Caution: performance sensitive.
  9841. if (opt) {
  9842. opt[key] = opt[key] || {};
  9843. opt.emphasis = opt.emphasis || {};
  9844. opt.emphasis[key] = opt.emphasis[key] || {};
  9845. // Default emphasis option from normal
  9846. for (var i = 0, len = subOpts.length; i < len; i++) {
  9847. var subOptName = subOpts[i];
  9848. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9849. && opt[key].hasOwnProperty(subOptName)
  9850. ) {
  9851. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9852. }
  9853. }
  9854. }
  9855. }
  9856. var TEXT_STYLE_OPTIONS = [
  9857. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9858. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9859. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9860. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9861. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9862. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9863. ];
  9864. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9865. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9866. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9867. // // FIXME: deprecated, check and remove it.
  9868. // 'textStyle'
  9869. // ]);
  9870. /**
  9871. * The method do not ensure performance.
  9872. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9873. * This helper method retieves value from data.
  9874. * @param {string|number|Date|Array|Object} dataItem
  9875. * @return {number|string|Date|Array.<number|string|Date>}
  9876. */
  9877. function getDataItemValue(dataItem) {
  9878. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9879. ? dataItem.value : dataItem;
  9880. }
  9881. /**
  9882. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9883. * This helper method determine if dataItem has extra option besides value
  9884. * @param {string|number|Date|Array|Object} dataItem
  9885. */
  9886. function isDataItemOption(dataItem) {
  9887. return isObject$2(dataItem)
  9888. && !(dataItem instanceof Array);
  9889. // // markLine data can be array
  9890. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9891. }
  9892. /**
  9893. * Mapping to exists for merge.
  9894. *
  9895. * @public
  9896. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9897. * @param {Object|Array.<Object>} newCptOptions
  9898. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9899. * index of which is the same as exists.
  9900. */
  9901. function mappingToExists(exists, newCptOptions) {
  9902. // Mapping by the order by original option (but not order of
  9903. // new option) in merge mode. Because we should ensure
  9904. // some specified index (like xAxisIndex) is consistent with
  9905. // original option, which is easy to understand, espatially in
  9906. // media query. And in most case, merge option is used to
  9907. // update partial option but not be expected to change order.
  9908. newCptOptions = (newCptOptions || []).slice();
  9909. var result = map(exists || [], function (obj, index) {
  9910. return {exist: obj};
  9911. });
  9912. // Mapping by id or name if specified.
  9913. each$2(newCptOptions, function (cptOption, index) {
  9914. if (!isObject$2(cptOption)) {
  9915. return;
  9916. }
  9917. // id has highest priority.
  9918. for (var i = 0; i < result.length; i++) {
  9919. if (!result[i].option // Consider name: two map to one.
  9920. && cptOption.id != null
  9921. && result[i].exist.id === cptOption.id + ''
  9922. ) {
  9923. result[i].option = cptOption;
  9924. newCptOptions[index] = null;
  9925. return;
  9926. }
  9927. }
  9928. for (var i = 0; i < result.length; i++) {
  9929. var exist = result[i].exist;
  9930. if (!result[i].option // Consider name: two map to one.
  9931. // Can not match when both ids exist but different.
  9932. && (exist.id == null || cptOption.id == null)
  9933. && cptOption.name != null
  9934. && !isIdInner(cptOption)
  9935. && !isIdInner(exist)
  9936. && exist.name === cptOption.name + ''
  9937. ) {
  9938. result[i].option = cptOption;
  9939. newCptOptions[index] = null;
  9940. return;
  9941. }
  9942. }
  9943. });
  9944. // Otherwise mapping by index.
  9945. each$2(newCptOptions, function (cptOption, index) {
  9946. if (!isObject$2(cptOption)) {
  9947. return;
  9948. }
  9949. var i = 0;
  9950. for (; i < result.length; i++) {
  9951. var exist = result[i].exist;
  9952. if (!result[i].option
  9953. // Existing model that already has id should be able to
  9954. // mapped to (because after mapping performed model may
  9955. // be assigned with a id, whish should not affect next
  9956. // mapping), except those has inner id.
  9957. && !isIdInner(exist)
  9958. // Caution:
  9959. // Do not overwrite id. But name can be overwritten,
  9960. // because axis use name as 'show label text'.
  9961. // 'exist' always has id and name and we dont
  9962. // need to check it.
  9963. && cptOption.id == null
  9964. ) {
  9965. result[i].option = cptOption;
  9966. break;
  9967. }
  9968. }
  9969. if (i >= result.length) {
  9970. result.push({option: cptOption});
  9971. }
  9972. });
  9973. return result;
  9974. }
  9975. /**
  9976. * Make id and name for mapping result (result of mappingToExists)
  9977. * into `keyInfo` field.
  9978. *
  9979. * @public
  9980. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9981. * which order is the same as exists.
  9982. * @return {Array.<Object>} The input.
  9983. */
  9984. function makeIdAndName(mapResult) {
  9985. // We use this id to hash component models and view instances
  9986. // in echarts. id can be specified by user, or auto generated.
  9987. // The id generation rule ensures new view instance are able
  9988. // to mapped to old instance when setOption are called in
  9989. // no-merge mode. So we generate model id by name and plus
  9990. // type in view id.
  9991. // name can be duplicated among components, which is convenient
  9992. // to specify multi components (like series) by one name.
  9993. // Ensure that each id is distinct.
  9994. var idMap = createHashMap();
  9995. each$2(mapResult, function (item, index) {
  9996. var existCpt = item.exist;
  9997. existCpt && idMap.set(existCpt.id, item);
  9998. });
  9999. each$2(mapResult, function (item, index) {
  10000. var opt = item.option;
  10001. assert$1(
  10002. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10003. 'id duplicates: ' + (opt && opt.id)
  10004. );
  10005. opt && opt.id != null && idMap.set(opt.id, item);
  10006. !item.keyInfo && (item.keyInfo = {});
  10007. });
  10008. // Make name and id.
  10009. each$2(mapResult, function (item, index) {
  10010. var existCpt = item.exist;
  10011. var opt = item.option;
  10012. var keyInfo = item.keyInfo;
  10013. if (!isObject$2(opt)) {
  10014. return;
  10015. }
  10016. // name can be overwitten. Consider case: axis.name = '20km'.
  10017. // But id generated by name will not be changed, which affect
  10018. // only in that case: setOption with 'not merge mode' and view
  10019. // instance will be recreated, which can be accepted.
  10020. keyInfo.name = opt.name != null
  10021. ? opt.name + ''
  10022. : existCpt
  10023. ? existCpt.name
  10024. // Avoid diffferent series has the same name,
  10025. // because name may be used like in color pallet.
  10026. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10027. if (existCpt) {
  10028. keyInfo.id = existCpt.id;
  10029. }
  10030. else if (opt.id != null) {
  10031. keyInfo.id = opt.id + '';
  10032. }
  10033. else {
  10034. // Consider this situatoin:
  10035. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10036. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10037. // Series with the same name between optionA and optionB
  10038. // should be mapped.
  10039. var idNum = 0;
  10040. do {
  10041. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10042. }
  10043. while (idMap.get(keyInfo.id));
  10044. }
  10045. idMap.set(keyInfo.id, item);
  10046. });
  10047. }
  10048. function isNameSpecified(componentModel) {
  10049. var name = componentModel.name;
  10050. // Is specified when `indexOf` get -1 or > 0.
  10051. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10052. }
  10053. /**
  10054. * @public
  10055. * @param {Object} cptOption
  10056. * @return {boolean}
  10057. */
  10058. function isIdInner(cptOption) {
  10059. return isObject$2(cptOption)
  10060. && cptOption.id
  10061. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10062. }
  10063. /**
  10064. * A helper for removing duplicate items between batchA and batchB,
  10065. * and in themselves, and categorize by series.
  10066. *
  10067. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10068. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10069. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10070. */
  10071. function compressBatches(batchA, batchB) {
  10072. var mapA = {};
  10073. var mapB = {};
  10074. makeMap(batchA || [], mapA);
  10075. makeMap(batchB || [], mapB, mapA);
  10076. return [mapToArray(mapA), mapToArray(mapB)];
  10077. function makeMap(sourceBatch, map$$1, otherMap) {
  10078. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10079. var seriesId = sourceBatch[i].seriesId;
  10080. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10081. var otherDataIndices = otherMap && otherMap[seriesId];
  10082. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10083. var dataIndex = dataIndices[j];
  10084. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10085. otherDataIndices[dataIndex] = null;
  10086. }
  10087. else {
  10088. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10089. }
  10090. }
  10091. }
  10092. }
  10093. function mapToArray(map$$1, isData) {
  10094. var result = [];
  10095. for (var i in map$$1) {
  10096. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10097. if (isData) {
  10098. result.push(+i);
  10099. }
  10100. else {
  10101. var dataIndices = mapToArray(map$$1[i], true);
  10102. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  10103. }
  10104. }
  10105. }
  10106. return result;
  10107. }
  10108. }
  10109. /**
  10110. * @param {module:echarts/data/List} data
  10111. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10112. * each of which can be Array or primary type.
  10113. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10114. */
  10115. function queryDataIndex(data, payload) {
  10116. if (payload.dataIndexInside != null) {
  10117. return payload.dataIndexInside;
  10118. }
  10119. else if (payload.dataIndex != null) {
  10120. return isArray(payload.dataIndex)
  10121. ? map(payload.dataIndex, function (value) {
  10122. return data.indexOfRawIndex(value);
  10123. })
  10124. : data.indexOfRawIndex(payload.dataIndex);
  10125. }
  10126. else if (payload.name != null) {
  10127. return isArray(payload.name)
  10128. ? map(payload.name, function (value) {
  10129. return data.indexOfName(value);
  10130. })
  10131. : data.indexOfName(payload.name);
  10132. }
  10133. }
  10134. /**
  10135. * Enable property storage to any host object.
  10136. * Notice: Serialization is not supported.
  10137. *
  10138. * For example:
  10139. * var inner = zrUitl.makeInner();
  10140. *
  10141. * function some1(hostObj) {
  10142. * inner(hostObj).someProperty = 1212;
  10143. * ...
  10144. * }
  10145. * function some2() {
  10146. * var fields = inner(this);
  10147. * fields.someProperty1 = 1212;
  10148. * fields.someProperty2 = 'xx';
  10149. * ...
  10150. * }
  10151. *
  10152. * @return {Function}
  10153. */
  10154. function makeInner() {
  10155. // Consider different scope by es module import.
  10156. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10157. return function (hostObj) {
  10158. return hostObj[key] || (hostObj[key] = {});
  10159. };
  10160. }
  10161. var innerUniqueIndex = 0;
  10162. /**
  10163. * @param {module:echarts/model/Global} ecModel
  10164. * @param {string|Object} finder
  10165. * If string, e.g., 'geo', means {geoIndex: 0}.
  10166. * If Object, could contain some of these properties below:
  10167. * {
  10168. * seriesIndex, seriesId, seriesName,
  10169. * geoIndex, geoId, geoName,
  10170. * bmapIndex, bmapId, bmapName,
  10171. * xAxisIndex, xAxisId, xAxisName,
  10172. * yAxisIndex, yAxisId, yAxisName,
  10173. * gridIndex, gridId, gridName,
  10174. * ... (can be extended)
  10175. * }
  10176. * Each properties can be number|string|Array.<number>|Array.<string>
  10177. * For example, a finder could be
  10178. * {
  10179. * seriesIndex: 3,
  10180. * geoId: ['aa', 'cc'],
  10181. * gridName: ['xx', 'rr']
  10182. * }
  10183. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10184. * If nothing or null/undefined specified, return nothing.
  10185. * @param {Object} [opt]
  10186. * @param {string} [opt.defaultMainType]
  10187. * @param {Array.<string>} [opt.includeMainTypes]
  10188. * @return {Object} result like:
  10189. * {
  10190. * seriesModels: [seriesModel1, seriesModel2],
  10191. * seriesModel: seriesModel1, // The first model
  10192. * geoModels: [geoModel1, geoModel2],
  10193. * geoModel: geoModel1, // The first model
  10194. * ...
  10195. * }
  10196. */
  10197. function parseFinder(ecModel, finder, opt) {
  10198. if (isString(finder)) {
  10199. var obj = {};
  10200. obj[finder + 'Index'] = 0;
  10201. finder = obj;
  10202. }
  10203. var defaultMainType = opt && opt.defaultMainType;
  10204. if (defaultMainType
  10205. && !has(finder, defaultMainType + 'Index')
  10206. && !has(finder, defaultMainType + 'Id')
  10207. && !has(finder, defaultMainType + 'Name')
  10208. ) {
  10209. finder[defaultMainType + 'Index'] = 0;
  10210. }
  10211. var result = {};
  10212. each$2(finder, function (value, key) {
  10213. var value = finder[key];
  10214. // Exclude 'dataIndex' and other illgal keys.
  10215. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10216. result[key] = value;
  10217. return;
  10218. }
  10219. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10220. var mainType = parsedKey[1];
  10221. var queryType = (parsedKey[2] || '').toLowerCase();
  10222. if (!mainType
  10223. || !queryType
  10224. || value == null
  10225. || (queryType === 'index' && value === 'none')
  10226. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10227. ) {
  10228. return;
  10229. }
  10230. var queryParam = {mainType: mainType};
  10231. if (queryType !== 'index' || value !== 'all') {
  10232. queryParam[queryType] = value;
  10233. }
  10234. var models = ecModel.queryComponents(queryParam);
  10235. result[mainType + 'Models'] = models;
  10236. result[mainType + 'Model'] = models[0];
  10237. });
  10238. return result;
  10239. }
  10240. function has(obj, prop) {
  10241. return obj && obj.hasOwnProperty(prop);
  10242. }
  10243. function setAttribute(dom, key, value) {
  10244. dom.setAttribute
  10245. ? dom.setAttribute(key, value)
  10246. : (dom[key] = value);
  10247. }
  10248. function getAttribute(dom, key) {
  10249. return dom.getAttribute
  10250. ? dom.getAttribute(key)
  10251. : dom[key];
  10252. }
  10253. function getTooltipRenderMode(renderModeOption) {
  10254. if (renderModeOption === 'auto') {
  10255. // Using html when `document` exists, use richText otherwise
  10256. return env$1.domSupported ? 'html' : 'richText';
  10257. }
  10258. else {
  10259. return renderModeOption || 'html';
  10260. }
  10261. }
  10262. /*
  10263. * Licensed to the Apache Software Foundation (ASF) under one
  10264. * or more contributor license agreements. See the NOTICE file
  10265. * distributed with this work for additional information
  10266. * regarding copyright ownership. The ASF licenses this file
  10267. * to you under the Apache License, Version 2.0 (the
  10268. * "License"); you may not use this file except in compliance
  10269. * with the License. You may obtain a copy of the License at
  10270. *
  10271. * http://www.apache.org/licenses/LICENSE-2.0
  10272. *
  10273. * Unless required by applicable law or agreed to in writing,
  10274. * software distributed under the License is distributed on an
  10275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10276. * KIND, either express or implied. See the License for the
  10277. * specific language governing permissions and limitations
  10278. * under the License.
  10279. */
  10280. var TYPE_DELIMITER = '.';
  10281. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10282. /**
  10283. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10284. * @public
  10285. */
  10286. function parseClassType$1(componentType) {
  10287. var ret = {main: '', sub: ''};
  10288. if (componentType) {
  10289. componentType = componentType.split(TYPE_DELIMITER);
  10290. ret.main = componentType[0] || '';
  10291. ret.sub = componentType[1] || '';
  10292. }
  10293. return ret;
  10294. }
  10295. /**
  10296. * @public
  10297. */
  10298. function checkClassType(componentType) {
  10299. assert$1(
  10300. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10301. 'componentType "' + componentType + '" illegal'
  10302. );
  10303. }
  10304. /**
  10305. * @public
  10306. */
  10307. function enableClassExtend(RootClass, mandatoryMethods) {
  10308. RootClass.$constructor = RootClass;
  10309. RootClass.extend = function (proto) {
  10310. if (__DEV__) {
  10311. each$1(mandatoryMethods, function (method) {
  10312. if (!proto[method]) {
  10313. console.warn(
  10314. 'Method `' + method + '` should be implemented'
  10315. + (proto.type ? ' in ' + proto.type : '') + '.'
  10316. );
  10317. }
  10318. });
  10319. }
  10320. var superClass = this;
  10321. var ExtendedClass = function () {
  10322. if (!proto.$constructor) {
  10323. superClass.apply(this, arguments);
  10324. }
  10325. else {
  10326. proto.$constructor.apply(this, arguments);
  10327. }
  10328. };
  10329. extend(ExtendedClass.prototype, proto);
  10330. ExtendedClass.extend = this.extend;
  10331. ExtendedClass.superCall = superCall;
  10332. ExtendedClass.superApply = superApply;
  10333. inherits(ExtendedClass, this);
  10334. ExtendedClass.superClass = superClass;
  10335. return ExtendedClass;
  10336. };
  10337. }
  10338. var classBase = 0;
  10339. /**
  10340. * Can not use instanceof, consider different scope by
  10341. * cross domain or es module import in ec extensions.
  10342. * Mount a method "isInstance()" to Clz.
  10343. */
  10344. function enableClassCheck(Clz) {
  10345. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10346. Clz.prototype[classAttr] = true;
  10347. if (__DEV__) {
  10348. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10349. }
  10350. Clz.isInstance = function (obj) {
  10351. return !!(obj && obj[classAttr]);
  10352. };
  10353. }
  10354. // superCall should have class info, which can not be fetch from 'this'.
  10355. // Consider this case:
  10356. // class A has method f,
  10357. // class B inherits class A, overrides method f, f call superApply('f'),
  10358. // class C inherits class B, do not overrides method f,
  10359. // then when method of class C is called, dead loop occured.
  10360. function superCall(context, methodName) {
  10361. var args = slice(arguments, 2);
  10362. return this.superClass.prototype[methodName].apply(context, args);
  10363. }
  10364. function superApply(context, methodName, args) {
  10365. return this.superClass.prototype[methodName].apply(context, args);
  10366. }
  10367. /**
  10368. * @param {Object} entity
  10369. * @param {Object} options
  10370. * @param {boolean} [options.registerWhenExtend]
  10371. * @public
  10372. */
  10373. function enableClassManagement(entity, options) {
  10374. options = options || {};
  10375. /**
  10376. * Component model classes
  10377. * key: componentType,
  10378. * value:
  10379. * componentClass, when componentType is 'xxx'
  10380. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10381. * @type {Object}
  10382. */
  10383. var storage = {};
  10384. entity.registerClass = function (Clazz, componentType) {
  10385. if (componentType) {
  10386. checkClassType(componentType);
  10387. componentType = parseClassType$1(componentType);
  10388. if (!componentType.sub) {
  10389. if (__DEV__) {
  10390. if (storage[componentType.main]) {
  10391. console.warn(componentType.main + ' exists.');
  10392. }
  10393. }
  10394. storage[componentType.main] = Clazz;
  10395. }
  10396. else if (componentType.sub !== IS_CONTAINER) {
  10397. var container = makeContainer(componentType);
  10398. container[componentType.sub] = Clazz;
  10399. }
  10400. }
  10401. return Clazz;
  10402. };
  10403. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10404. var Clazz = storage[componentMainType];
  10405. if (Clazz && Clazz[IS_CONTAINER]) {
  10406. Clazz = subType ? Clazz[subType] : null;
  10407. }
  10408. if (throwWhenNotFound && !Clazz) {
  10409. throw new Error(
  10410. !subType
  10411. ? componentMainType + '.' + 'type should be specified.'
  10412. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10413. );
  10414. }
  10415. return Clazz;
  10416. };
  10417. entity.getClassesByMainType = function (componentType) {
  10418. componentType = parseClassType$1(componentType);
  10419. var result = [];
  10420. var obj = storage[componentType.main];
  10421. if (obj && obj[IS_CONTAINER]) {
  10422. each$1(obj, function (o, type) {
  10423. type !== IS_CONTAINER && result.push(o);
  10424. });
  10425. }
  10426. else {
  10427. result.push(obj);
  10428. }
  10429. return result;
  10430. };
  10431. entity.hasClass = function (componentType) {
  10432. // Just consider componentType.main.
  10433. componentType = parseClassType$1(componentType);
  10434. return !!storage[componentType.main];
  10435. };
  10436. /**
  10437. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10438. */
  10439. entity.getAllClassMainTypes = function () {
  10440. var types = [];
  10441. each$1(storage, function (obj, type) {
  10442. types.push(type);
  10443. });
  10444. return types;
  10445. };
  10446. /**
  10447. * If a main type is container and has sub types
  10448. * @param {string} mainType
  10449. * @return {boolean}
  10450. */
  10451. entity.hasSubTypes = function (componentType) {
  10452. componentType = parseClassType$1(componentType);
  10453. var obj = storage[componentType.main];
  10454. return obj && obj[IS_CONTAINER];
  10455. };
  10456. entity.parseClassType = parseClassType$1;
  10457. function makeContainer(componentType) {
  10458. var container = storage[componentType.main];
  10459. if (!container || !container[IS_CONTAINER]) {
  10460. container = storage[componentType.main] = {};
  10461. container[IS_CONTAINER] = true;
  10462. }
  10463. return container;
  10464. }
  10465. if (options.registerWhenExtend) {
  10466. var originalExtend = entity.extend;
  10467. if (originalExtend) {
  10468. entity.extend = function (proto) {
  10469. var ExtendedClass = originalExtend.call(this, proto);
  10470. return entity.registerClass(ExtendedClass, proto.type);
  10471. };
  10472. }
  10473. }
  10474. return entity;
  10475. }
  10476. /**
  10477. * @param {string|Array.<string>} properties
  10478. */
  10479. /*
  10480. * Licensed to the Apache Software Foundation (ASF) under one
  10481. * or more contributor license agreements. See the NOTICE file
  10482. * distributed with this work for additional information
  10483. * regarding copyright ownership. The ASF licenses this file
  10484. * to you under the Apache License, Version 2.0 (the
  10485. * "License"); you may not use this file except in compliance
  10486. * with the License. You may obtain a copy of the License at
  10487. *
  10488. * http://www.apache.org/licenses/LICENSE-2.0
  10489. *
  10490. * Unless required by applicable law or agreed to in writing,
  10491. * software distributed under the License is distributed on an
  10492. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10493. * KIND, either express or implied. See the License for the
  10494. * specific language governing permissions and limitations
  10495. * under the License.
  10496. */
  10497. // TODO Parse shadow style
  10498. // TODO Only shallow path support
  10499. var makeStyleMapper = function (properties) {
  10500. // Normalize
  10501. for (var i = 0; i < properties.length; i++) {
  10502. if (!properties[i][1]) {
  10503. properties[i][1] = properties[i][0];
  10504. }
  10505. }
  10506. return function (model, excludes, includes) {
  10507. var style = {};
  10508. for (var i = 0; i < properties.length; i++) {
  10509. var propName = properties[i][1];
  10510. if ((excludes && indexOf(excludes, propName) >= 0)
  10511. || (includes && indexOf(includes, propName) < 0)
  10512. ) {
  10513. continue;
  10514. }
  10515. var val = model.getShallow(propName);
  10516. if (val != null) {
  10517. style[properties[i][0]] = val;
  10518. }
  10519. }
  10520. return style;
  10521. };
  10522. };
  10523. /*
  10524. * Licensed to the Apache Software Foundation (ASF) under one
  10525. * or more contributor license agreements. See the NOTICE file
  10526. * distributed with this work for additional information
  10527. * regarding copyright ownership. The ASF licenses this file
  10528. * to you under the Apache License, Version 2.0 (the
  10529. * "License"); you may not use this file except in compliance
  10530. * with the License. You may obtain a copy of the License at
  10531. *
  10532. * http://www.apache.org/licenses/LICENSE-2.0
  10533. *
  10534. * Unless required by applicable law or agreed to in writing,
  10535. * software distributed under the License is distributed on an
  10536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10537. * KIND, either express or implied. See the License for the
  10538. * specific language governing permissions and limitations
  10539. * under the License.
  10540. */
  10541. var getLineStyle = makeStyleMapper(
  10542. [
  10543. ['lineWidth', 'width'],
  10544. ['stroke', 'color'],
  10545. ['opacity'],
  10546. ['shadowBlur'],
  10547. ['shadowOffsetX'],
  10548. ['shadowOffsetY'],
  10549. ['shadowColor']
  10550. ]
  10551. );
  10552. var lineStyleMixin = {
  10553. getLineStyle: function (excludes) {
  10554. var style = getLineStyle(this, excludes);
  10555. var lineDash = this.getLineDash(style.lineWidth);
  10556. lineDash && (style.lineDash = lineDash);
  10557. return style;
  10558. },
  10559. getLineDash: function (lineWidth) {
  10560. if (lineWidth == null) {
  10561. lineWidth = 1;
  10562. }
  10563. var lineType = this.get('type');
  10564. var dotSize = Math.max(lineWidth, 2);
  10565. var dashSize = lineWidth * 4;
  10566. return (lineType === 'solid' || lineType == null) ? null
  10567. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10568. }
  10569. };
  10570. /*
  10571. * Licensed to the Apache Software Foundation (ASF) under one
  10572. * or more contributor license agreements. See the NOTICE file
  10573. * distributed with this work for additional information
  10574. * regarding copyright ownership. The ASF licenses this file
  10575. * to you under the Apache License, Version 2.0 (the
  10576. * "License"); you may not use this file except in compliance
  10577. * with the License. You may obtain a copy of the License at
  10578. *
  10579. * http://www.apache.org/licenses/LICENSE-2.0
  10580. *
  10581. * Unless required by applicable law or agreed to in writing,
  10582. * software distributed under the License is distributed on an
  10583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10584. * KIND, either express or implied. See the License for the
  10585. * specific language governing permissions and limitations
  10586. * under the License.
  10587. */
  10588. var getAreaStyle = makeStyleMapper(
  10589. [
  10590. ['fill', 'color'],
  10591. ['shadowBlur'],
  10592. ['shadowOffsetX'],
  10593. ['shadowOffsetY'],
  10594. ['opacity'],
  10595. ['shadowColor']
  10596. ]
  10597. );
  10598. var areaStyleMixin = {
  10599. getAreaStyle: function (excludes, includes) {
  10600. return getAreaStyle(this, excludes, includes);
  10601. }
  10602. };
  10603. /**
  10604. * 曲线辅助模块
  10605. * @module zrender/core/curve
  10606. * @author pissang(https://www.github.com/pissang)
  10607. */
  10608. var mathPow = Math.pow;
  10609. var mathSqrt$2 = Math.sqrt;
  10610. var EPSILON$1 = 1e-8;
  10611. var EPSILON_NUMERIC = 1e-4;
  10612. var THREE_SQRT = mathSqrt$2(3);
  10613. var ONE_THIRD = 1 / 3;
  10614. // 临时变量
  10615. var _v0 = create();
  10616. var _v1 = create();
  10617. var _v2 = create();
  10618. function isAroundZero(val) {
  10619. return val > -EPSILON$1 && val < EPSILON$1;
  10620. }
  10621. function isNotAroundZero$1(val) {
  10622. return val > EPSILON$1 || val < -EPSILON$1;
  10623. }
  10624. /**
  10625. * 计算三次贝塞尔值
  10626. * @memberOf module:zrender/core/curve
  10627. * @param {number} p0
  10628. * @param {number} p1
  10629. * @param {number} p2
  10630. * @param {number} p3
  10631. * @param {number} t
  10632. * @return {number}
  10633. */
  10634. function cubicAt(p0, p1, p2, p3, t) {
  10635. var onet = 1 - t;
  10636. return onet * onet * (onet * p0 + 3 * t * p1)
  10637. + t * t * (t * p3 + 3 * onet * p2);
  10638. }
  10639. /**
  10640. * 计算三次贝塞尔导数值
  10641. * @memberOf module:zrender/core/curve
  10642. * @param {number} p0
  10643. * @param {number} p1
  10644. * @param {number} p2
  10645. * @param {number} p3
  10646. * @param {number} t
  10647. * @return {number}
  10648. */
  10649. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10650. var onet = 1 - t;
  10651. return 3 * (
  10652. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10653. + (p3 - p2) * t * t
  10654. );
  10655. }
  10656. /**
  10657. * 计算三次贝塞尔方程根,使用盛金公式
  10658. * @memberOf module:zrender/core/curve
  10659. * @param {number} p0
  10660. * @param {number} p1
  10661. * @param {number} p2
  10662. * @param {number} p3
  10663. * @param {number} val
  10664. * @param {Array.<number>} roots
  10665. * @return {number} 有效根数目
  10666. */
  10667. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10668. // Evaluate roots of cubic functions
  10669. var a = p3 + 3 * (p1 - p2) - p0;
  10670. var b = 3 * (p2 - p1 * 2 + p0);
  10671. var c = 3 * (p1 - p0);
  10672. var d = p0 - val;
  10673. var A = b * b - 3 * a * c;
  10674. var B = b * c - 9 * a * d;
  10675. var C = c * c - 3 * b * d;
  10676. var n = 0;
  10677. if (isAroundZero(A) && isAroundZero(B)) {
  10678. if (isAroundZero(b)) {
  10679. roots[0] = 0;
  10680. }
  10681. else {
  10682. var t1 = -c / b; //t1, t2, t3, b is not zero
  10683. if (t1 >= 0 && t1 <= 1) {
  10684. roots[n++] = t1;
  10685. }
  10686. }
  10687. }
  10688. else {
  10689. var disc = B * B - 4 * A * C;
  10690. if (isAroundZero(disc)) {
  10691. var K = B / A;
  10692. var t1 = -b / a + K; // t1, a is not zero
  10693. var t2 = -K / 2; // t2, t3
  10694. if (t1 >= 0 && t1 <= 1) {
  10695. roots[n++] = t1;
  10696. }
  10697. if (t2 >= 0 && t2 <= 1) {
  10698. roots[n++] = t2;
  10699. }
  10700. }
  10701. else if (disc > 0) {
  10702. var discSqrt = mathSqrt$2(disc);
  10703. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10704. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10705. if (Y1 < 0) {
  10706. Y1 = -mathPow(-Y1, ONE_THIRD);
  10707. }
  10708. else {
  10709. Y1 = mathPow(Y1, ONE_THIRD);
  10710. }
  10711. if (Y2 < 0) {
  10712. Y2 = -mathPow(-Y2, ONE_THIRD);
  10713. }
  10714. else {
  10715. Y2 = mathPow(Y2, ONE_THIRD);
  10716. }
  10717. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10718. if (t1 >= 0 && t1 <= 1) {
  10719. roots[n++] = t1;
  10720. }
  10721. }
  10722. else {
  10723. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10724. var theta = Math.acos(T) / 3;
  10725. var ASqrt = mathSqrt$2(A);
  10726. var tmp = Math.cos(theta);
  10727. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10728. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10729. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10730. if (t1 >= 0 && t1 <= 1) {
  10731. roots[n++] = t1;
  10732. }
  10733. if (t2 >= 0 && t2 <= 1) {
  10734. roots[n++] = t2;
  10735. }
  10736. if (t3 >= 0 && t3 <= 1) {
  10737. roots[n++] = t3;
  10738. }
  10739. }
  10740. }
  10741. return n;
  10742. }
  10743. /**
  10744. * 计算三次贝塞尔方程极限值的位置
  10745. * @memberOf module:zrender/core/curve
  10746. * @param {number} p0
  10747. * @param {number} p1
  10748. * @param {number} p2
  10749. * @param {number} p3
  10750. * @param {Array.<number>} extrema
  10751. * @return {number} 有效数目
  10752. */
  10753. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10754. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10755. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10756. var c = 3 * p1 - 3 * p0;
  10757. var n = 0;
  10758. if (isAroundZero(a)) {
  10759. if (isNotAroundZero$1(b)) {
  10760. var t1 = -c / b;
  10761. if (t1 >= 0 && t1 <= 1) {
  10762. extrema[n++] = t1;
  10763. }
  10764. }
  10765. }
  10766. else {
  10767. var disc = b * b - 4 * a * c;
  10768. if (isAroundZero(disc)) {
  10769. extrema[0] = -b / (2 * a);
  10770. }
  10771. else if (disc > 0) {
  10772. var discSqrt = mathSqrt$2(disc);
  10773. var t1 = (-b + discSqrt) / (2 * a);
  10774. var t2 = (-b - discSqrt) / (2 * a);
  10775. if (t1 >= 0 && t1 <= 1) {
  10776. extrema[n++] = t1;
  10777. }
  10778. if (t2 >= 0 && t2 <= 1) {
  10779. extrema[n++] = t2;
  10780. }
  10781. }
  10782. }
  10783. return n;
  10784. }
  10785. /**
  10786. * 细分三次贝塞尔曲线
  10787. * @memberOf module:zrender/core/curve
  10788. * @param {number} p0
  10789. * @param {number} p1
  10790. * @param {number} p2
  10791. * @param {number} p3
  10792. * @param {number} t
  10793. * @param {Array.<number>} out
  10794. */
  10795. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10796. var p01 = (p1 - p0) * t + p0;
  10797. var p12 = (p2 - p1) * t + p1;
  10798. var p23 = (p3 - p2) * t + p2;
  10799. var p012 = (p12 - p01) * t + p01;
  10800. var p123 = (p23 - p12) * t + p12;
  10801. var p0123 = (p123 - p012) * t + p012;
  10802. // Seg0
  10803. out[0] = p0;
  10804. out[1] = p01;
  10805. out[2] = p012;
  10806. out[3] = p0123;
  10807. // Seg1
  10808. out[4] = p0123;
  10809. out[5] = p123;
  10810. out[6] = p23;
  10811. out[7] = p3;
  10812. }
  10813. /**
  10814. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10815. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10816. * @param {number} x0
  10817. * @param {number} y0
  10818. * @param {number} x1
  10819. * @param {number} y1
  10820. * @param {number} x2
  10821. * @param {number} y2
  10822. * @param {number} x3
  10823. * @param {number} y3
  10824. * @param {number} x
  10825. * @param {number} y
  10826. * @param {Array.<number>} [out] 投射点
  10827. * @return {number}
  10828. */
  10829. function cubicProjectPoint(
  10830. x0, y0, x1, y1, x2, y2, x3, y3,
  10831. x, y, out
  10832. ) {
  10833. // http://pomax.github.io/bezierinfo/#projections
  10834. var t;
  10835. var interval = 0.005;
  10836. var d = Infinity;
  10837. var prev;
  10838. var next;
  10839. var d1;
  10840. var d2;
  10841. _v0[0] = x;
  10842. _v0[1] = y;
  10843. // 先粗略估计一下可能的最小距离的 t 值
  10844. // PENDING
  10845. for (var _t = 0; _t < 1; _t += 0.05) {
  10846. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10847. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10848. d1 = distSquare(_v0, _v1);
  10849. if (d1 < d) {
  10850. t = _t;
  10851. d = d1;
  10852. }
  10853. }
  10854. d = Infinity;
  10855. // At most 32 iteration
  10856. for (var i = 0; i < 32; i++) {
  10857. if (interval < EPSILON_NUMERIC) {
  10858. break;
  10859. }
  10860. prev = t - interval;
  10861. next = t + interval;
  10862. // t - interval
  10863. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10864. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10865. d1 = distSquare(_v1, _v0);
  10866. if (prev >= 0 && d1 < d) {
  10867. t = prev;
  10868. d = d1;
  10869. }
  10870. else {
  10871. // t + interval
  10872. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10873. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10874. d2 = distSquare(_v2, _v0);
  10875. if (next <= 1 && d2 < d) {
  10876. t = next;
  10877. d = d2;
  10878. }
  10879. else {
  10880. interval *= 0.5;
  10881. }
  10882. }
  10883. }
  10884. // t
  10885. if (out) {
  10886. out[0] = cubicAt(x0, x1, x2, x3, t);
  10887. out[1] = cubicAt(y0, y1, y2, y3, t);
  10888. }
  10889. // console.log(interval, i);
  10890. return mathSqrt$2(d);
  10891. }
  10892. /**
  10893. * 计算二次方贝塞尔值
  10894. * @param {number} p0
  10895. * @param {number} p1
  10896. * @param {number} p2
  10897. * @param {number} t
  10898. * @return {number}
  10899. */
  10900. function quadraticAt(p0, p1, p2, t) {
  10901. var onet = 1 - t;
  10902. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10903. }
  10904. /**
  10905. * 计算二次方贝塞尔导数值
  10906. * @param {number} p0
  10907. * @param {number} p1
  10908. * @param {number} p2
  10909. * @param {number} t
  10910. * @return {number}
  10911. */
  10912. function quadraticDerivativeAt(p0, p1, p2, t) {
  10913. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10914. }
  10915. /**
  10916. * 计算二次方贝塞尔方程根
  10917. * @param {number} p0
  10918. * @param {number} p1
  10919. * @param {number} p2
  10920. * @param {number} t
  10921. * @param {Array.<number>} roots
  10922. * @return {number} 有效根数目
  10923. */
  10924. function quadraticRootAt(p0, p1, p2, val, roots) {
  10925. var a = p0 - 2 * p1 + p2;
  10926. var b = 2 * (p1 - p0);
  10927. var c = p0 - val;
  10928. var n = 0;
  10929. if (isAroundZero(a)) {
  10930. if (isNotAroundZero$1(b)) {
  10931. var t1 = -c / b;
  10932. if (t1 >= 0 && t1 <= 1) {
  10933. roots[n++] = t1;
  10934. }
  10935. }
  10936. }
  10937. else {
  10938. var disc = b * b - 4 * a * c;
  10939. if (isAroundZero(disc)) {
  10940. var t1 = -b / (2 * a);
  10941. if (t1 >= 0 && t1 <= 1) {
  10942. roots[n++] = t1;
  10943. }
  10944. }
  10945. else if (disc > 0) {
  10946. var discSqrt = mathSqrt$2(disc);
  10947. var t1 = (-b + discSqrt) / (2 * a);
  10948. var t2 = (-b - discSqrt) / (2 * a);
  10949. if (t1 >= 0 && t1 <= 1) {
  10950. roots[n++] = t1;
  10951. }
  10952. if (t2 >= 0 && t2 <= 1) {
  10953. roots[n++] = t2;
  10954. }
  10955. }
  10956. }
  10957. return n;
  10958. }
  10959. /**
  10960. * 计算二次贝塞尔方程极限值
  10961. * @memberOf module:zrender/core/curve
  10962. * @param {number} p0
  10963. * @param {number} p1
  10964. * @param {number} p2
  10965. * @return {number}
  10966. */
  10967. function quadraticExtremum(p0, p1, p2) {
  10968. var divider = p0 + p2 - 2 * p1;
  10969. if (divider === 0) {
  10970. // p1 is center of p0 and p2
  10971. return 0.5;
  10972. }
  10973. else {
  10974. return (p0 - p1) / divider;
  10975. }
  10976. }
  10977. /**
  10978. * 细分二次贝塞尔曲线
  10979. * @memberOf module:zrender/core/curve
  10980. * @param {number} p0
  10981. * @param {number} p1
  10982. * @param {number} p2
  10983. * @param {number} t
  10984. * @param {Array.<number>} out
  10985. */
  10986. function quadraticSubdivide(p0, p1, p2, t, out) {
  10987. var p01 = (p1 - p0) * t + p0;
  10988. var p12 = (p2 - p1) * t + p1;
  10989. var p012 = (p12 - p01) * t + p01;
  10990. // Seg0
  10991. out[0] = p0;
  10992. out[1] = p01;
  10993. out[2] = p012;
  10994. // Seg1
  10995. out[3] = p012;
  10996. out[4] = p12;
  10997. out[5] = p2;
  10998. }
  10999. /**
  11000. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11001. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11002. * @param {number} x0
  11003. * @param {number} y0
  11004. * @param {number} x1
  11005. * @param {number} y1
  11006. * @param {number} x2
  11007. * @param {number} y2
  11008. * @param {number} x
  11009. * @param {number} y
  11010. * @param {Array.<number>} out 投射点
  11011. * @return {number}
  11012. */
  11013. function quadraticProjectPoint(
  11014. x0, y0, x1, y1, x2, y2,
  11015. x, y, out
  11016. ) {
  11017. // http://pomax.github.io/bezierinfo/#projections
  11018. var t;
  11019. var interval = 0.005;
  11020. var d = Infinity;
  11021. _v0[0] = x;
  11022. _v0[1] = y;
  11023. // 先粗略估计一下可能的最小距离的 t 值
  11024. // PENDING
  11025. for (var _t = 0; _t < 1; _t += 0.05) {
  11026. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11027. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11028. var d1 = distSquare(_v0, _v1);
  11029. if (d1 < d) {
  11030. t = _t;
  11031. d = d1;
  11032. }
  11033. }
  11034. d = Infinity;
  11035. // At most 32 iteration
  11036. for (var i = 0; i < 32; i++) {
  11037. if (interval < EPSILON_NUMERIC) {
  11038. break;
  11039. }
  11040. var prev = t - interval;
  11041. var next = t + interval;
  11042. // t - interval
  11043. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11044. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11045. var d1 = distSquare(_v1, _v0);
  11046. if (prev >= 0 && d1 < d) {
  11047. t = prev;
  11048. d = d1;
  11049. }
  11050. else {
  11051. // t + interval
  11052. _v2[0] = quadraticAt(x0, x1, x2, next);
  11053. _v2[1] = quadraticAt(y0, y1, y2, next);
  11054. var d2 = distSquare(_v2, _v0);
  11055. if (next <= 1 && d2 < d) {
  11056. t = next;
  11057. d = d2;
  11058. }
  11059. else {
  11060. interval *= 0.5;
  11061. }
  11062. }
  11063. }
  11064. // t
  11065. if (out) {
  11066. out[0] = quadraticAt(x0, x1, x2, t);
  11067. out[1] = quadraticAt(y0, y1, y2, t);
  11068. }
  11069. // console.log(interval, i);
  11070. return mathSqrt$2(d);
  11071. }
  11072. /**
  11073. * @author Yi Shen(https://github.com/pissang)
  11074. */
  11075. var mathMin$3 = Math.min;
  11076. var mathMax$3 = Math.max;
  11077. var mathSin$2 = Math.sin;
  11078. var mathCos$2 = Math.cos;
  11079. var PI2 = Math.PI * 2;
  11080. var start = create();
  11081. var end = create();
  11082. var extremity = create();
  11083. /**
  11084. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11085. * @module zrender/core/bbox
  11086. * @param {Array<Object>} points 顶点数组
  11087. * @param {number} min
  11088. * @param {number} max
  11089. */
  11090. function fromPoints(points, min$$1, max$$1) {
  11091. if (points.length === 0) {
  11092. return;
  11093. }
  11094. var p = points[0];
  11095. var left = p[0];
  11096. var right = p[0];
  11097. var top = p[1];
  11098. var bottom = p[1];
  11099. var i;
  11100. for (i = 1; i < points.length; i++) {
  11101. p = points[i];
  11102. left = mathMin$3(left, p[0]);
  11103. right = mathMax$3(right, p[0]);
  11104. top = mathMin$3(top, p[1]);
  11105. bottom = mathMax$3(bottom, p[1]);
  11106. }
  11107. min$$1[0] = left;
  11108. min$$1[1] = top;
  11109. max$$1[0] = right;
  11110. max$$1[1] = bottom;
  11111. }
  11112. /**
  11113. * @memberOf module:zrender/core/bbox
  11114. * @param {number} x0
  11115. * @param {number} y0
  11116. * @param {number} x1
  11117. * @param {number} y1
  11118. * @param {Array.<number>} min
  11119. * @param {Array.<number>} max
  11120. */
  11121. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11122. min$$1[0] = mathMin$3(x0, x1);
  11123. min$$1[1] = mathMin$3(y0, y1);
  11124. max$$1[0] = mathMax$3(x0, x1);
  11125. max$$1[1] = mathMax$3(y0, y1);
  11126. }
  11127. var xDim = [];
  11128. var yDim = [];
  11129. /**
  11130. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11131. * @memberOf module:zrender/core/bbox
  11132. * @param {number} x0
  11133. * @param {number} y0
  11134. * @param {number} x1
  11135. * @param {number} y1
  11136. * @param {number} x2
  11137. * @param {number} y2
  11138. * @param {number} x3
  11139. * @param {number} y3
  11140. * @param {Array.<number>} min
  11141. * @param {Array.<number>} max
  11142. */
  11143. function fromCubic(
  11144. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11145. ) {
  11146. var cubicExtrema$$1 = cubicExtrema;
  11147. var cubicAt$$1 = cubicAt;
  11148. var i;
  11149. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11150. min$$1[0] = Infinity;
  11151. min$$1[1] = Infinity;
  11152. max$$1[0] = -Infinity;
  11153. max$$1[1] = -Infinity;
  11154. for (i = 0; i < n; i++) {
  11155. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11156. min$$1[0] = mathMin$3(x, min$$1[0]);
  11157. max$$1[0] = mathMax$3(x, max$$1[0]);
  11158. }
  11159. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11160. for (i = 0; i < n; i++) {
  11161. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11162. min$$1[1] = mathMin$3(y, min$$1[1]);
  11163. max$$1[1] = mathMax$3(y, max$$1[1]);
  11164. }
  11165. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11166. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11167. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11168. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11169. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11170. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11171. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11172. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11173. }
  11174. /**
  11175. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11176. * @memberOf module:zrender/core/bbox
  11177. * @param {number} x0
  11178. * @param {number} y0
  11179. * @param {number} x1
  11180. * @param {number} y1
  11181. * @param {number} x2
  11182. * @param {number} y2
  11183. * @param {Array.<number>} min
  11184. * @param {Array.<number>} max
  11185. */
  11186. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11187. var quadraticExtremum$$1 = quadraticExtremum;
  11188. var quadraticAt$$1 = quadraticAt;
  11189. // Find extremities, where derivative in x dim or y dim is zero
  11190. var tx =
  11191. mathMax$3(
  11192. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11193. );
  11194. var ty =
  11195. mathMax$3(
  11196. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11197. );
  11198. var x = quadraticAt$$1(x0, x1, x2, tx);
  11199. var y = quadraticAt$$1(y0, y1, y2, ty);
  11200. min$$1[0] = mathMin$3(x0, x2, x);
  11201. min$$1[1] = mathMin$3(y0, y2, y);
  11202. max$$1[0] = mathMax$3(x0, x2, x);
  11203. max$$1[1] = mathMax$3(y0, y2, y);
  11204. }
  11205. /**
  11206. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11207. * @method
  11208. * @memberOf module:zrender/core/bbox
  11209. * @param {number} x
  11210. * @param {number} y
  11211. * @param {number} rx
  11212. * @param {number} ry
  11213. * @param {number} startAngle
  11214. * @param {number} endAngle
  11215. * @param {number} anticlockwise
  11216. * @param {Array.<number>} min
  11217. * @param {Array.<number>} max
  11218. */
  11219. function fromArc(
  11220. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11221. ) {
  11222. var vec2Min = min;
  11223. var vec2Max = max;
  11224. var diff = Math.abs(startAngle - endAngle);
  11225. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11226. // Is a circle
  11227. min$$1[0] = x - rx;
  11228. min$$1[1] = y - ry;
  11229. max$$1[0] = x + rx;
  11230. max$$1[1] = y + ry;
  11231. return;
  11232. }
  11233. start[0] = mathCos$2(startAngle) * rx + x;
  11234. start[1] = mathSin$2(startAngle) * ry + y;
  11235. end[0] = mathCos$2(endAngle) * rx + x;
  11236. end[1] = mathSin$2(endAngle) * ry + y;
  11237. vec2Min(min$$1, start, end);
  11238. vec2Max(max$$1, start, end);
  11239. // Thresh to [0, Math.PI * 2]
  11240. startAngle = startAngle % (PI2);
  11241. if (startAngle < 0) {
  11242. startAngle = startAngle + PI2;
  11243. }
  11244. endAngle = endAngle % (PI2);
  11245. if (endAngle < 0) {
  11246. endAngle = endAngle + PI2;
  11247. }
  11248. if (startAngle > endAngle && !anticlockwise) {
  11249. endAngle += PI2;
  11250. }
  11251. else if (startAngle < endAngle && anticlockwise) {
  11252. startAngle += PI2;
  11253. }
  11254. if (anticlockwise) {
  11255. var tmp = endAngle;
  11256. endAngle = startAngle;
  11257. startAngle = tmp;
  11258. }
  11259. // var number = 0;
  11260. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11261. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11262. if (angle > startAngle) {
  11263. extremity[0] = mathCos$2(angle) * rx + x;
  11264. extremity[1] = mathSin$2(angle) * ry + y;
  11265. vec2Min(min$$1, extremity, min$$1);
  11266. vec2Max(max$$1, extremity, max$$1);
  11267. }
  11268. }
  11269. }
  11270. /**
  11271. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11272. * 可以用于 isInsidePath 判断以及获取boundingRect
  11273. *
  11274. * @module zrender/core/PathProxy
  11275. * @author Yi Shen (http://www.github.com/pissang)
  11276. */
  11277. // TODO getTotalLength, getPointAtLength
  11278. var CMD = {
  11279. M: 1,
  11280. L: 2,
  11281. C: 3,
  11282. Q: 4,
  11283. A: 5,
  11284. Z: 6,
  11285. // Rect
  11286. R: 7
  11287. };
  11288. // var CMD_MEM_SIZE = {
  11289. // M: 3,
  11290. // L: 3,
  11291. // C: 7,
  11292. // Q: 5,
  11293. // A: 9,
  11294. // R: 5,
  11295. // Z: 1
  11296. // };
  11297. var min$1 = [];
  11298. var max$1 = [];
  11299. var min2 = [];
  11300. var max2 = [];
  11301. var mathMin$2 = Math.min;
  11302. var mathMax$2 = Math.max;
  11303. var mathCos$1 = Math.cos;
  11304. var mathSin$1 = Math.sin;
  11305. var mathSqrt$1 = Math.sqrt;
  11306. var mathAbs = Math.abs;
  11307. var hasTypedArray = typeof Float32Array !== 'undefined';
  11308. /**
  11309. * @alias module:zrender/core/PathProxy
  11310. * @constructor
  11311. */
  11312. var PathProxy = function (notSaveData) {
  11313. this._saveData = !(notSaveData || false);
  11314. if (this._saveData) {
  11315. /**
  11316. * Path data. Stored as flat array
  11317. * @type {Array.<Object>}
  11318. */
  11319. this.data = [];
  11320. }
  11321. this._ctx = null;
  11322. };
  11323. /**
  11324. * 快速计算Path包围盒(并不是最小包围盒)
  11325. * @return {Object}
  11326. */
  11327. PathProxy.prototype = {
  11328. constructor: PathProxy,
  11329. _xi: 0,
  11330. _yi: 0,
  11331. _x0: 0,
  11332. _y0: 0,
  11333. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11334. _ux: 0,
  11335. _uy: 0,
  11336. _len: 0,
  11337. _lineDash: null,
  11338. _dashOffset: 0,
  11339. _dashIdx: 0,
  11340. _dashSum: 0,
  11341. /**
  11342. * @readOnly
  11343. */
  11344. setScale: function (sx, sy) {
  11345. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11346. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11347. },
  11348. getContext: function () {
  11349. return this._ctx;
  11350. },
  11351. /**
  11352. * @param {CanvasRenderingContext2D} ctx
  11353. * @return {module:zrender/core/PathProxy}
  11354. */
  11355. beginPath: function (ctx) {
  11356. this._ctx = ctx;
  11357. ctx && ctx.beginPath();
  11358. ctx && (this.dpr = ctx.dpr);
  11359. // Reset
  11360. if (this._saveData) {
  11361. this._len = 0;
  11362. }
  11363. if (this._lineDash) {
  11364. this._lineDash = null;
  11365. this._dashOffset = 0;
  11366. }
  11367. return this;
  11368. },
  11369. /**
  11370. * @param {number} x
  11371. * @param {number} y
  11372. * @return {module:zrender/core/PathProxy}
  11373. */
  11374. moveTo: function (x, y) {
  11375. this.addData(CMD.M, x, y);
  11376. this._ctx && this._ctx.moveTo(x, y);
  11377. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11378. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11379. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11380. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11381. this._x0 = x;
  11382. this._y0 = y;
  11383. this._xi = x;
  11384. this._yi = y;
  11385. return this;
  11386. },
  11387. /**
  11388. * @param {number} x
  11389. * @param {number} y
  11390. * @return {module:zrender/core/PathProxy}
  11391. */
  11392. lineTo: function (x, y) {
  11393. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11394. || mathAbs(y - this._yi) > this._uy
  11395. // Force draw the first segment
  11396. || this._len < 5;
  11397. this.addData(CMD.L, x, y);
  11398. if (this._ctx && exceedUnit) {
  11399. this._needsDash() ? this._dashedLineTo(x, y)
  11400. : this._ctx.lineTo(x, y);
  11401. }
  11402. if (exceedUnit) {
  11403. this._xi = x;
  11404. this._yi = y;
  11405. }
  11406. return this;
  11407. },
  11408. /**
  11409. * @param {number} x1
  11410. * @param {number} y1
  11411. * @param {number} x2
  11412. * @param {number} y2
  11413. * @param {number} x3
  11414. * @param {number} y3
  11415. * @return {module:zrender/core/PathProxy}
  11416. */
  11417. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11418. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11419. if (this._ctx) {
  11420. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11421. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11422. }
  11423. this._xi = x3;
  11424. this._yi = y3;
  11425. return this;
  11426. },
  11427. /**
  11428. * @param {number} x1
  11429. * @param {number} y1
  11430. * @param {number} x2
  11431. * @param {number} y2
  11432. * @return {module:zrender/core/PathProxy}
  11433. */
  11434. quadraticCurveTo: function (x1, y1, x2, y2) {
  11435. this.addData(CMD.Q, x1, y1, x2, y2);
  11436. if (this._ctx) {
  11437. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11438. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11439. }
  11440. this._xi = x2;
  11441. this._yi = y2;
  11442. return this;
  11443. },
  11444. /**
  11445. * @param {number} cx
  11446. * @param {number} cy
  11447. * @param {number} r
  11448. * @param {number} startAngle
  11449. * @param {number} endAngle
  11450. * @param {boolean} anticlockwise
  11451. * @return {module:zrender/core/PathProxy}
  11452. */
  11453. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11454. this.addData(
  11455. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11456. );
  11457. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11458. this._xi = mathCos$1(endAngle) * r + cx;
  11459. this._yi = mathSin$1(endAngle) * r + cy;
  11460. return this;
  11461. },
  11462. // TODO
  11463. arcTo: function (x1, y1, x2, y2, radius) {
  11464. if (this._ctx) {
  11465. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11466. }
  11467. return this;
  11468. },
  11469. // TODO
  11470. rect: function (x, y, w, h) {
  11471. this._ctx && this._ctx.rect(x, y, w, h);
  11472. this.addData(CMD.R, x, y, w, h);
  11473. return this;
  11474. },
  11475. /**
  11476. * @return {module:zrender/core/PathProxy}
  11477. */
  11478. closePath: function () {
  11479. this.addData(CMD.Z);
  11480. var ctx = this._ctx;
  11481. var x0 = this._x0;
  11482. var y0 = this._y0;
  11483. if (ctx) {
  11484. this._needsDash() && this._dashedLineTo(x0, y0);
  11485. ctx.closePath();
  11486. }
  11487. this._xi = x0;
  11488. this._yi = y0;
  11489. return this;
  11490. },
  11491. /**
  11492. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11493. * stroke 同样
  11494. * @param {CanvasRenderingContext2D} ctx
  11495. * @return {module:zrender/core/PathProxy}
  11496. */
  11497. fill: function (ctx) {
  11498. ctx && ctx.fill();
  11499. this.toStatic();
  11500. },
  11501. /**
  11502. * @param {CanvasRenderingContext2D} ctx
  11503. * @return {module:zrender/core/PathProxy}
  11504. */
  11505. stroke: function (ctx) {
  11506. ctx && ctx.stroke();
  11507. this.toStatic();
  11508. },
  11509. /**
  11510. * 必须在其它绘制命令前调用
  11511. * Must be invoked before all other path drawing methods
  11512. * @return {module:zrender/core/PathProxy}
  11513. */
  11514. setLineDash: function (lineDash) {
  11515. if (lineDash instanceof Array) {
  11516. this._lineDash = lineDash;
  11517. this._dashIdx = 0;
  11518. var lineDashSum = 0;
  11519. for (var i = 0; i < lineDash.length; i++) {
  11520. lineDashSum += lineDash[i];
  11521. }
  11522. this._dashSum = lineDashSum;
  11523. }
  11524. return this;
  11525. },
  11526. /**
  11527. * 必须在其它绘制命令前调用
  11528. * Must be invoked before all other path drawing methods
  11529. * @return {module:zrender/core/PathProxy}
  11530. */
  11531. setLineDashOffset: function (offset) {
  11532. this._dashOffset = offset;
  11533. return this;
  11534. },
  11535. /**
  11536. *
  11537. * @return {boolean}
  11538. */
  11539. len: function () {
  11540. return this._len;
  11541. },
  11542. /**
  11543. * 直接设置 Path 数据
  11544. */
  11545. setData: function (data) {
  11546. var len$$1 = data.length;
  11547. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11548. this.data = new Float32Array(len$$1);
  11549. }
  11550. for (var i = 0; i < len$$1; i++) {
  11551. this.data[i] = data[i];
  11552. }
  11553. this._len = len$$1;
  11554. },
  11555. /**
  11556. * 添加子路径
  11557. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11558. */
  11559. appendPath: function (path) {
  11560. if (!(path instanceof Array)) {
  11561. path = [path];
  11562. }
  11563. var len$$1 = path.length;
  11564. var appendSize = 0;
  11565. var offset = this._len;
  11566. for (var i = 0; i < len$$1; i++) {
  11567. appendSize += path[i].len();
  11568. }
  11569. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11570. this.data = new Float32Array(offset + appendSize);
  11571. }
  11572. for (var i = 0; i < len$$1; i++) {
  11573. var appendPathData = path[i].data;
  11574. for (var k = 0; k < appendPathData.length; k++) {
  11575. this.data[offset++] = appendPathData[k];
  11576. }
  11577. }
  11578. this._len = offset;
  11579. },
  11580. /**
  11581. * 填充 Path 数据。
  11582. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11583. */
  11584. addData: function (cmd) {
  11585. if (!this._saveData) {
  11586. return;
  11587. }
  11588. var data = this.data;
  11589. if (this._len + arguments.length > data.length) {
  11590. // 因为之前的数组已经转换成静态的 Float32Array
  11591. // 所以不够用时需要扩展一个新的动态数组
  11592. this._expandData();
  11593. data = this.data;
  11594. }
  11595. for (var i = 0; i < arguments.length; i++) {
  11596. data[this._len++] = arguments[i];
  11597. }
  11598. this._prevCmd = cmd;
  11599. },
  11600. _expandData: function () {
  11601. // Only if data is Float32Array
  11602. if (!(this.data instanceof Array)) {
  11603. var newData = [];
  11604. for (var i = 0; i < this._len; i++) {
  11605. newData[i] = this.data[i];
  11606. }
  11607. this.data = newData;
  11608. }
  11609. },
  11610. /**
  11611. * If needs js implemented dashed line
  11612. * @return {boolean}
  11613. * @private
  11614. */
  11615. _needsDash: function () {
  11616. return this._lineDash;
  11617. },
  11618. _dashedLineTo: function (x1, y1) {
  11619. var dashSum = this._dashSum;
  11620. var offset = this._dashOffset;
  11621. var lineDash = this._lineDash;
  11622. var ctx = this._ctx;
  11623. var x0 = this._xi;
  11624. var y0 = this._yi;
  11625. var dx = x1 - x0;
  11626. var dy = y1 - y0;
  11627. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11628. var x = x0;
  11629. var y = y0;
  11630. var dash;
  11631. var nDash = lineDash.length;
  11632. var idx;
  11633. dx /= dist$$1;
  11634. dy /= dist$$1;
  11635. if (offset < 0) {
  11636. // Convert to positive offset
  11637. offset = dashSum + offset;
  11638. }
  11639. offset %= dashSum;
  11640. x -= offset * dx;
  11641. y -= offset * dy;
  11642. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11643. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11644. idx = this._dashIdx;
  11645. dash = lineDash[idx];
  11646. x += dx * dash;
  11647. y += dy * dash;
  11648. this._dashIdx = (idx + 1) % nDash;
  11649. // Skip positive offset
  11650. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11651. continue;
  11652. }
  11653. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11654. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11655. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11656. );
  11657. }
  11658. // Offset for next lineTo
  11659. dx = x - x1;
  11660. dy = y - y1;
  11661. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11662. },
  11663. // Not accurate dashed line to
  11664. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11665. var dashSum = this._dashSum;
  11666. var offset = this._dashOffset;
  11667. var lineDash = this._lineDash;
  11668. var ctx = this._ctx;
  11669. var x0 = this._xi;
  11670. var y0 = this._yi;
  11671. var t;
  11672. var dx;
  11673. var dy;
  11674. var cubicAt$$1 = cubicAt;
  11675. var bezierLen = 0;
  11676. var idx = this._dashIdx;
  11677. var nDash = lineDash.length;
  11678. var x;
  11679. var y;
  11680. var tmpLen = 0;
  11681. if (offset < 0) {
  11682. // Convert to positive offset
  11683. offset = dashSum + offset;
  11684. }
  11685. offset %= dashSum;
  11686. // Bezier approx length
  11687. for (t = 0; t < 1; t += 0.1) {
  11688. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11689. - cubicAt$$1(x0, x1, x2, x3, t);
  11690. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11691. - cubicAt$$1(y0, y1, y2, y3, t);
  11692. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11693. }
  11694. // Find idx after add offset
  11695. for (; idx < nDash; idx++) {
  11696. tmpLen += lineDash[idx];
  11697. if (tmpLen > offset) {
  11698. break;
  11699. }
  11700. }
  11701. t = (tmpLen - offset) / bezierLen;
  11702. while (t <= 1) {
  11703. x = cubicAt$$1(x0, x1, x2, x3, t);
  11704. y = cubicAt$$1(y0, y1, y2, y3, t);
  11705. // Use line to approximate dashed bezier
  11706. // Bad result if dash is long
  11707. idx % 2 ? ctx.moveTo(x, y)
  11708. : ctx.lineTo(x, y);
  11709. t += lineDash[idx] / bezierLen;
  11710. idx = (idx + 1) % nDash;
  11711. }
  11712. // Finish the last segment and calculate the new offset
  11713. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11714. dx = x3 - x;
  11715. dy = y3 - y;
  11716. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11717. },
  11718. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11719. // Convert quadratic to cubic using degree elevation
  11720. var x3 = x2;
  11721. var y3 = y2;
  11722. x2 = (x2 + 2 * x1) / 3;
  11723. y2 = (y2 + 2 * y1) / 3;
  11724. x1 = (this._xi + 2 * x1) / 3;
  11725. y1 = (this._yi + 2 * y1) / 3;
  11726. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11727. },
  11728. /**
  11729. * 转成静态的 Float32Array 减少堆内存占用
  11730. * Convert dynamic array to static Float32Array
  11731. */
  11732. toStatic: function () {
  11733. var data = this.data;
  11734. if (data instanceof Array) {
  11735. data.length = this._len;
  11736. if (hasTypedArray) {
  11737. this.data = new Float32Array(data);
  11738. }
  11739. }
  11740. },
  11741. /**
  11742. * @return {module:zrender/core/BoundingRect}
  11743. */
  11744. getBoundingRect: function () {
  11745. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11746. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11747. var data = this.data;
  11748. var xi = 0;
  11749. var yi = 0;
  11750. var x0 = 0;
  11751. var y0 = 0;
  11752. for (var i = 0; i < data.length;) {
  11753. var cmd = data[i++];
  11754. if (i === 1) {
  11755. // 如果第一个命令是 L, C, Q
  11756. // 则 previous point 同绘制命令的第一个 point
  11757. //
  11758. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11759. xi = data[i];
  11760. yi = data[i + 1];
  11761. x0 = xi;
  11762. y0 = yi;
  11763. }
  11764. switch (cmd) {
  11765. case CMD.M:
  11766. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11767. // 在 closePath 的时候使用
  11768. x0 = data[i++];
  11769. y0 = data[i++];
  11770. xi = x0;
  11771. yi = y0;
  11772. min2[0] = x0;
  11773. min2[1] = y0;
  11774. max2[0] = x0;
  11775. max2[1] = y0;
  11776. break;
  11777. case CMD.L:
  11778. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11779. xi = data[i++];
  11780. yi = data[i++];
  11781. break;
  11782. case CMD.C:
  11783. fromCubic(
  11784. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11785. min2, max2
  11786. );
  11787. xi = data[i++];
  11788. yi = data[i++];
  11789. break;
  11790. case CMD.Q:
  11791. fromQuadratic(
  11792. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11793. min2, max2
  11794. );
  11795. xi = data[i++];
  11796. yi = data[i++];
  11797. break;
  11798. case CMD.A:
  11799. // TODO Arc 判断的开销比较大
  11800. var cx = data[i++];
  11801. var cy = data[i++];
  11802. var rx = data[i++];
  11803. var ry = data[i++];
  11804. var startAngle = data[i++];
  11805. var endAngle = data[i++] + startAngle;
  11806. // TODO Arc 旋转
  11807. i += 1;
  11808. var anticlockwise = 1 - data[i++];
  11809. if (i === 1) {
  11810. // 直接使用 arc 命令
  11811. // 第一个命令起点还未定义
  11812. x0 = mathCos$1(startAngle) * rx + cx;
  11813. y0 = mathSin$1(startAngle) * ry + cy;
  11814. }
  11815. fromArc(
  11816. cx, cy, rx, ry, startAngle, endAngle,
  11817. anticlockwise, min2, max2
  11818. );
  11819. xi = mathCos$1(endAngle) * rx + cx;
  11820. yi = mathSin$1(endAngle) * ry + cy;
  11821. break;
  11822. case CMD.R:
  11823. x0 = xi = data[i++];
  11824. y0 = yi = data[i++];
  11825. var width = data[i++];
  11826. var height = data[i++];
  11827. // Use fromLine
  11828. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11829. break;
  11830. case CMD.Z:
  11831. xi = x0;
  11832. yi = y0;
  11833. break;
  11834. }
  11835. // Union
  11836. min(min$1, min$1, min2);
  11837. max(max$1, max$1, max2);
  11838. }
  11839. // No data
  11840. if (i === 0) {
  11841. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11842. }
  11843. return new BoundingRect(
  11844. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11845. );
  11846. },
  11847. /**
  11848. * Rebuild path from current data
  11849. * Rebuild path will not consider javascript implemented line dash.
  11850. * @param {CanvasRenderingContext2D} ctx
  11851. */
  11852. rebuildPath: function (ctx) {
  11853. var d = this.data;
  11854. var x0, y0;
  11855. var xi, yi;
  11856. var x, y;
  11857. var ux = this._ux;
  11858. var uy = this._uy;
  11859. var len$$1 = this._len;
  11860. for (var i = 0; i < len$$1;) {
  11861. var cmd = d[i++];
  11862. if (i === 1) {
  11863. // 如果第一个命令是 L, C, Q
  11864. // 则 previous point 同绘制命令的第一个 point
  11865. //
  11866. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11867. xi = d[i];
  11868. yi = d[i + 1];
  11869. x0 = xi;
  11870. y0 = yi;
  11871. }
  11872. switch (cmd) {
  11873. case CMD.M:
  11874. x0 = xi = d[i++];
  11875. y0 = yi = d[i++];
  11876. ctx.moveTo(xi, yi);
  11877. break;
  11878. case CMD.L:
  11879. x = d[i++];
  11880. y = d[i++];
  11881. // Not draw too small seg between
  11882. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11883. ctx.lineTo(x, y);
  11884. xi = x;
  11885. yi = y;
  11886. }
  11887. break;
  11888. case CMD.C:
  11889. ctx.bezierCurveTo(
  11890. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11891. );
  11892. xi = d[i - 2];
  11893. yi = d[i - 1];
  11894. break;
  11895. case CMD.Q:
  11896. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11897. xi = d[i - 2];
  11898. yi = d[i - 1];
  11899. break;
  11900. case CMD.A:
  11901. var cx = d[i++];
  11902. var cy = d[i++];
  11903. var rx = d[i++];
  11904. var ry = d[i++];
  11905. var theta = d[i++];
  11906. var dTheta = d[i++];
  11907. var psi = d[i++];
  11908. var fs = d[i++];
  11909. var r = (rx > ry) ? rx : ry;
  11910. var scaleX = (rx > ry) ? 1 : rx / ry;
  11911. var scaleY = (rx > ry) ? ry / rx : 1;
  11912. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11913. var endAngle = theta + dTheta;
  11914. if (isEllipse) {
  11915. ctx.translate(cx, cy);
  11916. ctx.rotate(psi);
  11917. ctx.scale(scaleX, scaleY);
  11918. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11919. ctx.scale(1 / scaleX, 1 / scaleY);
  11920. ctx.rotate(-psi);
  11921. ctx.translate(-cx, -cy);
  11922. }
  11923. else {
  11924. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11925. }
  11926. if (i === 1) {
  11927. // 直接使用 arc 命令
  11928. // 第一个命令起点还未定义
  11929. x0 = mathCos$1(theta) * rx + cx;
  11930. y0 = mathSin$1(theta) * ry + cy;
  11931. }
  11932. xi = mathCos$1(endAngle) * rx + cx;
  11933. yi = mathSin$1(endAngle) * ry + cy;
  11934. break;
  11935. case CMD.R:
  11936. x0 = xi = d[i];
  11937. y0 = yi = d[i + 1];
  11938. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11939. break;
  11940. case CMD.Z:
  11941. ctx.closePath();
  11942. xi = x0;
  11943. yi = y0;
  11944. }
  11945. }
  11946. }
  11947. };
  11948. PathProxy.CMD = CMD;
  11949. /**
  11950. * 线段包含判断
  11951. * @param {number} x0
  11952. * @param {number} y0
  11953. * @param {number} x1
  11954. * @param {number} y1
  11955. * @param {number} lineWidth
  11956. * @param {number} x
  11957. * @param {number} y
  11958. * @return {boolean}
  11959. */
  11960. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11961. if (lineWidth === 0) {
  11962. return false;
  11963. }
  11964. var _l = lineWidth;
  11965. var _a = 0;
  11966. var _b = x0;
  11967. // Quick reject
  11968. if (
  11969. (y > y0 + _l && y > y1 + _l)
  11970. || (y < y0 - _l && y < y1 - _l)
  11971. || (x > x0 + _l && x > x1 + _l)
  11972. || (x < x0 - _l && x < x1 - _l)
  11973. ) {
  11974. return false;
  11975. }
  11976. if (x0 !== x1) {
  11977. _a = (y0 - y1) / (x0 - x1);
  11978. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11979. }
  11980. else {
  11981. return Math.abs(x - x0) <= _l / 2;
  11982. }
  11983. var tmp = _a * x - y + _b;
  11984. var _s = tmp * tmp / (_a * _a + 1);
  11985. return _s <= _l / 2 * _l / 2;
  11986. }
  11987. /**
  11988. * 三次贝塞尔曲线描边包含判断
  11989. * @param {number} x0
  11990. * @param {number} y0
  11991. * @param {number} x1
  11992. * @param {number} y1
  11993. * @param {number} x2
  11994. * @param {number} y2
  11995. * @param {number} x3
  11996. * @param {number} y3
  11997. * @param {number} lineWidth
  11998. * @param {number} x
  11999. * @param {number} y
  12000. * @return {boolean}
  12001. */
  12002. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12003. if (lineWidth === 0) {
  12004. return false;
  12005. }
  12006. var _l = lineWidth;
  12007. // Quick reject
  12008. if (
  12009. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12010. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12011. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12012. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12013. ) {
  12014. return false;
  12015. }
  12016. var d = cubicProjectPoint(
  12017. x0, y0, x1, y1, x2, y2, x3, y3,
  12018. x, y, null
  12019. );
  12020. return d <= _l / 2;
  12021. }
  12022. /**
  12023. * 二次贝塞尔曲线描边包含判断
  12024. * @param {number} x0
  12025. * @param {number} y0
  12026. * @param {number} x1
  12027. * @param {number} y1
  12028. * @param {number} x2
  12029. * @param {number} y2
  12030. * @param {number} lineWidth
  12031. * @param {number} x
  12032. * @param {number} y
  12033. * @return {boolean}
  12034. */
  12035. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12036. if (lineWidth === 0) {
  12037. return false;
  12038. }
  12039. var _l = lineWidth;
  12040. // Quick reject
  12041. if (
  12042. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12043. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12044. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12045. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12046. ) {
  12047. return false;
  12048. }
  12049. var d = quadraticProjectPoint(
  12050. x0, y0, x1, y1, x2, y2,
  12051. x, y, null
  12052. );
  12053. return d <= _l / 2;
  12054. }
  12055. var PI2$3 = Math.PI * 2;
  12056. function normalizeRadian(angle) {
  12057. angle %= PI2$3;
  12058. if (angle < 0) {
  12059. angle += PI2$3;
  12060. }
  12061. return angle;
  12062. }
  12063. var PI2$2 = Math.PI * 2;
  12064. /**
  12065. * 圆弧描边包含判断
  12066. * @param {number} cx
  12067. * @param {number} cy
  12068. * @param {number} r
  12069. * @param {number} startAngle
  12070. * @param {number} endAngle
  12071. * @param {boolean} anticlockwise
  12072. * @param {number} lineWidth
  12073. * @param {number} x
  12074. * @param {number} y
  12075. * @return {Boolean}
  12076. */
  12077. function containStroke$4(
  12078. cx, cy, r, startAngle, endAngle, anticlockwise,
  12079. lineWidth, x, y
  12080. ) {
  12081. if (lineWidth === 0) {
  12082. return false;
  12083. }
  12084. var _l = lineWidth;
  12085. x -= cx;
  12086. y -= cy;
  12087. var d = Math.sqrt(x * x + y * y);
  12088. if ((d - _l > r) || (d + _l < r)) {
  12089. return false;
  12090. }
  12091. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12092. // Is a circle
  12093. return true;
  12094. }
  12095. if (anticlockwise) {
  12096. var tmp = startAngle;
  12097. startAngle = normalizeRadian(endAngle);
  12098. endAngle = normalizeRadian(tmp);
  12099. }
  12100. else {
  12101. startAngle = normalizeRadian(startAngle);
  12102. endAngle = normalizeRadian(endAngle);
  12103. }
  12104. if (startAngle > endAngle) {
  12105. endAngle += PI2$2;
  12106. }
  12107. var angle = Math.atan2(y, x);
  12108. if (angle < 0) {
  12109. angle += PI2$2;
  12110. }
  12111. return (angle >= startAngle && angle <= endAngle)
  12112. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12113. }
  12114. function windingLine(x0, y0, x1, y1, x, y) {
  12115. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12116. return 0;
  12117. }
  12118. // Ignore horizontal line
  12119. if (y1 === y0) {
  12120. return 0;
  12121. }
  12122. var dir = y1 < y0 ? 1 : -1;
  12123. var t = (y - y0) / (y1 - y0);
  12124. // Avoid winding error when intersection point is the connect point of two line of polygon
  12125. if (t === 1 || t === 0) {
  12126. dir = y1 < y0 ? 0.5 : -0.5;
  12127. }
  12128. var x_ = t * (x1 - x0) + x0;
  12129. // If (x, y) on the line, considered as "contain".
  12130. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12131. }
  12132. var CMD$1 = PathProxy.CMD;
  12133. var PI2$1 = Math.PI * 2;
  12134. var EPSILON$2 = 1e-4;
  12135. function isAroundEqual(a, b) {
  12136. return Math.abs(a - b) < EPSILON$2;
  12137. }
  12138. // 临时数组
  12139. var roots = [-1, -1, -1];
  12140. var extrema = [-1, -1];
  12141. function swapExtrema() {
  12142. var tmp = extrema[0];
  12143. extrema[0] = extrema[1];
  12144. extrema[1] = tmp;
  12145. }
  12146. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12147. // Quick reject
  12148. if (
  12149. (y > y0 && y > y1 && y > y2 && y > y3)
  12150. || (y < y0 && y < y1 && y < y2 && y < y3)
  12151. ) {
  12152. return 0;
  12153. }
  12154. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12155. if (nRoots === 0) {
  12156. return 0;
  12157. }
  12158. else {
  12159. var w = 0;
  12160. var nExtrema = -1;
  12161. var y0_;
  12162. var y1_;
  12163. for (var i = 0; i < nRoots; i++) {
  12164. var t = roots[i];
  12165. // Avoid winding error when intersection point is the connect point of two line of polygon
  12166. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12167. var x_ = cubicAt(x0, x1, x2, x3, t);
  12168. if (x_ < x) { // Quick reject
  12169. continue;
  12170. }
  12171. if (nExtrema < 0) {
  12172. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12173. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12174. swapExtrema();
  12175. }
  12176. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12177. if (nExtrema > 1) {
  12178. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12179. }
  12180. }
  12181. if (nExtrema === 2) {
  12182. // 分成三段单调函数
  12183. if (t < extrema[0]) {
  12184. w += y0_ < y0 ? unit : -unit;
  12185. }
  12186. else if (t < extrema[1]) {
  12187. w += y1_ < y0_ ? unit : -unit;
  12188. }
  12189. else {
  12190. w += y3 < y1_ ? unit : -unit;
  12191. }
  12192. }
  12193. else {
  12194. // 分成两段单调函数
  12195. if (t < extrema[0]) {
  12196. w += y0_ < y0 ? unit : -unit;
  12197. }
  12198. else {
  12199. w += y3 < y0_ ? unit : -unit;
  12200. }
  12201. }
  12202. }
  12203. return w;
  12204. }
  12205. }
  12206. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12207. // Quick reject
  12208. if (
  12209. (y > y0 && y > y1 && y > y2)
  12210. || (y < y0 && y < y1 && y < y2)
  12211. ) {
  12212. return 0;
  12213. }
  12214. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12215. if (nRoots === 0) {
  12216. return 0;
  12217. }
  12218. else {
  12219. var t = quadraticExtremum(y0, y1, y2);
  12220. if (t >= 0 && t <= 1) {
  12221. var w = 0;
  12222. var y_ = quadraticAt(y0, y1, y2, t);
  12223. for (var i = 0; i < nRoots; i++) {
  12224. // Remove one endpoint.
  12225. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12226. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12227. if (x_ < x) { // Quick reject
  12228. continue;
  12229. }
  12230. if (roots[i] < t) {
  12231. w += y_ < y0 ? unit : -unit;
  12232. }
  12233. else {
  12234. w += y2 < y_ ? unit : -unit;
  12235. }
  12236. }
  12237. return w;
  12238. }
  12239. else {
  12240. // Remove one endpoint.
  12241. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12242. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12243. if (x_ < x) { // Quick reject
  12244. return 0;
  12245. }
  12246. return y2 < y0 ? unit : -unit;
  12247. }
  12248. }
  12249. }
  12250. // TODO
  12251. // Arc 旋转
  12252. function windingArc(
  12253. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12254. ) {
  12255. y -= cy;
  12256. if (y > r || y < -r) {
  12257. return 0;
  12258. }
  12259. var tmp = Math.sqrt(r * r - y * y);
  12260. roots[0] = -tmp;
  12261. roots[1] = tmp;
  12262. var diff = Math.abs(startAngle - endAngle);
  12263. if (diff < 1e-4) {
  12264. return 0;
  12265. }
  12266. if (diff % PI2$1 < 1e-4) {
  12267. // Is a circle
  12268. startAngle = 0;
  12269. endAngle = PI2$1;
  12270. var dir = anticlockwise ? 1 : -1;
  12271. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12272. return dir;
  12273. }
  12274. else {
  12275. return 0;
  12276. }
  12277. }
  12278. if (anticlockwise) {
  12279. var tmp = startAngle;
  12280. startAngle = normalizeRadian(endAngle);
  12281. endAngle = normalizeRadian(tmp);
  12282. }
  12283. else {
  12284. startAngle = normalizeRadian(startAngle);
  12285. endAngle = normalizeRadian(endAngle);
  12286. }
  12287. if (startAngle > endAngle) {
  12288. endAngle += PI2$1;
  12289. }
  12290. var w = 0;
  12291. for (var i = 0; i < 2; i++) {
  12292. var x_ = roots[i];
  12293. if (x_ + cx > x) {
  12294. var angle = Math.atan2(y, x_);
  12295. var dir = anticlockwise ? 1 : -1;
  12296. if (angle < 0) {
  12297. angle = PI2$1 + angle;
  12298. }
  12299. if (
  12300. (angle >= startAngle && angle <= endAngle)
  12301. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12302. ) {
  12303. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12304. dir = -dir;
  12305. }
  12306. w += dir;
  12307. }
  12308. }
  12309. }
  12310. return w;
  12311. }
  12312. function containPath(data, lineWidth, isStroke, x, y) {
  12313. var w = 0;
  12314. var xi = 0;
  12315. var yi = 0;
  12316. var x0 = 0;
  12317. var y0 = 0;
  12318. for (var i = 0; i < data.length;) {
  12319. var cmd = data[i++];
  12320. // Begin a new subpath
  12321. if (cmd === CMD$1.M && i > 1) {
  12322. // Close previous subpath
  12323. if (!isStroke) {
  12324. w += windingLine(xi, yi, x0, y0, x, y);
  12325. }
  12326. // 如果被任何一个 subpath 包含
  12327. // if (w !== 0) {
  12328. // return true;
  12329. // }
  12330. }
  12331. if (i === 1) {
  12332. // 如果第一个命令是 L, C, Q
  12333. // 则 previous point 同绘制命令的第一个 point
  12334. //
  12335. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12336. xi = data[i];
  12337. yi = data[i + 1];
  12338. x0 = xi;
  12339. y0 = yi;
  12340. }
  12341. switch (cmd) {
  12342. case CMD$1.M:
  12343. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12344. // 在 closePath 的时候使用
  12345. x0 = data[i++];
  12346. y0 = data[i++];
  12347. xi = x0;
  12348. yi = y0;
  12349. break;
  12350. case CMD$1.L:
  12351. if (isStroke) {
  12352. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12353. return true;
  12354. }
  12355. }
  12356. else {
  12357. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12358. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12359. }
  12360. xi = data[i++];
  12361. yi = data[i++];
  12362. break;
  12363. case CMD$1.C:
  12364. if (isStroke) {
  12365. if (containStroke$2(xi, yi,
  12366. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12367. lineWidth, x, y
  12368. )) {
  12369. return true;
  12370. }
  12371. }
  12372. else {
  12373. w += windingCubic(
  12374. xi, yi,
  12375. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12376. x, y
  12377. ) || 0;
  12378. }
  12379. xi = data[i++];
  12380. yi = data[i++];
  12381. break;
  12382. case CMD$1.Q:
  12383. if (isStroke) {
  12384. if (containStroke$3(xi, yi,
  12385. data[i++], data[i++], data[i], data[i + 1],
  12386. lineWidth, x, y
  12387. )) {
  12388. return true;
  12389. }
  12390. }
  12391. else {
  12392. w += windingQuadratic(
  12393. xi, yi,
  12394. data[i++], data[i++], data[i], data[i + 1],
  12395. x, y
  12396. ) || 0;
  12397. }
  12398. xi = data[i++];
  12399. yi = data[i++];
  12400. break;
  12401. case CMD$1.A:
  12402. // TODO Arc 判断的开销比较大
  12403. var cx = data[i++];
  12404. var cy = data[i++];
  12405. var rx = data[i++];
  12406. var ry = data[i++];
  12407. var theta = data[i++];
  12408. var dTheta = data[i++];
  12409. // TODO Arc 旋转
  12410. i += 1;
  12411. var anticlockwise = 1 - data[i++];
  12412. var x1 = Math.cos(theta) * rx + cx;
  12413. var y1 = Math.sin(theta) * ry + cy;
  12414. // 不是直接使用 arc 命令
  12415. if (i > 1) {
  12416. w += windingLine(xi, yi, x1, y1, x, y);
  12417. }
  12418. else {
  12419. // 第一个命令起点还未定义
  12420. x0 = x1;
  12421. y0 = y1;
  12422. }
  12423. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12424. var _x = (x - cx) * ry / rx + cx;
  12425. if (isStroke) {
  12426. if (containStroke$4(
  12427. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12428. lineWidth, _x, y
  12429. )) {
  12430. return true;
  12431. }
  12432. }
  12433. else {
  12434. w += windingArc(
  12435. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12436. _x, y
  12437. );
  12438. }
  12439. xi = Math.cos(theta + dTheta) * rx + cx;
  12440. yi = Math.sin(theta + dTheta) * ry + cy;
  12441. break;
  12442. case CMD$1.R:
  12443. x0 = xi = data[i++];
  12444. y0 = yi = data[i++];
  12445. var width = data[i++];
  12446. var height = data[i++];
  12447. var x1 = x0 + width;
  12448. var y1 = y0 + height;
  12449. if (isStroke) {
  12450. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12451. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12452. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12453. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12454. ) {
  12455. return true;
  12456. }
  12457. }
  12458. else {
  12459. // FIXME Clockwise ?
  12460. w += windingLine(x1, y0, x1, y1, x, y);
  12461. w += windingLine(x0, y1, x0, y0, x, y);
  12462. }
  12463. break;
  12464. case CMD$1.Z:
  12465. if (isStroke) {
  12466. if (containStroke$1(
  12467. xi, yi, x0, y0, lineWidth, x, y
  12468. )) {
  12469. return true;
  12470. }
  12471. }
  12472. else {
  12473. // Close a subpath
  12474. w += windingLine(xi, yi, x0, y0, x, y);
  12475. // 如果被任何一个 subpath 包含
  12476. // FIXME subpaths may overlap
  12477. // if (w !== 0) {
  12478. // return true;
  12479. // }
  12480. }
  12481. xi = x0;
  12482. yi = y0;
  12483. break;
  12484. }
  12485. }
  12486. if (!isStroke && !isAroundEqual(yi, y0)) {
  12487. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12488. }
  12489. return w !== 0;
  12490. }
  12491. function contain(pathData, x, y) {
  12492. return containPath(pathData, 0, false, x, y);
  12493. }
  12494. function containStroke(pathData, lineWidth, x, y) {
  12495. return containPath(pathData, lineWidth, true, x, y);
  12496. }
  12497. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12498. var abs = Math.abs;
  12499. var pathProxyForDraw = new PathProxy(true);
  12500. /**
  12501. * @alias module:zrender/graphic/Path
  12502. * @extends module:zrender/graphic/Displayable
  12503. * @constructor
  12504. * @param {Object} opts
  12505. */
  12506. function Path(opts) {
  12507. Displayable.call(this, opts);
  12508. /**
  12509. * @type {module:zrender/core/PathProxy}
  12510. * @readOnly
  12511. */
  12512. this.path = null;
  12513. }
  12514. Path.prototype = {
  12515. constructor: Path,
  12516. type: 'path',
  12517. __dirtyPath: true,
  12518. strokeContainThreshold: 5,
  12519. /**
  12520. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12521. * @type {boolean}
  12522. */
  12523. subPixelOptimize: false,
  12524. brush: function (ctx, prevEl) {
  12525. var style = this.style;
  12526. var path = this.path || pathProxyForDraw;
  12527. var hasStroke = style.hasStroke();
  12528. var hasFill = style.hasFill();
  12529. var fill = style.fill;
  12530. var stroke = style.stroke;
  12531. var hasFillGradient = hasFill && !!(fill.colorStops);
  12532. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12533. var hasFillPattern = hasFill && !!(fill.image);
  12534. var hasStrokePattern = hasStroke && !!(stroke.image);
  12535. style.bind(ctx, this, prevEl);
  12536. this.setTransform(ctx);
  12537. if (this.__dirty) {
  12538. var rect;
  12539. // Update gradient because bounding rect may changed
  12540. if (hasFillGradient) {
  12541. rect = rect || this.getBoundingRect();
  12542. this._fillGradient = style.getGradient(ctx, fill, rect);
  12543. }
  12544. if (hasStrokeGradient) {
  12545. rect = rect || this.getBoundingRect();
  12546. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12547. }
  12548. }
  12549. // Use the gradient or pattern
  12550. if (hasFillGradient) {
  12551. // PENDING If may have affect the state
  12552. ctx.fillStyle = this._fillGradient;
  12553. }
  12554. else if (hasFillPattern) {
  12555. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12556. }
  12557. if (hasStrokeGradient) {
  12558. ctx.strokeStyle = this._strokeGradient;
  12559. }
  12560. else if (hasStrokePattern) {
  12561. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12562. }
  12563. var lineDash = style.lineDash;
  12564. var lineDashOffset = style.lineDashOffset;
  12565. var ctxLineDash = !!ctx.setLineDash;
  12566. // Update path sx, sy
  12567. var scale = this.getGlobalScale();
  12568. path.setScale(scale[0], scale[1]);
  12569. // Proxy context
  12570. // Rebuild path in following 2 cases
  12571. // 1. Path is dirty
  12572. // 2. Path needs javascript implemented lineDash stroking.
  12573. // In this case, lineDash information will not be saved in PathProxy
  12574. if (this.__dirtyPath
  12575. || (lineDash && !ctxLineDash && hasStroke)
  12576. ) {
  12577. path.beginPath(ctx);
  12578. // Setting line dash before build path
  12579. if (lineDash && !ctxLineDash) {
  12580. path.setLineDash(lineDash);
  12581. path.setLineDashOffset(lineDashOffset);
  12582. }
  12583. this.buildPath(path, this.shape, false);
  12584. // Clear path dirty flag
  12585. if (this.path) {
  12586. this.__dirtyPath = false;
  12587. }
  12588. }
  12589. else {
  12590. // Replay path building
  12591. ctx.beginPath();
  12592. this.path.rebuildPath(ctx);
  12593. }
  12594. if (hasFill) {
  12595. if (style.fillOpacity != null) {
  12596. var originalGlobalAlpha = ctx.globalAlpha;
  12597. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12598. path.fill(ctx);
  12599. ctx.globalAlpha = originalGlobalAlpha;
  12600. }
  12601. else {
  12602. path.fill(ctx);
  12603. }
  12604. }
  12605. if (lineDash && ctxLineDash) {
  12606. ctx.setLineDash(lineDash);
  12607. ctx.lineDashOffset = lineDashOffset;
  12608. }
  12609. if (hasStroke) {
  12610. if (style.strokeOpacity != null) {
  12611. var originalGlobalAlpha = ctx.globalAlpha;
  12612. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12613. path.stroke(ctx);
  12614. ctx.globalAlpha = originalGlobalAlpha;
  12615. }
  12616. else {
  12617. path.stroke(ctx);
  12618. }
  12619. }
  12620. if (lineDash && ctxLineDash) {
  12621. // PENDING
  12622. // Remove lineDash
  12623. ctx.setLineDash([]);
  12624. }
  12625. // Draw rect text
  12626. if (style.text != null) {
  12627. // Only restore transform when needs draw text.
  12628. this.restoreTransform(ctx);
  12629. this.drawRectText(ctx, this.getBoundingRect());
  12630. }
  12631. },
  12632. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12633. // Like in circle
  12634. buildPath: function (ctx, shapeCfg, inBundle) {},
  12635. createPathProxy: function () {
  12636. this.path = new PathProxy();
  12637. },
  12638. getBoundingRect: function () {
  12639. var rect = this._rect;
  12640. var style = this.style;
  12641. var needsUpdateRect = !rect;
  12642. if (needsUpdateRect) {
  12643. var path = this.path;
  12644. if (!path) {
  12645. // Create path on demand.
  12646. path = this.path = new PathProxy();
  12647. }
  12648. if (this.__dirtyPath) {
  12649. path.beginPath();
  12650. this.buildPath(path, this.shape, false);
  12651. }
  12652. rect = path.getBoundingRect();
  12653. }
  12654. this._rect = rect;
  12655. if (style.hasStroke()) {
  12656. // Needs update rect with stroke lineWidth when
  12657. // 1. Element changes scale or lineWidth
  12658. // 2. Shape is changed
  12659. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12660. if (this.__dirty || needsUpdateRect) {
  12661. rectWithStroke.copy(rect);
  12662. // FIXME Must after updateTransform
  12663. var w = style.lineWidth;
  12664. // PENDING, Min line width is needed when line is horizontal or vertical
  12665. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12666. // Only add extra hover lineWidth when there are no fill
  12667. if (!style.hasFill()) {
  12668. w = Math.max(w, this.strokeContainThreshold || 4);
  12669. }
  12670. // Consider line width
  12671. // Line scale can't be 0;
  12672. if (lineScale > 1e-10) {
  12673. rectWithStroke.width += w / lineScale;
  12674. rectWithStroke.height += w / lineScale;
  12675. rectWithStroke.x -= w / lineScale / 2;
  12676. rectWithStroke.y -= w / lineScale / 2;
  12677. }
  12678. }
  12679. // Return rect with stroke
  12680. return rectWithStroke;
  12681. }
  12682. return rect;
  12683. },
  12684. contain: function (x, y) {
  12685. var localPos = this.transformCoordToLocal(x, y);
  12686. var rect = this.getBoundingRect();
  12687. var style = this.style;
  12688. x = localPos[0];
  12689. y = localPos[1];
  12690. if (rect.contain(x, y)) {
  12691. var pathData = this.path.data;
  12692. if (style.hasStroke()) {
  12693. var lineWidth = style.lineWidth;
  12694. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12695. // Line scale can't be 0;
  12696. if (lineScale > 1e-10) {
  12697. // Only add extra hover lineWidth when there are no fill
  12698. if (!style.hasFill()) {
  12699. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12700. }
  12701. if (containStroke(
  12702. pathData, lineWidth / lineScale, x, y
  12703. )) {
  12704. return true;
  12705. }
  12706. }
  12707. }
  12708. if (style.hasFill()) {
  12709. return contain(pathData, x, y);
  12710. }
  12711. }
  12712. return false;
  12713. },
  12714. /**
  12715. * @param {boolean} dirtyPath
  12716. */
  12717. dirty: function (dirtyPath) {
  12718. if (dirtyPath == null) {
  12719. dirtyPath = true;
  12720. }
  12721. // Only mark dirty, not mark clean
  12722. if (dirtyPath) {
  12723. this.__dirtyPath = dirtyPath;
  12724. this._rect = null;
  12725. }
  12726. this.__dirty = this.__dirtyText = true;
  12727. this.__zr && this.__zr.refresh();
  12728. // Used as a clipping path
  12729. if (this.__clipTarget) {
  12730. this.__clipTarget.dirty();
  12731. }
  12732. },
  12733. /**
  12734. * Alias for animate('shape')
  12735. * @param {boolean} loop
  12736. */
  12737. animateShape: function (loop) {
  12738. return this.animate('shape', loop);
  12739. },
  12740. // Overwrite attrKV
  12741. attrKV: function (key, value) {
  12742. // FIXME
  12743. if (key === 'shape') {
  12744. this.setShape(value);
  12745. this.__dirtyPath = true;
  12746. this._rect = null;
  12747. }
  12748. else {
  12749. Displayable.prototype.attrKV.call(this, key, value);
  12750. }
  12751. },
  12752. /**
  12753. * @param {Object|string} key
  12754. * @param {*} value
  12755. */
  12756. setShape: function (key, value) {
  12757. var shape = this.shape;
  12758. // Path from string may not have shape
  12759. if (shape) {
  12760. if (isObject$1(key)) {
  12761. for (var name in key) {
  12762. if (key.hasOwnProperty(name)) {
  12763. shape[name] = key[name];
  12764. }
  12765. }
  12766. }
  12767. else {
  12768. shape[key] = value;
  12769. }
  12770. this.dirty(true);
  12771. }
  12772. return this;
  12773. },
  12774. getLineScale: function () {
  12775. var m = this.transform;
  12776. // Get the line scale.
  12777. // Determinant of `m` means how much the area is enlarged by the
  12778. // transformation. So its square root can be used as a scale factor
  12779. // for width.
  12780. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12781. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12782. : 1;
  12783. }
  12784. };
  12785. /**
  12786. * 扩展一个 Path element, 比如星形,圆等。
  12787. * Extend a path element
  12788. * @param {Object} props
  12789. * @param {string} props.type Path type
  12790. * @param {Function} props.init Initialize
  12791. * @param {Function} props.buildPath Overwrite buildPath method
  12792. * @param {Object} [props.style] Extended default style config
  12793. * @param {Object} [props.shape] Extended default shape config
  12794. */
  12795. Path.extend = function (defaults$$1) {
  12796. var Sub = function (opts) {
  12797. Path.call(this, opts);
  12798. if (defaults$$1.style) {
  12799. // Extend default style
  12800. this.style.extendFrom(defaults$$1.style, false);
  12801. }
  12802. // Extend default shape
  12803. var defaultShape = defaults$$1.shape;
  12804. if (defaultShape) {
  12805. this.shape = this.shape || {};
  12806. var thisShape = this.shape;
  12807. for (var name in defaultShape) {
  12808. if (
  12809. !thisShape.hasOwnProperty(name)
  12810. && defaultShape.hasOwnProperty(name)
  12811. ) {
  12812. thisShape[name] = defaultShape[name];
  12813. }
  12814. }
  12815. }
  12816. defaults$$1.init && defaults$$1.init.call(this, opts);
  12817. };
  12818. inherits(Sub, Path);
  12819. // FIXME 不能 extend position, rotation 等引用对象
  12820. for (var name in defaults$$1) {
  12821. // Extending prototype values and methods
  12822. if (name !== 'style' && name !== 'shape') {
  12823. Sub.prototype[name] = defaults$$1[name];
  12824. }
  12825. }
  12826. return Sub;
  12827. };
  12828. inherits(Path, Displayable);
  12829. var CMD$2 = PathProxy.CMD;
  12830. var points = [[], [], []];
  12831. var mathSqrt$3 = Math.sqrt;
  12832. var mathAtan2 = Math.atan2;
  12833. var transformPath = function (path, m) {
  12834. var data = path.data;
  12835. var cmd;
  12836. var nPoint;
  12837. var i;
  12838. var j;
  12839. var k;
  12840. var p;
  12841. var M = CMD$2.M;
  12842. var C = CMD$2.C;
  12843. var L = CMD$2.L;
  12844. var R = CMD$2.R;
  12845. var A = CMD$2.A;
  12846. var Q = CMD$2.Q;
  12847. for (i = 0, j = 0; i < data.length;) {
  12848. cmd = data[i++];
  12849. j = i;
  12850. nPoint = 0;
  12851. switch (cmd) {
  12852. case M:
  12853. nPoint = 1;
  12854. break;
  12855. case L:
  12856. nPoint = 1;
  12857. break;
  12858. case C:
  12859. nPoint = 3;
  12860. break;
  12861. case Q:
  12862. nPoint = 2;
  12863. break;
  12864. case A:
  12865. var x = m[4];
  12866. var y = m[5];
  12867. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12868. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12869. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12870. // cx
  12871. data[i] *= sx;
  12872. data[i++] += x;
  12873. // cy
  12874. data[i] *= sy;
  12875. data[i++] += y;
  12876. // Scale rx and ry
  12877. // FIXME Assume psi is 0 here
  12878. data[i++] *= sx;
  12879. data[i++] *= sy;
  12880. // Start angle
  12881. data[i++] += angle;
  12882. // end angle
  12883. data[i++] += angle;
  12884. // FIXME psi
  12885. i += 2;
  12886. j = i;
  12887. break;
  12888. case R:
  12889. // x0, y0
  12890. p[0] = data[i++];
  12891. p[1] = data[i++];
  12892. applyTransform(p, p, m);
  12893. data[j++] = p[0];
  12894. data[j++] = p[1];
  12895. // x1, y1
  12896. p[0] += data[i++];
  12897. p[1] += data[i++];
  12898. applyTransform(p, p, m);
  12899. data[j++] = p[0];
  12900. data[j++] = p[1];
  12901. }
  12902. for (k = 0; k < nPoint; k++) {
  12903. var p = points[k];
  12904. p[0] = data[i++];
  12905. p[1] = data[i++];
  12906. applyTransform(p, p, m);
  12907. // Write back
  12908. data[j++] = p[0];
  12909. data[j++] = p[1];
  12910. }
  12911. }
  12912. };
  12913. // command chars
  12914. // var cc = [
  12915. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12916. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12917. // ];
  12918. var mathSqrt = Math.sqrt;
  12919. var mathSin = Math.sin;
  12920. var mathCos = Math.cos;
  12921. var PI = Math.PI;
  12922. var vMag = function (v) {
  12923. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12924. };
  12925. var vRatio = function (u, v) {
  12926. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12927. };
  12928. var vAngle = function (u, v) {
  12929. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12930. * Math.acos(vRatio(u, v));
  12931. };
  12932. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12933. var psi = psiDeg * (PI / 180.0);
  12934. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12935. + mathSin(psi) * (y1 - y2) / 2.0;
  12936. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12937. + mathCos(psi) * (y1 - y2) / 2.0;
  12938. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12939. if (lambda > 1) {
  12940. rx *= mathSqrt(lambda);
  12941. ry *= mathSqrt(lambda);
  12942. }
  12943. var f = (fa === fs ? -1 : 1)
  12944. * mathSqrt((((rx * rx) * (ry * ry))
  12945. - ((rx * rx) * (yp * yp))
  12946. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12947. + (ry * ry) * (xp * xp))
  12948. ) || 0;
  12949. var cxp = f * rx * yp / ry;
  12950. var cyp = f * -ry * xp / rx;
  12951. var cx = (x1 + x2) / 2.0
  12952. + mathCos(psi) * cxp
  12953. - mathSin(psi) * cyp;
  12954. var cy = (y1 + y2) / 2.0
  12955. + mathSin(psi) * cxp
  12956. + mathCos(psi) * cyp;
  12957. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12958. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12959. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12960. var dTheta = vAngle(u, v);
  12961. if (vRatio(u, v) <= -1) {
  12962. dTheta = PI;
  12963. }
  12964. if (vRatio(u, v) >= 1) {
  12965. dTheta = 0;
  12966. }
  12967. if (fs === 0 && dTheta > 0) {
  12968. dTheta = dTheta - 2 * PI;
  12969. }
  12970. if (fs === 1 && dTheta < 0) {
  12971. dTheta = dTheta + 2 * PI;
  12972. }
  12973. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12974. }
  12975. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12976. // Consider case:
  12977. // (1) delimiter can be comma or space, where continuous commas
  12978. // or spaces should be seen as one comma.
  12979. // (2) value can be like:
  12980. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12981. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12982. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12983. // var valueSplitReg = /[\s,]+/;
  12984. function createPathProxyFromString(data) {
  12985. if (!data) {
  12986. return new PathProxy();
  12987. }
  12988. // var data = data.replace(/-/g, ' -')
  12989. // .replace(/ /g, ' ')
  12990. // .replace(/ /g, ',')
  12991. // .replace(/,,/g, ',');
  12992. // var n;
  12993. // create pipes so that we can split the data
  12994. // for (n = 0; n < cc.length; n++) {
  12995. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12996. // }
  12997. // data = data.replace(/-/g, ',-');
  12998. // create array
  12999. // var arr = cs.split('|');
  13000. // init context point
  13001. var cpx = 0;
  13002. var cpy = 0;
  13003. var subpathX = cpx;
  13004. var subpathY = cpy;
  13005. var prevCmd;
  13006. var path = new PathProxy();
  13007. var CMD = PathProxy.CMD;
  13008. // commandReg.lastIndex = 0;
  13009. // var cmdResult;
  13010. // while ((cmdResult = commandReg.exec(data)) != null) {
  13011. // var cmdStr = cmdResult[1];
  13012. // var cmdContent = cmdResult[2];
  13013. var cmdList = data.match(commandReg);
  13014. for (var l = 0; l < cmdList.length; l++) {
  13015. var cmdText = cmdList[l];
  13016. var cmdStr = cmdText.charAt(0);
  13017. var cmd;
  13018. // String#split is faster a little bit than String#replace or RegExp#exec.
  13019. // var p = cmdContent.split(valueSplitReg);
  13020. // var pLen = 0;
  13021. // for (var i = 0; i < p.length; i++) {
  13022. // // '' and other invalid str => NaN
  13023. // var val = parseFloat(p[i]);
  13024. // !isNaN(val) && (p[pLen++] = val);
  13025. // }
  13026. var p = cmdText.match(numberReg) || [];
  13027. var pLen = p.length;
  13028. for (var i = 0; i < pLen; i++) {
  13029. p[i] = parseFloat(p[i]);
  13030. }
  13031. var off = 0;
  13032. while (off < pLen) {
  13033. var ctlPtx;
  13034. var ctlPty;
  13035. var rx;
  13036. var ry;
  13037. var psi;
  13038. var fa;
  13039. var fs;
  13040. var x1 = cpx;
  13041. var y1 = cpy;
  13042. // convert l, H, h, V, and v to L
  13043. switch (cmdStr) {
  13044. case 'l':
  13045. cpx += p[off++];
  13046. cpy += p[off++];
  13047. cmd = CMD.L;
  13048. path.addData(cmd, cpx, cpy);
  13049. break;
  13050. case 'L':
  13051. cpx = p[off++];
  13052. cpy = p[off++];
  13053. cmd = CMD.L;
  13054. path.addData(cmd, cpx, cpy);
  13055. break;
  13056. case 'm':
  13057. cpx += p[off++];
  13058. cpy += p[off++];
  13059. cmd = CMD.M;
  13060. path.addData(cmd, cpx, cpy);
  13061. subpathX = cpx;
  13062. subpathY = cpy;
  13063. cmdStr = 'l';
  13064. break;
  13065. case 'M':
  13066. cpx = p[off++];
  13067. cpy = p[off++];
  13068. cmd = CMD.M;
  13069. path.addData(cmd, cpx, cpy);
  13070. subpathX = cpx;
  13071. subpathY = cpy;
  13072. cmdStr = 'L';
  13073. break;
  13074. case 'h':
  13075. cpx += p[off++];
  13076. cmd = CMD.L;
  13077. path.addData(cmd, cpx, cpy);
  13078. break;
  13079. case 'H':
  13080. cpx = p[off++];
  13081. cmd = CMD.L;
  13082. path.addData(cmd, cpx, cpy);
  13083. break;
  13084. case 'v':
  13085. cpy += p[off++];
  13086. cmd = CMD.L;
  13087. path.addData(cmd, cpx, cpy);
  13088. break;
  13089. case 'V':
  13090. cpy = p[off++];
  13091. cmd = CMD.L;
  13092. path.addData(cmd, cpx, cpy);
  13093. break;
  13094. case 'C':
  13095. cmd = CMD.C;
  13096. path.addData(
  13097. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13098. );
  13099. cpx = p[off - 2];
  13100. cpy = p[off - 1];
  13101. break;
  13102. case 'c':
  13103. cmd = CMD.C;
  13104. path.addData(
  13105. cmd,
  13106. p[off++] + cpx, p[off++] + cpy,
  13107. p[off++] + cpx, p[off++] + cpy,
  13108. p[off++] + cpx, p[off++] + cpy
  13109. );
  13110. cpx += p[off - 2];
  13111. cpy += p[off - 1];
  13112. break;
  13113. case 'S':
  13114. ctlPtx = cpx;
  13115. ctlPty = cpy;
  13116. var len = path.len();
  13117. var pathData = path.data;
  13118. if (prevCmd === CMD.C) {
  13119. ctlPtx += cpx - pathData[len - 4];
  13120. ctlPty += cpy - pathData[len - 3];
  13121. }
  13122. cmd = CMD.C;
  13123. x1 = p[off++];
  13124. y1 = p[off++];
  13125. cpx = p[off++];
  13126. cpy = p[off++];
  13127. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13128. break;
  13129. case 's':
  13130. ctlPtx = cpx;
  13131. ctlPty = cpy;
  13132. var len = path.len();
  13133. var pathData = path.data;
  13134. if (prevCmd === CMD.C) {
  13135. ctlPtx += cpx - pathData[len - 4];
  13136. ctlPty += cpy - pathData[len - 3];
  13137. }
  13138. cmd = CMD.C;
  13139. x1 = cpx + p[off++];
  13140. y1 = cpy + p[off++];
  13141. cpx += p[off++];
  13142. cpy += p[off++];
  13143. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13144. break;
  13145. case 'Q':
  13146. x1 = p[off++];
  13147. y1 = p[off++];
  13148. cpx = p[off++];
  13149. cpy = p[off++];
  13150. cmd = CMD.Q;
  13151. path.addData(cmd, x1, y1, cpx, cpy);
  13152. break;
  13153. case 'q':
  13154. x1 = p[off++] + cpx;
  13155. y1 = p[off++] + cpy;
  13156. cpx += p[off++];
  13157. cpy += p[off++];
  13158. cmd = CMD.Q;
  13159. path.addData(cmd, x1, y1, cpx, cpy);
  13160. break;
  13161. case 'T':
  13162. ctlPtx = cpx;
  13163. ctlPty = cpy;
  13164. var len = path.len();
  13165. var pathData = path.data;
  13166. if (prevCmd === CMD.Q) {
  13167. ctlPtx += cpx - pathData[len - 4];
  13168. ctlPty += cpy - pathData[len - 3];
  13169. }
  13170. cpx = p[off++];
  13171. cpy = p[off++];
  13172. cmd = CMD.Q;
  13173. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13174. break;
  13175. case 't':
  13176. ctlPtx = cpx;
  13177. ctlPty = cpy;
  13178. var len = path.len();
  13179. var pathData = path.data;
  13180. if (prevCmd === CMD.Q) {
  13181. ctlPtx += cpx - pathData[len - 4];
  13182. ctlPty += cpy - pathData[len - 3];
  13183. }
  13184. cpx += p[off++];
  13185. cpy += p[off++];
  13186. cmd = CMD.Q;
  13187. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13188. break;
  13189. case 'A':
  13190. rx = p[off++];
  13191. ry = p[off++];
  13192. psi = p[off++];
  13193. fa = p[off++];
  13194. fs = p[off++];
  13195. x1 = cpx, y1 = cpy;
  13196. cpx = p[off++];
  13197. cpy = p[off++];
  13198. cmd = CMD.A;
  13199. processArc(
  13200. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13201. );
  13202. break;
  13203. case 'a':
  13204. rx = p[off++];
  13205. ry = p[off++];
  13206. psi = p[off++];
  13207. fa = p[off++];
  13208. fs = p[off++];
  13209. x1 = cpx, y1 = cpy;
  13210. cpx += p[off++];
  13211. cpy += p[off++];
  13212. cmd = CMD.A;
  13213. processArc(
  13214. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13215. );
  13216. break;
  13217. }
  13218. }
  13219. if (cmdStr === 'z' || cmdStr === 'Z') {
  13220. cmd = CMD.Z;
  13221. path.addData(cmd);
  13222. // z may be in the middle of the path.
  13223. cpx = subpathX;
  13224. cpy = subpathY;
  13225. }
  13226. prevCmd = cmd;
  13227. }
  13228. path.toStatic();
  13229. return path;
  13230. }
  13231. // TODO Optimize double memory cost problem
  13232. function createPathOptions(str, opts) {
  13233. var pathProxy = createPathProxyFromString(str);
  13234. opts = opts || {};
  13235. opts.buildPath = function (path) {
  13236. if (path.setData) {
  13237. path.setData(pathProxy.data);
  13238. // Svg and vml renderer don't have context
  13239. var ctx = path.getContext();
  13240. if (ctx) {
  13241. path.rebuildPath(ctx);
  13242. }
  13243. }
  13244. else {
  13245. var ctx = path;
  13246. pathProxy.rebuildPath(ctx);
  13247. }
  13248. };
  13249. opts.applyTransform = function (m) {
  13250. transformPath(pathProxy, m);
  13251. this.dirty(true);
  13252. };
  13253. return opts;
  13254. }
  13255. /**
  13256. * Create a Path object from path string data
  13257. * http://www.w3.org/TR/SVG/paths.html#PathData
  13258. * @param {Object} opts Other options
  13259. */
  13260. function createFromString(str, opts) {
  13261. return new Path(createPathOptions(str, opts));
  13262. }
  13263. /**
  13264. * Create a Path class from path string data
  13265. * @param {string} str
  13266. * @param {Object} opts Other options
  13267. */
  13268. function extendFromString(str, opts) {
  13269. return Path.extend(createPathOptions(str, opts));
  13270. }
  13271. /**
  13272. * Merge multiple paths
  13273. */
  13274. // TODO Apply transform
  13275. // TODO stroke dash
  13276. // TODO Optimize double memory cost problem
  13277. function mergePath$1(pathEls, opts) {
  13278. var pathList = [];
  13279. var len = pathEls.length;
  13280. for (var i = 0; i < len; i++) {
  13281. var pathEl = pathEls[i];
  13282. if (!pathEl.path) {
  13283. pathEl.createPathProxy();
  13284. }
  13285. if (pathEl.__dirtyPath) {
  13286. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13287. }
  13288. pathList.push(pathEl.path);
  13289. }
  13290. var pathBundle = new Path(opts);
  13291. // Need path proxy.
  13292. pathBundle.createPathProxy();
  13293. pathBundle.buildPath = function (path) {
  13294. path.appendPath(pathList);
  13295. // Svg and vml renderer don't have context
  13296. var ctx = path.getContext();
  13297. if (ctx) {
  13298. path.rebuildPath(ctx);
  13299. }
  13300. };
  13301. return pathBundle;
  13302. }
  13303. /**
  13304. * @alias zrender/graphic/Text
  13305. * @extends module:zrender/graphic/Displayable
  13306. * @constructor
  13307. * @param {Object} opts
  13308. */
  13309. var Text = function (opts) { // jshint ignore:line
  13310. Displayable.call(this, opts);
  13311. };
  13312. Text.prototype = {
  13313. constructor: Text,
  13314. type: 'text',
  13315. brush: function (ctx, prevEl) {
  13316. var style = this.style;
  13317. // Optimize, avoid normalize every time.
  13318. this.__dirty && normalizeTextStyle(style, true);
  13319. // Use props with prefix 'text'.
  13320. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13321. style.shadowOffsetX = style.shadowOffsetY = null;
  13322. var text = style.text;
  13323. // Convert to string
  13324. text != null && (text += '');
  13325. // Do not apply style.bind in Text node. Because the real bind job
  13326. // is in textHelper.renderText, and performance of text render should
  13327. // be considered.
  13328. // style.bind(ctx, this, prevEl);
  13329. if (!needDrawText(text, style)) {
  13330. // The current el.style is not applied
  13331. // and should not be used as cache.
  13332. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13333. return;
  13334. }
  13335. this.setTransform(ctx);
  13336. renderText(this, ctx, text, style, null, prevEl);
  13337. this.restoreTransform(ctx);
  13338. },
  13339. getBoundingRect: function () {
  13340. var style = this.style;
  13341. // Optimize, avoid normalize every time.
  13342. this.__dirty && normalizeTextStyle(style, true);
  13343. if (!this._rect) {
  13344. var text = style.text;
  13345. text != null ? (text += '') : (text = '');
  13346. var rect = getBoundingRect(
  13347. style.text + '',
  13348. style.font,
  13349. style.textAlign,
  13350. style.textVerticalAlign,
  13351. style.textPadding,
  13352. style.rich
  13353. );
  13354. rect.x += style.x || 0;
  13355. rect.y += style.y || 0;
  13356. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13357. var w = style.textStrokeWidth;
  13358. rect.x -= w / 2;
  13359. rect.y -= w / 2;
  13360. rect.width += w;
  13361. rect.height += w;
  13362. }
  13363. this._rect = rect;
  13364. }
  13365. return this._rect;
  13366. }
  13367. };
  13368. inherits(Text, Displayable);
  13369. /**
  13370. * 圆形
  13371. * @module zrender/shape/Circle
  13372. */
  13373. var Circle = Path.extend({
  13374. type: 'circle',
  13375. shape: {
  13376. cx: 0,
  13377. cy: 0,
  13378. r: 0
  13379. },
  13380. buildPath: function (ctx, shape, inBundle) {
  13381. // Better stroking in ShapeBundle
  13382. // Always do it may have performence issue ( fill may be 2x more cost)
  13383. if (inBundle) {
  13384. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13385. }
  13386. // else {
  13387. // if (ctx.allocate && !ctx.data.length) {
  13388. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13389. // }
  13390. // }
  13391. // Better stroking in ShapeBundle
  13392. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13393. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13394. }
  13395. });
  13396. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13397. // where exception "unexpected call to method or property access"
  13398. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13399. // whose area size is zero is drawn and ctx.clip() is called and
  13400. // shadowBlur is set. See #4572, #3112, #5777.
  13401. // (e.g.,
  13402. // ctx.moveTo(10, 10);
  13403. // ctx.lineTo(20, 10);
  13404. // ctx.closePath();
  13405. // ctx.clip();
  13406. // ctx.shadowBlur = 10;
  13407. // ...
  13408. // ctx.fill();
  13409. // )
  13410. var shadowTemp = [
  13411. ['shadowBlur', 0],
  13412. ['shadowColor', '#000'],
  13413. ['shadowOffsetX', 0],
  13414. ['shadowOffsetY', 0]
  13415. ];
  13416. var fixClipWithShadow = function (orignalBrush) {
  13417. // version string can be: '11.0'
  13418. return (env$1.browser.ie && env$1.browser.version >= 11)
  13419. ? function () {
  13420. var clipPaths = this.__clipPaths;
  13421. var style = this.style;
  13422. var modified;
  13423. if (clipPaths) {
  13424. for (var i = 0; i < clipPaths.length; i++) {
  13425. var clipPath = clipPaths[i];
  13426. var shape = clipPath && clipPath.shape;
  13427. var type = clipPath && clipPath.type;
  13428. if (shape && (
  13429. (type === 'sector' && shape.startAngle === shape.endAngle)
  13430. || (type === 'rect' && (!shape.width || !shape.height))
  13431. )) {
  13432. for (var j = 0; j < shadowTemp.length; j++) {
  13433. // It is save to put shadowTemp static, because shadowTemp
  13434. // will be all modified each item brush called.
  13435. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13436. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13437. }
  13438. modified = true;
  13439. break;
  13440. }
  13441. }
  13442. }
  13443. orignalBrush.apply(this, arguments);
  13444. if (modified) {
  13445. for (var j = 0; j < shadowTemp.length; j++) {
  13446. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13447. }
  13448. }
  13449. }
  13450. : orignalBrush;
  13451. };
  13452. /**
  13453. * 扇形
  13454. * @module zrender/graphic/shape/Sector
  13455. */
  13456. var Sector = Path.extend({
  13457. type: 'sector',
  13458. shape: {
  13459. cx: 0,
  13460. cy: 0,
  13461. r0: 0,
  13462. r: 0,
  13463. startAngle: 0,
  13464. endAngle: Math.PI * 2,
  13465. clockwise: true
  13466. },
  13467. brush: fixClipWithShadow(Path.prototype.brush),
  13468. buildPath: function (ctx, shape) {
  13469. var x = shape.cx;
  13470. var y = shape.cy;
  13471. var r0 = Math.max(shape.r0 || 0, 0);
  13472. var r = Math.max(shape.r, 0);
  13473. var startAngle = shape.startAngle;
  13474. var endAngle = shape.endAngle;
  13475. var clockwise = shape.clockwise;
  13476. var unitX = Math.cos(startAngle);
  13477. var unitY = Math.sin(startAngle);
  13478. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13479. ctx.lineTo(unitX * r + x, unitY * r + y);
  13480. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13481. ctx.lineTo(
  13482. Math.cos(endAngle) * r0 + x,
  13483. Math.sin(endAngle) * r0 + y
  13484. );
  13485. if (r0 !== 0) {
  13486. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13487. }
  13488. ctx.closePath();
  13489. }
  13490. });
  13491. /**
  13492. * 圆环
  13493. * @module zrender/graphic/shape/Ring
  13494. */
  13495. var Ring = Path.extend({
  13496. type: 'ring',
  13497. shape: {
  13498. cx: 0,
  13499. cy: 0,
  13500. r: 0,
  13501. r0: 0
  13502. },
  13503. buildPath: function (ctx, shape) {
  13504. var x = shape.cx;
  13505. var y = shape.cy;
  13506. var PI2 = Math.PI * 2;
  13507. ctx.moveTo(x + shape.r, y);
  13508. ctx.arc(x, y, shape.r, 0, PI2, false);
  13509. ctx.moveTo(x + shape.r0, y);
  13510. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13511. }
  13512. });
  13513. /**
  13514. * Catmull-Rom spline 插值折线
  13515. * @module zrender/shape/util/smoothSpline
  13516. * @author pissang (https://www.github.com/pissang)
  13517. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13518. * errorrik (errorrik@gmail.com)
  13519. */
  13520. /**
  13521. * @inner
  13522. */
  13523. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13524. var v0 = (p2 - p0) * 0.5;
  13525. var v1 = (p3 - p1) * 0.5;
  13526. return (2 * (p1 - p2) + v0 + v1) * t3
  13527. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13528. + v0 * t + p1;
  13529. }
  13530. /**
  13531. * @alias module:zrender/shape/util/smoothSpline
  13532. * @param {Array} points 线段顶点数组
  13533. * @param {boolean} isLoop
  13534. * @return {Array}
  13535. */
  13536. var smoothSpline = function (points, isLoop) {
  13537. var len$$1 = points.length;
  13538. var ret = [];
  13539. var distance$$1 = 0;
  13540. for (var i = 1; i < len$$1; i++) {
  13541. distance$$1 += distance(points[i - 1], points[i]);
  13542. }
  13543. var segs = distance$$1 / 2;
  13544. segs = segs < len$$1 ? len$$1 : segs;
  13545. for (var i = 0; i < segs; i++) {
  13546. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13547. var idx = Math.floor(pos);
  13548. var w = pos - idx;
  13549. var p0;
  13550. var p1 = points[idx % len$$1];
  13551. var p2;
  13552. var p3;
  13553. if (!isLoop) {
  13554. p0 = points[idx === 0 ? idx : idx - 1];
  13555. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13556. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13557. }
  13558. else {
  13559. p0 = points[(idx - 1 + len$$1) % len$$1];
  13560. p2 = points[(idx + 1) % len$$1];
  13561. p3 = points[(idx + 2) % len$$1];
  13562. }
  13563. var w2 = w * w;
  13564. var w3 = w * w2;
  13565. ret.push([
  13566. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13567. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13568. ]);
  13569. }
  13570. return ret;
  13571. };
  13572. /**
  13573. * 贝塞尔平滑曲线
  13574. * @module zrender/shape/util/smoothBezier
  13575. * @author pissang (https://www.github.com/pissang)
  13576. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13577. * errorrik (errorrik@gmail.com)
  13578. */
  13579. /**
  13580. * 贝塞尔平滑曲线
  13581. * @alias module:zrender/shape/util/smoothBezier
  13582. * @param {Array} points 线段顶点数组
  13583. * @param {number} smooth 平滑等级, 0-1
  13584. * @param {boolean} isLoop
  13585. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13586. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13587. * 整个折线的包围盒做一个并集用来约束控制点。
  13588. * @param {Array} 计算出来的控制点数组
  13589. */
  13590. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13591. var cps = [];
  13592. var v = [];
  13593. var v1 = [];
  13594. var v2 = [];
  13595. var prevPoint;
  13596. var nextPoint;
  13597. var min$$1;
  13598. var max$$1;
  13599. if (constraint) {
  13600. min$$1 = [Infinity, Infinity];
  13601. max$$1 = [-Infinity, -Infinity];
  13602. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13603. min(min$$1, min$$1, points[i]);
  13604. max(max$$1, max$$1, points[i]);
  13605. }
  13606. // 与指定的包围盒做并集
  13607. min(min$$1, min$$1, constraint[0]);
  13608. max(max$$1, max$$1, constraint[1]);
  13609. }
  13610. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13611. var point = points[i];
  13612. if (isLoop) {
  13613. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13614. nextPoint = points[(i + 1) % len$$1];
  13615. }
  13616. else {
  13617. if (i === 0 || i === len$$1 - 1) {
  13618. cps.push(clone$1(points[i]));
  13619. continue;
  13620. }
  13621. else {
  13622. prevPoint = points[i - 1];
  13623. nextPoint = points[i + 1];
  13624. }
  13625. }
  13626. sub(v, nextPoint, prevPoint);
  13627. // use degree to scale the handle length
  13628. scale(v, v, smooth);
  13629. var d0 = distance(point, prevPoint);
  13630. var d1 = distance(point, nextPoint);
  13631. var sum = d0 + d1;
  13632. if (sum !== 0) {
  13633. d0 /= sum;
  13634. d1 /= sum;
  13635. }
  13636. scale(v1, v, -d0);
  13637. scale(v2, v, d1);
  13638. var cp0 = add([], point, v1);
  13639. var cp1 = add([], point, v2);
  13640. if (constraint) {
  13641. max(cp0, cp0, min$$1);
  13642. min(cp0, cp0, max$$1);
  13643. max(cp1, cp1, min$$1);
  13644. min(cp1, cp1, max$$1);
  13645. }
  13646. cps.push(cp0);
  13647. cps.push(cp1);
  13648. }
  13649. if (isLoop) {
  13650. cps.push(cps.shift());
  13651. }
  13652. return cps;
  13653. };
  13654. function buildPath$1(ctx, shape, closePath) {
  13655. var points = shape.points;
  13656. var smooth = shape.smooth;
  13657. if (points && points.length >= 2) {
  13658. if (smooth && smooth !== 'spline') {
  13659. var controlPoints = smoothBezier(
  13660. points, smooth, closePath, shape.smoothConstraint
  13661. );
  13662. ctx.moveTo(points[0][0], points[0][1]);
  13663. var len = points.length;
  13664. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13665. var cp1 = controlPoints[i * 2];
  13666. var cp2 = controlPoints[i * 2 + 1];
  13667. var p = points[(i + 1) % len];
  13668. ctx.bezierCurveTo(
  13669. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13670. );
  13671. }
  13672. }
  13673. else {
  13674. if (smooth === 'spline') {
  13675. points = smoothSpline(points, closePath);
  13676. }
  13677. ctx.moveTo(points[0][0], points[0][1]);
  13678. for (var i = 1, l = points.length; i < l; i++) {
  13679. ctx.lineTo(points[i][0], points[i][1]);
  13680. }
  13681. }
  13682. closePath && ctx.closePath();
  13683. }
  13684. }
  13685. /**
  13686. * 多边形
  13687. * @module zrender/shape/Polygon
  13688. */
  13689. var Polygon = Path.extend({
  13690. type: 'polygon',
  13691. shape: {
  13692. points: null,
  13693. smooth: false,
  13694. smoothConstraint: null
  13695. },
  13696. buildPath: function (ctx, shape) {
  13697. buildPath$1(ctx, shape, true);
  13698. }
  13699. });
  13700. /**
  13701. * @module zrender/graphic/shape/Polyline
  13702. */
  13703. var Polyline = Path.extend({
  13704. type: 'polyline',
  13705. shape: {
  13706. points: null,
  13707. smooth: false,
  13708. smoothConstraint: null
  13709. },
  13710. style: {
  13711. stroke: '#000',
  13712. fill: null
  13713. },
  13714. buildPath: function (ctx, shape) {
  13715. buildPath$1(ctx, shape, false);
  13716. }
  13717. });
  13718. /**
  13719. * Sub-pixel optimize for canvas rendering, prevent from blur
  13720. * when rendering a thin vertical/horizontal line.
  13721. */
  13722. var round$1 = Math.round;
  13723. /**
  13724. * Sub pixel optimize line for canvas
  13725. *
  13726. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13727. * `outputShape` and `inputShape` can be the same object.
  13728. * `outputShape` object can be used repeatly, because all of
  13729. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13730. * @param {Object} [inputShape]
  13731. * @param {number} [inputShape.x1]
  13732. * @param {number} [inputShape.y1]
  13733. * @param {number} [inputShape.x2]
  13734. * @param {number} [inputShape.y2]
  13735. * @param {Object} [style]
  13736. * @param {number} [style.lineWidth]
  13737. */
  13738. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13739. var lineWidth = style && style.lineWidth;
  13740. if (!inputShape || !lineWidth) {
  13741. return;
  13742. }
  13743. var x1 = inputShape.x1;
  13744. var x2 = inputShape.x2;
  13745. var y1 = inputShape.y1;
  13746. var y2 = inputShape.y2;
  13747. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  13748. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13749. }
  13750. else {
  13751. outputShape.x1 = x1;
  13752. outputShape.x2 = x2;
  13753. }
  13754. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  13755. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13756. }
  13757. else {
  13758. outputShape.y1 = y1;
  13759. outputShape.y2 = y2;
  13760. }
  13761. }
  13762. /**
  13763. * Sub pixel optimize rect for canvas
  13764. *
  13765. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13766. * `outputShape` and `inputShape` can be the same object.
  13767. * `outputShape` object can be used repeatly, because all of
  13768. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13769. * @param {Object} [inputShape]
  13770. * @param {number} [inputShape.x]
  13771. * @param {number} [inputShape.y]
  13772. * @param {number} [inputShape.width]
  13773. * @param {number} [inputShape.height]
  13774. * @param {Object} [style]
  13775. * @param {number} [style.lineWidth]
  13776. */
  13777. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13778. var lineWidth = style && style.lineWidth;
  13779. if (!inputShape || !lineWidth) {
  13780. return;
  13781. }
  13782. var originX = inputShape.x;
  13783. var originY = inputShape.y;
  13784. var originWidth = inputShape.width;
  13785. var originHeight = inputShape.height;
  13786. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13787. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13788. outputShape.width = Math.max(
  13789. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13790. originWidth === 0 ? 0 : 1
  13791. );
  13792. outputShape.height = Math.max(
  13793. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13794. originHeight === 0 ? 0 : 1
  13795. );
  13796. }
  13797. /**
  13798. * Sub pixel optimize for canvas
  13799. *
  13800. * @param {number} position Coordinate, such as x, y
  13801. * @param {number} lineWidth Should be nonnegative integer.
  13802. * @param {boolean=} positiveOrNegative Default false (negative).
  13803. * @return {number} Optimized position.
  13804. */
  13805. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13806. // Assure that (position + lineWidth / 2) is near integer edge,
  13807. // otherwise line will be fuzzy in canvas.
  13808. var doubledPosition = round$1(position * 2);
  13809. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13810. ? doubledPosition / 2
  13811. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13812. }
  13813. /**
  13814. * 矩形
  13815. * @module zrender/graphic/shape/Rect
  13816. */
  13817. // Avoid create repeatly.
  13818. var subPixelOptimizeOutputShape = {};
  13819. var Rect = Path.extend({
  13820. type: 'rect',
  13821. shape: {
  13822. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13823. // r缩写为1 相当于 [1, 1, 1, 1]
  13824. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13825. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13826. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13827. r: 0,
  13828. x: 0,
  13829. y: 0,
  13830. width: 0,
  13831. height: 0
  13832. },
  13833. buildPath: function (ctx, shape) {
  13834. var x;
  13835. var y;
  13836. var width;
  13837. var height;
  13838. if (this.subPixelOptimize) {
  13839. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13840. x = subPixelOptimizeOutputShape.x;
  13841. y = subPixelOptimizeOutputShape.y;
  13842. width = subPixelOptimizeOutputShape.width;
  13843. height = subPixelOptimizeOutputShape.height;
  13844. subPixelOptimizeOutputShape.r = shape.r;
  13845. shape = subPixelOptimizeOutputShape;
  13846. }
  13847. else {
  13848. x = shape.x;
  13849. y = shape.y;
  13850. width = shape.width;
  13851. height = shape.height;
  13852. }
  13853. if (!shape.r) {
  13854. ctx.rect(x, y, width, height);
  13855. }
  13856. else {
  13857. buildPath(ctx, shape);
  13858. }
  13859. ctx.closePath();
  13860. return;
  13861. }
  13862. });
  13863. /**
  13864. * 直线
  13865. * @module zrender/graphic/shape/Line
  13866. */
  13867. // Avoid create repeatly.
  13868. var subPixelOptimizeOutputShape$1 = {};
  13869. var Line = Path.extend({
  13870. type: 'line',
  13871. shape: {
  13872. // Start point
  13873. x1: 0,
  13874. y1: 0,
  13875. // End point
  13876. x2: 0,
  13877. y2: 0,
  13878. percent: 1
  13879. },
  13880. style: {
  13881. stroke: '#000',
  13882. fill: null
  13883. },
  13884. buildPath: function (ctx, shape) {
  13885. var x1;
  13886. var y1;
  13887. var x2;
  13888. var y2;
  13889. if (this.subPixelOptimize) {
  13890. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13891. x1 = subPixelOptimizeOutputShape$1.x1;
  13892. y1 = subPixelOptimizeOutputShape$1.y1;
  13893. x2 = subPixelOptimizeOutputShape$1.x2;
  13894. y2 = subPixelOptimizeOutputShape$1.y2;
  13895. }
  13896. else {
  13897. x1 = shape.x1;
  13898. y1 = shape.y1;
  13899. x2 = shape.x2;
  13900. y2 = shape.y2;
  13901. }
  13902. var percent = shape.percent;
  13903. if (percent === 0) {
  13904. return;
  13905. }
  13906. ctx.moveTo(x1, y1);
  13907. if (percent < 1) {
  13908. x2 = x1 * (1 - percent) + x2 * percent;
  13909. y2 = y1 * (1 - percent) + y2 * percent;
  13910. }
  13911. ctx.lineTo(x2, y2);
  13912. },
  13913. /**
  13914. * Get point at percent
  13915. * @param {number} percent
  13916. * @return {Array.<number>}
  13917. */
  13918. pointAt: function (p) {
  13919. var shape = this.shape;
  13920. return [
  13921. shape.x1 * (1 - p) + shape.x2 * p,
  13922. shape.y1 * (1 - p) + shape.y2 * p
  13923. ];
  13924. }
  13925. });
  13926. /**
  13927. * 贝塞尔曲线
  13928. * @module zrender/shape/BezierCurve
  13929. */
  13930. var out = [];
  13931. function someVectorAt(shape, t, isTangent) {
  13932. var cpx2 = shape.cpx2;
  13933. var cpy2 = shape.cpy2;
  13934. if (cpx2 === null || cpy2 === null) {
  13935. return [
  13936. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13937. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13938. ];
  13939. }
  13940. else {
  13941. return [
  13942. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13943. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13944. ];
  13945. }
  13946. }
  13947. var BezierCurve = Path.extend({
  13948. type: 'bezier-curve',
  13949. shape: {
  13950. x1: 0,
  13951. y1: 0,
  13952. x2: 0,
  13953. y2: 0,
  13954. cpx1: 0,
  13955. cpy1: 0,
  13956. // cpx2: 0,
  13957. // cpy2: 0
  13958. // Curve show percent, for animating
  13959. percent: 1
  13960. },
  13961. style: {
  13962. stroke: '#000',
  13963. fill: null
  13964. },
  13965. buildPath: function (ctx, shape) {
  13966. var x1 = shape.x1;
  13967. var y1 = shape.y1;
  13968. var x2 = shape.x2;
  13969. var y2 = shape.y2;
  13970. var cpx1 = shape.cpx1;
  13971. var cpy1 = shape.cpy1;
  13972. var cpx2 = shape.cpx2;
  13973. var cpy2 = shape.cpy2;
  13974. var percent = shape.percent;
  13975. if (percent === 0) {
  13976. return;
  13977. }
  13978. ctx.moveTo(x1, y1);
  13979. if (cpx2 == null || cpy2 == null) {
  13980. if (percent < 1) {
  13981. quadraticSubdivide(
  13982. x1, cpx1, x2, percent, out
  13983. );
  13984. cpx1 = out[1];
  13985. x2 = out[2];
  13986. quadraticSubdivide(
  13987. y1, cpy1, y2, percent, out
  13988. );
  13989. cpy1 = out[1];
  13990. y2 = out[2];
  13991. }
  13992. ctx.quadraticCurveTo(
  13993. cpx1, cpy1,
  13994. x2, y2
  13995. );
  13996. }
  13997. else {
  13998. if (percent < 1) {
  13999. cubicSubdivide(
  14000. x1, cpx1, cpx2, x2, percent, out
  14001. );
  14002. cpx1 = out[1];
  14003. cpx2 = out[2];
  14004. x2 = out[3];
  14005. cubicSubdivide(
  14006. y1, cpy1, cpy2, y2, percent, out
  14007. );
  14008. cpy1 = out[1];
  14009. cpy2 = out[2];
  14010. y2 = out[3];
  14011. }
  14012. ctx.bezierCurveTo(
  14013. cpx1, cpy1,
  14014. cpx2, cpy2,
  14015. x2, y2
  14016. );
  14017. }
  14018. },
  14019. /**
  14020. * Get point at percent
  14021. * @param {number} t
  14022. * @return {Array.<number>}
  14023. */
  14024. pointAt: function (t) {
  14025. return someVectorAt(this.shape, t, false);
  14026. },
  14027. /**
  14028. * Get tangent at percent
  14029. * @param {number} t
  14030. * @return {Array.<number>}
  14031. */
  14032. tangentAt: function (t) {
  14033. var p = someVectorAt(this.shape, t, true);
  14034. return normalize(p, p);
  14035. }
  14036. });
  14037. /**
  14038. * 圆弧
  14039. * @module zrender/graphic/shape/Arc
  14040. */
  14041. var Arc = Path.extend({
  14042. type: 'arc',
  14043. shape: {
  14044. cx: 0,
  14045. cy: 0,
  14046. r: 0,
  14047. startAngle: 0,
  14048. endAngle: Math.PI * 2,
  14049. clockwise: true
  14050. },
  14051. style: {
  14052. stroke: '#000',
  14053. fill: null
  14054. },
  14055. buildPath: function (ctx, shape) {
  14056. var x = shape.cx;
  14057. var y = shape.cy;
  14058. var r = Math.max(shape.r, 0);
  14059. var startAngle = shape.startAngle;
  14060. var endAngle = shape.endAngle;
  14061. var clockwise = shape.clockwise;
  14062. var unitX = Math.cos(startAngle);
  14063. var unitY = Math.sin(startAngle);
  14064. ctx.moveTo(unitX * r + x, unitY * r + y);
  14065. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14066. }
  14067. });
  14068. // CompoundPath to improve performance
  14069. var CompoundPath = Path.extend({
  14070. type: 'compound',
  14071. shape: {
  14072. paths: null
  14073. },
  14074. _updatePathDirty: function () {
  14075. var dirtyPath = this.__dirtyPath;
  14076. var paths = this.shape.paths;
  14077. for (var i = 0; i < paths.length; i++) {
  14078. // Mark as dirty if any subpath is dirty
  14079. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14080. }
  14081. this.__dirtyPath = dirtyPath;
  14082. this.__dirty = this.__dirty || dirtyPath;
  14083. },
  14084. beforeBrush: function () {
  14085. this._updatePathDirty();
  14086. var paths = this.shape.paths || [];
  14087. var scale = this.getGlobalScale();
  14088. // Update path scale
  14089. for (var i = 0; i < paths.length; i++) {
  14090. if (!paths[i].path) {
  14091. paths[i].createPathProxy();
  14092. }
  14093. paths[i].path.setScale(scale[0], scale[1]);
  14094. }
  14095. },
  14096. buildPath: function (ctx, shape) {
  14097. var paths = shape.paths || [];
  14098. for (var i = 0; i < paths.length; i++) {
  14099. paths[i].buildPath(ctx, paths[i].shape, true);
  14100. }
  14101. },
  14102. afterBrush: function () {
  14103. var paths = this.shape.paths || [];
  14104. for (var i = 0; i < paths.length; i++) {
  14105. paths[i].__dirtyPath = false;
  14106. }
  14107. },
  14108. getBoundingRect: function () {
  14109. this._updatePathDirty();
  14110. return Path.prototype.getBoundingRect.call(this);
  14111. }
  14112. });
  14113. /**
  14114. * @param {Array.<Object>} colorStops
  14115. */
  14116. var Gradient = function (colorStops) {
  14117. this.colorStops = colorStops || [];
  14118. };
  14119. Gradient.prototype = {
  14120. constructor: Gradient,
  14121. addColorStop: function (offset, color) {
  14122. this.colorStops.push({
  14123. offset: offset,
  14124. color: color
  14125. });
  14126. }
  14127. };
  14128. /**
  14129. * x, y, x2, y2 are all percent from 0 to 1
  14130. * @param {number} [x=0]
  14131. * @param {number} [y=0]
  14132. * @param {number} [x2=1]
  14133. * @param {number} [y2=0]
  14134. * @param {Array.<Object>} colorStops
  14135. * @param {boolean} [globalCoord=false]
  14136. */
  14137. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14138. // Should do nothing more in this constructor. Because gradient can be
  14139. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14140. // this constructor will not be called.
  14141. this.x = x == null ? 0 : x;
  14142. this.y = y == null ? 0 : y;
  14143. this.x2 = x2 == null ? 1 : x2;
  14144. this.y2 = y2 == null ? 0 : y2;
  14145. // Can be cloned
  14146. this.type = 'linear';
  14147. // If use global coord
  14148. this.global = globalCoord || false;
  14149. Gradient.call(this, colorStops);
  14150. };
  14151. LinearGradient.prototype = {
  14152. constructor: LinearGradient
  14153. };
  14154. inherits(LinearGradient, Gradient);
  14155. /**
  14156. * x, y, r are all percent from 0 to 1
  14157. * @param {number} [x=0.5]
  14158. * @param {number} [y=0.5]
  14159. * @param {number} [r=0.5]
  14160. * @param {Array.<Object>} [colorStops]
  14161. * @param {boolean} [globalCoord=false]
  14162. */
  14163. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14164. // Should do nothing more in this constructor. Because gradient can be
  14165. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14166. // this constructor will not be called.
  14167. this.x = x == null ? 0.5 : x;
  14168. this.y = y == null ? 0.5 : y;
  14169. this.r = r == null ? 0.5 : r;
  14170. // Can be cloned
  14171. this.type = 'radial';
  14172. // If use global coord
  14173. this.global = globalCoord || false;
  14174. Gradient.call(this, colorStops);
  14175. };
  14176. RadialGradient.prototype = {
  14177. constructor: RadialGradient
  14178. };
  14179. inherits(RadialGradient, Gradient);
  14180. /**
  14181. * Displayable for incremental rendering. It will be rendered in a separate layer
  14182. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14183. * addDisplayables will render the added displayables incremetally.
  14184. *
  14185. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14186. */
  14187. // TODO Style override ?
  14188. function IncrementalDisplayble(opts) {
  14189. Displayable.call(this, opts);
  14190. this._displayables = [];
  14191. this._temporaryDisplayables = [];
  14192. this._cursor = 0;
  14193. this.notClear = true;
  14194. }
  14195. IncrementalDisplayble.prototype.incremental = true;
  14196. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14197. this._displayables = [];
  14198. this._temporaryDisplayables = [];
  14199. this._cursor = 0;
  14200. this.dirty();
  14201. this.notClear = false;
  14202. };
  14203. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14204. if (notPersistent) {
  14205. this._temporaryDisplayables.push(displayable);
  14206. }
  14207. else {
  14208. this._displayables.push(displayable);
  14209. }
  14210. this.dirty();
  14211. };
  14212. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14213. notPersistent = notPersistent || false;
  14214. for (var i = 0; i < displayables.length; i++) {
  14215. this.addDisplayable(displayables[i], notPersistent);
  14216. }
  14217. };
  14218. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14219. for (var i = this._cursor; i < this._displayables.length; i++) {
  14220. cb && cb(this._displayables[i]);
  14221. }
  14222. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14223. cb && cb(this._temporaryDisplayables[i]);
  14224. }
  14225. };
  14226. IncrementalDisplayble.prototype.update = function () {
  14227. this.updateTransform();
  14228. for (var i = this._cursor; i < this._displayables.length; i++) {
  14229. var displayable = this._displayables[i];
  14230. // PENDING
  14231. displayable.parent = this;
  14232. displayable.update();
  14233. displayable.parent = null;
  14234. }
  14235. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14236. var displayable = this._temporaryDisplayables[i];
  14237. // PENDING
  14238. displayable.parent = this;
  14239. displayable.update();
  14240. displayable.parent = null;
  14241. }
  14242. };
  14243. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14244. // Render persistant displayables.
  14245. for (var i = this._cursor; i < this._displayables.length; i++) {
  14246. var displayable = this._displayables[i];
  14247. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14248. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14249. displayable.afterBrush && displayable.afterBrush(ctx);
  14250. }
  14251. this._cursor = i;
  14252. // Render temporary displayables.
  14253. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14254. var displayable = this._temporaryDisplayables[i];
  14255. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14256. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14257. displayable.afterBrush && displayable.afterBrush(ctx);
  14258. }
  14259. this._temporaryDisplayables = [];
  14260. this.notClear = true;
  14261. };
  14262. var m = [];
  14263. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14264. if (!this._rect) {
  14265. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14266. for (var i = 0; i < this._displayables.length; i++) {
  14267. var displayable = this._displayables[i];
  14268. var childRect = displayable.getBoundingRect().clone();
  14269. if (displayable.needLocalTransform()) {
  14270. childRect.applyTransform(displayable.getLocalTransform(m));
  14271. }
  14272. rect.union(childRect);
  14273. }
  14274. this._rect = rect;
  14275. }
  14276. return this._rect;
  14277. };
  14278. IncrementalDisplayble.prototype.contain = function (x, y) {
  14279. var localPos = this.transformCoordToLocal(x, y);
  14280. var rect = this.getBoundingRect();
  14281. if (rect.contain(localPos[0], localPos[1])) {
  14282. for (var i = 0; i < this._displayables.length; i++) {
  14283. var displayable = this._displayables[i];
  14284. if (displayable.contain(x, y)) {
  14285. return true;
  14286. }
  14287. }
  14288. }
  14289. return false;
  14290. };
  14291. inherits(IncrementalDisplayble, Displayable);
  14292. /*
  14293. * Licensed to the Apache Software Foundation (ASF) under one
  14294. * or more contributor license agreements. See the NOTICE file
  14295. * distributed with this work for additional information
  14296. * regarding copyright ownership. The ASF licenses this file
  14297. * to you under the Apache License, Version 2.0 (the
  14298. * "License"); you may not use this file except in compliance
  14299. * with the License. You may obtain a copy of the License at
  14300. *
  14301. * http://www.apache.org/licenses/LICENSE-2.0
  14302. *
  14303. * Unless required by applicable law or agreed to in writing,
  14304. * software distributed under the License is distributed on an
  14305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14306. * KIND, either express or implied. See the License for the
  14307. * specific language governing permissions and limitations
  14308. * under the License.
  14309. */
  14310. var round = Math.round;
  14311. var mathMax$1 = Math.max;
  14312. var mathMin$1 = Math.min;
  14313. var EMPTY_OBJ = {};
  14314. var Z2_EMPHASIS_LIFT = 1;
  14315. /**
  14316. * Extend shape with parameters
  14317. */
  14318. function extendShape(opts) {
  14319. return Path.extend(opts);
  14320. }
  14321. /**
  14322. * Extend path
  14323. */
  14324. function extendPath(pathData, opts) {
  14325. return extendFromString(pathData, opts);
  14326. }
  14327. /**
  14328. * Create a path element from path data string
  14329. * @param {string} pathData
  14330. * @param {Object} opts
  14331. * @param {module:zrender/core/BoundingRect} rect
  14332. * @param {string} [layout=cover] 'center' or 'cover'
  14333. */
  14334. function makePath(pathData, opts, rect, layout) {
  14335. var path = createFromString(pathData, opts);
  14336. if (rect) {
  14337. if (layout === 'center') {
  14338. rect = centerGraphic(rect, path.getBoundingRect());
  14339. }
  14340. resizePath(path, rect);
  14341. }
  14342. return path;
  14343. }
  14344. /**
  14345. * Create a image element from image url
  14346. * @param {string} imageUrl image url
  14347. * @param {Object} opts options
  14348. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14349. * @param {string} [layout=cover] 'center' or 'cover'
  14350. */
  14351. function makeImage(imageUrl, rect, layout) {
  14352. var path = new ZImage({
  14353. style: {
  14354. image: imageUrl,
  14355. x: rect.x,
  14356. y: rect.y,
  14357. width: rect.width,
  14358. height: rect.height
  14359. },
  14360. onload: function (img) {
  14361. if (layout === 'center') {
  14362. var boundingRect = {
  14363. width: img.width,
  14364. height: img.height
  14365. };
  14366. path.setStyle(centerGraphic(rect, boundingRect));
  14367. }
  14368. }
  14369. });
  14370. return path;
  14371. }
  14372. /**
  14373. * Get position of centered element in bounding box.
  14374. *
  14375. * @param {Object} rect element local bounding box
  14376. * @param {Object} boundingRect constraint bounding box
  14377. * @return {Object} element position containing x, y, width, and height
  14378. */
  14379. function centerGraphic(rect, boundingRect) {
  14380. // Set rect to center, keep width / height ratio.
  14381. var aspect = boundingRect.width / boundingRect.height;
  14382. var width = rect.height * aspect;
  14383. var height;
  14384. if (width <= rect.width) {
  14385. height = rect.height;
  14386. }
  14387. else {
  14388. width = rect.width;
  14389. height = width / aspect;
  14390. }
  14391. var cx = rect.x + rect.width / 2;
  14392. var cy = rect.y + rect.height / 2;
  14393. return {
  14394. x: cx - width / 2,
  14395. y: cy - height / 2,
  14396. width: width,
  14397. height: height
  14398. };
  14399. }
  14400. var mergePath = mergePath$1;
  14401. /**
  14402. * Resize a path to fit the rect
  14403. * @param {module:zrender/graphic/Path} path
  14404. * @param {Object} rect
  14405. */
  14406. function resizePath(path, rect) {
  14407. if (!path.applyTransform) {
  14408. return;
  14409. }
  14410. var pathRect = path.getBoundingRect();
  14411. var m = pathRect.calculateTransform(rect);
  14412. path.applyTransform(m);
  14413. }
  14414. /**
  14415. * Sub pixel optimize line for canvas
  14416. *
  14417. * @param {Object} param
  14418. * @param {Object} [param.shape]
  14419. * @param {number} [param.shape.x1]
  14420. * @param {number} [param.shape.y1]
  14421. * @param {number} [param.shape.x2]
  14422. * @param {number} [param.shape.y2]
  14423. * @param {Object} [param.style]
  14424. * @param {number} [param.style.lineWidth]
  14425. * @return {Object} Modified param
  14426. */
  14427. function subPixelOptimizeLine(param) {
  14428. var shape = param.shape;
  14429. var lineWidth = param.style.lineWidth;
  14430. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  14431. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  14432. }
  14433. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  14434. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  14435. }
  14436. return param;
  14437. }
  14438. /**
  14439. * Sub pixel optimize rect for canvas
  14440. *
  14441. * @param {Object} param
  14442. * @param {Object} [param.shape]
  14443. * @param {number} [param.shape.x]
  14444. * @param {number} [param.shape.y]
  14445. * @param {number} [param.shape.width]
  14446. * @param {number} [param.shape.height]
  14447. * @param {Object} [param.style]
  14448. * @param {number} [param.style.lineWidth]
  14449. * @return {Object} Modified param
  14450. */
  14451. function subPixelOptimizeRect(param) {
  14452. var shape = param.shape;
  14453. var lineWidth = param.style.lineWidth;
  14454. var originX = shape.x;
  14455. var originY = shape.y;
  14456. var originWidth = shape.width;
  14457. var originHeight = shape.height;
  14458. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  14459. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  14460. shape.width = Math.max(
  14461. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  14462. originWidth === 0 ? 0 : 1
  14463. );
  14464. shape.height = Math.max(
  14465. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  14466. originHeight === 0 ? 0 : 1
  14467. );
  14468. return param;
  14469. }
  14470. /**
  14471. * Sub pixel optimize for canvas
  14472. *
  14473. * @param {number} position Coordinate, such as x, y
  14474. * @param {number} lineWidth Should be nonnegative integer.
  14475. * @param {boolean=} positiveOrNegative Default false (negative).
  14476. * @return {number} Optimized position.
  14477. */
  14478. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14479. // Assure that (position + lineWidth / 2) is near integer edge,
  14480. // otherwise line will be fuzzy in canvas.
  14481. var doubledPosition = round(position * 2);
  14482. return (doubledPosition + round(lineWidth)) % 2 === 0
  14483. ? doubledPosition / 2
  14484. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14485. }
  14486. function hasFillOrStroke(fillOrStroke) {
  14487. return fillOrStroke != null && fillOrStroke !== 'none';
  14488. }
  14489. // Most lifted color are duplicated.
  14490. var liftedColorMap = createHashMap();
  14491. var liftedColorCount = 0;
  14492. function liftColor(color) {
  14493. if (typeof color !== 'string') {
  14494. return color;
  14495. }
  14496. var liftedColor = liftedColorMap.get(color);
  14497. if (!liftedColor) {
  14498. liftedColor = lift(color, -0.1);
  14499. if (liftedColorCount < 10000) {
  14500. liftedColorMap.set(color, liftedColor);
  14501. liftedColorCount++;
  14502. }
  14503. }
  14504. return liftedColor;
  14505. }
  14506. function cacheElementStl(el) {
  14507. if (!el.__hoverStlDirty) {
  14508. return;
  14509. }
  14510. el.__hoverStlDirty = false;
  14511. var hoverStyle = el.__hoverStl;
  14512. if (!hoverStyle) {
  14513. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14514. return;
  14515. }
  14516. var normalStyle = el.__cachedNormalStl = {};
  14517. el.__cachedNormalZ2 = el.z2;
  14518. var elStyle = el.style;
  14519. for (var name in hoverStyle) {
  14520. // See comment in `doSingleEnterHover`.
  14521. if (hoverStyle[name] != null) {
  14522. normalStyle[name] = elStyle[name];
  14523. }
  14524. }
  14525. // Always cache fill and stroke to normalStyle for lifting color.
  14526. normalStyle.fill = elStyle.fill;
  14527. normalStyle.stroke = elStyle.stroke;
  14528. }
  14529. function doSingleEnterHover(el) {
  14530. var hoverStl = el.__hoverStl;
  14531. if (!hoverStl || el.__highlighted) {
  14532. return;
  14533. }
  14534. var useHoverLayer = el.useHoverLayer;
  14535. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14536. var zr = el.__zr;
  14537. if (!zr && useHoverLayer) {
  14538. return;
  14539. }
  14540. var elTarget = el;
  14541. var targetStyle = el.style;
  14542. if (useHoverLayer) {
  14543. elTarget = zr.addHover(el);
  14544. targetStyle = elTarget.style;
  14545. }
  14546. rollbackDefaultTextStyle(targetStyle);
  14547. if (!useHoverLayer) {
  14548. cacheElementStl(elTarget);
  14549. }
  14550. // styles can be:
  14551. // {
  14552. // label: {
  14553. // show: false,
  14554. // position: 'outside',
  14555. // fontSize: 18
  14556. // },
  14557. // emphasis: {
  14558. // label: {
  14559. // show: true
  14560. // }
  14561. // }
  14562. // },
  14563. // where properties of `emphasis` may not appear in `normal`. We previously use
  14564. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14565. // But consider rich text and setOption in merge mode, it is impossible to cover
  14566. // all properties in merge. So we use merge mode when setting style here, where
  14567. // only properties that is not `null/undefined` can be set. The disadventage:
  14568. // null/undefined can not be used to remove style any more in `emphasis`.
  14569. targetStyle.extendFrom(hoverStl);
  14570. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14571. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14572. applyDefaultTextStyle(targetStyle);
  14573. if (!useHoverLayer) {
  14574. el.dirty(false);
  14575. el.z2 += Z2_EMPHASIS_LIFT;
  14576. }
  14577. }
  14578. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14579. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14580. targetStyle[prop] = liftColor(targetStyle[prop]);
  14581. }
  14582. }
  14583. function doSingleLeaveHover(el) {
  14584. var highlighted = el.__highlighted;
  14585. if (!highlighted) {
  14586. return;
  14587. }
  14588. el.__highlighted = false;
  14589. if (highlighted === 'layer') {
  14590. el.__zr && el.__zr.removeHover(el);
  14591. }
  14592. else if (highlighted) {
  14593. var style = el.style;
  14594. var normalStl = el.__cachedNormalStl;
  14595. if (normalStl) {
  14596. rollbackDefaultTextStyle(style);
  14597. // Consider null/undefined value, should use
  14598. // `setStyle` but not `extendFrom(stl, true)`.
  14599. el.setStyle(normalStl);
  14600. applyDefaultTextStyle(style);
  14601. }
  14602. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14603. // when `el` is on emphasis state. So here by comparing with 1, we try
  14604. // hard to make the bug case rare.
  14605. var normalZ2 = el.__cachedNormalZ2;
  14606. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14607. el.z2 = normalZ2;
  14608. }
  14609. }
  14610. }
  14611. function traverseCall(el, method) {
  14612. el.isGroup
  14613. ? el.traverse(function (child) {
  14614. !child.isGroup && method(child);
  14615. })
  14616. : method(el);
  14617. }
  14618. /**
  14619. * Set hover style (namely "emphasis style") of element, based on the current
  14620. * style of the given `el`.
  14621. * This method should be called after all of the normal styles have been adopted
  14622. * to the `el`. See the reason on `setHoverStyle`.
  14623. *
  14624. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14625. * @param {Object|boolean} [hoverStl] The specified hover style.
  14626. * If set as `false`, disable the hover style.
  14627. * Similarly, The `el.hoverStyle` can alse be set
  14628. * as `false` to disable the hover style.
  14629. * Otherwise, use the default hover style if not provided.
  14630. * @param {Object} [opt]
  14631. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`
  14632. */
  14633. function setElementHoverStyle(el, hoverStl) {
  14634. // For performance consideration, it might be better to make the "hover style" only the
  14635. // difference properties from the "normal style", but not a entire copy of all styles.
  14636. hoverStl = el.__hoverStl = hoverStl !== false && (hoverStl || {});
  14637. el.__hoverStlDirty = true;
  14638. // FIXME
  14639. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14640. // It probably should be saved on `data` of series. Consider the cases:
  14641. // (1) A highlighted elements are moved out of the view port and re-enter
  14642. // again by dataZoom.
  14643. // (2) call `setOption` and replace elements totally when they are highlighted.
  14644. if (el.__highlighted) {
  14645. // Consider the case:
  14646. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14647. // should be adapted to the `el`. Notice here new "normal styles" should have
  14648. // been set outside and the cached "normal style" is out of date.
  14649. el.__cachedNormalStl = null;
  14650. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14651. // of this method. In most cases, `z2` is not set and hover style should be able
  14652. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14653. // `doSingleLeaveHover` for details.
  14654. doSingleLeaveHover(el);
  14655. doSingleEnterHover(el);
  14656. }
  14657. }
  14658. /**
  14659. * Emphasis (called by API) has higher priority than `mouseover`.
  14660. * When element has been called to be entered emphasis, mouse over
  14661. * should not trigger the highlight effect (for example, animation
  14662. * scale) again, and `mouseout` should not downplay the highlight
  14663. * effect. So the listener of `mouseover` and `mouseout` should
  14664. * check `isInEmphasis`.
  14665. *
  14666. * @param {module:zrender/Element} el
  14667. * @return {boolean}
  14668. */
  14669. function isInEmphasis(el) {
  14670. return el && el.__isEmphasisEntered;
  14671. }
  14672. function onElementMouseOver(e) {
  14673. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14674. return;
  14675. }
  14676. // Only if element is not in emphasis status
  14677. !this.__isEmphasisEntered && traverseCall(this, doSingleEnterHover);
  14678. }
  14679. function onElementMouseOut(e) {
  14680. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14681. return;
  14682. }
  14683. // Only if element is not in emphasis status
  14684. !this.__isEmphasisEntered && traverseCall(this, doSingleLeaveHover);
  14685. }
  14686. function enterEmphasis() {
  14687. this.__isEmphasisEntered = true;
  14688. traverseCall(this, doSingleEnterHover);
  14689. }
  14690. function leaveEmphasis() {
  14691. this.__isEmphasisEntered = false;
  14692. traverseCall(this, doSingleLeaveHover);
  14693. }
  14694. /**
  14695. * Set hover style (namely "emphasis style") of element,
  14696. * based on the current style of the given `el`.
  14697. *
  14698. * (1)
  14699. * **CONSTRAINTS** for this method:
  14700. * <A> This method MUST be called after all of the normal styles having been adopted
  14701. * to the `el`.
  14702. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14703. * "normal style" having been set to the el.
  14704. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14705. * a default hover style).
  14706. *
  14707. * The reason: this method treat the current style of the `el` as the "normal style"
  14708. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14709. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14710. * logic, where the el should shift from the original emphasis style to the new
  14711. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14712. *
  14713. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14714. * not found a better solution yet to fit the backward compatibility, performance and
  14715. * the current programming style.
  14716. *
  14717. * (2)
  14718. * Call the method for a "root" element once. Do not call it for each descendants.
  14719. * If the descendants elemenets of a group has itself hover style different from the
  14720. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14721. * not call this method for them.
  14722. *
  14723. * @param {module:zrender/Element} el
  14724. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14725. * @param {Object} [opt]
  14726. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`.
  14727. */
  14728. function setHoverStyle(el, hoverStyle, opt) {
  14729. el.isGroup
  14730. ? el.traverse(function (child) {
  14731. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14732. // Often used when item group has a label element and it's hoverStyle is different
  14733. !child.isGroup && setElementHoverStyle(child, child.hoverStyle || hoverStyle);
  14734. })
  14735. : setElementHoverStyle(el, el.hoverStyle || hoverStyle);
  14736. setAsHoverStyleTrigger(el, opt);
  14737. }
  14738. /**
  14739. * @param {Object|boolean} [opt] If `false`, means disable trigger.
  14740. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14741. * In touch device, mouseover event will be trigger on touchstart event
  14742. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14743. * conveniently use hoverStyle when tap on touch screen without additional
  14744. * code for compatibility.
  14745. * But if the chart/component has select feature, which usually also use
  14746. * hoverStyle, there might be conflict between 'select-highlight' and
  14747. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14748. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14749. * on touch device.
  14750. */
  14751. function setAsHoverStyleTrigger(el, opt) {
  14752. var disable = opt === false;
  14753. el.__hoverSilentOnTouch = opt != null && opt.hoverSilentOnTouch;
  14754. // Simple optimize, since this method might be
  14755. // called for each elements of a group in some cases.
  14756. if (!disable || el.__hoverStyleTrigger) {
  14757. var method = disable ? 'off' : 'on';
  14758. // Duplicated function will be auto-ignored, see Eventful.js.
  14759. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14760. // Emphasis, normal can be triggered manually
  14761. el[method]('emphasis', enterEmphasis)[method]('normal', leaveEmphasis);
  14762. el.__hoverStyleTrigger = !disable;
  14763. }
  14764. }
  14765. /**
  14766. * See more info in `setTextStyleCommon`.
  14767. * @param {Object|module:zrender/graphic/Style} normalStyle
  14768. * @param {Object} emphasisStyle
  14769. * @param {module:echarts/model/Model} normalModel
  14770. * @param {module:echarts/model/Model} emphasisModel
  14771. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14772. * @param {string|Function} [opt.defaultText]
  14773. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14774. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14775. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14776. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14777. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14778. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14779. * @param {Object} [normalSpecified]
  14780. * @param {Object} [emphasisSpecified]
  14781. */
  14782. function setLabelStyle(
  14783. normalStyle, emphasisStyle,
  14784. normalModel, emphasisModel,
  14785. opt,
  14786. normalSpecified, emphasisSpecified
  14787. ) {
  14788. opt = opt || EMPTY_OBJ;
  14789. var labelFetcher = opt.labelFetcher;
  14790. var labelDataIndex = opt.labelDataIndex;
  14791. var labelDimIndex = opt.labelDimIndex;
  14792. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14793. // is not supported util someone requests.
  14794. var showNormal = normalModel.getShallow('show');
  14795. var showEmphasis = emphasisModel.getShallow('show');
  14796. // Consider performance, only fetch label when necessary.
  14797. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14798. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14799. var baseText;
  14800. if (showNormal || showEmphasis) {
  14801. if (labelFetcher) {
  14802. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14803. }
  14804. if (baseText == null) {
  14805. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14806. }
  14807. }
  14808. var normalStyleText = showNormal ? baseText : null;
  14809. var emphasisStyleText = showEmphasis
  14810. ? retrieve2(
  14811. labelFetcher
  14812. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14813. : null,
  14814. baseText
  14815. )
  14816. : null;
  14817. // Optimize: If style.text is null, text will not be drawn.
  14818. if (normalStyleText != null || emphasisStyleText != null) {
  14819. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14820. // values have to be set on `normalStyle`.
  14821. // If we set default values on `emphasisStyle`, consider case:
  14822. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14823. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14824. // Then the 'red' will not work on emphasis.
  14825. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14826. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14827. }
  14828. normalStyle.text = normalStyleText;
  14829. emphasisStyle.text = emphasisStyleText;
  14830. }
  14831. /**
  14832. * Set basic textStyle properties.
  14833. * See more info in `setTextStyleCommon`.
  14834. * @param {Object|module:zrender/graphic/Style} textStyle
  14835. * @param {module:echarts/model/Model} model
  14836. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14837. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14838. * @param {boolean} [isEmphasis]
  14839. */
  14840. function setTextStyle(
  14841. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14842. ) {
  14843. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14844. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14845. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14846. return textStyle;
  14847. }
  14848. /**
  14849. * Set text option in the style.
  14850. * See more info in `setTextStyleCommon`.
  14851. * @deprecated
  14852. * @param {Object} textStyle
  14853. * @param {module:echarts/model/Model} labelModel
  14854. * @param {string|boolean} defaultColor Default text color.
  14855. * If set as false, it will be processed as a emphasis style.
  14856. */
  14857. function setText(textStyle, labelModel, defaultColor) {
  14858. var opt = {isRectText: true};
  14859. var isEmphasis;
  14860. if (defaultColor === false) {
  14861. isEmphasis = true;
  14862. }
  14863. else {
  14864. // Support setting color as 'auto' to get visual color.
  14865. opt.autoColor = defaultColor;
  14866. }
  14867. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14868. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14869. }
  14870. /**
  14871. * The uniform entry of set text style, that is, retrieve style definitions
  14872. * from `model` and set to `textStyle` object.
  14873. *
  14874. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14875. * properties will be set. (Consider the states of normal and emphasis and
  14876. * default value can be adopted, merge would make the logic too complicated
  14877. * to manage.)
  14878. *
  14879. * The `textStyle` object can either be a plain object or an instance of
  14880. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14881. * After this mothod called, the `textStyle` object can then be used in
  14882. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14883. *
  14884. * Default value will be adopted and `insideRollbackOpt` will be created.
  14885. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14886. *
  14887. * opt: {
  14888. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14889. * isRectText: boolean,
  14890. * autoColor: string, specify a color when color is 'auto',
  14891. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14892. * If autoColor specified, it is used as default textFill.
  14893. * useInsideStyle:
  14894. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14895. * if `textFill` is not specified.
  14896. * `false`: Do not use inside style.
  14897. * `null/undefined`: use inside style if `isRectText` is true and
  14898. * `textFill` is not specified and textPosition contains `'inside'`.
  14899. * forceRich: boolean
  14900. * }
  14901. */
  14902. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14903. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14904. opt = opt || EMPTY_OBJ;
  14905. if (opt.isRectText) {
  14906. var textPosition = textStyleModel.getShallow('position')
  14907. || (isEmphasis ? null : 'inside');
  14908. // 'outside' is not a valid zr textPostion value, but used
  14909. // in bar series, and magric type should be considered.
  14910. textPosition === 'outside' && (textPosition = 'top');
  14911. textStyle.textPosition = textPosition;
  14912. textStyle.textOffset = textStyleModel.getShallow('offset');
  14913. var labelRotate = textStyleModel.getShallow('rotate');
  14914. labelRotate != null && (labelRotate *= Math.PI / 180);
  14915. textStyle.textRotation = labelRotate;
  14916. textStyle.textDistance = retrieve2(
  14917. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14918. );
  14919. }
  14920. var ecModel = textStyleModel.ecModel;
  14921. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14922. // Consider case:
  14923. // {
  14924. // data: [{
  14925. // value: 12,
  14926. // label: {
  14927. // rich: {
  14928. // // no 'a' here but using parent 'a'.
  14929. // }
  14930. // }
  14931. // }],
  14932. // rich: {
  14933. // a: { ... }
  14934. // }
  14935. // }
  14936. var richItemNames = getRichItemNames(textStyleModel);
  14937. var richResult;
  14938. if (richItemNames) {
  14939. richResult = {};
  14940. for (var name in richItemNames) {
  14941. if (richItemNames.hasOwnProperty(name)) {
  14942. // Cascade is supported in rich.
  14943. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14944. // In rich, never `disableBox`.
  14945. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14946. }
  14947. }
  14948. }
  14949. textStyle.rich = richResult;
  14950. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14951. if (opt.forceRich && !opt.textStyle) {
  14952. opt.textStyle = {};
  14953. }
  14954. return textStyle;
  14955. }
  14956. // Consider case:
  14957. // {
  14958. // data: [{
  14959. // value: 12,
  14960. // label: {
  14961. // rich: {
  14962. // // no 'a' here but using parent 'a'.
  14963. // }
  14964. // }
  14965. // }],
  14966. // rich: {
  14967. // a: { ... }
  14968. // }
  14969. // }
  14970. function getRichItemNames(textStyleModel) {
  14971. // Use object to remove duplicated names.
  14972. var richItemNameMap;
  14973. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14974. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14975. if (rich) {
  14976. richItemNameMap = richItemNameMap || {};
  14977. for (var name in rich) {
  14978. if (rich.hasOwnProperty(name)) {
  14979. richItemNameMap[name] = 1;
  14980. }
  14981. }
  14982. }
  14983. textStyleModel = textStyleModel.parentModel;
  14984. }
  14985. return richItemNameMap;
  14986. }
  14987. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14988. // In merge mode, default value should not be given.
  14989. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14990. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14991. || globalTextStyle.color;
  14992. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14993. || globalTextStyle.textBorderColor;
  14994. textStyle.textStrokeWidth = retrieve2(
  14995. textStyleModel.getShallow('textBorderWidth'),
  14996. globalTextStyle.textBorderWidth
  14997. );
  14998. // Save original textPosition, because style.textPosition will be repalced by
  14999. // real location (like [10, 30]) in zrender.
  15000. textStyle.insideRawTextPosition = textStyle.textPosition;
  15001. if (!isEmphasis) {
  15002. if (isBlock) {
  15003. textStyle.insideRollbackOpt = opt;
  15004. applyDefaultTextStyle(textStyle);
  15005. }
  15006. // Set default finally.
  15007. if (textStyle.textFill == null) {
  15008. textStyle.textFill = opt.autoColor;
  15009. }
  15010. }
  15011. // Do not use `getFont` here, because merge should be supported, where
  15012. // part of these properties may be changed in emphasis style, and the
  15013. // others should remain their original value got from normal style.
  15014. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15015. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15016. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15017. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15018. textStyle.textAlign = textStyleModel.getShallow('align');
  15019. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15020. || textStyleModel.getShallow('baseline');
  15021. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15022. textStyle.textWidth = textStyleModel.getShallow('width');
  15023. textStyle.textHeight = textStyleModel.getShallow('height');
  15024. textStyle.textTag = textStyleModel.getShallow('tag');
  15025. if (!isBlock || !opt.disableBox) {
  15026. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15027. textStyle.textPadding = textStyleModel.getShallow('padding');
  15028. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15029. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15030. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15031. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15032. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15033. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15034. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15035. }
  15036. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15037. || globalTextStyle.textShadowColor;
  15038. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15039. || globalTextStyle.textShadowBlur;
  15040. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15041. || globalTextStyle.textShadowOffsetX;
  15042. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15043. || globalTextStyle.textShadowOffsetY;
  15044. }
  15045. function getAutoColor(color, opt) {
  15046. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15047. }
  15048. /**
  15049. * Give some default value to the input `textStyle` object, based on the current settings
  15050. * in this `textStyle` object.
  15051. *
  15052. * The Scenario:
  15053. * when text position is `inside` and `textFill` is not specified, we show
  15054. * text border by default for better view. But it should be considered that text position
  15055. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15056. * restore the style.
  15057. *
  15058. * Usage (& NOTICE):
  15059. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15060. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15061. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15062. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15063. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15064. */
  15065. function applyDefaultTextStyle(textStyle) {
  15066. var opt = textStyle.insideRollbackOpt;
  15067. // Only `insideRollbackOpt` created (in `setTextStyleCommon`),
  15068. // applyDefaultTextStyle works.
  15069. if (!opt || textStyle.textFill != null) {
  15070. return;
  15071. }
  15072. var useInsideStyle = opt.useInsideStyle;
  15073. var textPosition = textStyle.insideRawTextPosition;
  15074. var insideRollback;
  15075. var autoColor = opt.autoColor;
  15076. if (useInsideStyle !== false
  15077. && (useInsideStyle === true
  15078. || (opt.isRectText
  15079. && textPosition
  15080. // textPosition can be [10, 30]
  15081. && typeof textPosition === 'string'
  15082. && textPosition.indexOf('inside') >= 0
  15083. )
  15084. )
  15085. ) {
  15086. insideRollback = {
  15087. textFill: null,
  15088. textStroke: textStyle.textStroke,
  15089. textStrokeWidth: textStyle.textStrokeWidth
  15090. };
  15091. textStyle.textFill = '#fff';
  15092. // Consider text with #fff overflow its container.
  15093. if (textStyle.textStroke == null) {
  15094. textStyle.textStroke = autoColor;
  15095. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15096. }
  15097. }
  15098. else if (autoColor != null) {
  15099. insideRollback = {textFill: null};
  15100. textStyle.textFill = autoColor;
  15101. }
  15102. // Always set `insideRollback`, for clearing previous.
  15103. if (insideRollback) {
  15104. textStyle.insideRollback = insideRollback;
  15105. }
  15106. }
  15107. /**
  15108. * Consider the case: in a scatter,
  15109. * label: {
  15110. * normal: {position: 'inside'},
  15111. * emphasis: {position: 'top'}
  15112. * }
  15113. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15114. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15115. * should be retured to 'autoColor', but not keep '#fff'.
  15116. */
  15117. function rollbackDefaultTextStyle(style) {
  15118. var insideRollback = style.insideRollback;
  15119. if (insideRollback) {
  15120. style.textFill = insideRollback.textFill;
  15121. style.textStroke = insideRollback.textStroke;
  15122. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15123. style.insideRollback = null;
  15124. }
  15125. }
  15126. function getFont(opt, ecModel) {
  15127. // ecModel or default text style model.
  15128. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  15129. return trim([
  15130. // FIXME in node-canvas fontWeight is before fontStyle
  15131. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15132. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15133. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15134. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15135. ].join(' '));
  15136. }
  15137. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15138. if (typeof dataIndex === 'function') {
  15139. cb = dataIndex;
  15140. dataIndex = null;
  15141. }
  15142. // Do not check 'animation' property directly here. Consider this case:
  15143. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15144. // but its parent model (`seriesModel`) does.
  15145. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15146. if (animationEnabled) {
  15147. var postfix = isUpdate ? 'Update' : '';
  15148. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15149. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15150. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15151. if (typeof animationDelay === 'function') {
  15152. animationDelay = animationDelay(
  15153. dataIndex,
  15154. animatableModel.getAnimationDelayParams
  15155. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15156. : null
  15157. );
  15158. }
  15159. if (typeof duration === 'function') {
  15160. duration = duration(dataIndex);
  15161. }
  15162. duration > 0
  15163. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15164. : (el.stopAnimation(), el.attr(props), cb && cb());
  15165. }
  15166. else {
  15167. el.stopAnimation();
  15168. el.attr(props);
  15169. cb && cb();
  15170. }
  15171. }
  15172. /**
  15173. * Update graphic element properties with or without animation according to the
  15174. * configuration in series.
  15175. *
  15176. * Caution: this method will stop previous animation.
  15177. * So if do not use this method to one element twice before
  15178. * animation starts, unless you know what you are doing.
  15179. *
  15180. * @param {module:zrender/Element} el
  15181. * @param {Object} props
  15182. * @param {module:echarts/model/Model} [animatableModel]
  15183. * @param {number} [dataIndex]
  15184. * @param {Function} [cb]
  15185. * @example
  15186. * graphic.updateProps(el, {
  15187. * position: [100, 100]
  15188. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15189. * // Or
  15190. * graphic.updateProps(el, {
  15191. * position: [100, 100]
  15192. * }, seriesModel, function () { console.log('Animation done!'); });
  15193. */
  15194. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15195. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15196. }
  15197. /**
  15198. * Init graphic element properties with or without animation according to the
  15199. * configuration in series.
  15200. *
  15201. * Caution: this method will stop previous animation.
  15202. * So if do not use this method to one element twice before
  15203. * animation starts, unless you know what you are doing.
  15204. *
  15205. * @param {module:zrender/Element} el
  15206. * @param {Object} props
  15207. * @param {module:echarts/model/Model} [animatableModel]
  15208. * @param {number} [dataIndex]
  15209. * @param {Function} cb
  15210. */
  15211. function initProps(el, props, animatableModel, dataIndex, cb) {
  15212. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15213. }
  15214. /**
  15215. * Get transform matrix of target (param target),
  15216. * in coordinate of its ancestor (param ancestor)
  15217. *
  15218. * @param {module:zrender/mixin/Transformable} target
  15219. * @param {module:zrender/mixin/Transformable} [ancestor]
  15220. */
  15221. function getTransform(target, ancestor) {
  15222. var mat = identity([]);
  15223. while (target && target !== ancestor) {
  15224. mul$1(mat, target.getLocalTransform(), mat);
  15225. target = target.parent;
  15226. }
  15227. return mat;
  15228. }
  15229. /**
  15230. * Apply transform to an vertex.
  15231. * @param {Array.<number>} target [x, y]
  15232. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15233. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15234. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15235. * @param {boolean=} invert Whether use invert matrix.
  15236. * @return {Array.<number>} [x, y]
  15237. */
  15238. function applyTransform$1(target, transform, invert$$1) {
  15239. if (transform && !isArrayLike(transform)) {
  15240. transform = Transformable.getLocalTransform(transform);
  15241. }
  15242. if (invert$$1) {
  15243. transform = invert([], transform);
  15244. }
  15245. return applyTransform([], target, transform);
  15246. }
  15247. /**
  15248. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15249. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15250. * @param {boolean=} invert Whether use invert matrix.
  15251. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15252. */
  15253. function transformDirection(direction, transform, invert$$1) {
  15254. // Pick a base, ensure that transform result will not be (0, 0).
  15255. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15256. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15257. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15258. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15259. var vertex = [
  15260. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15261. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15262. ];
  15263. vertex = applyTransform$1(vertex, transform, invert$$1);
  15264. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15265. ? (vertex[0] > 0 ? 'right' : 'left')
  15266. : (vertex[1] > 0 ? 'bottom' : 'top');
  15267. }
  15268. /**
  15269. * Apply group transition animation from g1 to g2.
  15270. * If no animatableModel, no animation.
  15271. */
  15272. function groupTransition(g1, g2, animatableModel, cb) {
  15273. if (!g1 || !g2) {
  15274. return;
  15275. }
  15276. function getElMap(g) {
  15277. var elMap = {};
  15278. g.traverse(function (el) {
  15279. if (!el.isGroup && el.anid) {
  15280. elMap[el.anid] = el;
  15281. }
  15282. });
  15283. return elMap;
  15284. }
  15285. function getAnimatableProps(el) {
  15286. var obj = {
  15287. position: clone$1(el.position),
  15288. rotation: el.rotation
  15289. };
  15290. if (el.shape) {
  15291. obj.shape = extend({}, el.shape);
  15292. }
  15293. return obj;
  15294. }
  15295. var elMap1 = getElMap(g1);
  15296. g2.traverse(function (el) {
  15297. if (!el.isGroup && el.anid) {
  15298. var oldEl = elMap1[el.anid];
  15299. if (oldEl) {
  15300. var newProp = getAnimatableProps(el);
  15301. el.attr(getAnimatableProps(oldEl));
  15302. updateProps(el, newProp, animatableModel, el.dataIndex);
  15303. }
  15304. // else {
  15305. // if (el.previousProps) {
  15306. // graphic.updateProps
  15307. // }
  15308. // }
  15309. }
  15310. });
  15311. }
  15312. /**
  15313. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15314. * @param {Object} rect {x, y, width, height}
  15315. * @return {Array.<Array.<number>>} A new clipped points.
  15316. */
  15317. function clipPointsByRect(points, rect) {
  15318. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15319. // and when element have border.
  15320. return map(points, function (point) {
  15321. var x = point[0];
  15322. x = mathMax$1(x, rect.x);
  15323. x = mathMin$1(x, rect.x + rect.width);
  15324. var y = point[1];
  15325. y = mathMax$1(y, rect.y);
  15326. y = mathMin$1(y, rect.y + rect.height);
  15327. return [x, y];
  15328. });
  15329. }
  15330. /**
  15331. * @param {Object} targetRect {x, y, width, height}
  15332. * @param {Object} rect {x, y, width, height}
  15333. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15334. */
  15335. function clipRectByRect(targetRect, rect) {
  15336. var x = mathMax$1(targetRect.x, rect.x);
  15337. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15338. var y = mathMax$1(targetRect.y, rect.y);
  15339. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15340. // If the total rect is cliped, nothing, including the border,
  15341. // should be painted. So return undefined.
  15342. if (x2 >= x && y2 >= y) {
  15343. return {
  15344. x: x,
  15345. y: y,
  15346. width: x2 - x,
  15347. height: y2 - y
  15348. };
  15349. }
  15350. }
  15351. /**
  15352. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15353. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15354. * @param {Object} [rect] {x, y, width, height}
  15355. * @return {module:zrender/Element} Icon path or image element.
  15356. */
  15357. function createIcon(iconStr, opt, rect) {
  15358. opt = extend({rectHover: true}, opt);
  15359. var style = opt.style = {strokeNoScale: true};
  15360. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15361. if (iconStr) {
  15362. return iconStr.indexOf('image://') === 0
  15363. ? (
  15364. style.image = iconStr.slice(8),
  15365. defaults(style, rect),
  15366. new ZImage(opt)
  15367. )
  15368. : (
  15369. makePath(
  15370. iconStr.replace('path://', ''),
  15371. opt,
  15372. rect,
  15373. 'center'
  15374. )
  15375. );
  15376. }
  15377. }
  15378. var graphic = (Object.freeze || Object)({
  15379. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15380. extendShape: extendShape,
  15381. extendPath: extendPath,
  15382. makePath: makePath,
  15383. makeImage: makeImage,
  15384. mergePath: mergePath,
  15385. resizePath: resizePath,
  15386. subPixelOptimizeLine: subPixelOptimizeLine,
  15387. subPixelOptimizeRect: subPixelOptimizeRect,
  15388. subPixelOptimize: subPixelOptimize,
  15389. setElementHoverStyle: setElementHoverStyle,
  15390. isInEmphasis: isInEmphasis,
  15391. setHoverStyle: setHoverStyle,
  15392. setAsHoverStyleTrigger: setAsHoverStyleTrigger,
  15393. setLabelStyle: setLabelStyle,
  15394. setTextStyle: setTextStyle,
  15395. setText: setText,
  15396. getFont: getFont,
  15397. updateProps: updateProps,
  15398. initProps: initProps,
  15399. getTransform: getTransform,
  15400. applyTransform: applyTransform$1,
  15401. transformDirection: transformDirection,
  15402. groupTransition: groupTransition,
  15403. clipPointsByRect: clipPointsByRect,
  15404. clipRectByRect: clipRectByRect,
  15405. createIcon: createIcon,
  15406. Group: Group,
  15407. Image: ZImage,
  15408. Text: Text,
  15409. Circle: Circle,
  15410. Sector: Sector,
  15411. Ring: Ring,
  15412. Polygon: Polygon,
  15413. Polyline: Polyline,
  15414. Rect: Rect,
  15415. Line: Line,
  15416. BezierCurve: BezierCurve,
  15417. Arc: Arc,
  15418. IncrementalDisplayable: IncrementalDisplayble,
  15419. CompoundPath: CompoundPath,
  15420. LinearGradient: LinearGradient,
  15421. RadialGradient: RadialGradient,
  15422. BoundingRect: BoundingRect
  15423. });
  15424. /*
  15425. * Licensed to the Apache Software Foundation (ASF) under one
  15426. * or more contributor license agreements. See the NOTICE file
  15427. * distributed with this work for additional information
  15428. * regarding copyright ownership. The ASF licenses this file
  15429. * to you under the Apache License, Version 2.0 (the
  15430. * "License"); you may not use this file except in compliance
  15431. * with the License. You may obtain a copy of the License at
  15432. *
  15433. * http://www.apache.org/licenses/LICENSE-2.0
  15434. *
  15435. * Unless required by applicable law or agreed to in writing,
  15436. * software distributed under the License is distributed on an
  15437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15438. * KIND, either express or implied. See the License for the
  15439. * specific language governing permissions and limitations
  15440. * under the License.
  15441. */
  15442. var PATH_COLOR = ['textStyle', 'color'];
  15443. var textStyleMixin = {
  15444. /**
  15445. * Get color property or get color from option.textStyle.color
  15446. * @param {boolean} [isEmphasis]
  15447. * @return {string}
  15448. */
  15449. getTextColor: function (isEmphasis) {
  15450. var ecModel = this.ecModel;
  15451. return this.getShallow('color')
  15452. || (
  15453. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15454. );
  15455. },
  15456. /**
  15457. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15458. * @return {string}
  15459. */
  15460. getFont: function () {
  15461. return getFont({
  15462. fontStyle: this.getShallow('fontStyle'),
  15463. fontWeight: this.getShallow('fontWeight'),
  15464. fontSize: this.getShallow('fontSize'),
  15465. fontFamily: this.getShallow('fontFamily')
  15466. }, this.ecModel);
  15467. },
  15468. getTextRect: function (text) {
  15469. return getBoundingRect(
  15470. text,
  15471. this.getFont(),
  15472. this.getShallow('align'),
  15473. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15474. this.getShallow('padding'),
  15475. this.getShallow('rich'),
  15476. this.getShallow('truncateText')
  15477. );
  15478. }
  15479. };
  15480. /*
  15481. * Licensed to the Apache Software Foundation (ASF) under one
  15482. * or more contributor license agreements. See the NOTICE file
  15483. * distributed with this work for additional information
  15484. * regarding copyright ownership. The ASF licenses this file
  15485. * to you under the Apache License, Version 2.0 (the
  15486. * "License"); you may not use this file except in compliance
  15487. * with the License. You may obtain a copy of the License at
  15488. *
  15489. * http://www.apache.org/licenses/LICENSE-2.0
  15490. *
  15491. * Unless required by applicable law or agreed to in writing,
  15492. * software distributed under the License is distributed on an
  15493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15494. * KIND, either express or implied. See the License for the
  15495. * specific language governing permissions and limitations
  15496. * under the License.
  15497. */
  15498. var getItemStyle = makeStyleMapper(
  15499. [
  15500. ['fill', 'color'],
  15501. ['stroke', 'borderColor'],
  15502. ['lineWidth', 'borderWidth'],
  15503. ['opacity'],
  15504. ['shadowBlur'],
  15505. ['shadowOffsetX'],
  15506. ['shadowOffsetY'],
  15507. ['shadowColor'],
  15508. ['textPosition'],
  15509. ['textAlign']
  15510. ]
  15511. );
  15512. var itemStyleMixin = {
  15513. getItemStyle: function (excludes, includes) {
  15514. var style = getItemStyle(this, excludes, includes);
  15515. var lineDash = this.getBorderLineDash();
  15516. lineDash && (style.lineDash = lineDash);
  15517. return style;
  15518. },
  15519. getBorderLineDash: function () {
  15520. var lineType = this.get('borderType');
  15521. return (lineType === 'solid' || lineType == null) ? null
  15522. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15523. }
  15524. };
  15525. /*
  15526. * Licensed to the Apache Software Foundation (ASF) under one
  15527. * or more contributor license agreements. See the NOTICE file
  15528. * distributed with this work for additional information
  15529. * regarding copyright ownership. The ASF licenses this file
  15530. * to you under the Apache License, Version 2.0 (the
  15531. * "License"); you may not use this file except in compliance
  15532. * with the License. You may obtain a copy of the License at
  15533. *
  15534. * http://www.apache.org/licenses/LICENSE-2.0
  15535. *
  15536. * Unless required by applicable law or agreed to in writing,
  15537. * software distributed under the License is distributed on an
  15538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15539. * KIND, either express or implied. See the License for the
  15540. * specific language governing permissions and limitations
  15541. * under the License.
  15542. */
  15543. /**
  15544. * @module echarts/model/Model
  15545. */
  15546. var mixin$1 = mixin;
  15547. var inner = makeInner();
  15548. /**
  15549. * @alias module:echarts/model/Model
  15550. * @constructor
  15551. * @param {Object} [option]
  15552. * @param {module:echarts/model/Model} [parentModel]
  15553. * @param {module:echarts/model/Global} [ecModel]
  15554. */
  15555. function Model(option, parentModel, ecModel) {
  15556. /**
  15557. * @type {module:echarts/model/Model}
  15558. * @readOnly
  15559. */
  15560. this.parentModel = parentModel;
  15561. /**
  15562. * @type {module:echarts/model/Global}
  15563. * @readOnly
  15564. */
  15565. this.ecModel = ecModel;
  15566. /**
  15567. * @type {Object}
  15568. * @protected
  15569. */
  15570. this.option = option;
  15571. // Simple optimization
  15572. // if (this.init) {
  15573. // if (arguments.length <= 4) {
  15574. // this.init(option, parentModel, ecModel, extraOpt);
  15575. // }
  15576. // else {
  15577. // this.init.apply(this, arguments);
  15578. // }
  15579. // }
  15580. }
  15581. Model.prototype = {
  15582. constructor: Model,
  15583. /**
  15584. * Model 的初始化函数
  15585. * @param {Object} option
  15586. */
  15587. init: null,
  15588. /**
  15589. * 从新的 Option merge
  15590. */
  15591. mergeOption: function (option) {
  15592. merge(this.option, option, true);
  15593. },
  15594. /**
  15595. * @param {string|Array.<string>} path
  15596. * @param {boolean} [ignoreParent=false]
  15597. * @return {*}
  15598. */
  15599. get: function (path, ignoreParent) {
  15600. if (path == null) {
  15601. return this.option;
  15602. }
  15603. return doGet(
  15604. this.option,
  15605. this.parsePath(path),
  15606. !ignoreParent && getParent(this, path)
  15607. );
  15608. },
  15609. /**
  15610. * @param {string} key
  15611. * @param {boolean} [ignoreParent=false]
  15612. * @return {*}
  15613. */
  15614. getShallow: function (key, ignoreParent) {
  15615. var option = this.option;
  15616. var val = option == null ? option : option[key];
  15617. var parentModel = !ignoreParent && getParent(this, key);
  15618. if (val == null && parentModel) {
  15619. val = parentModel.getShallow(key);
  15620. }
  15621. return val;
  15622. },
  15623. /**
  15624. * @param {string|Array.<string>} [path]
  15625. * @param {module:echarts/model/Model} [parentModel]
  15626. * @return {module:echarts/model/Model}
  15627. */
  15628. getModel: function (path, parentModel) {
  15629. var obj = path == null
  15630. ? this.option
  15631. : doGet(this.option, path = this.parsePath(path));
  15632. var thisParentModel;
  15633. parentModel = parentModel || (
  15634. (thisParentModel = getParent(this, path))
  15635. && thisParentModel.getModel(path)
  15636. );
  15637. return new Model(obj, parentModel, this.ecModel);
  15638. },
  15639. /**
  15640. * If model has option
  15641. */
  15642. isEmpty: function () {
  15643. return this.option == null;
  15644. },
  15645. restoreData: function () {},
  15646. // Pending
  15647. clone: function () {
  15648. var Ctor = this.constructor;
  15649. return new Ctor(clone(this.option));
  15650. },
  15651. setReadOnly: function (properties) {
  15652. // clazzUtil.setReadOnly(this, properties);
  15653. },
  15654. // If path is null/undefined, return null/undefined.
  15655. parsePath: function (path) {
  15656. if (typeof path === 'string') {
  15657. path = path.split('.');
  15658. }
  15659. return path;
  15660. },
  15661. /**
  15662. * @param {Function} getParentMethod
  15663. * param {Array.<string>|string} path
  15664. * return {module:echarts/model/Model}
  15665. */
  15666. customizeGetParent: function (getParentMethod) {
  15667. inner(this).getParent = getParentMethod;
  15668. },
  15669. isAnimationEnabled: function () {
  15670. if (!env$1.node) {
  15671. if (this.option.animation != null) {
  15672. return !!this.option.animation;
  15673. }
  15674. else if (this.parentModel) {
  15675. return this.parentModel.isAnimationEnabled();
  15676. }
  15677. }
  15678. }
  15679. };
  15680. function doGet(obj, pathArr, parentModel) {
  15681. for (var i = 0; i < pathArr.length; i++) {
  15682. // Ignore empty
  15683. if (!pathArr[i]) {
  15684. continue;
  15685. }
  15686. // obj could be number/string/... (like 0)
  15687. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15688. if (obj == null) {
  15689. break;
  15690. }
  15691. }
  15692. if (obj == null && parentModel) {
  15693. obj = parentModel.get(pathArr);
  15694. }
  15695. return obj;
  15696. }
  15697. // `path` can be null/undefined
  15698. function getParent(model, path) {
  15699. var getParentMethod = inner(model).getParent;
  15700. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15701. }
  15702. // Enable Model.extend.
  15703. enableClassExtend(Model);
  15704. enableClassCheck(Model);
  15705. mixin$1(Model, lineStyleMixin);
  15706. mixin$1(Model, areaStyleMixin);
  15707. mixin$1(Model, textStyleMixin);
  15708. mixin$1(Model, itemStyleMixin);
  15709. /*
  15710. * Licensed to the Apache Software Foundation (ASF) under one
  15711. * or more contributor license agreements. See the NOTICE file
  15712. * distributed with this work for additional information
  15713. * regarding copyright ownership. The ASF licenses this file
  15714. * to you under the Apache License, Version 2.0 (the
  15715. * "License"); you may not use this file except in compliance
  15716. * with the License. You may obtain a copy of the License at
  15717. *
  15718. * http://www.apache.org/licenses/LICENSE-2.0
  15719. *
  15720. * Unless required by applicable law or agreed to in writing,
  15721. * software distributed under the License is distributed on an
  15722. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15723. * KIND, either express or implied. See the License for the
  15724. * specific language governing permissions and limitations
  15725. * under the License.
  15726. */
  15727. var base = 0;
  15728. /**
  15729. * @public
  15730. * @param {string} type
  15731. * @return {string}
  15732. */
  15733. function getUID(type) {
  15734. // Considering the case of crossing js context,
  15735. // use Math.random to make id as unique as possible.
  15736. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15737. }
  15738. /**
  15739. * @inner
  15740. */
  15741. function enableSubTypeDefaulter(entity) {
  15742. var subTypeDefaulters = {};
  15743. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15744. componentType = parseClassType$1(componentType);
  15745. subTypeDefaulters[componentType.main] = defaulter;
  15746. };
  15747. entity.determineSubType = function (componentType, option) {
  15748. var type = option.type;
  15749. if (!type) {
  15750. var componentTypeMain = parseClassType$1(componentType).main;
  15751. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15752. type = subTypeDefaulters[componentTypeMain](option);
  15753. }
  15754. }
  15755. return type;
  15756. };
  15757. return entity;
  15758. }
  15759. /**
  15760. * Topological travel on Activity Network (Activity On Vertices).
  15761. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15762. *
  15763. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15764. *
  15765. * If there is circle dependencey, Error will be thrown.
  15766. *
  15767. */
  15768. function enableTopologicalTravel(entity, dependencyGetter) {
  15769. /**
  15770. * @public
  15771. * @param {Array.<string>} targetNameList Target Component type list.
  15772. * Can be ['aa', 'bb', 'aa.xx']
  15773. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15774. * @param {Function} callback Params: componentType, dependencies.
  15775. * @param {Object} context Scope of callback.
  15776. */
  15777. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15778. if (!targetNameList.length) {
  15779. return;
  15780. }
  15781. var result = makeDepndencyGraph(fullNameList);
  15782. var graph = result.graph;
  15783. var stack = result.noEntryList;
  15784. var targetNameSet = {};
  15785. each$1(targetNameList, function (name) {
  15786. targetNameSet[name] = true;
  15787. });
  15788. while (stack.length) {
  15789. var currComponentType = stack.pop();
  15790. var currVertex = graph[currComponentType];
  15791. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15792. if (isInTargetNameSet) {
  15793. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15794. delete targetNameSet[currComponentType];
  15795. }
  15796. each$1(
  15797. currVertex.successor,
  15798. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15799. );
  15800. }
  15801. each$1(targetNameSet, function () {
  15802. throw new Error('Circle dependency may exists');
  15803. });
  15804. function removeEdge(succComponentType) {
  15805. graph[succComponentType].entryCount--;
  15806. if (graph[succComponentType].entryCount === 0) {
  15807. stack.push(succComponentType);
  15808. }
  15809. }
  15810. // Consider this case: legend depends on series, and we call
  15811. // chart.setOption({series: [...]}), where only series is in option.
  15812. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15813. // not be called, but only sereis.mergeOption is called. Thus legend
  15814. // have no chance to update its local record about series (like which
  15815. // name of series is available in legend).
  15816. function removeEdgeAndAdd(succComponentType) {
  15817. targetNameSet[succComponentType] = true;
  15818. removeEdge(succComponentType);
  15819. }
  15820. };
  15821. /**
  15822. * DepndencyGraph: {Object}
  15823. * key: conponentType,
  15824. * value: {
  15825. * successor: [conponentTypes...],
  15826. * originalDeps: [conponentTypes...],
  15827. * entryCount: {number}
  15828. * }
  15829. */
  15830. function makeDepndencyGraph(fullNameList) {
  15831. var graph = {};
  15832. var noEntryList = [];
  15833. each$1(fullNameList, function (name) {
  15834. var thisItem = createDependencyGraphItem(graph, name);
  15835. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15836. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15837. thisItem.entryCount = availableDeps.length;
  15838. if (thisItem.entryCount === 0) {
  15839. noEntryList.push(name);
  15840. }
  15841. each$1(availableDeps, function (dependentName) {
  15842. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15843. thisItem.predecessor.push(dependentName);
  15844. }
  15845. var thatItem = createDependencyGraphItem(graph, dependentName);
  15846. if (indexOf(thatItem.successor, dependentName) < 0) {
  15847. thatItem.successor.push(name);
  15848. }
  15849. });
  15850. });
  15851. return {graph: graph, noEntryList: noEntryList};
  15852. }
  15853. function createDependencyGraphItem(graph, name) {
  15854. if (!graph[name]) {
  15855. graph[name] = {predecessor: [], successor: []};
  15856. }
  15857. return graph[name];
  15858. }
  15859. function getAvailableDependencies(originalDeps, fullNameList) {
  15860. var availableDeps = [];
  15861. each$1(originalDeps, function (dep) {
  15862. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15863. });
  15864. return availableDeps;
  15865. }
  15866. }
  15867. /*
  15868. * Licensed to the Apache Software Foundation (ASF) under one
  15869. * or more contributor license agreements. See the NOTICE file
  15870. * distributed with this work for additional information
  15871. * regarding copyright ownership. The ASF licenses this file
  15872. * to you under the Apache License, Version 2.0 (the
  15873. * "License"); you may not use this file except in compliance
  15874. * with the License. You may obtain a copy of the License at
  15875. *
  15876. * http://www.apache.org/licenses/LICENSE-2.0
  15877. *
  15878. * Unless required by applicable law or agreed to in writing,
  15879. * software distributed under the License is distributed on an
  15880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15881. * KIND, either express or implied. See the License for the
  15882. * specific language governing permissions and limitations
  15883. * under the License.
  15884. */
  15885. var RADIAN_EPSILON = 1e-4;
  15886. function _trim(str) {
  15887. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15888. }
  15889. /**
  15890. * Linear mapping a value from domain to range
  15891. * @memberOf module:echarts/util/number
  15892. * @param {(number|Array.<number>)} val
  15893. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15894. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15895. * @param {boolean} clamp
  15896. * @return {(number|Array.<number>}
  15897. */
  15898. function linearMap(val, domain, range, clamp) {
  15899. var subDomain = domain[1] - domain[0];
  15900. var subRange = range[1] - range[0];
  15901. if (subDomain === 0) {
  15902. return subRange === 0
  15903. ? range[0]
  15904. : (range[0] + range[1]) / 2;
  15905. }
  15906. // Avoid accuracy problem in edge, such as
  15907. // 146.39 - 62.83 === 83.55999999999999.
  15908. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15909. // It is a little verbose for efficiency considering this method
  15910. // is a hotspot.
  15911. if (clamp) {
  15912. if (subDomain > 0) {
  15913. if (val <= domain[0]) {
  15914. return range[0];
  15915. }
  15916. else if (val >= domain[1]) {
  15917. return range[1];
  15918. }
  15919. }
  15920. else {
  15921. if (val >= domain[0]) {
  15922. return range[0];
  15923. }
  15924. else if (val <= domain[1]) {
  15925. return range[1];
  15926. }
  15927. }
  15928. }
  15929. else {
  15930. if (val === domain[0]) {
  15931. return range[0];
  15932. }
  15933. if (val === domain[1]) {
  15934. return range[1];
  15935. }
  15936. }
  15937. return (val - domain[0]) / subDomain * subRange + range[0];
  15938. }
  15939. /**
  15940. * Convert a percent string to absolute number.
  15941. * Returns NaN if percent is not a valid string or number
  15942. * @memberOf module:echarts/util/number
  15943. * @param {string|number} percent
  15944. * @param {number} all
  15945. * @return {number}
  15946. */
  15947. function parsePercent$1(percent, all) {
  15948. switch (percent) {
  15949. case 'center':
  15950. case 'middle':
  15951. percent = '50%';
  15952. break;
  15953. case 'left':
  15954. case 'top':
  15955. percent = '0%';
  15956. break;
  15957. case 'right':
  15958. case 'bottom':
  15959. percent = '100%';
  15960. break;
  15961. }
  15962. if (typeof percent === 'string') {
  15963. if (_trim(percent).match(/%$/)) {
  15964. return parseFloat(percent) / 100 * all;
  15965. }
  15966. return parseFloat(percent);
  15967. }
  15968. return percent == null ? NaN : +percent;
  15969. }
  15970. /**
  15971. * (1) Fix rounding error of float numbers.
  15972. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15973. *
  15974. * @param {number} x
  15975. * @param {number} [precision]
  15976. * @param {boolean} [returnStr]
  15977. * @return {number|string}
  15978. */
  15979. function round$2(x, precision, returnStr) {
  15980. if (precision == null) {
  15981. precision = 10;
  15982. }
  15983. // Avoid range error
  15984. precision = Math.min(Math.max(0, precision), 20);
  15985. x = (+x).toFixed(precision);
  15986. return returnStr ? x : +x;
  15987. }
  15988. function asc(arr) {
  15989. arr.sort(function (a, b) {
  15990. return a - b;
  15991. });
  15992. return arr;
  15993. }
  15994. /**
  15995. * Get precision
  15996. * @param {number} val
  15997. */
  15998. function getPrecision(val) {
  15999. val = +val;
  16000. if (isNaN(val)) {
  16001. return 0;
  16002. }
  16003. // It is much faster than methods converting number to string as follows
  16004. // var tmp = val.toString();
  16005. // return tmp.length - 1 - tmp.indexOf('.');
  16006. // especially when precision is low
  16007. var e = 1;
  16008. var count = 0;
  16009. while (Math.round(val * e) / e !== val) {
  16010. e *= 10;
  16011. count++;
  16012. }
  16013. return count;
  16014. }
  16015. /**
  16016. * @param {string|number} val
  16017. * @return {number}
  16018. */
  16019. function getPrecisionSafe(val) {
  16020. var str = val.toString();
  16021. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16022. var eIndex = str.indexOf('e');
  16023. if (eIndex > 0) {
  16024. var precision = +str.slice(eIndex + 1);
  16025. return precision < 0 ? -precision : 0;
  16026. }
  16027. else {
  16028. var dotIndex = str.indexOf('.');
  16029. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16030. }
  16031. }
  16032. /**
  16033. * Minimal dicernible data precisioin according to a single pixel.
  16034. *
  16035. * @param {Array.<number>} dataExtent
  16036. * @param {Array.<number>} pixelExtent
  16037. * @return {number} precision
  16038. */
  16039. function getPixelPrecision(dataExtent, pixelExtent) {
  16040. var log = Math.log;
  16041. var LN10 = Math.LN10;
  16042. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16043. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16044. // toFixed() digits argument must be between 0 and 20.
  16045. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16046. return !isFinite(precision) ? 20 : precision;
  16047. }
  16048. /**
  16049. * Get a data of given precision, assuring the sum of percentages
  16050. * in valueList is 1.
  16051. * The largest remainer method is used.
  16052. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16053. *
  16054. * @param {Array.<number>} valueList a list of all data
  16055. * @param {number} idx index of the data to be processed in valueList
  16056. * @param {number} precision integer number showing digits of precision
  16057. * @return {number} percent ranging from 0 to 100
  16058. */
  16059. function getPercentWithPrecision(valueList, idx, precision) {
  16060. if (!valueList[idx]) {
  16061. return 0;
  16062. }
  16063. var sum = reduce(valueList, function (acc, val) {
  16064. return acc + (isNaN(val) ? 0 : val);
  16065. }, 0);
  16066. if (sum === 0) {
  16067. return 0;
  16068. }
  16069. var digits = Math.pow(10, precision);
  16070. var votesPerQuota = map(valueList, function (val) {
  16071. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16072. });
  16073. var targetSeats = digits * 100;
  16074. var seats = map(votesPerQuota, function (votes) {
  16075. // Assign automatic seats.
  16076. return Math.floor(votes);
  16077. });
  16078. var currentSum = reduce(seats, function (acc, val) {
  16079. return acc + val;
  16080. }, 0);
  16081. var remainder = map(votesPerQuota, function (votes, idx) {
  16082. return votes - seats[idx];
  16083. });
  16084. // Has remainding votes.
  16085. while (currentSum < targetSeats) {
  16086. // Find next largest remainder.
  16087. var max = Number.NEGATIVE_INFINITY;
  16088. var maxId = null;
  16089. for (var i = 0, len = remainder.length; i < len; ++i) {
  16090. if (remainder[i] > max) {
  16091. max = remainder[i];
  16092. maxId = i;
  16093. }
  16094. }
  16095. // Add a vote to max remainder.
  16096. ++seats[maxId];
  16097. remainder[maxId] = 0;
  16098. ++currentSum;
  16099. }
  16100. return seats[idx] / digits;
  16101. }
  16102. // Number.MAX_SAFE_INTEGER, ie do not support.
  16103. var MAX_SAFE_INTEGER = 9007199254740991;
  16104. /**
  16105. * To 0 - 2 * PI, considering negative radian.
  16106. * @param {number} radian
  16107. * @return {number}
  16108. */
  16109. function remRadian(radian) {
  16110. var pi2 = Math.PI * 2;
  16111. return (radian % pi2 + pi2) % pi2;
  16112. }
  16113. /**
  16114. * @param {type} radian
  16115. * @return {boolean}
  16116. */
  16117. function isRadianAroundZero(val) {
  16118. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16119. }
  16120. /* eslint-disable */
  16121. 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
  16122. /* eslint-enable */
  16123. /**
  16124. * @param {string|Date|number} value These values can be accepted:
  16125. * + An instance of Date, represent a time in its own time zone.
  16126. * + Or string in a subset of ISO 8601, only including:
  16127. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16128. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16129. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16130. * all of which will be treated as local time if time zone is not specified
  16131. * (see <https://momentjs.com/>).
  16132. * + Or other string format, including (all of which will be treated as loacal time):
  16133. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16134. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16135. * + a timestamp, which represent a time in UTC.
  16136. * @return {Date} date
  16137. */
  16138. function parseDate(value) {
  16139. if (value instanceof Date) {
  16140. return value;
  16141. }
  16142. else if (typeof value === 'string') {
  16143. // Different browsers parse date in different way, so we parse it manually.
  16144. // Some other issues:
  16145. // new Date('1970-01-01') is UTC,
  16146. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16147. // See issue #3623
  16148. var match = TIME_REG.exec(value);
  16149. if (!match) {
  16150. // return Invalid Date.
  16151. return new Date(NaN);
  16152. }
  16153. // Use local time when no timezone offset specifed.
  16154. if (!match[8]) {
  16155. // match[n] can only be string or undefined.
  16156. // But take care of '12' + 1 => '121'.
  16157. return new Date(
  16158. +match[1],
  16159. +(match[2] || 1) - 1,
  16160. +match[3] || 1,
  16161. +match[4] || 0,
  16162. +(match[5] || 0),
  16163. +match[6] || 0,
  16164. +match[7] || 0
  16165. );
  16166. }
  16167. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16168. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16169. // For example, system timezone is set as "Time Zone: America/Toronto",
  16170. // then these code will get different result:
  16171. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16172. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16173. // So we should not use `new Date`, but use `Date.UTC`.
  16174. else {
  16175. var hour = +match[4] || 0;
  16176. if (match[8].toUpperCase() !== 'Z') {
  16177. hour -= match[8].slice(0, 3);
  16178. }
  16179. return new Date(Date.UTC(
  16180. +match[1],
  16181. +(match[2] || 1) - 1,
  16182. +match[3] || 1,
  16183. hour,
  16184. +(match[5] || 0),
  16185. +match[6] || 0,
  16186. +match[7] || 0
  16187. ));
  16188. }
  16189. }
  16190. else if (value == null) {
  16191. return new Date(NaN);
  16192. }
  16193. return new Date(Math.round(value));
  16194. }
  16195. /**
  16196. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16197. *
  16198. * @param {number} val
  16199. * @return {number}
  16200. */
  16201. function quantity(val) {
  16202. return Math.pow(10, quantityExponent(val));
  16203. }
  16204. function quantityExponent(val) {
  16205. return Math.floor(Math.log(val) / Math.LN10);
  16206. }
  16207. /**
  16208. * find a “nice” number approximately equal to x. Round the number if round = true,
  16209. * take ceiling if round = false. The primary observation is that the “nicest”
  16210. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16211. *
  16212. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16213. *
  16214. * @param {number} val Non-negative value.
  16215. * @param {boolean} round
  16216. * @return {number}
  16217. */
  16218. function nice(val, round) {
  16219. var exponent = quantityExponent(val);
  16220. var exp10 = Math.pow(10, exponent);
  16221. var f = val / exp10; // 1 <= f < 10
  16222. var nf;
  16223. if (round) {
  16224. if (f < 1.5) {
  16225. nf = 1;
  16226. }
  16227. else if (f < 2.5) {
  16228. nf = 2;
  16229. }
  16230. else if (f < 4) {
  16231. nf = 3;
  16232. }
  16233. else if (f < 7) {
  16234. nf = 5;
  16235. }
  16236. else {
  16237. nf = 10;
  16238. }
  16239. }
  16240. else {
  16241. if (f < 1) {
  16242. nf = 1;
  16243. }
  16244. else if (f < 2) {
  16245. nf = 2;
  16246. }
  16247. else if (f < 3) {
  16248. nf = 3;
  16249. }
  16250. else if (f < 5) {
  16251. nf = 5;
  16252. }
  16253. else {
  16254. nf = 10;
  16255. }
  16256. }
  16257. val = nf * exp10;
  16258. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16259. // 20 is the uppper bound of toFixed.
  16260. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16261. }
  16262. /**
  16263. * BSD 3-Clause
  16264. *
  16265. * Copyright (c) 2010-2015, Michael Bostock
  16266. * All rights reserved.
  16267. *
  16268. * Redistribution and use in source and binary forms, with or without
  16269. * modification, are permitted provided that the following conditions are met:
  16270. *
  16271. * * Redistributions of source code must retain the above copyright notice, this
  16272. * list of conditions and the following disclaimer.
  16273. *
  16274. * * Redistributions in binary form must reproduce the above copyright notice,
  16275. * this list of conditions and the following disclaimer in the documentation
  16276. * and/or other materials provided with the distribution.
  16277. *
  16278. * * The name Michael Bostock may not be used to endorse or promote products
  16279. * derived from this software without specific prior written permission.
  16280. *
  16281. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16282. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16283. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16284. * DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
  16285. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  16286. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  16287. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  16288. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  16289. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  16290. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16291. */
  16292. /**
  16293. * @see <https://github.com/mbostock/d3/blob/master/src/arrays/quantile.js>
  16294. * @see <http://en.wikipedia.org/wiki/Quantile>
  16295. * @param {Array.<number>} ascArr
  16296. */
  16297. function quantile(ascArr, p) {
  16298. var H = (ascArr.length - 1) * p + 1;
  16299. var h = Math.floor(H);
  16300. var v = +ascArr[h - 1];
  16301. var e = H - h;
  16302. return e ? v + e * (ascArr[h] - v) : v;
  16303. }
  16304. /**
  16305. * Order intervals asc, and split them when overlap.
  16306. * expect(numberUtil.reformIntervals([
  16307. * {interval: [18, 62], close: [1, 1]},
  16308. * {interval: [-Infinity, -70], close: [0, 0]},
  16309. * {interval: [-70, -26], close: [1, 1]},
  16310. * {interval: [-26, 18], close: [1, 1]},
  16311. * {interval: [62, 150], close: [1, 1]},
  16312. * {interval: [106, 150], close: [1, 1]},
  16313. * {interval: [150, Infinity], close: [0, 0]}
  16314. * ])).toEqual([
  16315. * {interval: [-Infinity, -70], close: [0, 0]},
  16316. * {interval: [-70, -26], close: [1, 1]},
  16317. * {interval: [-26, 18], close: [0, 1]},
  16318. * {interval: [18, 62], close: [0, 1]},
  16319. * {interval: [62, 150], close: [0, 1]},
  16320. * {interval: [150, Infinity], close: [0, 0]}
  16321. * ]);
  16322. * @param {Array.<Object>} list, where `close` mean open or close
  16323. * of the interval, and Infinity can be used.
  16324. * @return {Array.<Object>} The origin list, which has been reformed.
  16325. */
  16326. function reformIntervals(list) {
  16327. list.sort(function (a, b) {
  16328. return littleThan(a, b, 0) ? -1 : 1;
  16329. });
  16330. var curr = -Infinity;
  16331. var currClose = 1;
  16332. for (var i = 0; i < list.length;) {
  16333. var interval = list[i].interval;
  16334. var close = list[i].close;
  16335. for (var lg = 0; lg < 2; lg++) {
  16336. if (interval[lg] <= curr) {
  16337. interval[lg] = curr;
  16338. close[lg] = !lg ? 1 - currClose : 1;
  16339. }
  16340. curr = interval[lg];
  16341. currClose = close[lg];
  16342. }
  16343. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  16344. list.splice(i, 1);
  16345. }
  16346. else {
  16347. i++;
  16348. }
  16349. }
  16350. return list;
  16351. function littleThan(a, b, lg) {
  16352. return a.interval[lg] < b.interval[lg]
  16353. || (
  16354. a.interval[lg] === b.interval[lg]
  16355. && (
  16356. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  16357. || (!lg && littleThan(a, b, 1))
  16358. )
  16359. );
  16360. }
  16361. }
  16362. /**
  16363. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16364. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16365. * subtraction forces infinities to NaN
  16366. *
  16367. * @param {*} v
  16368. * @return {boolean}
  16369. */
  16370. function isNumeric(v) {
  16371. return v - parseFloat(v) >= 0;
  16372. }
  16373. var number = (Object.freeze || Object)({
  16374. linearMap: linearMap,
  16375. parsePercent: parsePercent$1,
  16376. round: round$2,
  16377. asc: asc,
  16378. getPrecision: getPrecision,
  16379. getPrecisionSafe: getPrecisionSafe,
  16380. getPixelPrecision: getPixelPrecision,
  16381. getPercentWithPrecision: getPercentWithPrecision,
  16382. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  16383. remRadian: remRadian,
  16384. isRadianAroundZero: isRadianAroundZero,
  16385. parseDate: parseDate,
  16386. quantity: quantity,
  16387. nice: nice,
  16388. quantile: quantile,
  16389. reformIntervals: reformIntervals,
  16390. isNumeric: isNumeric
  16391. });
  16392. /*
  16393. * Licensed to the Apache Software Foundation (ASF) under one
  16394. * or more contributor license agreements. See the NOTICE file
  16395. * distributed with this work for additional information
  16396. * regarding copyright ownership. The ASF licenses this file
  16397. * to you under the Apache License, Version 2.0 (the
  16398. * "License"); you may not use this file except in compliance
  16399. * with the License. You may obtain a copy of the License at
  16400. *
  16401. * http://www.apache.org/licenses/LICENSE-2.0
  16402. *
  16403. * Unless required by applicable law or agreed to in writing,
  16404. * software distributed under the License is distributed on an
  16405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16406. * KIND, either express or implied. See the License for the
  16407. * specific language governing permissions and limitations
  16408. * under the License.
  16409. */
  16410. // import Text from 'zrender/src/graphic/Text';
  16411. /**
  16412. * 每三位默认加,格式化
  16413. * @param {string|number} x
  16414. * @return {string}
  16415. */
  16416. function addCommas(x) {
  16417. if (isNaN(x)) {
  16418. return '-';
  16419. }
  16420. x = (x + '').split('.');
  16421. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16422. + (x.length > 1 ? ('.' + x[1]) : '');
  16423. }
  16424. /**
  16425. * @param {string} str
  16426. * @param {boolean} [upperCaseFirst=false]
  16427. * @return {string} str
  16428. */
  16429. function toCamelCase(str, upperCaseFirst) {
  16430. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16431. return group1.toUpperCase();
  16432. });
  16433. if (upperCaseFirst && str) {
  16434. str = str.charAt(0).toUpperCase() + str.slice(1);
  16435. }
  16436. return str;
  16437. }
  16438. var normalizeCssArray$1 = normalizeCssArray;
  16439. var replaceReg = /([&<>"'])/g;
  16440. var replaceMap = {
  16441. '&': '&amp;',
  16442. '<': '&lt;',
  16443. '>': '&gt;',
  16444. '"': '&quot;',
  16445. '\'': '&#39;'
  16446. };
  16447. function encodeHTML(source) {
  16448. return source == null
  16449. ? ''
  16450. : (source + '').replace(replaceReg, function (str, c) {
  16451. return replaceMap[c];
  16452. });
  16453. }
  16454. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16455. var wrapVar = function (varName, seriesIdx) {
  16456. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16457. };
  16458. /**
  16459. * Template formatter
  16460. * @param {string} tpl
  16461. * @param {Array.<Object>|Object} paramsList
  16462. * @param {boolean} [encode=false]
  16463. * @return {string}
  16464. */
  16465. function formatTpl(tpl, paramsList, encode) {
  16466. if (!isArray(paramsList)) {
  16467. paramsList = [paramsList];
  16468. }
  16469. var seriesLen = paramsList.length;
  16470. if (!seriesLen) {
  16471. return '';
  16472. }
  16473. var $vars = paramsList[0].$vars || [];
  16474. for (var i = 0; i < $vars.length; i++) {
  16475. var alias = TPL_VAR_ALIAS[i];
  16476. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16477. }
  16478. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16479. for (var k = 0; k < $vars.length; k++) {
  16480. var val = paramsList[seriesIdx][$vars[k]];
  16481. tpl = tpl.replace(
  16482. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16483. encode ? encodeHTML(val) : val
  16484. );
  16485. }
  16486. }
  16487. return tpl;
  16488. }
  16489. /**
  16490. * simple Template formatter
  16491. *
  16492. * @param {string} tpl
  16493. * @param {Object} param
  16494. * @param {boolean} [encode=false]
  16495. * @return {string}
  16496. */
  16497. function formatTplSimple(tpl, param, encode) {
  16498. each$1(param, function (value, key) {
  16499. tpl = tpl.replace(
  16500. '{' + key + '}',
  16501. encode ? encodeHTML(value) : value
  16502. );
  16503. });
  16504. return tpl;
  16505. }
  16506. /**
  16507. * @param {Object|string} [opt] If string, means color.
  16508. * @param {string} [opt.color]
  16509. * @param {string} [opt.extraCssText]
  16510. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16511. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16512. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16513. * @return {string}
  16514. */
  16515. function getTooltipMarker(opt, extraCssText) {
  16516. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16517. var color = opt.color;
  16518. var type = opt.type;
  16519. var extraCssText = opt.extraCssText;
  16520. var renderMode = opt.renderMode || 'html';
  16521. var markerId = opt.markerId || 'X';
  16522. if (!color) {
  16523. return '';
  16524. }
  16525. if (renderMode === 'html') {
  16526. return type === 'subItem'
  16527. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16528. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16529. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16530. : '<span style="display:inline-block;margin-right:5px;'
  16531. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16532. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16533. }
  16534. else {
  16535. // Space for rich element marker
  16536. return {
  16537. renderMode: renderMode,
  16538. content: '{marker' + markerId + '|} ',
  16539. style: {
  16540. color: color
  16541. }
  16542. };
  16543. }
  16544. }
  16545. function pad(str, len) {
  16546. str += '';
  16547. return '0000'.substr(0, len - str.length) + str;
  16548. }
  16549. /**
  16550. * ISO Date format
  16551. * @param {string} tpl
  16552. * @param {number} value
  16553. * @param {boolean} [isUTC=false] Default in local time.
  16554. * see `module:echarts/scale/Time`
  16555. * and `module:echarts/util/number#parseDate`.
  16556. * @inner
  16557. */
  16558. function formatTime(tpl, value, isUTC) {
  16559. if (tpl === 'week'
  16560. || tpl === 'month'
  16561. || tpl === 'quarter'
  16562. || tpl === 'half-year'
  16563. || tpl === 'year'
  16564. ) {
  16565. tpl = 'MM-dd\nyyyy';
  16566. }
  16567. var date = parseDate(value);
  16568. var utc = isUTC ? 'UTC' : '';
  16569. var y = date['get' + utc + 'FullYear']();
  16570. var M = date['get' + utc + 'Month']() + 1;
  16571. var d = date['get' + utc + 'Date']();
  16572. var h = date['get' + utc + 'Hours']();
  16573. var m = date['get' + utc + 'Minutes']();
  16574. var s = date['get' + utc + 'Seconds']();
  16575. var S = date['get' + utc + 'Milliseconds']();
  16576. tpl = tpl.replace('MM', pad(M, 2))
  16577. .replace('M', M)
  16578. .replace('yyyy', y)
  16579. .replace('yy', y % 100)
  16580. .replace('dd', pad(d, 2))
  16581. .replace('d', d)
  16582. .replace('hh', pad(h, 2))
  16583. .replace('h', h)
  16584. .replace('mm', pad(m, 2))
  16585. .replace('m', m)
  16586. .replace('ss', pad(s, 2))
  16587. .replace('s', s)
  16588. .replace('SSS', pad(S, 3));
  16589. return tpl;
  16590. }
  16591. /**
  16592. * Capital first
  16593. * @param {string} str
  16594. * @return {string}
  16595. */
  16596. function capitalFirst(str) {
  16597. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16598. }
  16599. var truncateText$1 = truncateText;
  16600. var getTextRect = getBoundingRect;
  16601. var format = (Object.freeze || Object)({
  16602. addCommas: addCommas,
  16603. toCamelCase: toCamelCase,
  16604. normalizeCssArray: normalizeCssArray$1,
  16605. encodeHTML: encodeHTML,
  16606. formatTpl: formatTpl,
  16607. formatTplSimple: formatTplSimple,
  16608. getTooltipMarker: getTooltipMarker,
  16609. formatTime: formatTime,
  16610. capitalFirst: capitalFirst,
  16611. truncateText: truncateText$1,
  16612. getTextRect: getTextRect
  16613. });
  16614. /*
  16615. * Licensed to the Apache Software Foundation (ASF) under one
  16616. * or more contributor license agreements. See the NOTICE file
  16617. * distributed with this work for additional information
  16618. * regarding copyright ownership. The ASF licenses this file
  16619. * to you under the Apache License, Version 2.0 (the
  16620. * "License"); you may not use this file except in compliance
  16621. * with the License. You may obtain a copy of the License at
  16622. *
  16623. * http://www.apache.org/licenses/LICENSE-2.0
  16624. *
  16625. * Unless required by applicable law or agreed to in writing,
  16626. * software distributed under the License is distributed on an
  16627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16628. * KIND, either express or implied. See the License for the
  16629. * specific language governing permissions and limitations
  16630. * under the License.
  16631. */
  16632. // Layout helpers for each component positioning
  16633. var each$3 = each$1;
  16634. /**
  16635. * @public
  16636. */
  16637. var LOCATION_PARAMS = [
  16638. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16639. ];
  16640. /**
  16641. * @public
  16642. */
  16643. var HV_NAMES = [
  16644. ['width', 'left', 'right'],
  16645. ['height', 'top', 'bottom']
  16646. ];
  16647. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16648. var x = 0;
  16649. var y = 0;
  16650. if (maxWidth == null) {
  16651. maxWidth = Infinity;
  16652. }
  16653. if (maxHeight == null) {
  16654. maxHeight = Infinity;
  16655. }
  16656. var currentLineMaxSize = 0;
  16657. group.eachChild(function (child, idx) {
  16658. var position = child.position;
  16659. var rect = child.getBoundingRect();
  16660. var nextChild = group.childAt(idx + 1);
  16661. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16662. var nextX;
  16663. var nextY;
  16664. if (orient === 'horizontal') {
  16665. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16666. nextX = x + moveX;
  16667. // Wrap when width exceeds maxWidth or meet a `newline` group
  16668. // FIXME compare before adding gap?
  16669. if (nextX > maxWidth || child.newline) {
  16670. x = 0;
  16671. nextX = moveX;
  16672. y += currentLineMaxSize + gap;
  16673. currentLineMaxSize = rect.height;
  16674. }
  16675. else {
  16676. // FIXME: consider rect.y is not `0`?
  16677. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16678. }
  16679. }
  16680. else {
  16681. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16682. nextY = y + moveY;
  16683. // Wrap when width exceeds maxHeight or meet a `newline` group
  16684. if (nextY > maxHeight || child.newline) {
  16685. x += currentLineMaxSize + gap;
  16686. y = 0;
  16687. nextY = moveY;
  16688. currentLineMaxSize = rect.width;
  16689. }
  16690. else {
  16691. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16692. }
  16693. }
  16694. if (child.newline) {
  16695. return;
  16696. }
  16697. position[0] = x;
  16698. position[1] = y;
  16699. orient === 'horizontal'
  16700. ? (x = nextX + gap)
  16701. : (y = nextY + gap);
  16702. });
  16703. }
  16704. /**
  16705. * VBox or HBox layouting
  16706. * @param {string} orient
  16707. * @param {module:zrender/container/Group} group
  16708. * @param {number} gap
  16709. * @param {number} [width=Infinity]
  16710. * @param {number} [height=Infinity]
  16711. */
  16712. var box = boxLayout;
  16713. /**
  16714. * VBox layouting
  16715. * @param {module:zrender/container/Group} group
  16716. * @param {number} gap
  16717. * @param {number} [width=Infinity]
  16718. * @param {number} [height=Infinity]
  16719. */
  16720. var vbox = curry(boxLayout, 'vertical');
  16721. /**
  16722. * HBox layouting
  16723. * @param {module:zrender/container/Group} group
  16724. * @param {number} gap
  16725. * @param {number} [width=Infinity]
  16726. * @param {number} [height=Infinity]
  16727. */
  16728. var hbox = curry(boxLayout, 'horizontal');
  16729. /**
  16730. * If x or x2 is not specified or 'center' 'left' 'right',
  16731. * the width would be as long as possible.
  16732. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16733. * the height would be as long as possible.
  16734. *
  16735. * @param {Object} positionInfo
  16736. * @param {number|string} [positionInfo.x]
  16737. * @param {number|string} [positionInfo.y]
  16738. * @param {number|string} [positionInfo.x2]
  16739. * @param {number|string} [positionInfo.y2]
  16740. * @param {Object} containerRect {width, height}
  16741. * @param {string|number} margin
  16742. * @return {Object} {width, height}
  16743. */
  16744. function getAvailableSize(positionInfo, containerRect, margin) {
  16745. var containerWidth = containerRect.width;
  16746. var containerHeight = containerRect.height;
  16747. var x = parsePercent$1(positionInfo.x, containerWidth);
  16748. var y = parsePercent$1(positionInfo.y, containerHeight);
  16749. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16750. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16751. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16752. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16753. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16754. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16755. margin = normalizeCssArray$1(margin || 0);
  16756. return {
  16757. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16758. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16759. };
  16760. }
  16761. /**
  16762. * Parse position info.
  16763. *
  16764. * @param {Object} positionInfo
  16765. * @param {number|string} [positionInfo.left]
  16766. * @param {number|string} [positionInfo.top]
  16767. * @param {number|string} [positionInfo.right]
  16768. * @param {number|string} [positionInfo.bottom]
  16769. * @param {number|string} [positionInfo.width]
  16770. * @param {number|string} [positionInfo.height]
  16771. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16772. * @param {Object} containerRect
  16773. * @param {string|number} [margin]
  16774. *
  16775. * @return {module:zrender/core/BoundingRect}
  16776. */
  16777. function getLayoutRect(
  16778. positionInfo, containerRect, margin
  16779. ) {
  16780. margin = normalizeCssArray$1(margin || 0);
  16781. var containerWidth = containerRect.width;
  16782. var containerHeight = containerRect.height;
  16783. var left = parsePercent$1(positionInfo.left, containerWidth);
  16784. var top = parsePercent$1(positionInfo.top, containerHeight);
  16785. var right = parsePercent$1(positionInfo.right, containerWidth);
  16786. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16787. var width = parsePercent$1(positionInfo.width, containerWidth);
  16788. var height = parsePercent$1(positionInfo.height, containerHeight);
  16789. var verticalMargin = margin[2] + margin[0];
  16790. var horizontalMargin = margin[1] + margin[3];
  16791. var aspect = positionInfo.aspect;
  16792. // If width is not specified, calculate width from left and right
  16793. if (isNaN(width)) {
  16794. width = containerWidth - right - horizontalMargin - left;
  16795. }
  16796. if (isNaN(height)) {
  16797. height = containerHeight - bottom - verticalMargin - top;
  16798. }
  16799. if (aspect != null) {
  16800. // If width and height are not given
  16801. // 1. Graph should not exceeds the container
  16802. // 2. Aspect must be keeped
  16803. // 3. Graph should take the space as more as possible
  16804. // FIXME
  16805. // Margin is not considered, because there is no case that both
  16806. // using margin and aspect so far.
  16807. if (isNaN(width) && isNaN(height)) {
  16808. if (aspect > containerWidth / containerHeight) {
  16809. width = containerWidth * 0.8;
  16810. }
  16811. else {
  16812. height = containerHeight * 0.8;
  16813. }
  16814. }
  16815. // Calculate width or height with given aspect
  16816. if (isNaN(width)) {
  16817. width = aspect * height;
  16818. }
  16819. if (isNaN(height)) {
  16820. height = width / aspect;
  16821. }
  16822. }
  16823. // If left is not specified, calculate left from right and width
  16824. if (isNaN(left)) {
  16825. left = containerWidth - right - width - horizontalMargin;
  16826. }
  16827. if (isNaN(top)) {
  16828. top = containerHeight - bottom - height - verticalMargin;
  16829. }
  16830. // Align left and top
  16831. switch (positionInfo.left || positionInfo.right) {
  16832. case 'center':
  16833. left = containerWidth / 2 - width / 2 - margin[3];
  16834. break;
  16835. case 'right':
  16836. left = containerWidth - width - horizontalMargin;
  16837. break;
  16838. }
  16839. switch (positionInfo.top || positionInfo.bottom) {
  16840. case 'middle':
  16841. case 'center':
  16842. top = containerHeight / 2 - height / 2 - margin[0];
  16843. break;
  16844. case 'bottom':
  16845. top = containerHeight - height - verticalMargin;
  16846. break;
  16847. }
  16848. // If something is wrong and left, top, width, height are calculated as NaN
  16849. left = left || 0;
  16850. top = top || 0;
  16851. if (isNaN(width)) {
  16852. // Width may be NaN if only one value is given except width
  16853. width = containerWidth - horizontalMargin - left - (right || 0);
  16854. }
  16855. if (isNaN(height)) {
  16856. // Height may be NaN if only one value is given except height
  16857. height = containerHeight - verticalMargin - top - (bottom || 0);
  16858. }
  16859. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16860. rect.margin = margin;
  16861. return rect;
  16862. }
  16863. /**
  16864. * Position a zr element in viewport
  16865. * Group position is specified by either
  16866. * {left, top}, {right, bottom}
  16867. * If all properties exists, right and bottom will be igonred.
  16868. *
  16869. * Logic:
  16870. * 1. Scale (against origin point in parent coord)
  16871. * 2. Rotate (against origin point in parent coord)
  16872. * 3. Traslate (with el.position by this method)
  16873. * So this method only fixes the last step 'Traslate', which does not affect
  16874. * scaling and rotating.
  16875. *
  16876. * If be called repeatly with the same input el, the same result will be gotten.
  16877. *
  16878. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16879. * @param {Object} positionInfo
  16880. * @param {number|string} [positionInfo.left]
  16881. * @param {number|string} [positionInfo.top]
  16882. * @param {number|string} [positionInfo.right]
  16883. * @param {number|string} [positionInfo.bottom]
  16884. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16885. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16886. * @param {Object} containerRect
  16887. * @param {string|number} margin
  16888. * @param {Object} [opt]
  16889. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16890. * @param {Array.<number>} [opt.boundingMode='all']
  16891. * Specify how to calculate boundingRect when locating.
  16892. * 'all': Position the boundingRect that is transformed and uioned
  16893. * both itself and its descendants.
  16894. * This mode simplies confine the elements in the bounding
  16895. * of their container (e.g., using 'right: 0').
  16896. * 'raw': Position the boundingRect that is not transformed and only itself.
  16897. * This mode is useful when you want a element can overflow its
  16898. * container. (Consider a rotated circle needs to be located in a corner.)
  16899. * In this mode positionInfo.width/height can only be number.
  16900. */
  16901. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16902. var h = !opt || !opt.hv || opt.hv[0];
  16903. var v = !opt || !opt.hv || opt.hv[1];
  16904. var boundingMode = opt && opt.boundingMode || 'all';
  16905. if (!h && !v) {
  16906. return;
  16907. }
  16908. var rect;
  16909. if (boundingMode === 'raw') {
  16910. rect = el.type === 'group'
  16911. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16912. : el.getBoundingRect();
  16913. }
  16914. else {
  16915. rect = el.getBoundingRect();
  16916. if (el.needLocalTransform()) {
  16917. var transform = el.getLocalTransform();
  16918. // Notice: raw rect may be inner object of el,
  16919. // which should not be modified.
  16920. rect = rect.clone();
  16921. rect.applyTransform(transform);
  16922. }
  16923. }
  16924. // The real width and height can not be specified but calculated by the given el.
  16925. positionInfo = getLayoutRect(
  16926. defaults(
  16927. {width: rect.width, height: rect.height},
  16928. positionInfo
  16929. ),
  16930. containerRect,
  16931. margin
  16932. );
  16933. // Because 'tranlate' is the last step in transform
  16934. // (see zrender/core/Transformable#getLocalTransform),
  16935. // we can just only modify el.position to get final result.
  16936. var elPos = el.position;
  16937. var dx = h ? positionInfo.x - rect.x : 0;
  16938. var dy = v ? positionInfo.y - rect.y : 0;
  16939. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16940. }
  16941. /**
  16942. * @param {Object} option Contains some of the properties in HV_NAMES.
  16943. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16944. */
  16945. function sizeCalculable(option, hvIdx) {
  16946. return option[HV_NAMES[hvIdx][0]] != null
  16947. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16948. }
  16949. /**
  16950. * Consider Case:
  16951. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16952. * through setOption or media query, using normal zrUtil.merge will cause
  16953. * {right: 0} does not take effect.
  16954. *
  16955. * @example
  16956. * ComponentModel.extend({
  16957. * init: function () {
  16958. * ...
  16959. * var inputPositionParams = layout.getLayoutParams(option);
  16960. * this.mergeOption(inputPositionParams);
  16961. * },
  16962. * mergeOption: function (newOption) {
  16963. * newOption && zrUtil.merge(thisOption, newOption, true);
  16964. * layout.mergeLayoutParam(thisOption, newOption);
  16965. * }
  16966. * });
  16967. *
  16968. * @param {Object} targetOption
  16969. * @param {Object} newOption
  16970. * @param {Object|string} [opt]
  16971. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16972. * that width (or height) should not be calculated by left and right (or top and bottom).
  16973. */
  16974. function mergeLayoutParam(targetOption, newOption, opt) {
  16975. !isObject$1(opt) && (opt = {});
  16976. var ignoreSize = opt.ignoreSize;
  16977. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16978. var hResult = merge$$1(HV_NAMES[0], 0);
  16979. var vResult = merge$$1(HV_NAMES[1], 1);
  16980. copy(HV_NAMES[0], targetOption, hResult);
  16981. copy(HV_NAMES[1], targetOption, vResult);
  16982. function merge$$1(names, hvIdx) {
  16983. var newParams = {};
  16984. var newValueCount = 0;
  16985. var merged = {};
  16986. var mergedValueCount = 0;
  16987. var enoughParamNumber = 2;
  16988. each$3(names, function (name) {
  16989. merged[name] = targetOption[name];
  16990. });
  16991. each$3(names, function (name) {
  16992. // Consider case: newOption.width is null, which is
  16993. // set by user for removing width setting.
  16994. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16995. hasValue(newParams, name) && newValueCount++;
  16996. hasValue(merged, name) && mergedValueCount++;
  16997. });
  16998. if (ignoreSize[hvIdx]) {
  16999. // Only one of left/right is premitted to exist.
  17000. if (hasValue(newOption, names[1])) {
  17001. merged[names[2]] = null;
  17002. }
  17003. else if (hasValue(newOption, names[2])) {
  17004. merged[names[1]] = null;
  17005. }
  17006. return merged;
  17007. }
  17008. // Case: newOption: {width: ..., right: ...},
  17009. // or targetOption: {right: ...} and newOption: {width: ...},
  17010. // There is no conflict when merged only has params count
  17011. // little than enoughParamNumber.
  17012. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17013. return merged;
  17014. }
  17015. // Case: newOption: {width: ..., right: ...},
  17016. // Than we can make sure user only want those two, and ignore
  17017. // all origin params in targetOption.
  17018. else if (newValueCount >= enoughParamNumber) {
  17019. return newParams;
  17020. }
  17021. else {
  17022. // Chose another param from targetOption by priority.
  17023. for (var i = 0; i < names.length; i++) {
  17024. var name = names[i];
  17025. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17026. newParams[name] = targetOption[name];
  17027. break;
  17028. }
  17029. }
  17030. return newParams;
  17031. }
  17032. }
  17033. function hasProp(obj, name) {
  17034. return obj.hasOwnProperty(name);
  17035. }
  17036. function hasValue(obj, name) {
  17037. return obj[name] != null && obj[name] !== 'auto';
  17038. }
  17039. function copy(names, target, source) {
  17040. each$3(names, function (name) {
  17041. target[name] = source[name];
  17042. });
  17043. }
  17044. }
  17045. /**
  17046. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17047. * @param {Object} source
  17048. * @return {Object} Result contains those props.
  17049. */
  17050. function getLayoutParams(source) {
  17051. return copyLayoutParams({}, source);
  17052. }
  17053. /**
  17054. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17055. * @param {Object} source
  17056. * @return {Object} Result contains those props.
  17057. */
  17058. function copyLayoutParams(target, source) {
  17059. source && target && each$3(LOCATION_PARAMS, function (name) {
  17060. source.hasOwnProperty(name) && (target[name] = source[name]);
  17061. });
  17062. return target;
  17063. }
  17064. /*
  17065. * Licensed to the Apache Software Foundation (ASF) under one
  17066. * or more contributor license agreements. See the NOTICE file
  17067. * distributed with this work for additional information
  17068. * regarding copyright ownership. The ASF licenses this file
  17069. * to you under the Apache License, Version 2.0 (the
  17070. * "License"); you may not use this file except in compliance
  17071. * with the License. You may obtain a copy of the License at
  17072. *
  17073. * http://www.apache.org/licenses/LICENSE-2.0
  17074. *
  17075. * Unless required by applicable law or agreed to in writing,
  17076. * software distributed under the License is distributed on an
  17077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17078. * KIND, either express or implied. See the License for the
  17079. * specific language governing permissions and limitations
  17080. * under the License.
  17081. */
  17082. var boxLayoutMixin = {
  17083. getBoxLayoutParams: function () {
  17084. return {
  17085. left: this.get('left'),
  17086. top: this.get('top'),
  17087. right: this.get('right'),
  17088. bottom: this.get('bottom'),
  17089. width: this.get('width'),
  17090. height: this.get('height')
  17091. };
  17092. }
  17093. };
  17094. /*
  17095. * Licensed to the Apache Software Foundation (ASF) under one
  17096. * or more contributor license agreements. See the NOTICE file
  17097. * distributed with this work for additional information
  17098. * regarding copyright ownership. The ASF licenses this file
  17099. * to you under the Apache License, Version 2.0 (the
  17100. * "License"); you may not use this file except in compliance
  17101. * with the License. You may obtain a copy of the License at
  17102. *
  17103. * http://www.apache.org/licenses/LICENSE-2.0
  17104. *
  17105. * Unless required by applicable law or agreed to in writing,
  17106. * software distributed under the License is distributed on an
  17107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17108. * KIND, either express or implied. See the License for the
  17109. * specific language governing permissions and limitations
  17110. * under the License.
  17111. */
  17112. /**
  17113. * Component model
  17114. *
  17115. * @module echarts/model/Component
  17116. */
  17117. var inner$1 = makeInner();
  17118. /**
  17119. * @alias module:echarts/model/Component
  17120. * @constructor
  17121. * @param {Object} option
  17122. * @param {module:echarts/model/Model} parentModel
  17123. * @param {module:echarts/model/Model} ecModel
  17124. */
  17125. var ComponentModel = Model.extend({
  17126. type: 'component',
  17127. /**
  17128. * @readOnly
  17129. * @type {string}
  17130. */
  17131. id: '',
  17132. /**
  17133. * Because simplified concept is probably better, series.name (or component.name)
  17134. * has been having too many resposibilities:
  17135. * (1) Generating id (which requires name in option should not be modified).
  17136. * (2) As an index to mapping series when merging option or calling API (a name
  17137. * can refer to more then one components, which is convinient is some case).
  17138. * (3) Display.
  17139. * @readOnly
  17140. */
  17141. name: '',
  17142. /**
  17143. * @readOnly
  17144. * @type {string}
  17145. */
  17146. mainType: '',
  17147. /**
  17148. * @readOnly
  17149. * @type {string}
  17150. */
  17151. subType: '',
  17152. /**
  17153. * @readOnly
  17154. * @type {number}
  17155. */
  17156. componentIndex: 0,
  17157. /**
  17158. * @type {Object}
  17159. * @protected
  17160. */
  17161. defaultOption: null,
  17162. /**
  17163. * @type {module:echarts/model/Global}
  17164. * @readOnly
  17165. */
  17166. ecModel: null,
  17167. /**
  17168. * key: componentType
  17169. * value: Component model list, can not be null.
  17170. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17171. * @readOnly
  17172. */
  17173. dependentModels: [],
  17174. /**
  17175. * @type {string}
  17176. * @readOnly
  17177. */
  17178. uid: null,
  17179. /**
  17180. * Support merge layout params.
  17181. * Only support 'box' now (left/right/top/bottom/width/height).
  17182. * @type {string|Object} Object can be {ignoreSize: true}
  17183. * @readOnly
  17184. */
  17185. layoutMode: null,
  17186. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17187. Model.call(this, option, parentModel, ecModel, extraOpt);
  17188. this.uid = getUID('ec_cpt_model');
  17189. },
  17190. init: function (option, parentModel, ecModel, extraOpt) {
  17191. this.mergeDefaultAndTheme(option, ecModel);
  17192. },
  17193. mergeDefaultAndTheme: function (option, ecModel) {
  17194. var layoutMode = this.layoutMode;
  17195. var inputPositionParams = layoutMode
  17196. ? getLayoutParams(option) : {};
  17197. var themeModel = ecModel.getTheme();
  17198. merge(option, themeModel.get(this.mainType));
  17199. merge(option, this.getDefaultOption());
  17200. if (layoutMode) {
  17201. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17202. }
  17203. },
  17204. mergeOption: function (option, extraOpt) {
  17205. merge(this.option, option, true);
  17206. var layoutMode = this.layoutMode;
  17207. if (layoutMode) {
  17208. mergeLayoutParam(this.option, option, layoutMode);
  17209. }
  17210. },
  17211. // Hooker after init or mergeOption
  17212. optionUpdated: function (newCptOption, isInit) {},
  17213. getDefaultOption: function () {
  17214. var fields = inner$1(this);
  17215. if (!fields.defaultOption) {
  17216. var optList = [];
  17217. var Class = this.constructor;
  17218. while (Class) {
  17219. var opt = Class.prototype.defaultOption;
  17220. opt && optList.push(opt);
  17221. Class = Class.superClass;
  17222. }
  17223. var defaultOption = {};
  17224. for (var i = optList.length - 1; i >= 0; i--) {
  17225. defaultOption = merge(defaultOption, optList[i], true);
  17226. }
  17227. fields.defaultOption = defaultOption;
  17228. }
  17229. return fields.defaultOption;
  17230. },
  17231. getReferringComponents: function (mainType) {
  17232. return this.ecModel.queryComponents({
  17233. mainType: mainType,
  17234. index: this.get(mainType + 'Index', true),
  17235. id: this.get(mainType + 'Id', true)
  17236. });
  17237. }
  17238. });
  17239. // Reset ComponentModel.extend, add preConstruct.
  17240. // clazzUtil.enableClassExtend(
  17241. // ComponentModel,
  17242. // function (option, parentModel, ecModel, extraOpt) {
  17243. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17244. // zrUtil.extend(this, extraOpt);
  17245. // this.uid = componentUtil.getUID('componentModel');
  17246. // // this.setReadOnly([
  17247. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17248. // // 'dependentModels', 'componentIndex'
  17249. // // ]);
  17250. // }
  17251. // );
  17252. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17253. enableClassManagement(
  17254. ComponentModel, {registerWhenExtend: true}
  17255. );
  17256. enableSubTypeDefaulter(ComponentModel);
  17257. // Add capability of ComponentModel.topologicalTravel.
  17258. enableTopologicalTravel(ComponentModel, getDependencies);
  17259. function getDependencies(componentType) {
  17260. var deps = [];
  17261. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17262. deps = deps.concat(Clazz.prototype.dependencies || []);
  17263. });
  17264. // Ensure main type.
  17265. deps = map(deps, function (type) {
  17266. return parseClassType$1(type).main;
  17267. });
  17268. // Hack dataset for convenience.
  17269. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17270. deps.unshift('dataset');
  17271. }
  17272. return deps;
  17273. }
  17274. mixin(ComponentModel, boxLayoutMixin);
  17275. /*
  17276. * Licensed to the Apache Software Foundation (ASF) under one
  17277. * or more contributor license agreements. See the NOTICE file
  17278. * distributed with this work for additional information
  17279. * regarding copyright ownership. The ASF licenses this file
  17280. * to you under the Apache License, Version 2.0 (the
  17281. * "License"); you may not use this file except in compliance
  17282. * with the License. You may obtain a copy of the License at
  17283. *
  17284. * http://www.apache.org/licenses/LICENSE-2.0
  17285. *
  17286. * Unless required by applicable law or agreed to in writing,
  17287. * software distributed under the License is distributed on an
  17288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17289. * KIND, either express or implied. See the License for the
  17290. * specific language governing permissions and limitations
  17291. * under the License.
  17292. */
  17293. var platform = '';
  17294. // Navigator not exists in node
  17295. if (typeof navigator !== 'undefined') {
  17296. platform = navigator.platform || '';
  17297. }
  17298. var globalDefault = {
  17299. // backgroundColor: 'rgba(0,0,0,0)',
  17300. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17301. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17302. // Light colors:
  17303. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17304. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17305. // Dark colors:
  17306. color: [
  17307. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17308. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17309. ],
  17310. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17311. // If xAxis and yAxis declared, grid is created by default.
  17312. // grid: {},
  17313. textStyle: {
  17314. // color: '#000',
  17315. // decoration: 'none',
  17316. // PENDING
  17317. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17318. // fontFamily: 'Arial, Verdana, sans-serif',
  17319. fontSize: 12,
  17320. fontStyle: 'normal',
  17321. fontWeight: 'normal'
  17322. },
  17323. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17324. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17325. // Default is source-over
  17326. blendMode: null,
  17327. animation: 'auto',
  17328. animationDuration: 1000,
  17329. animationDurationUpdate: 300,
  17330. animationEasing: 'exponentialOut',
  17331. animationEasingUpdate: 'cubicOut',
  17332. animationThreshold: 2000,
  17333. // Configuration for progressive/incremental rendering
  17334. progressiveThreshold: 3000,
  17335. progressive: 400,
  17336. // Threshold of if use single hover layer to optimize.
  17337. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17338. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17339. // which is unexpected.
  17340. // see example <echarts/test/heatmap-large.html>.
  17341. hoverLayerThreshold: 3000,
  17342. // See: module:echarts/scale/Time
  17343. useUTC: false
  17344. };
  17345. /*
  17346. * Licensed to the Apache Software Foundation (ASF) under one
  17347. * or more contributor license agreements. See the NOTICE file
  17348. * distributed with this work for additional information
  17349. * regarding copyright ownership. The ASF licenses this file
  17350. * to you under the Apache License, Version 2.0 (the
  17351. * "License"); you may not use this file except in compliance
  17352. * with the License. You may obtain a copy of the License at
  17353. *
  17354. * http://www.apache.org/licenses/LICENSE-2.0
  17355. *
  17356. * Unless required by applicable law or agreed to in writing,
  17357. * software distributed under the License is distributed on an
  17358. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17359. * KIND, either express or implied. See the License for the
  17360. * specific language governing permissions and limitations
  17361. * under the License.
  17362. */
  17363. var inner$2 = makeInner();
  17364. function getNearestColorPalette(colors, requestColorNum) {
  17365. var paletteNum = colors.length;
  17366. // TODO colors must be in order
  17367. for (var i = 0; i < paletteNum; i++) {
  17368. if (colors[i].length > requestColorNum) {
  17369. return colors[i];
  17370. }
  17371. }
  17372. return colors[paletteNum - 1];
  17373. }
  17374. var colorPaletteMixin = {
  17375. clearColorPalette: function () {
  17376. inner$2(this).colorIdx = 0;
  17377. inner$2(this).colorNameMap = {};
  17378. },
  17379. /**
  17380. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17381. * twise with the same parameters will get different result.
  17382. * @param {Object} [scope=this]
  17383. * @param {Object} [requestColorNum]
  17384. * @return {string} color string.
  17385. */
  17386. getColorFromPalette: function (name, scope, requestColorNum) {
  17387. scope = scope || this;
  17388. var scopeFields = inner$2(scope);
  17389. var colorIdx = scopeFields.colorIdx || 0;
  17390. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17391. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17392. if (colorNameMap.hasOwnProperty(name)) {
  17393. return colorNameMap[name];
  17394. }
  17395. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17396. var layeredColorPalette = this.get('colorLayer', true);
  17397. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17398. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17399. // In case can't find in layered color palette.
  17400. colorPalette = colorPalette || defaultColorPalette;
  17401. if (!colorPalette || !colorPalette.length) {
  17402. return;
  17403. }
  17404. var color = colorPalette[colorIdx];
  17405. if (name) {
  17406. colorNameMap[name] = color;
  17407. }
  17408. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17409. return color;
  17410. }
  17411. };
  17412. /*
  17413. * Licensed to the Apache Software Foundation (ASF) under one
  17414. * or more contributor license agreements. See the NOTICE file
  17415. * distributed with this work for additional information
  17416. * regarding copyright ownership. The ASF licenses this file
  17417. * to you under the Apache License, Version 2.0 (the
  17418. * "License"); you may not use this file except in compliance
  17419. * with the License. You may obtain a copy of the License at
  17420. *
  17421. * http://www.apache.org/licenses/LICENSE-2.0
  17422. *
  17423. * Unless required by applicable law or agreed to in writing,
  17424. * software distributed under the License is distributed on an
  17425. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17426. * KIND, either express or implied. See the License for the
  17427. * specific language governing permissions and limitations
  17428. * under the License.
  17429. */
  17430. /**
  17431. * Helper for model references.
  17432. * There are many manners to refer axis/coordSys.
  17433. */
  17434. // TODO
  17435. // merge relevant logic to this file?
  17436. // check: "modelHelper" of tooltip and "BrushTargetManager".
  17437. /**
  17438. * @return {Object} For example:
  17439. * {
  17440. * coordSysName: 'cartesian2d',
  17441. * coordSysDims: ['x', 'y', ...],
  17442. * axisMap: HashMap({
  17443. * x: xAxisModel,
  17444. * y: yAxisModel
  17445. * }),
  17446. * categoryAxisMap: HashMap({
  17447. * x: xAxisModel,
  17448. * y: undefined
  17449. * }),
  17450. * // It also indicate that whether there is category axis.
  17451. * firstCategoryDimIndex: 1,
  17452. * // To replace user specified encode.
  17453. * }
  17454. */
  17455. function getCoordSysDefineBySeries(seriesModel) {
  17456. var coordSysName = seriesModel.get('coordinateSystem');
  17457. var result = {
  17458. coordSysName: coordSysName,
  17459. coordSysDims: [],
  17460. axisMap: createHashMap(),
  17461. categoryAxisMap: createHashMap()
  17462. };
  17463. var fetch = fetchers[coordSysName];
  17464. if (fetch) {
  17465. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  17466. return result;
  17467. }
  17468. }
  17469. var fetchers = {
  17470. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  17471. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  17472. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  17473. if (__DEV__) {
  17474. if (!xAxisModel) {
  17475. throw new Error('xAxis "' + retrieve(
  17476. seriesModel.get('xAxisIndex'),
  17477. seriesModel.get('xAxisId'),
  17478. 0
  17479. ) + '" not found');
  17480. }
  17481. if (!yAxisModel) {
  17482. throw new Error('yAxis "' + retrieve(
  17483. seriesModel.get('xAxisIndex'),
  17484. seriesModel.get('yAxisId'),
  17485. 0
  17486. ) + '" not found');
  17487. }
  17488. }
  17489. result.coordSysDims = ['x', 'y'];
  17490. axisMap.set('x', xAxisModel);
  17491. axisMap.set('y', yAxisModel);
  17492. if (isCategory(xAxisModel)) {
  17493. categoryAxisMap.set('x', xAxisModel);
  17494. result.firstCategoryDimIndex = 0;
  17495. }
  17496. if (isCategory(yAxisModel)) {
  17497. categoryAxisMap.set('y', yAxisModel);
  17498. result.firstCategoryDimIndex = 1;
  17499. }
  17500. },
  17501. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  17502. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  17503. if (__DEV__) {
  17504. if (!singleAxisModel) {
  17505. throw new Error('singleAxis should be specified.');
  17506. }
  17507. }
  17508. result.coordSysDims = ['single'];
  17509. axisMap.set('single', singleAxisModel);
  17510. if (isCategory(singleAxisModel)) {
  17511. categoryAxisMap.set('single', singleAxisModel);
  17512. result.firstCategoryDimIndex = 0;
  17513. }
  17514. },
  17515. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  17516. var polarModel = seriesModel.getReferringComponents('polar')[0];
  17517. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  17518. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  17519. if (__DEV__) {
  17520. if (!angleAxisModel) {
  17521. throw new Error('angleAxis option not found');
  17522. }
  17523. if (!radiusAxisModel) {
  17524. throw new Error('radiusAxis option not found');
  17525. }
  17526. }
  17527. result.coordSysDims = ['radius', 'angle'];
  17528. axisMap.set('radius', radiusAxisModel);
  17529. axisMap.set('angle', angleAxisModel);
  17530. if (isCategory(radiusAxisModel)) {
  17531. categoryAxisMap.set('radius', radiusAxisModel);
  17532. result.firstCategoryDimIndex = 0;
  17533. }
  17534. if (isCategory(angleAxisModel)) {
  17535. categoryAxisMap.set('angle', angleAxisModel);
  17536. result.firstCategoryDimIndex = 1;
  17537. }
  17538. },
  17539. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  17540. result.coordSysDims = ['lng', 'lat'];
  17541. },
  17542. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  17543. var ecModel = seriesModel.ecModel;
  17544. var parallelModel = ecModel.getComponent(
  17545. 'parallel', seriesModel.get('parallelIndex')
  17546. );
  17547. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  17548. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  17549. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  17550. var axisDim = coordSysDims[index];
  17551. axisMap.set(axisDim, axisModel);
  17552. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  17553. categoryAxisMap.set(axisDim, axisModel);
  17554. result.firstCategoryDimIndex = index;
  17555. }
  17556. });
  17557. }
  17558. };
  17559. function isCategory(axisModel) {
  17560. return axisModel.get('type') === 'category';
  17561. }
  17562. /*
  17563. * Licensed to the Apache Software Foundation (ASF) under one
  17564. * or more contributor license agreements. See the NOTICE file
  17565. * distributed with this work for additional information
  17566. * regarding copyright ownership. The ASF licenses this file
  17567. * to you under the Apache License, Version 2.0 (the
  17568. * "License"); you may not use this file except in compliance
  17569. * with the License. You may obtain a copy of the License at
  17570. *
  17571. * http://www.apache.org/licenses/LICENSE-2.0
  17572. *
  17573. * Unless required by applicable law or agreed to in writing,
  17574. * software distributed under the License is distributed on an
  17575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17576. * KIND, either express or implied. See the License for the
  17577. * specific language governing permissions and limitations
  17578. * under the License.
  17579. */
  17580. // Avoid typo.
  17581. var SOURCE_FORMAT_ORIGINAL = 'original';
  17582. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17583. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17584. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17585. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17586. // ??? CHANGE A NAME
  17587. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17588. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17589. var SERIES_LAYOUT_BY_ROW = 'row';
  17590. /*
  17591. * Licensed to the Apache Software Foundation (ASF) under one
  17592. * or more contributor license agreements. See the NOTICE file
  17593. * distributed with this work for additional information
  17594. * regarding copyright ownership. The ASF licenses this file
  17595. * to you under the Apache License, Version 2.0 (the
  17596. * "License"); you may not use this file except in compliance
  17597. * with the License. You may obtain a copy of the License at
  17598. *
  17599. * http://www.apache.org/licenses/LICENSE-2.0
  17600. *
  17601. * Unless required by applicable law or agreed to in writing,
  17602. * software distributed under the License is distributed on an
  17603. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17604. * KIND, either express or implied. See the License for the
  17605. * specific language governing permissions and limitations
  17606. * under the License.
  17607. */
  17608. /**
  17609. * [sourceFormat]
  17610. *
  17611. * + "original":
  17612. * This format is only used in series.data, where
  17613. * itemStyle can be specified in data item.
  17614. *
  17615. * + "arrayRows":
  17616. * [
  17617. * ['product', 'score', 'amount'],
  17618. * ['Matcha Latte', 89.3, 95.8],
  17619. * ['Milk Tea', 92.1, 89.4],
  17620. * ['Cheese Cocoa', 94.4, 91.2],
  17621. * ['Walnut Brownie', 85.4, 76.9]
  17622. * ]
  17623. *
  17624. * + "objectRows":
  17625. * [
  17626. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17627. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17628. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17629. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17630. * ]
  17631. *
  17632. * + "keyedColumns":
  17633. * {
  17634. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17635. * 'count': [823, 235, 1042, 988],
  17636. * 'score': [95.8, 81.4, 91.2, 76.9]
  17637. * }
  17638. *
  17639. * + "typedArray"
  17640. *
  17641. * + "unknown"
  17642. */
  17643. /**
  17644. * @constructor
  17645. * @param {Object} fields
  17646. * @param {string} fields.sourceFormat
  17647. * @param {Array|Object} fields.fromDataset
  17648. * @param {Array|Object} [fields.data]
  17649. * @param {string} [seriesLayoutBy='column']
  17650. * @param {Array.<Object|string>} [dimensionsDefine]
  17651. * @param {Objet|HashMap} [encodeDefine]
  17652. * @param {number} [startIndex=0]
  17653. * @param {number} [dimensionsDetectCount]
  17654. */
  17655. function Source(fields) {
  17656. /**
  17657. * @type {boolean}
  17658. */
  17659. this.fromDataset = fields.fromDataset;
  17660. /**
  17661. * Not null/undefined.
  17662. * @type {Array|Object}
  17663. */
  17664. this.data = fields.data || (
  17665. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17666. );
  17667. /**
  17668. * See also "detectSourceFormat".
  17669. * Not null/undefined.
  17670. * @type {string}
  17671. */
  17672. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17673. /**
  17674. * 'row' or 'column'
  17675. * Not null/undefined.
  17676. * @type {string} seriesLayoutBy
  17677. */
  17678. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17679. /**
  17680. * dimensions definition in option.
  17681. * can be null/undefined.
  17682. * @type {Array.<Object|string>}
  17683. */
  17684. this.dimensionsDefine = fields.dimensionsDefine;
  17685. /**
  17686. * encode definition in option.
  17687. * can be null/undefined.
  17688. * @type {Objet|HashMap}
  17689. */
  17690. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17691. /**
  17692. * Not null/undefined, uint.
  17693. * @type {number}
  17694. */
  17695. this.startIndex = fields.startIndex || 0;
  17696. /**
  17697. * Can be null/undefined (when unknown), uint.
  17698. * @type {number}
  17699. */
  17700. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17701. }
  17702. /**
  17703. * Wrap original series data for some compatibility cases.
  17704. */
  17705. Source.seriesDataToSource = function (data) {
  17706. return new Source({
  17707. data: data,
  17708. sourceFormat: isTypedArray(data)
  17709. ? SOURCE_FORMAT_TYPED_ARRAY
  17710. : SOURCE_FORMAT_ORIGINAL,
  17711. fromDataset: false
  17712. });
  17713. };
  17714. enableClassCheck(Source);
  17715. /*
  17716. * Licensed to the Apache Software Foundation (ASF) under one
  17717. * or more contributor license agreements. See the NOTICE file
  17718. * distributed with this work for additional information
  17719. * regarding copyright ownership. The ASF licenses this file
  17720. * to you under the Apache License, Version 2.0 (the
  17721. * "License"); you may not use this file except in compliance
  17722. * with the License. You may obtain a copy of the License at
  17723. *
  17724. * http://www.apache.org/licenses/LICENSE-2.0
  17725. *
  17726. * Unless required by applicable law or agreed to in writing,
  17727. * software distributed under the License is distributed on an
  17728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17729. * KIND, either express or implied. See the License for the
  17730. * specific language governing permissions and limitations
  17731. * under the License.
  17732. */
  17733. var inner$3 = makeInner();
  17734. /**
  17735. * @see {module:echarts/data/Source}
  17736. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17737. * @return {string} sourceFormat
  17738. */
  17739. function detectSourceFormat(datasetModel) {
  17740. var data = datasetModel.option.source;
  17741. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17742. if (isTypedArray(data)) {
  17743. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17744. }
  17745. else if (isArray(data)) {
  17746. // FIXME Whether tolerate null in top level array?
  17747. if (data.length === 0) {
  17748. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17749. }
  17750. for (var i = 0, len = data.length; i < len; i++) {
  17751. var item = data[i];
  17752. if (item == null) {
  17753. continue;
  17754. }
  17755. else if (isArray(item)) {
  17756. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17757. break;
  17758. }
  17759. else if (isObject$1(item)) {
  17760. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17761. break;
  17762. }
  17763. }
  17764. }
  17765. else if (isObject$1(data)) {
  17766. for (var key in data) {
  17767. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17768. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17769. break;
  17770. }
  17771. }
  17772. }
  17773. else if (data != null) {
  17774. throw new Error('Invalid data');
  17775. }
  17776. inner$3(datasetModel).sourceFormat = sourceFormat;
  17777. }
  17778. /**
  17779. * [Scenarios]:
  17780. * (1) Provide source data directly:
  17781. * series: {
  17782. * encode: {...},
  17783. * dimensions: [...]
  17784. * seriesLayoutBy: 'row',
  17785. * data: [[...]]
  17786. * }
  17787. * (2) Refer to datasetModel.
  17788. * series: [{
  17789. * encode: {...}
  17790. * // Ignore datasetIndex means `datasetIndex: 0`
  17791. * // and the dimensions defination in dataset is used
  17792. * }, {
  17793. * encode: {...},
  17794. * seriesLayoutBy: 'column',
  17795. * datasetIndex: 1
  17796. * }]
  17797. *
  17798. * Get data from series itself or datset.
  17799. * @return {module:echarts/data/Source} source
  17800. */
  17801. function getSource(seriesModel) {
  17802. return inner$3(seriesModel).source;
  17803. }
  17804. /**
  17805. * MUST be called before mergeOption of all series.
  17806. * @param {module:echarts/model/Global} ecModel
  17807. */
  17808. function resetSourceDefaulter(ecModel) {
  17809. // `datasetMap` is used to make default encode.
  17810. inner$3(ecModel).datasetMap = createHashMap();
  17811. }
  17812. /**
  17813. * [Caution]:
  17814. * MUST be called after series option merged and
  17815. * before "series.getInitailData()" called.
  17816. *
  17817. * [The rule of making default encode]:
  17818. * Category axis (if exists) alway map to the first dimension.
  17819. * Each other axis occupies a subsequent dimension.
  17820. *
  17821. * [Why make default encode]:
  17822. * Simplify the typing of encode in option, avoiding the case like that:
  17823. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17824. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17825. *
  17826. * @param {module:echarts/model/Series} seriesModel
  17827. */
  17828. function prepareSource(seriesModel) {
  17829. var seriesOption = seriesModel.option;
  17830. var data = seriesOption.data;
  17831. var sourceFormat = isTypedArray(data)
  17832. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17833. var fromDataset = false;
  17834. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17835. var sourceHeader = seriesOption.sourceHeader;
  17836. var dimensionsDefine = seriesOption.dimensions;
  17837. var datasetModel = getDatasetModel(seriesModel);
  17838. if (datasetModel) {
  17839. var datasetOption = datasetModel.option;
  17840. data = datasetOption.source;
  17841. sourceFormat = inner$3(datasetModel).sourceFormat;
  17842. fromDataset = true;
  17843. // These settings from series has higher priority.
  17844. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17845. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17846. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17847. }
  17848. var completeResult = completeBySourceData(
  17849. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17850. );
  17851. // Note: dataset option does not have `encode`.
  17852. var encodeDefine = seriesOption.encode;
  17853. if (!encodeDefine && datasetModel) {
  17854. encodeDefine = makeDefaultEncode(
  17855. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17856. );
  17857. }
  17858. inner$3(seriesModel).source = new Source({
  17859. data: data,
  17860. fromDataset: fromDataset,
  17861. seriesLayoutBy: seriesLayoutBy,
  17862. sourceFormat: sourceFormat,
  17863. dimensionsDefine: completeResult.dimensionsDefine,
  17864. startIndex: completeResult.startIndex,
  17865. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17866. encodeDefine: encodeDefine
  17867. });
  17868. }
  17869. // return {startIndex, dimensionsDefine, dimensionsCount}
  17870. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17871. if (!data) {
  17872. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17873. }
  17874. var dimensionsDetectCount;
  17875. var startIndex;
  17876. var findPotentialName;
  17877. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17878. // Rule: Most of the first line are string: it is header.
  17879. // Caution: consider a line with 5 string and 1 number,
  17880. // it still can not be sure it is a head, because the
  17881. // 5 string may be 5 values of category columns.
  17882. if (sourceHeader === 'auto' || sourceHeader == null) {
  17883. arrayRowsTravelFirst(function (val) {
  17884. // '-' is regarded as null/undefined.
  17885. if (val != null && val !== '-') {
  17886. if (isString(val)) {
  17887. startIndex == null && (startIndex = 1);
  17888. }
  17889. else {
  17890. startIndex = 0;
  17891. }
  17892. }
  17893. // 10 is an experience number, avoid long loop.
  17894. }, seriesLayoutBy, data, 10);
  17895. }
  17896. else {
  17897. startIndex = sourceHeader ? 1 : 0;
  17898. }
  17899. if (!dimensionsDefine && startIndex === 1) {
  17900. dimensionsDefine = [];
  17901. arrayRowsTravelFirst(function (val, index) {
  17902. dimensionsDefine[index] = val != null ? val : '';
  17903. }, seriesLayoutBy, data);
  17904. }
  17905. dimensionsDetectCount = dimensionsDefine
  17906. ? dimensionsDefine.length
  17907. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17908. ? data.length
  17909. : data[0]
  17910. ? data[0].length
  17911. : null;
  17912. }
  17913. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17914. if (!dimensionsDefine) {
  17915. dimensionsDefine = objectRowsCollectDimensions(data);
  17916. findPotentialName = true;
  17917. }
  17918. }
  17919. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17920. if (!dimensionsDefine) {
  17921. dimensionsDefine = [];
  17922. findPotentialName = true;
  17923. each$1(data, function (colArr, key) {
  17924. dimensionsDefine.push(key);
  17925. });
  17926. }
  17927. }
  17928. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17929. var value0 = getDataItemValue(data[0]);
  17930. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17931. }
  17932. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17933. if (__DEV__) {
  17934. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17935. }
  17936. }
  17937. var potentialNameDimIndex;
  17938. if (findPotentialName) {
  17939. each$1(dimensionsDefine, function (dim, idx) {
  17940. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17941. potentialNameDimIndex = idx;
  17942. }
  17943. });
  17944. }
  17945. return {
  17946. startIndex: startIndex,
  17947. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17948. dimensionsDetectCount: dimensionsDetectCount,
  17949. potentialNameDimIndex: potentialNameDimIndex
  17950. // TODO: potentialIdDimIdx
  17951. };
  17952. }
  17953. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17954. // which is reasonable. But dimension name is duplicated.
  17955. // Returns undefined or an array contains only object without null/undefiend or string.
  17956. function normalizeDimensionsDefine(dimensionsDefine) {
  17957. if (!dimensionsDefine) {
  17958. // The meaning of null/undefined is different from empty array.
  17959. return;
  17960. }
  17961. var nameMap = createHashMap();
  17962. return map(dimensionsDefine, function (item, index) {
  17963. item = extend({}, isObject$1(item) ? item : {name: item});
  17964. // User can set null in dimensions.
  17965. // We dont auto specify name, othewise a given name may
  17966. // cause it be refered unexpectedly.
  17967. if (item.name == null) {
  17968. return item;
  17969. }
  17970. // Also consider number form like 2012.
  17971. item.name += '';
  17972. // User may also specify displayName.
  17973. // displayName will always exists except user not
  17974. // specified or dim name is not specified or detected.
  17975. // (A auto generated dim name will not be used as
  17976. // displayName).
  17977. if (item.displayName == null) {
  17978. item.displayName = item.name;
  17979. }
  17980. var exist = nameMap.get(item.name);
  17981. if (!exist) {
  17982. nameMap.set(item.name, {count: 1});
  17983. }
  17984. else {
  17985. item.name += '-' + exist.count++;
  17986. }
  17987. return item;
  17988. });
  17989. }
  17990. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17991. maxLoop == null && (maxLoop = Infinity);
  17992. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17993. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17994. cb(data[i] ? data[i][0] : null, i);
  17995. }
  17996. }
  17997. else {
  17998. var value0 = data[0] || [];
  17999. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18000. cb(value0[i], i);
  18001. }
  18002. }
  18003. }
  18004. function objectRowsCollectDimensions(data) {
  18005. var firstIndex = 0;
  18006. var obj;
  18007. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18008. if (obj) {
  18009. var dimensions = [];
  18010. each$1(obj, function (value, key) {
  18011. dimensions.push(key);
  18012. });
  18013. return dimensions;
  18014. }
  18015. }
  18016. // ??? TODO merge to completedimensions, where also has
  18017. // default encode making logic. And the default rule
  18018. // should depends on series? consider 'map'.
  18019. function makeDefaultEncode(
  18020. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  18021. ) {
  18022. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  18023. var encode = {};
  18024. // var encodeTooltip = [];
  18025. // var encodeLabel = [];
  18026. var encodeItemName = [];
  18027. var encodeSeriesName = [];
  18028. var seriesType = seriesModel.subType;
  18029. // ??? TODO refactor: provide by series itself.
  18030. // Consider the case: 'map' series is based on geo coordSys,
  18031. // 'graph', 'heatmap' can be based on cartesian. But can not
  18032. // give default rule simply here.
  18033. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  18034. var cSeriesMap = createHashMap([
  18035. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  18036. ]);
  18037. // Usually in this case series will use the first data
  18038. // dimension as the "value" dimension, or other default
  18039. // processes respectively.
  18040. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  18041. var ecModel = seriesModel.ecModel;
  18042. var datasetMap = inner$3(ecModel).datasetMap;
  18043. var key = datasetModel.uid + '_' + seriesLayoutBy;
  18044. var datasetRecord = datasetMap.get(key)
  18045. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  18046. // TODO
  18047. // Auto detect first time axis and do arrangement.
  18048. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  18049. // In value way.
  18050. if (coordSysDefine.firstCategoryDimIndex == null) {
  18051. var dataDim = datasetRecord.valueWayDim++;
  18052. encode[coordDim] = dataDim;
  18053. // ??? TODO give a better default series name rule?
  18054. // especially when encode x y specified.
  18055. // consider: when mutiple series share one dimension
  18056. // category axis, series name should better use
  18057. // the other dimsion name. On the other hand, use
  18058. // both dimensions name.
  18059. encodeSeriesName.push(dataDim);
  18060. // encodeTooltip.push(dataDim);
  18061. // encodeLabel.push(dataDim);
  18062. }
  18063. // In category way, category axis.
  18064. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  18065. encode[coordDim] = 0;
  18066. encodeItemName.push(0);
  18067. }
  18068. // In category way, non-category axis.
  18069. else {
  18070. var dataDim = datasetRecord.categoryWayDim++;
  18071. encode[coordDim] = dataDim;
  18072. // encodeTooltip.push(dataDim);
  18073. // encodeLabel.push(dataDim);
  18074. encodeSeriesName.push(dataDim);
  18075. }
  18076. });
  18077. }
  18078. // Do not make a complex rule! Hard to code maintain and not necessary.
  18079. // ??? TODO refactor: provide by series itself.
  18080. // [{name: ..., value: ...}, ...] like:
  18081. else if (nSeriesMap.get(seriesType) != null) {
  18082. // Find the first not ordinal. (5 is an experience value)
  18083. var firstNotOrdinal;
  18084. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  18085. if (!doGuessOrdinal(
  18086. data, sourceFormat, seriesLayoutBy,
  18087. completeResult.dimensionsDefine, completeResult.startIndex, i
  18088. )) {
  18089. firstNotOrdinal = i;
  18090. }
  18091. }
  18092. if (firstNotOrdinal != null) {
  18093. encode.value = firstNotOrdinal;
  18094. var nameDimIndex = completeResult.potentialNameDimIndex
  18095. || Math.max(firstNotOrdinal - 1, 0);
  18096. // By default, label use itemName in charts.
  18097. // So we dont set encodeLabel here.
  18098. encodeSeriesName.push(nameDimIndex);
  18099. encodeItemName.push(nameDimIndex);
  18100. // encodeTooltip.push(firstNotOrdinal);
  18101. }
  18102. }
  18103. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  18104. // encodeLabel.length && (encode.label = encodeLabel);
  18105. encodeItemName.length && (encode.itemName = encodeItemName);
  18106. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18107. return encode;
  18108. }
  18109. /**
  18110. * If return null/undefined, indicate that should not use datasetModel.
  18111. */
  18112. function getDatasetModel(seriesModel) {
  18113. var option = seriesModel.option;
  18114. // Caution: consider the scenario:
  18115. // A dataset is declared and a series is not expected to use the dataset,
  18116. // and at the beginning `setOption({series: { noData })` (just prepare other
  18117. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18118. // the user should set an empty array to avoid that dataset is used by default.
  18119. var thisData = option.data;
  18120. if (!thisData) {
  18121. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18122. }
  18123. }
  18124. /**
  18125. * The rule should not be complex, otherwise user might not
  18126. * be able to known where the data is wrong.
  18127. * The code is ugly, but how to make it neat?
  18128. *
  18129. * @param {module:echars/data/Source} source
  18130. * @param {number} dimIndex
  18131. * @return {boolean} Whether ordinal.
  18132. */
  18133. function guessOrdinal(source, dimIndex) {
  18134. return doGuessOrdinal(
  18135. source.data,
  18136. source.sourceFormat,
  18137. source.seriesLayoutBy,
  18138. source.dimensionsDefine,
  18139. source.startIndex,
  18140. dimIndex
  18141. );
  18142. }
  18143. // dimIndex may be overflow source data.
  18144. function doGuessOrdinal(
  18145. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18146. ) {
  18147. var result;
  18148. // Experience value.
  18149. var maxLoop = 5;
  18150. if (isTypedArray(data)) {
  18151. return false;
  18152. }
  18153. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18154. // always exists in source.
  18155. var dimName;
  18156. if (dimensionsDefine) {
  18157. dimName = dimensionsDefine[dimIndex];
  18158. dimName = isObject$1(dimName) ? dimName.name : dimName;
  18159. }
  18160. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18161. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18162. var sample = data[dimIndex];
  18163. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18164. if ((result = detectValue(sample[startIndex + i])) != null) {
  18165. return result;
  18166. }
  18167. }
  18168. }
  18169. else {
  18170. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18171. var row = data[startIndex + i];
  18172. if (row && (result = detectValue(row[dimIndex])) != null) {
  18173. return result;
  18174. }
  18175. }
  18176. }
  18177. }
  18178. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18179. if (!dimName) {
  18180. return;
  18181. }
  18182. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18183. var item = data[i];
  18184. if (item && (result = detectValue(item[dimName])) != null) {
  18185. return result;
  18186. }
  18187. }
  18188. }
  18189. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18190. if (!dimName) {
  18191. return;
  18192. }
  18193. var sample = data[dimName];
  18194. if (!sample || isTypedArray(sample)) {
  18195. return false;
  18196. }
  18197. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18198. if ((result = detectValue(sample[i])) != null) {
  18199. return result;
  18200. }
  18201. }
  18202. }
  18203. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18204. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18205. var item = data[i];
  18206. var val = getDataItemValue(item);
  18207. if (!isArray(val)) {
  18208. return false;
  18209. }
  18210. if ((result = detectValue(val[dimIndex])) != null) {
  18211. return result;
  18212. }
  18213. }
  18214. }
  18215. function detectValue(val) {
  18216. // Consider usage convenience, '1', '2' will be treated as "number".
  18217. // `isFinit('')` get `true`.
  18218. if (val != null && isFinite(val) && val !== '') {
  18219. return false;
  18220. }
  18221. else if (isString(val) && val !== '-') {
  18222. return true;
  18223. }
  18224. }
  18225. return false;
  18226. }
  18227. /*
  18228. * Licensed to the Apache Software Foundation (ASF) under one
  18229. * or more contributor license agreements. See the NOTICE file
  18230. * distributed with this work for additional information
  18231. * regarding copyright ownership. The ASF licenses this file
  18232. * to you under the Apache License, Version 2.0 (the
  18233. * "License"); you may not use this file except in compliance
  18234. * with the License. You may obtain a copy of the License at
  18235. *
  18236. * http://www.apache.org/licenses/LICENSE-2.0
  18237. *
  18238. * Unless required by applicable law or agreed to in writing,
  18239. * software distributed under the License is distributed on an
  18240. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18241. * KIND, either express or implied. See the License for the
  18242. * specific language governing permissions and limitations
  18243. * under the License.
  18244. */
  18245. /**
  18246. * ECharts global model
  18247. *
  18248. * @module {echarts/model/Global}
  18249. */
  18250. /**
  18251. * Caution: If the mechanism should be changed some day, these cases
  18252. * should be considered:
  18253. *
  18254. * (1) In `merge option` mode, if using the same option to call `setOption`
  18255. * many times, the result should be the same (try our best to ensure that).
  18256. * (2) In `merge option` mode, if a component has no id/name specified, it
  18257. * will be merged by index, and the result sequence of the components is
  18258. * consistent to the original sequence.
  18259. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18260. * `mergeOption` in module:echarts/model/OptionManager.
  18261. */
  18262. var OPTION_INNER_KEY = '\0_ec_inner';
  18263. /**
  18264. * @alias module:echarts/model/Global
  18265. *
  18266. * @param {Object} option
  18267. * @param {module:echarts/model/Model} parentModel
  18268. * @param {Object} theme
  18269. */
  18270. var GlobalModel = Model.extend({
  18271. init: function (option, parentModel, theme, optionManager) {
  18272. theme = theme || {};
  18273. this.option = null; // Mark as not initialized.
  18274. /**
  18275. * @type {module:echarts/model/Model}
  18276. * @private
  18277. */
  18278. this._theme = new Model(theme);
  18279. /**
  18280. * @type {module:echarts/model/OptionManager}
  18281. */
  18282. this._optionManager = optionManager;
  18283. },
  18284. setOption: function (option, optionPreprocessorFuncs) {
  18285. assert$1(
  18286. !(OPTION_INNER_KEY in option),
  18287. 'please use chart.getOption()'
  18288. );
  18289. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18290. this.resetOption(null);
  18291. },
  18292. /**
  18293. * @param {string} type null/undefined: reset all.
  18294. * 'recreate': force recreate all.
  18295. * 'timeline': only reset timeline option
  18296. * 'media': only reset media query option
  18297. * @return {boolean} Whether option changed.
  18298. */
  18299. resetOption: function (type) {
  18300. var optionChanged = false;
  18301. var optionManager = this._optionManager;
  18302. if (!type || type === 'recreate') {
  18303. var baseOption = optionManager.mountOption(type === 'recreate');
  18304. if (!this.option || type === 'recreate') {
  18305. initBase.call(this, baseOption);
  18306. }
  18307. else {
  18308. this.restoreData();
  18309. this.mergeOption(baseOption);
  18310. }
  18311. optionChanged = true;
  18312. }
  18313. if (type === 'timeline' || type === 'media') {
  18314. this.restoreData();
  18315. }
  18316. if (!type || type === 'recreate' || type === 'timeline') {
  18317. var timelineOption = optionManager.getTimelineOption(this);
  18318. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18319. }
  18320. if (!type || type === 'recreate' || type === 'media') {
  18321. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18322. if (mediaOptions.length) {
  18323. each$1(mediaOptions, function (mediaOption) {
  18324. this.mergeOption(mediaOption, optionChanged = true);
  18325. }, this);
  18326. }
  18327. }
  18328. return optionChanged;
  18329. },
  18330. /**
  18331. * @protected
  18332. */
  18333. mergeOption: function (newOption) {
  18334. var option = this.option;
  18335. var componentsMap = this._componentsMap;
  18336. var newCptTypes = [];
  18337. resetSourceDefaulter(this);
  18338. // If no component class, merge directly.
  18339. // For example: color, animaiton options, etc.
  18340. each$1(newOption, function (componentOption, mainType) {
  18341. if (componentOption == null) {
  18342. return;
  18343. }
  18344. if (!ComponentModel.hasClass(mainType)) {
  18345. // globalSettingTask.dirty();
  18346. option[mainType] = option[mainType] == null
  18347. ? clone(componentOption)
  18348. : merge(option[mainType], componentOption, true);
  18349. }
  18350. else if (mainType) {
  18351. newCptTypes.push(mainType);
  18352. }
  18353. });
  18354. ComponentModel.topologicalTravel(
  18355. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18356. );
  18357. function visitComponent(mainType, dependencies) {
  18358. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18359. var mapResult = mappingToExists(
  18360. componentsMap.get(mainType), newCptOptionList
  18361. );
  18362. makeIdAndName(mapResult);
  18363. // Set mainType and complete subType.
  18364. each$1(mapResult, function (item, index) {
  18365. var opt = item.option;
  18366. if (isObject$1(opt)) {
  18367. item.keyInfo.mainType = mainType;
  18368. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18369. }
  18370. });
  18371. var dependentModels = getComponentsByTypes(
  18372. componentsMap, dependencies
  18373. );
  18374. option[mainType] = [];
  18375. componentsMap.set(mainType, []);
  18376. each$1(mapResult, function (resultItem, index) {
  18377. var componentModel = resultItem.exist;
  18378. var newCptOption = resultItem.option;
  18379. assert$1(
  18380. isObject$1(newCptOption) || componentModel,
  18381. 'Empty component definition'
  18382. );
  18383. // Consider where is no new option and should be merged using {},
  18384. // see removeEdgeAndAdd in topologicalTravel and
  18385. // ComponentModel.getAllClassMainTypes.
  18386. if (!newCptOption) {
  18387. componentModel.mergeOption({}, this);
  18388. componentModel.optionUpdated({}, false);
  18389. }
  18390. else {
  18391. var ComponentModelClass = ComponentModel.getClass(
  18392. mainType, resultItem.keyInfo.subType, true
  18393. );
  18394. if (componentModel && componentModel instanceof ComponentModelClass) {
  18395. componentModel.name = resultItem.keyInfo.name;
  18396. // componentModel.settingTask && componentModel.settingTask.dirty();
  18397. componentModel.mergeOption(newCptOption, this);
  18398. componentModel.optionUpdated(newCptOption, false);
  18399. }
  18400. else {
  18401. // PENDING Global as parent ?
  18402. var extraOpt = extend(
  18403. {
  18404. dependentModels: dependentModels,
  18405. componentIndex: index
  18406. },
  18407. resultItem.keyInfo
  18408. );
  18409. componentModel = new ComponentModelClass(
  18410. newCptOption, this, this, extraOpt
  18411. );
  18412. extend(componentModel, extraOpt);
  18413. componentModel.init(newCptOption, this, this, extraOpt);
  18414. // Call optionUpdated after init.
  18415. // newCptOption has been used as componentModel.option
  18416. // and may be merged with theme and default, so pass null
  18417. // to avoid confusion.
  18418. componentModel.optionUpdated(null, true);
  18419. }
  18420. }
  18421. componentsMap.get(mainType)[index] = componentModel;
  18422. option[mainType][index] = componentModel.option;
  18423. }, this);
  18424. // Backup series for filtering.
  18425. if (mainType === 'series') {
  18426. createSeriesIndices(this, componentsMap.get('series'));
  18427. }
  18428. }
  18429. this._seriesIndicesMap = createHashMap(
  18430. this._seriesIndices = this._seriesIndices || []
  18431. );
  18432. },
  18433. /**
  18434. * Get option for output (cloned option and inner info removed)
  18435. * @public
  18436. * @return {Object}
  18437. */
  18438. getOption: function () {
  18439. var option = clone(this.option);
  18440. each$1(option, function (opts, mainType) {
  18441. if (ComponentModel.hasClass(mainType)) {
  18442. var opts = normalizeToArray(opts);
  18443. for (var i = opts.length - 1; i >= 0; i--) {
  18444. // Remove options with inner id.
  18445. if (isIdInner(opts[i])) {
  18446. opts.splice(i, 1);
  18447. }
  18448. }
  18449. option[mainType] = opts;
  18450. }
  18451. });
  18452. delete option[OPTION_INNER_KEY];
  18453. return option;
  18454. },
  18455. /**
  18456. * @return {module:echarts/model/Model}
  18457. */
  18458. getTheme: function () {
  18459. return this._theme;
  18460. },
  18461. /**
  18462. * @param {string} mainType
  18463. * @param {number} [idx=0]
  18464. * @return {module:echarts/model/Component}
  18465. */
  18466. getComponent: function (mainType, idx) {
  18467. var list = this._componentsMap.get(mainType);
  18468. if (list) {
  18469. return list[idx || 0];
  18470. }
  18471. },
  18472. /**
  18473. * If none of index and id and name used, return all components with mainType.
  18474. * @param {Object} condition
  18475. * @param {string} condition.mainType
  18476. * @param {string} [condition.subType] If ignore, only query by mainType
  18477. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18478. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18479. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18480. * @return {Array.<module:echarts/model/Component>}
  18481. */
  18482. queryComponents: function (condition) {
  18483. var mainType = condition.mainType;
  18484. if (!mainType) {
  18485. return [];
  18486. }
  18487. var index = condition.index;
  18488. var id = condition.id;
  18489. var name = condition.name;
  18490. var cpts = this._componentsMap.get(mainType);
  18491. if (!cpts || !cpts.length) {
  18492. return [];
  18493. }
  18494. var result;
  18495. if (index != null) {
  18496. if (!isArray(index)) {
  18497. index = [index];
  18498. }
  18499. result = filter(map(index, function (idx) {
  18500. return cpts[idx];
  18501. }), function (val) {
  18502. return !!val;
  18503. });
  18504. }
  18505. else if (id != null) {
  18506. var isIdArray = isArray(id);
  18507. result = filter(cpts, function (cpt) {
  18508. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18509. || (!isIdArray && cpt.id === id);
  18510. });
  18511. }
  18512. else if (name != null) {
  18513. var isNameArray = isArray(name);
  18514. result = filter(cpts, function (cpt) {
  18515. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18516. || (!isNameArray && cpt.name === name);
  18517. });
  18518. }
  18519. else {
  18520. // Return all components with mainType
  18521. result = cpts.slice();
  18522. }
  18523. return filterBySubType(result, condition);
  18524. },
  18525. /**
  18526. * The interface is different from queryComponents,
  18527. * which is convenient for inner usage.
  18528. *
  18529. * @usage
  18530. * var result = findComponents(
  18531. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18532. * );
  18533. * var result = findComponents(
  18534. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18535. * );
  18536. * var result = findComponents(
  18537. * {mainType: 'series'},
  18538. * function (model, index) {...}
  18539. * );
  18540. * // result like [component0, componnet1, ...]
  18541. *
  18542. * @param {Object} condition
  18543. * @param {string} condition.mainType Mandatory.
  18544. * @param {string} [condition.subType] Optional.
  18545. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18546. * where xxx is mainType.
  18547. * If query attribute is null/undefined or has no index/id/name,
  18548. * do not filtering by query conditions, which is convenient for
  18549. * no-payload situations or when target of action is global.
  18550. * @param {Function} [condition.filter] parameter: component, return boolean.
  18551. * @return {Array.<module:echarts/model/Component>}
  18552. */
  18553. findComponents: function (condition) {
  18554. var query = condition.query;
  18555. var mainType = condition.mainType;
  18556. var queryCond = getQueryCond(query);
  18557. var result = queryCond
  18558. ? this.queryComponents(queryCond)
  18559. : this._componentsMap.get(mainType);
  18560. return doFilter(filterBySubType(result, condition));
  18561. function getQueryCond(q) {
  18562. var indexAttr = mainType + 'Index';
  18563. var idAttr = mainType + 'Id';
  18564. var nameAttr = mainType + 'Name';
  18565. return q && (
  18566. q[indexAttr] != null
  18567. || q[idAttr] != null
  18568. || q[nameAttr] != null
  18569. )
  18570. ? {
  18571. mainType: mainType,
  18572. // subType will be filtered finally.
  18573. index: q[indexAttr],
  18574. id: q[idAttr],
  18575. name: q[nameAttr]
  18576. }
  18577. : null;
  18578. }
  18579. function doFilter(res) {
  18580. return condition.filter
  18581. ? filter(res, condition.filter)
  18582. : res;
  18583. }
  18584. },
  18585. /**
  18586. * @usage
  18587. * eachComponent('legend', function (legendModel, index) {
  18588. * ...
  18589. * });
  18590. * eachComponent(function (componentType, model, index) {
  18591. * // componentType does not include subType
  18592. * // (componentType is 'xxx' but not 'xxx.aa')
  18593. * });
  18594. * eachComponent(
  18595. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18596. * function (model, index) {...}
  18597. * );
  18598. * eachComponent(
  18599. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18600. * function (model, index) {...}
  18601. * );
  18602. *
  18603. * @param {string|Object=} mainType When mainType is object, the definition
  18604. * is the same as the method 'findComponents'.
  18605. * @param {Function} cb
  18606. * @param {*} context
  18607. */
  18608. eachComponent: function (mainType, cb, context) {
  18609. var componentsMap = this._componentsMap;
  18610. if (typeof mainType === 'function') {
  18611. context = cb;
  18612. cb = mainType;
  18613. componentsMap.each(function (components, componentType) {
  18614. each$1(components, function (component, index) {
  18615. cb.call(context, componentType, component, index);
  18616. });
  18617. });
  18618. }
  18619. else if (isString(mainType)) {
  18620. each$1(componentsMap.get(mainType), cb, context);
  18621. }
  18622. else if (isObject$1(mainType)) {
  18623. var queryResult = this.findComponents(mainType);
  18624. each$1(queryResult, cb, context);
  18625. }
  18626. },
  18627. /**
  18628. * @param {string} name
  18629. * @return {Array.<module:echarts/model/Series>}
  18630. */
  18631. getSeriesByName: function (name) {
  18632. var series = this._componentsMap.get('series');
  18633. return filter(series, function (oneSeries) {
  18634. return oneSeries.name === name;
  18635. });
  18636. },
  18637. /**
  18638. * @param {number} seriesIndex
  18639. * @return {module:echarts/model/Series}
  18640. */
  18641. getSeriesByIndex: function (seriesIndex) {
  18642. return this._componentsMap.get('series')[seriesIndex];
  18643. },
  18644. /**
  18645. * Get series list before filtered by type.
  18646. * FIXME: rename to getRawSeriesByType?
  18647. *
  18648. * @param {string} subType
  18649. * @return {Array.<module:echarts/model/Series>}
  18650. */
  18651. getSeriesByType: function (subType) {
  18652. var series = this._componentsMap.get('series');
  18653. return filter(series, function (oneSeries) {
  18654. return oneSeries.subType === subType;
  18655. });
  18656. },
  18657. /**
  18658. * @return {Array.<module:echarts/model/Series>}
  18659. */
  18660. getSeries: function () {
  18661. return this._componentsMap.get('series').slice();
  18662. },
  18663. /**
  18664. * @return {number}
  18665. */
  18666. getSeriesCount: function () {
  18667. return this._componentsMap.get('series').length;
  18668. },
  18669. /**
  18670. * After filtering, series may be different
  18671. * frome raw series.
  18672. *
  18673. * @param {Function} cb
  18674. * @param {*} context
  18675. */
  18676. eachSeries: function (cb, context) {
  18677. assertSeriesInitialized(this);
  18678. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18679. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18680. cb.call(context, series, rawSeriesIndex);
  18681. }, this);
  18682. },
  18683. /**
  18684. * Iterate raw series before filtered.
  18685. *
  18686. * @param {Function} cb
  18687. * @param {*} context
  18688. */
  18689. eachRawSeries: function (cb, context) {
  18690. each$1(this._componentsMap.get('series'), cb, context);
  18691. },
  18692. /**
  18693. * After filtering, series may be different.
  18694. * frome raw series.
  18695. *
  18696. * @parma {string} subType
  18697. * @param {Function} cb
  18698. * @param {*} context
  18699. */
  18700. eachSeriesByType: function (subType, cb, context) {
  18701. assertSeriesInitialized(this);
  18702. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18703. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18704. if (series.subType === subType) {
  18705. cb.call(context, series, rawSeriesIndex);
  18706. }
  18707. }, this);
  18708. },
  18709. /**
  18710. * Iterate raw series before filtered of given type.
  18711. *
  18712. * @parma {string} subType
  18713. * @param {Function} cb
  18714. * @param {*} context
  18715. */
  18716. eachRawSeriesByType: function (subType, cb, context) {
  18717. return each$1(this.getSeriesByType(subType), cb, context);
  18718. },
  18719. /**
  18720. * @param {module:echarts/model/Series} seriesModel
  18721. */
  18722. isSeriesFiltered: function (seriesModel) {
  18723. assertSeriesInitialized(this);
  18724. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18725. },
  18726. /**
  18727. * @return {Array.<number>}
  18728. */
  18729. getCurrentSeriesIndices: function () {
  18730. return (this._seriesIndices || []).slice();
  18731. },
  18732. /**
  18733. * @param {Function} cb
  18734. * @param {*} context
  18735. */
  18736. filterSeries: function (cb, context) {
  18737. assertSeriesInitialized(this);
  18738. var filteredSeries = filter(
  18739. this._componentsMap.get('series'), cb, context
  18740. );
  18741. createSeriesIndices(this, filteredSeries);
  18742. },
  18743. restoreData: function (payload) {
  18744. var componentsMap = this._componentsMap;
  18745. createSeriesIndices(this, componentsMap.get('series'));
  18746. var componentTypes = [];
  18747. componentsMap.each(function (components, componentType) {
  18748. componentTypes.push(componentType);
  18749. });
  18750. ComponentModel.topologicalTravel(
  18751. componentTypes,
  18752. ComponentModel.getAllClassMainTypes(),
  18753. function (componentType, dependencies) {
  18754. each$1(componentsMap.get(componentType), function (component) {
  18755. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18756. && component.restoreData();
  18757. });
  18758. }
  18759. );
  18760. }
  18761. });
  18762. function isNotTargetSeries(seriesModel, payload) {
  18763. if (payload) {
  18764. var index = payload.seiresIndex;
  18765. var id = payload.seriesId;
  18766. var name = payload.seriesName;
  18767. return (index != null && seriesModel.componentIndex !== index)
  18768. || (id != null && seriesModel.id !== id)
  18769. || (name != null && seriesModel.name !== name);
  18770. }
  18771. }
  18772. /**
  18773. * @inner
  18774. */
  18775. function mergeTheme(option, theme) {
  18776. // PENDING
  18777. // NOT use `colorLayer` in theme if option has `color`
  18778. var notMergeColorLayer = option.color && !option.colorLayer;
  18779. each$1(theme, function (themeItem, name) {
  18780. if (name === 'colorLayer' && notMergeColorLayer) {
  18781. return;
  18782. }
  18783. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18784. if (!ComponentModel.hasClass(name)) {
  18785. if (typeof themeItem === 'object') {
  18786. option[name] = !option[name]
  18787. ? clone(themeItem)
  18788. : merge(option[name], themeItem, false);
  18789. }
  18790. else {
  18791. if (option[name] == null) {
  18792. option[name] = themeItem;
  18793. }
  18794. }
  18795. }
  18796. });
  18797. }
  18798. function initBase(baseOption) {
  18799. baseOption = baseOption;
  18800. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18801. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18802. this.option = {};
  18803. this.option[OPTION_INNER_KEY] = 1;
  18804. /**
  18805. * Init with series: [], in case of calling findSeries method
  18806. * before series initialized.
  18807. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18808. * @private
  18809. */
  18810. this._componentsMap = createHashMap({series: []});
  18811. /**
  18812. * Mapping between filtered series list and raw series list.
  18813. * key: filtered series indices, value: raw series indices.
  18814. * @type {Array.<nubmer>}
  18815. * @private
  18816. */
  18817. this._seriesIndices;
  18818. this._seriesIndicesMap;
  18819. mergeTheme(baseOption, this._theme.option);
  18820. // TODO Needs clone when merging to the unexisted property
  18821. merge(baseOption, globalDefault, false);
  18822. this.mergeOption(baseOption);
  18823. }
  18824. /**
  18825. * @inner
  18826. * @param {Array.<string>|string} types model types
  18827. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18828. */
  18829. function getComponentsByTypes(componentsMap, types) {
  18830. if (!isArray(types)) {
  18831. types = types ? [types] : [];
  18832. }
  18833. var ret = {};
  18834. each$1(types, function (type) {
  18835. ret[type] = (componentsMap.get(type) || []).slice();
  18836. });
  18837. return ret;
  18838. }
  18839. /**
  18840. * @inner
  18841. */
  18842. function determineSubType(mainType, newCptOption, existComponent) {
  18843. var subType = newCptOption.type
  18844. ? newCptOption.type
  18845. : existComponent
  18846. ? existComponent.subType
  18847. // Use determineSubType only when there is no existComponent.
  18848. : ComponentModel.determineSubType(mainType, newCptOption);
  18849. // tooltip, markline, markpoint may always has no subType
  18850. return subType;
  18851. }
  18852. /**
  18853. * @inner
  18854. */
  18855. function createSeriesIndices(ecModel, seriesModels) {
  18856. ecModel._seriesIndicesMap = createHashMap(
  18857. ecModel._seriesIndices = map(seriesModels, function (series) {
  18858. return series.componentIndex;
  18859. }) || []
  18860. );
  18861. }
  18862. /**
  18863. * @inner
  18864. */
  18865. function filterBySubType(components, condition) {
  18866. // Using hasOwnProperty for restrict. Consider
  18867. // subType is undefined in user payload.
  18868. return condition.hasOwnProperty('subType')
  18869. ? filter(components, function (cpt) {
  18870. return cpt.subType === condition.subType;
  18871. })
  18872. : components;
  18873. }
  18874. /**
  18875. * @inner
  18876. */
  18877. function assertSeriesInitialized(ecModel) {
  18878. // Components that use _seriesIndices should depends on series component,
  18879. // which make sure that their initialization is after series.
  18880. if (__DEV__) {
  18881. if (!ecModel._seriesIndices) {
  18882. throw new Error('Option should contains series.');
  18883. }
  18884. }
  18885. }
  18886. mixin(GlobalModel, colorPaletteMixin);
  18887. /*
  18888. * Licensed to the Apache Software Foundation (ASF) under one
  18889. * or more contributor license agreements. See the NOTICE file
  18890. * distributed with this work for additional information
  18891. * regarding copyright ownership. The ASF licenses this file
  18892. * to you under the Apache License, Version 2.0 (the
  18893. * "License"); you may not use this file except in compliance
  18894. * with the License. You may obtain a copy of the License at
  18895. *
  18896. * http://www.apache.org/licenses/LICENSE-2.0
  18897. *
  18898. * Unless required by applicable law or agreed to in writing,
  18899. * software distributed under the License is distributed on an
  18900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18901. * KIND, either express or implied. See the License for the
  18902. * specific language governing permissions and limitations
  18903. * under the License.
  18904. */
  18905. var echartsAPIList = [
  18906. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18907. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18908. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18909. ];
  18910. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18911. function ExtensionAPI(chartInstance) {
  18912. each$1(echartsAPIList, function (name) {
  18913. this[name] = bind(chartInstance[name], chartInstance);
  18914. }, this);
  18915. }
  18916. /*
  18917. * Licensed to the Apache Software Foundation (ASF) under one
  18918. * or more contributor license agreements. See the NOTICE file
  18919. * distributed with this work for additional information
  18920. * regarding copyright ownership. The ASF licenses this file
  18921. * to you under the Apache License, Version 2.0 (the
  18922. * "License"); you may not use this file except in compliance
  18923. * with the License. You may obtain a copy of the License at
  18924. *
  18925. * http://www.apache.org/licenses/LICENSE-2.0
  18926. *
  18927. * Unless required by applicable law or agreed to in writing,
  18928. * software distributed under the License is distributed on an
  18929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18930. * KIND, either express or implied. See the License for the
  18931. * specific language governing permissions and limitations
  18932. * under the License.
  18933. */
  18934. var coordinateSystemCreators = {};
  18935. function CoordinateSystemManager() {
  18936. this._coordinateSystems = [];
  18937. }
  18938. CoordinateSystemManager.prototype = {
  18939. constructor: CoordinateSystemManager,
  18940. create: function (ecModel, api) {
  18941. var coordinateSystems = [];
  18942. each$1(coordinateSystemCreators, function (creater, type) {
  18943. var list = creater.create(ecModel, api);
  18944. coordinateSystems = coordinateSystems.concat(list || []);
  18945. });
  18946. this._coordinateSystems = coordinateSystems;
  18947. },
  18948. update: function (ecModel, api) {
  18949. each$1(this._coordinateSystems, function (coordSys) {
  18950. coordSys.update && coordSys.update(ecModel, api);
  18951. });
  18952. },
  18953. getCoordinateSystems: function () {
  18954. return this._coordinateSystems.slice();
  18955. }
  18956. };
  18957. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18958. coordinateSystemCreators[type] = coordinateSystemCreator;
  18959. };
  18960. CoordinateSystemManager.get = function (type) {
  18961. return coordinateSystemCreators[type];
  18962. };
  18963. /*
  18964. * Licensed to the Apache Software Foundation (ASF) under one
  18965. * or more contributor license agreements. See the NOTICE file
  18966. * distributed with this work for additional information
  18967. * regarding copyright ownership. The ASF licenses this file
  18968. * to you under the Apache License, Version 2.0 (the
  18969. * "License"); you may not use this file except in compliance
  18970. * with the License. You may obtain a copy of the License at
  18971. *
  18972. * http://www.apache.org/licenses/LICENSE-2.0
  18973. *
  18974. * Unless required by applicable law or agreed to in writing,
  18975. * software distributed under the License is distributed on an
  18976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18977. * KIND, either express or implied. See the License for the
  18978. * specific language governing permissions and limitations
  18979. * under the License.
  18980. */
  18981. /**
  18982. * ECharts option manager
  18983. *
  18984. * @module {echarts/model/OptionManager}
  18985. */
  18986. var each$4 = each$1;
  18987. var clone$3 = clone;
  18988. var map$1 = map;
  18989. var merge$1 = merge;
  18990. var QUERY_REG = /^(min|max)?(.+)$/;
  18991. /**
  18992. * TERM EXPLANATIONS:
  18993. *
  18994. * [option]:
  18995. *
  18996. * An object that contains definitions of components. For example:
  18997. * var option = {
  18998. * title: {...},
  18999. * legend: {...},
  19000. * visualMap: {...},
  19001. * series: [
  19002. * {data: [...]},
  19003. * {data: [...]},
  19004. * ...
  19005. * ]
  19006. * };
  19007. *
  19008. * [rawOption]:
  19009. *
  19010. * An object input to echarts.setOption. 'rawOption' may be an
  19011. * 'option', or may be an object contains multi-options. For example:
  19012. * var option = {
  19013. * baseOption: {
  19014. * title: {...},
  19015. * legend: {...},
  19016. * series: [
  19017. * {data: [...]},
  19018. * {data: [...]},
  19019. * ...
  19020. * ]
  19021. * },
  19022. * timeline: {...},
  19023. * options: [
  19024. * {title: {...}, series: {data: [...]}},
  19025. * {title: {...}, series: {data: [...]}},
  19026. * ...
  19027. * ],
  19028. * media: [
  19029. * {
  19030. * query: {maxWidth: 320},
  19031. * option: {series: {x: 20}, visualMap: {show: false}}
  19032. * },
  19033. * {
  19034. * query: {minWidth: 320, maxWidth: 720},
  19035. * option: {series: {x: 500}, visualMap: {show: true}}
  19036. * },
  19037. * {
  19038. * option: {series: {x: 1200}, visualMap: {show: true}}
  19039. * }
  19040. * ]
  19041. * };
  19042. *
  19043. * @alias module:echarts/model/OptionManager
  19044. * @param {module:echarts/ExtensionAPI} api
  19045. */
  19046. function OptionManager(api) {
  19047. /**
  19048. * @private
  19049. * @type {module:echarts/ExtensionAPI}
  19050. */
  19051. this._api = api;
  19052. /**
  19053. * @private
  19054. * @type {Array.<number>}
  19055. */
  19056. this._timelineOptions = [];
  19057. /**
  19058. * @private
  19059. * @type {Array.<Object>}
  19060. */
  19061. this._mediaList = [];
  19062. /**
  19063. * @private
  19064. * @type {Object}
  19065. */
  19066. this._mediaDefault;
  19067. /**
  19068. * -1, means default.
  19069. * empty means no media.
  19070. * @private
  19071. * @type {Array.<number>}
  19072. */
  19073. this._currentMediaIndices = [];
  19074. /**
  19075. * @private
  19076. * @type {Object}
  19077. */
  19078. this._optionBackup;
  19079. /**
  19080. * @private
  19081. * @type {Object}
  19082. */
  19083. this._newBaseOption;
  19084. }
  19085. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19086. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19087. // rawOption cloned and backuped when timeline changed, which does no
  19088. // good to performance. What's more, that both timeline and setOption
  19089. // method supply 'notMerge' brings complex and some problems.
  19090. // Consider this case:
  19091. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19092. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19093. OptionManager.prototype = {
  19094. constructor: OptionManager,
  19095. /**
  19096. * @public
  19097. * @param {Object} rawOption Raw option.
  19098. * @param {module:echarts/model/Global} ecModel
  19099. * @param {Array.<Function>} optionPreprocessorFuncs
  19100. * @return {Object} Init option
  19101. */
  19102. setOption: function (rawOption, optionPreprocessorFuncs) {
  19103. if (rawOption) {
  19104. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19105. each$1(normalizeToArray(rawOption.series), function (series) {
  19106. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19107. });
  19108. }
  19109. // Caution: some series modify option data, if do not clone,
  19110. // it should ensure that the repeat modify correctly
  19111. // (create a new object when modify itself).
  19112. rawOption = clone$3(rawOption, true);
  19113. // FIXME
  19114. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19115. var oldOptionBackup = this._optionBackup;
  19116. var newParsedOption = parseRawOption.call(
  19117. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19118. );
  19119. this._newBaseOption = newParsedOption.baseOption;
  19120. // For setOption at second time (using merge mode);
  19121. if (oldOptionBackup) {
  19122. // Only baseOption can be merged.
  19123. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19124. // For simplicity, timeline options and media options do not support merge,
  19125. // that is, if you `setOption` twice and both has timeline options, the latter
  19126. // timeline opitons will not be merged to the formers, but just substitude them.
  19127. if (newParsedOption.timelineOptions.length) {
  19128. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19129. }
  19130. if (newParsedOption.mediaList.length) {
  19131. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19132. }
  19133. if (newParsedOption.mediaDefault) {
  19134. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19135. }
  19136. }
  19137. else {
  19138. this._optionBackup = newParsedOption;
  19139. }
  19140. },
  19141. /**
  19142. * @param {boolean} isRecreate
  19143. * @return {Object}
  19144. */
  19145. mountOption: function (isRecreate) {
  19146. var optionBackup = this._optionBackup;
  19147. // TODO
  19148. // 如果没有reset功能则不clone。
  19149. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19150. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19151. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19152. this._currentMediaIndices = [];
  19153. return clone$3(isRecreate
  19154. // this._optionBackup.baseOption, which is created at the first `setOption`
  19155. // called, and is merged into every new option by inner method `mergeOption`
  19156. // each time `setOption` called, can be only used in `isRecreate`, because
  19157. // its reliability is under suspicion. In other cases option merge is
  19158. // performed by `model.mergeOption`.
  19159. ? optionBackup.baseOption : this._newBaseOption
  19160. );
  19161. },
  19162. /**
  19163. * @param {module:echarts/model/Global} ecModel
  19164. * @return {Object}
  19165. */
  19166. getTimelineOption: function (ecModel) {
  19167. var option;
  19168. var timelineOptions = this._timelineOptions;
  19169. if (timelineOptions.length) {
  19170. // getTimelineOption can only be called after ecModel inited,
  19171. // so we can get currentIndex from timelineModel.
  19172. var timelineModel = ecModel.getComponent('timeline');
  19173. if (timelineModel) {
  19174. option = clone$3(
  19175. timelineOptions[timelineModel.getCurrentIndex()],
  19176. true
  19177. );
  19178. }
  19179. }
  19180. return option;
  19181. },
  19182. /**
  19183. * @param {module:echarts/model/Global} ecModel
  19184. * @return {Array.<Object>}
  19185. */
  19186. getMediaOption: function (ecModel) {
  19187. var ecWidth = this._api.getWidth();
  19188. var ecHeight = this._api.getHeight();
  19189. var mediaList = this._mediaList;
  19190. var mediaDefault = this._mediaDefault;
  19191. var indices = [];
  19192. var result = [];
  19193. // No media defined.
  19194. if (!mediaList.length && !mediaDefault) {
  19195. return result;
  19196. }
  19197. // Multi media may be applied, the latter defined media has higher priority.
  19198. for (var i = 0, len = mediaList.length; i < len; i++) {
  19199. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19200. indices.push(i);
  19201. }
  19202. }
  19203. // FIXME
  19204. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19205. if (!indices.length && mediaDefault) {
  19206. indices = [-1];
  19207. }
  19208. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19209. result = map$1(indices, function (index) {
  19210. return clone$3(
  19211. index === -1 ? mediaDefault.option : mediaList[index].option
  19212. );
  19213. });
  19214. }
  19215. // Otherwise return nothing.
  19216. this._currentMediaIndices = indices;
  19217. return result;
  19218. }
  19219. };
  19220. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19221. var timelineOptions = [];
  19222. var mediaList = [];
  19223. var mediaDefault;
  19224. var baseOption;
  19225. // Compatible with ec2.
  19226. var timelineOpt = rawOption.timeline;
  19227. if (rawOption.baseOption) {
  19228. baseOption = rawOption.baseOption;
  19229. }
  19230. // For timeline
  19231. if (timelineOpt || rawOption.options) {
  19232. baseOption = baseOption || {};
  19233. timelineOptions = (rawOption.options || []).slice();
  19234. }
  19235. // For media query
  19236. if (rawOption.media) {
  19237. baseOption = baseOption || {};
  19238. var media = rawOption.media;
  19239. each$4(media, function (singleMedia) {
  19240. if (singleMedia && singleMedia.option) {
  19241. if (singleMedia.query) {
  19242. mediaList.push(singleMedia);
  19243. }
  19244. else if (!mediaDefault) {
  19245. // Use the first media default.
  19246. mediaDefault = singleMedia;
  19247. }
  19248. }
  19249. });
  19250. }
  19251. // For normal option
  19252. if (!baseOption) {
  19253. baseOption = rawOption;
  19254. }
  19255. // Set timelineOpt to baseOption in ec3,
  19256. // which is convenient for merge option.
  19257. if (!baseOption.timeline) {
  19258. baseOption.timeline = timelineOpt;
  19259. }
  19260. // Preprocess.
  19261. each$4([baseOption].concat(timelineOptions)
  19262. .concat(map(mediaList, function (media) {
  19263. return media.option;
  19264. })),
  19265. function (option) {
  19266. each$4(optionPreprocessorFuncs, function (preProcess) {
  19267. preProcess(option, isNew);
  19268. });
  19269. }
  19270. );
  19271. return {
  19272. baseOption: baseOption,
  19273. timelineOptions: timelineOptions,
  19274. mediaDefault: mediaDefault,
  19275. mediaList: mediaList
  19276. };
  19277. }
  19278. /**
  19279. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19280. * Support: width, height, aspectRatio
  19281. * Can use max or min as prefix.
  19282. */
  19283. function applyMediaQuery(query, ecWidth, ecHeight) {
  19284. var realMap = {
  19285. width: ecWidth,
  19286. height: ecHeight,
  19287. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19288. };
  19289. var applicatable = true;
  19290. each$1(query, function (value, attr) {
  19291. var matched = attr.match(QUERY_REG);
  19292. if (!matched || !matched[1] || !matched[2]) {
  19293. return;
  19294. }
  19295. var operator = matched[1];
  19296. var realAttr = matched[2].toLowerCase();
  19297. if (!compare(realMap[realAttr], value, operator)) {
  19298. applicatable = false;
  19299. }
  19300. });
  19301. return applicatable;
  19302. }
  19303. function compare(real, expect, operator) {
  19304. if (operator === 'min') {
  19305. return real >= expect;
  19306. }
  19307. else if (operator === 'max') {
  19308. return real <= expect;
  19309. }
  19310. else { // Equals
  19311. return real === expect;
  19312. }
  19313. }
  19314. function indicesEquals(indices1, indices2) {
  19315. // indices is always order by asc and has only finite number.
  19316. return indices1.join(',') === indices2.join(',');
  19317. }
  19318. /**
  19319. * Consider case:
  19320. * `chart.setOption(opt1);`
  19321. * Then user do some interaction like dataZoom, dataView changing.
  19322. * `chart.setOption(opt2);`
  19323. * Then user press 'reset button' in toolbox.
  19324. *
  19325. * After doing that all of the interaction effects should be reset, the
  19326. * chart should be the same as the result of invoke
  19327. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19328. *
  19329. * Although it is not able ensure that
  19330. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19331. * `chart.setOption(merge(opt1, opt2));` exactly,
  19332. * this might be the only simple way to implement that feature.
  19333. *
  19334. * MEMO: We've considered some other approaches:
  19335. * 1. Each model handle its self restoration but not uniform treatment.
  19336. * (Too complex in logic and error-prone)
  19337. * 2. Use a shadow ecModel. (Performace expensive)
  19338. */
  19339. function mergeOption(oldOption, newOption) {
  19340. newOption = newOption || {};
  19341. each$4(newOption, function (newCptOpt, mainType) {
  19342. if (newCptOpt == null) {
  19343. return;
  19344. }
  19345. var oldCptOpt = oldOption[mainType];
  19346. if (!ComponentModel.hasClass(mainType)) {
  19347. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19348. }
  19349. else {
  19350. newCptOpt = normalizeToArray(newCptOpt);
  19351. oldCptOpt = normalizeToArray(oldCptOpt);
  19352. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19353. oldOption[mainType] = map$1(mapResult, function (item) {
  19354. return (item.option && item.exist)
  19355. ? merge$1(item.exist, item.option, true)
  19356. : (item.exist || item.option);
  19357. });
  19358. }
  19359. });
  19360. }
  19361. /*
  19362. * Licensed to the Apache Software Foundation (ASF) under one
  19363. * or more contributor license agreements. See the NOTICE file
  19364. * distributed with this work for additional information
  19365. * regarding copyright ownership. The ASF licenses this file
  19366. * to you under the Apache License, Version 2.0 (the
  19367. * "License"); you may not use this file except in compliance
  19368. * with the License. You may obtain a copy of the License at
  19369. *
  19370. * http://www.apache.org/licenses/LICENSE-2.0
  19371. *
  19372. * Unless required by applicable law or agreed to in writing,
  19373. * software distributed under the License is distributed on an
  19374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19375. * KIND, either express or implied. See the License for the
  19376. * specific language governing permissions and limitations
  19377. * under the License.
  19378. */
  19379. var each$5 = each$1;
  19380. var isObject$3 = isObject$1;
  19381. var POSSIBLE_STYLES = [
  19382. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19383. 'chordStyle', 'label', 'labelLine'
  19384. ];
  19385. function compatEC2ItemStyle(opt) {
  19386. var itemStyleOpt = opt && opt.itemStyle;
  19387. if (!itemStyleOpt) {
  19388. return;
  19389. }
  19390. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19391. var styleName = POSSIBLE_STYLES[i];
  19392. var normalItemStyleOpt = itemStyleOpt.normal;
  19393. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19394. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19395. opt[styleName] = opt[styleName] || {};
  19396. if (!opt[styleName].normal) {
  19397. opt[styleName].normal = normalItemStyleOpt[styleName];
  19398. }
  19399. else {
  19400. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19401. }
  19402. normalItemStyleOpt[styleName] = null;
  19403. }
  19404. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19405. opt[styleName] = opt[styleName] || {};
  19406. if (!opt[styleName].emphasis) {
  19407. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19408. }
  19409. else {
  19410. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19411. }
  19412. emphasisItemStyleOpt[styleName] = null;
  19413. }
  19414. }
  19415. }
  19416. function convertNormalEmphasis(opt, optType, useExtend) {
  19417. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19418. var normalOpt = opt[optType].normal;
  19419. var emphasisOpt = opt[optType].emphasis;
  19420. if (normalOpt) {
  19421. // Timeline controlStyle has other properties besides normal and emphasis
  19422. if (useExtend) {
  19423. opt[optType].normal = opt[optType].emphasis = null;
  19424. defaults(opt[optType], normalOpt);
  19425. }
  19426. else {
  19427. opt[optType] = normalOpt;
  19428. }
  19429. }
  19430. if (emphasisOpt) {
  19431. opt.emphasis = opt.emphasis || {};
  19432. opt.emphasis[optType] = emphasisOpt;
  19433. }
  19434. }
  19435. }
  19436. function removeEC3NormalStatus(opt) {
  19437. convertNormalEmphasis(opt, 'itemStyle');
  19438. convertNormalEmphasis(opt, 'lineStyle');
  19439. convertNormalEmphasis(opt, 'areaStyle');
  19440. convertNormalEmphasis(opt, 'label');
  19441. convertNormalEmphasis(opt, 'labelLine');
  19442. // treemap
  19443. convertNormalEmphasis(opt, 'upperLabel');
  19444. // graph
  19445. convertNormalEmphasis(opt, 'edgeLabel');
  19446. }
  19447. function compatTextStyle(opt, propName) {
  19448. // Check whether is not object (string\null\undefined ...)
  19449. var labelOptSingle = isObject$3(opt) && opt[propName];
  19450. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19451. if (textStyle) {
  19452. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19453. var propName = TEXT_STYLE_OPTIONS[i];
  19454. if (textStyle.hasOwnProperty(propName)) {
  19455. labelOptSingle[propName] = textStyle[propName];
  19456. }
  19457. }
  19458. }
  19459. }
  19460. function compatEC3CommonStyles(opt) {
  19461. if (opt) {
  19462. removeEC3NormalStatus(opt);
  19463. compatTextStyle(opt, 'label');
  19464. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19465. }
  19466. }
  19467. function processSeries(seriesOpt) {
  19468. if (!isObject$3(seriesOpt)) {
  19469. return;
  19470. }
  19471. compatEC2ItemStyle(seriesOpt);
  19472. removeEC3NormalStatus(seriesOpt);
  19473. compatTextStyle(seriesOpt, 'label');
  19474. // treemap
  19475. compatTextStyle(seriesOpt, 'upperLabel');
  19476. // graph
  19477. compatTextStyle(seriesOpt, 'edgeLabel');
  19478. if (seriesOpt.emphasis) {
  19479. compatTextStyle(seriesOpt.emphasis, 'label');
  19480. // treemap
  19481. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19482. // graph
  19483. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19484. }
  19485. var markPoint = seriesOpt.markPoint;
  19486. if (markPoint) {
  19487. compatEC2ItemStyle(markPoint);
  19488. compatEC3CommonStyles(markPoint);
  19489. }
  19490. var markLine = seriesOpt.markLine;
  19491. if (markLine) {
  19492. compatEC2ItemStyle(markLine);
  19493. compatEC3CommonStyles(markLine);
  19494. }
  19495. var markArea = seriesOpt.markArea;
  19496. if (markArea) {
  19497. compatEC3CommonStyles(markArea);
  19498. }
  19499. var data = seriesOpt.data;
  19500. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19501. // then the backward compat based on option type will not be performed.
  19502. if (seriesOpt.type === 'graph') {
  19503. data = data || seriesOpt.nodes;
  19504. var edgeData = seriesOpt.links || seriesOpt.edges;
  19505. if (edgeData && !isTypedArray(edgeData)) {
  19506. for (var i = 0; i < edgeData.length; i++) {
  19507. compatEC3CommonStyles(edgeData[i]);
  19508. }
  19509. }
  19510. each$1(seriesOpt.categories, function (opt) {
  19511. removeEC3NormalStatus(opt);
  19512. });
  19513. }
  19514. if (data && !isTypedArray(data)) {
  19515. for (var i = 0; i < data.length; i++) {
  19516. compatEC3CommonStyles(data[i]);
  19517. }
  19518. }
  19519. // mark point data
  19520. var markPoint = seriesOpt.markPoint;
  19521. if (markPoint && markPoint.data) {
  19522. var mpData = markPoint.data;
  19523. for (var i = 0; i < mpData.length; i++) {
  19524. compatEC3CommonStyles(mpData[i]);
  19525. }
  19526. }
  19527. // mark line data
  19528. var markLine = seriesOpt.markLine;
  19529. if (markLine && markLine.data) {
  19530. var mlData = markLine.data;
  19531. for (var i = 0; i < mlData.length; i++) {
  19532. if (isArray(mlData[i])) {
  19533. compatEC3CommonStyles(mlData[i][0]);
  19534. compatEC3CommonStyles(mlData[i][1]);
  19535. }
  19536. else {
  19537. compatEC3CommonStyles(mlData[i]);
  19538. }
  19539. }
  19540. }
  19541. // Series
  19542. if (seriesOpt.type === 'gauge') {
  19543. compatTextStyle(seriesOpt, 'axisLabel');
  19544. compatTextStyle(seriesOpt, 'title');
  19545. compatTextStyle(seriesOpt, 'detail');
  19546. }
  19547. else if (seriesOpt.type === 'treemap') {
  19548. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19549. each$1(seriesOpt.levels, function (opt) {
  19550. removeEC3NormalStatus(opt);
  19551. });
  19552. }
  19553. else if (seriesOpt.type === 'tree') {
  19554. removeEC3NormalStatus(seriesOpt.leaves);
  19555. }
  19556. // sunburst starts from ec4, so it does not need to compat levels.
  19557. }
  19558. function toArr(o) {
  19559. return isArray(o) ? o : o ? [o] : [];
  19560. }
  19561. function toObj(o) {
  19562. return (isArray(o) ? o[0] : o) || {};
  19563. }
  19564. var compatStyle = function (option, isTheme) {
  19565. each$5(toArr(option.series), function (seriesOpt) {
  19566. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19567. });
  19568. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19569. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19570. each$5(
  19571. axes,
  19572. function (axisName) {
  19573. each$5(toArr(option[axisName]), function (axisOpt) {
  19574. if (axisOpt) {
  19575. compatTextStyle(axisOpt, 'axisLabel');
  19576. compatTextStyle(axisOpt.axisPointer, 'label');
  19577. }
  19578. });
  19579. }
  19580. );
  19581. each$5(toArr(option.parallel), function (parallelOpt) {
  19582. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19583. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19584. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19585. });
  19586. each$5(toArr(option.calendar), function (calendarOpt) {
  19587. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19588. compatTextStyle(calendarOpt, 'dayLabel');
  19589. compatTextStyle(calendarOpt, 'monthLabel');
  19590. compatTextStyle(calendarOpt, 'yearLabel');
  19591. });
  19592. // radar.name.textStyle
  19593. each$5(toArr(option.radar), function (radarOpt) {
  19594. compatTextStyle(radarOpt, 'name');
  19595. });
  19596. each$5(toArr(option.geo), function (geoOpt) {
  19597. if (isObject$3(geoOpt)) {
  19598. compatEC3CommonStyles(geoOpt);
  19599. each$5(toArr(geoOpt.regions), function (regionObj) {
  19600. compatEC3CommonStyles(regionObj);
  19601. });
  19602. }
  19603. });
  19604. each$5(toArr(option.timeline), function (timelineOpt) {
  19605. compatEC3CommonStyles(timelineOpt);
  19606. convertNormalEmphasis(timelineOpt, 'label');
  19607. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19608. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19609. var data = timelineOpt.data;
  19610. isArray(data) && each$1(data, function (item) {
  19611. if (isObject$1(item)) {
  19612. convertNormalEmphasis(item, 'label');
  19613. convertNormalEmphasis(item, 'itemStyle');
  19614. }
  19615. });
  19616. });
  19617. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19618. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19619. each$5(toolboxOpt.feature, function (featureOpt) {
  19620. convertNormalEmphasis(featureOpt, 'iconStyle');
  19621. });
  19622. });
  19623. compatTextStyle(toObj(option.axisPointer), 'label');
  19624. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19625. };
  19626. /*
  19627. * Licensed to the Apache Software Foundation (ASF) under one
  19628. * or more contributor license agreements. See the NOTICE file
  19629. * distributed with this work for additional information
  19630. * regarding copyright ownership. The ASF licenses this file
  19631. * to you under the Apache License, Version 2.0 (the
  19632. * "License"); you may not use this file except in compliance
  19633. * with the License. You may obtain a copy of the License at
  19634. *
  19635. * http://www.apache.org/licenses/LICENSE-2.0
  19636. *
  19637. * Unless required by applicable law or agreed to in writing,
  19638. * software distributed under the License is distributed on an
  19639. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19640. * KIND, either express or implied. See the License for the
  19641. * specific language governing permissions and limitations
  19642. * under the License.
  19643. */
  19644. // Compatitable with 2.0
  19645. function get(opt, path) {
  19646. path = path.split(',');
  19647. var obj = opt;
  19648. for (var i = 0; i < path.length; i++) {
  19649. obj = obj && obj[path[i]];
  19650. if (obj == null) {
  19651. break;
  19652. }
  19653. }
  19654. return obj;
  19655. }
  19656. function set$1(opt, path, val, overwrite) {
  19657. path = path.split(',');
  19658. var obj = opt;
  19659. var key;
  19660. for (var i = 0; i < path.length - 1; i++) {
  19661. key = path[i];
  19662. if (obj[key] == null) {
  19663. obj[key] = {};
  19664. }
  19665. obj = obj[key];
  19666. }
  19667. if (overwrite || obj[path[i]] == null) {
  19668. obj[path[i]] = val;
  19669. }
  19670. }
  19671. function compatLayoutProperties(option) {
  19672. each$1(LAYOUT_PROPERTIES, function (prop) {
  19673. if (prop[0] in option && !(prop[1] in option)) {
  19674. option[prop[1]] = option[prop[0]];
  19675. }
  19676. });
  19677. }
  19678. var LAYOUT_PROPERTIES = [
  19679. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19680. ];
  19681. var COMPATITABLE_COMPONENTS = [
  19682. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19683. ];
  19684. var backwardCompat = function (option, isTheme) {
  19685. compatStyle(option, isTheme);
  19686. // Make sure series array for model initialization.
  19687. option.series = normalizeToArray(option.series);
  19688. each$1(option.series, function (seriesOpt) {
  19689. if (!isObject$1(seriesOpt)) {
  19690. return;
  19691. }
  19692. var seriesType = seriesOpt.type;
  19693. if (seriesType === 'pie' || seriesType === 'gauge') {
  19694. if (seriesOpt.clockWise != null) {
  19695. seriesOpt.clockwise = seriesOpt.clockWise;
  19696. }
  19697. }
  19698. if (seriesType === 'gauge') {
  19699. var pointerColor = get(seriesOpt, 'pointer.color');
  19700. pointerColor != null
  19701. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19702. }
  19703. compatLayoutProperties(seriesOpt);
  19704. });
  19705. // dataRange has changed to visualMap
  19706. if (option.dataRange) {
  19707. option.visualMap = option.dataRange;
  19708. }
  19709. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19710. var options = option[componentName];
  19711. if (options) {
  19712. if (!isArray(options)) {
  19713. options = [options];
  19714. }
  19715. each$1(options, function (option) {
  19716. compatLayoutProperties(option);
  19717. });
  19718. }
  19719. });
  19720. };
  19721. /*
  19722. * Licensed to the Apache Software Foundation (ASF) under one
  19723. * or more contributor license agreements. See the NOTICE file
  19724. * distributed with this work for additional information
  19725. * regarding copyright ownership. The ASF licenses this file
  19726. * to you under the Apache License, Version 2.0 (the
  19727. * "License"); you may not use this file except in compliance
  19728. * with the License. You may obtain a copy of the License at
  19729. *
  19730. * http://www.apache.org/licenses/LICENSE-2.0
  19731. *
  19732. * Unless required by applicable law or agreed to in writing,
  19733. * software distributed under the License is distributed on an
  19734. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19735. * KIND, either express or implied. See the License for the
  19736. * specific language governing permissions and limitations
  19737. * under the License.
  19738. */
  19739. // (1) [Caution]: the logic is correct based on the premises:
  19740. // data processing stage is blocked in stream.
  19741. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19742. // (2) Only register once when import repeatly.
  19743. // Should be executed before after series filtered and before stack calculation.
  19744. var dataStack = function (ecModel) {
  19745. var stackInfoMap = createHashMap();
  19746. ecModel.eachSeries(function (seriesModel) {
  19747. var stack = seriesModel.get('stack');
  19748. // Compatibal: when `stack` is set as '', do not stack.
  19749. if (stack) {
  19750. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19751. var data = seriesModel.getData();
  19752. var stackInfo = {
  19753. // Used for calculate axis extent automatically.
  19754. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19755. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19756. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19757. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19758. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19759. data: data,
  19760. seriesModel: seriesModel
  19761. };
  19762. // If stacked on axis that do not support data stack.
  19763. if (!stackInfo.stackedDimension
  19764. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19765. ) {
  19766. return;
  19767. }
  19768. stackInfoList.length && data.setCalculationInfo(
  19769. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19770. );
  19771. stackInfoList.push(stackInfo);
  19772. }
  19773. });
  19774. stackInfoMap.each(calculateStack);
  19775. };
  19776. function calculateStack(stackInfoList) {
  19777. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19778. var resultVal = [];
  19779. var resultNaN = [NaN, NaN];
  19780. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19781. var targetData = targetStackInfo.data;
  19782. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19783. // Should not write on raw data, because stack series model list changes
  19784. // depending on legend selection.
  19785. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19786. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19787. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19788. // should also be NaN, to draw a appropriate belt area.
  19789. if (isNaN(sum)) {
  19790. return resultNaN;
  19791. }
  19792. var byValue;
  19793. var stackedDataRawIndex;
  19794. if (isStackedByIndex) {
  19795. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19796. }
  19797. else {
  19798. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19799. }
  19800. // If stackOver is NaN, chart view will render point on value start.
  19801. var stackedOver = NaN;
  19802. for (var j = idxInStack - 1; j >= 0; j--) {
  19803. var stackInfo = stackInfoList[j];
  19804. // Has been optimized by inverted indices on `stackedByDimension`.
  19805. if (!isStackedByIndex) {
  19806. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19807. }
  19808. if (stackedDataRawIndex >= 0) {
  19809. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19810. // Considering positive stack, negative stack and empty data
  19811. if ((sum >= 0 && val > 0) // Positive stack
  19812. || (sum <= 0 && val < 0) // Negative stack
  19813. ) {
  19814. sum += val;
  19815. stackedOver = val;
  19816. break;
  19817. }
  19818. }
  19819. }
  19820. resultVal[0] = sum;
  19821. resultVal[1] = stackedOver;
  19822. return resultVal;
  19823. });
  19824. targetData.hostModel.setData(newData);
  19825. // Update for consequent calculation
  19826. targetStackInfo.data = newData;
  19827. });
  19828. }
  19829. /*
  19830. * Licensed to the Apache Software Foundation (ASF) under one
  19831. * or more contributor license agreements. See the NOTICE file
  19832. * distributed with this work for additional information
  19833. * regarding copyright ownership. The ASF licenses this file
  19834. * to you under the Apache License, Version 2.0 (the
  19835. * "License"); you may not use this file except in compliance
  19836. * with the License. You may obtain a copy of the License at
  19837. *
  19838. * http://www.apache.org/licenses/LICENSE-2.0
  19839. *
  19840. * Unless required by applicable law or agreed to in writing,
  19841. * software distributed under the License is distributed on an
  19842. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19843. * KIND, either express or implied. See the License for the
  19844. * specific language governing permissions and limitations
  19845. * under the License.
  19846. */
  19847. // TODO
  19848. // ??? refactor? check the outer usage of data provider.
  19849. // merge with defaultDimValueGetter?
  19850. /**
  19851. * If normal array used, mutable chunk size is supported.
  19852. * If typed array used, chunk size must be fixed.
  19853. */
  19854. function DefaultDataProvider(source, dimSize) {
  19855. if (!Source.isInstance(source)) {
  19856. source = Source.seriesDataToSource(source);
  19857. }
  19858. this._source = source;
  19859. var data = this._data = source.data;
  19860. var sourceFormat = source.sourceFormat;
  19861. // Typed array. TODO IE10+?
  19862. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19863. if (__DEV__) {
  19864. if (dimSize == null) {
  19865. throw new Error('Typed array data must specify dimension size');
  19866. }
  19867. }
  19868. this._offset = 0;
  19869. this._dimSize = dimSize;
  19870. this._data = data;
  19871. }
  19872. var methods = providerMethods[
  19873. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19874. ? sourceFormat + '_' + source.seriesLayoutBy
  19875. : sourceFormat
  19876. ];
  19877. if (__DEV__) {
  19878. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19879. }
  19880. extend(this, methods);
  19881. }
  19882. var providerProto = DefaultDataProvider.prototype;
  19883. // If data is pure without style configuration
  19884. providerProto.pure = false;
  19885. // If data is persistent and will not be released after use.
  19886. providerProto.persistent = true;
  19887. // ???! FIXME legacy data provider do not has method getSource
  19888. providerProto.getSource = function () {
  19889. return this._source;
  19890. };
  19891. var providerMethods = {
  19892. 'arrayRows_column': {
  19893. pure: true,
  19894. count: function () {
  19895. return Math.max(0, this._data.length - this._source.startIndex);
  19896. },
  19897. getItem: function (idx) {
  19898. return this._data[idx + this._source.startIndex];
  19899. },
  19900. appendData: appendDataSimply
  19901. },
  19902. 'arrayRows_row': {
  19903. pure: true,
  19904. count: function () {
  19905. var row = this._data[0];
  19906. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19907. },
  19908. getItem: function (idx) {
  19909. idx += this._source.startIndex;
  19910. var item = [];
  19911. var data = this._data;
  19912. for (var i = 0; i < data.length; i++) {
  19913. var row = data[i];
  19914. item.push(row ? row[idx] : null);
  19915. }
  19916. return item;
  19917. },
  19918. appendData: function () {
  19919. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19920. }
  19921. },
  19922. 'objectRows': {
  19923. pure: true,
  19924. count: countSimply,
  19925. getItem: getItemSimply,
  19926. appendData: appendDataSimply
  19927. },
  19928. 'keyedColumns': {
  19929. pure: true,
  19930. count: function () {
  19931. var dimName = this._source.dimensionsDefine[0].name;
  19932. var col = this._data[dimName];
  19933. return col ? col.length : 0;
  19934. },
  19935. getItem: function (idx) {
  19936. var item = [];
  19937. var dims = this._source.dimensionsDefine;
  19938. for (var i = 0; i < dims.length; i++) {
  19939. var col = this._data[dims[i].name];
  19940. item.push(col ? col[idx] : null);
  19941. }
  19942. return item;
  19943. },
  19944. appendData: function (newData) {
  19945. var data = this._data;
  19946. each$1(newData, function (newCol, key) {
  19947. var oldCol = data[key] || (data[key] = []);
  19948. for (var i = 0; i < (newCol || []).length; i++) {
  19949. oldCol.push(newCol[i]);
  19950. }
  19951. });
  19952. }
  19953. },
  19954. 'original': {
  19955. count: countSimply,
  19956. getItem: getItemSimply,
  19957. appendData: appendDataSimply
  19958. },
  19959. 'typedArray': {
  19960. persistent: false,
  19961. pure: true,
  19962. count: function () {
  19963. return this._data ? (this._data.length / this._dimSize) : 0;
  19964. },
  19965. getItem: function (idx, out) {
  19966. idx = idx - this._offset;
  19967. out = out || [];
  19968. var offset = this._dimSize * idx;
  19969. for (var i = 0; i < this._dimSize; i++) {
  19970. out[i] = this._data[offset + i];
  19971. }
  19972. return out;
  19973. },
  19974. appendData: function (newData) {
  19975. if (__DEV__) {
  19976. assert$1(
  19977. isTypedArray(newData),
  19978. 'Added data must be TypedArray if data in initialization is TypedArray'
  19979. );
  19980. }
  19981. this._data = newData;
  19982. },
  19983. // Clean self if data is already used.
  19984. clean: function () {
  19985. // PENDING
  19986. this._offset += this.count();
  19987. this._data = null;
  19988. }
  19989. }
  19990. };
  19991. function countSimply() {
  19992. return this._data.length;
  19993. }
  19994. function getItemSimply(idx) {
  19995. return this._data[idx];
  19996. }
  19997. function appendDataSimply(newData) {
  19998. for (var i = 0; i < newData.length; i++) {
  19999. this._data.push(newData[i]);
  20000. }
  20001. }
  20002. var rawValueGetters = {
  20003. arrayRows: getRawValueSimply,
  20004. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20005. return dimIndex != null ? dataItem[dimName] : dataItem;
  20006. },
  20007. keyedColumns: getRawValueSimply,
  20008. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20009. // FIXME
  20010. // In some case (markpoint in geo (geo-map.html)), dataItem
  20011. // is {coord: [...]}
  20012. var value = getDataItemValue(dataItem);
  20013. return (dimIndex == null || !(value instanceof Array))
  20014. ? value
  20015. : value[dimIndex];
  20016. },
  20017. typedArray: getRawValueSimply
  20018. };
  20019. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20020. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20021. }
  20022. var defaultDimValueGetters = {
  20023. arrayRows: getDimValueSimply,
  20024. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20025. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20026. },
  20027. keyedColumns: getDimValueSimply,
  20028. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20029. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20030. // If dataItem is an plain object with no value field, the var `value`
  20031. // will be assigned with the object, but it will be tread correctly
  20032. // in the `convertDataValue`.
  20033. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20034. // If any dataItem is like { value: 10 }
  20035. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20036. this.hasItemOption = true;
  20037. }
  20038. return converDataValue(
  20039. (value instanceof Array)
  20040. ? value[dimIndex]
  20041. // If value is a single number or something else not array.
  20042. : value,
  20043. this._dimensionInfos[dimName]
  20044. );
  20045. },
  20046. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20047. return dataItem[dimIndex];
  20048. }
  20049. };
  20050. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20051. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20052. }
  20053. /**
  20054. * This helper method convert value in data.
  20055. * @param {string|number|Date} value
  20056. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20057. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20058. */
  20059. function converDataValue(value, dimInfo) {
  20060. // Performance sensitive.
  20061. var dimType = dimInfo && dimInfo.type;
  20062. if (dimType === 'ordinal') {
  20063. // If given value is a category string
  20064. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20065. return ordinalMeta
  20066. ? ordinalMeta.parseAndCollect(value)
  20067. : value;
  20068. }
  20069. if (dimType === 'time'
  20070. // spead up when using timestamp
  20071. && typeof value !== 'number'
  20072. && value != null
  20073. && value !== '-'
  20074. ) {
  20075. value = +parseDate(value);
  20076. }
  20077. // dimType defaults 'number'.
  20078. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20079. // parse to NaN.
  20080. return (value == null || value === '')
  20081. ? NaN
  20082. // If string (like '-'), using '+' parse to NaN
  20083. // If object, also parse to NaN
  20084. : +value;
  20085. }
  20086. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20087. // Consider persistent.
  20088. // Caution: why use raw value to display on label or tooltip?
  20089. // A reason is to avoid format. For example time value we do not know
  20090. // how to format is expected. More over, if stack is used, calculated
  20091. // value may be 0.91000000001, which have brings trouble to display.
  20092. // TODO: consider how to treat null/undefined/NaN when display?
  20093. /**
  20094. * @param {module:echarts/data/List} data
  20095. * @param {number} dataIndex
  20096. * @param {string|number} [dim] dimName or dimIndex
  20097. * @return {Array.<number>|string|number} can be null/undefined.
  20098. */
  20099. function retrieveRawValue(data, dataIndex, dim) {
  20100. if (!data) {
  20101. return;
  20102. }
  20103. // Consider data may be not persistent.
  20104. var dataItem = data.getRawDataItem(dataIndex);
  20105. if (dataItem == null) {
  20106. return;
  20107. }
  20108. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20109. var dimName;
  20110. var dimIndex;
  20111. var dimInfo = data.getDimensionInfo(dim);
  20112. if (dimInfo) {
  20113. dimName = dimInfo.name;
  20114. dimIndex = dimInfo.index;
  20115. }
  20116. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20117. }
  20118. /**
  20119. * Compatible with some cases (in pie, map) like:
  20120. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20121. * where only sourceFormat is 'original' and 'objectRows' supported.
  20122. *
  20123. * ??? TODO
  20124. * Supported detail options in data item when using 'arrayRows'.
  20125. *
  20126. * @param {module:echarts/data/List} data
  20127. * @param {number} dataIndex
  20128. * @param {string} attr like 'selected'
  20129. */
  20130. function retrieveRawAttr(data, dataIndex, attr) {
  20131. if (!data) {
  20132. return;
  20133. }
  20134. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20135. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20136. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20137. ) {
  20138. return;
  20139. }
  20140. var dataItem = data.getRawDataItem(dataIndex);
  20141. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20142. dataItem = null;
  20143. }
  20144. if (dataItem) {
  20145. return dataItem[attr];
  20146. }
  20147. }
  20148. /*
  20149. * Licensed to the Apache Software Foundation (ASF) under one
  20150. * or more contributor license agreements. See the NOTICE file
  20151. * distributed with this work for additional information
  20152. * regarding copyright ownership. The ASF licenses this file
  20153. * to you under the Apache License, Version 2.0 (the
  20154. * "License"); you may not use this file except in compliance
  20155. * with the License. You may obtain a copy of the License at
  20156. *
  20157. * http://www.apache.org/licenses/LICENSE-2.0
  20158. *
  20159. * Unless required by applicable law or agreed to in writing,
  20160. * software distributed under the License is distributed on an
  20161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20162. * KIND, either express or implied. See the License for the
  20163. * specific language governing permissions and limitations
  20164. * under the License.
  20165. */
  20166. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20167. // PENDING A little ugly
  20168. var dataFormatMixin = {
  20169. /**
  20170. * Get params for formatter
  20171. * @param {number} dataIndex
  20172. * @param {string} [dataType]
  20173. * @return {Object}
  20174. */
  20175. getDataParams: function (dataIndex, dataType) {
  20176. var data = this.getData(dataType);
  20177. var rawValue = this.getRawValue(dataIndex, dataType);
  20178. var rawDataIndex = data.getRawIndex(dataIndex);
  20179. var name = data.getName(dataIndex);
  20180. var itemOpt = data.getRawDataItem(dataIndex);
  20181. var color = data.getItemVisual(dataIndex, 'color');
  20182. var tooltipModel = this.ecModel.getComponent('tooltip');
  20183. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20184. var renderMode = getTooltipRenderMode(renderModeOption);
  20185. var mainType = this.mainType;
  20186. var isSeries = mainType === 'series';
  20187. return {
  20188. componentType: mainType,
  20189. componentSubType: this.subType,
  20190. componentIndex: this.componentIndex,
  20191. seriesType: isSeries ? this.subType : null,
  20192. seriesIndex: this.seriesIndex,
  20193. seriesId: isSeries ? this.id : null,
  20194. seriesName: isSeries ? this.name : null,
  20195. name: name,
  20196. dataIndex: rawDataIndex,
  20197. data: itemOpt,
  20198. dataType: dataType,
  20199. value: rawValue,
  20200. color: color,
  20201. marker: getTooltipMarker({
  20202. color: color,
  20203. renderMode: renderMode
  20204. }),
  20205. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20206. $vars: ['seriesName', 'name', 'value']
  20207. };
  20208. },
  20209. /**
  20210. * Format label
  20211. * @param {number} dataIndex
  20212. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20213. * @param {string} [dataType]
  20214. * @param {number} [dimIndex]
  20215. * @param {string} [labelProp='label']
  20216. * @return {string} If not formatter, return null/undefined
  20217. */
  20218. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20219. status = status || 'normal';
  20220. var data = this.getData(dataType);
  20221. var itemModel = data.getItemModel(dataIndex);
  20222. var params = this.getDataParams(dataIndex, dataType);
  20223. if (dimIndex != null && (params.value instanceof Array)) {
  20224. params.value = params.value[dimIndex];
  20225. }
  20226. var formatter = itemModel.get(
  20227. status === 'normal'
  20228. ? [labelProp || 'label', 'formatter']
  20229. : [status, labelProp || 'label', 'formatter']
  20230. );
  20231. if (typeof formatter === 'function') {
  20232. params.status = status;
  20233. return formatter(params);
  20234. }
  20235. else if (typeof formatter === 'string') {
  20236. var str = formatTpl(formatter, params);
  20237. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20238. // Do not support '}' in dim name util have to.
  20239. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20240. var len = dim.length;
  20241. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20242. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20243. }
  20244. return retrieveRawValue(data, dataIndex, dim);
  20245. });
  20246. }
  20247. },
  20248. /**
  20249. * Get raw value in option
  20250. * @param {number} idx
  20251. * @param {string} [dataType]
  20252. * @return {Array|number|string}
  20253. */
  20254. getRawValue: function (idx, dataType) {
  20255. return retrieveRawValue(this.getData(dataType), idx);
  20256. },
  20257. /**
  20258. * Should be implemented.
  20259. * @param {number} dataIndex
  20260. * @param {boolean} [multipleSeries=false]
  20261. * @param {number} [dataType]
  20262. * @return {string} tooltip string
  20263. */
  20264. formatTooltip: function () {
  20265. // Empty function
  20266. }
  20267. };
  20268. /*
  20269. * Licensed to the Apache Software Foundation (ASF) under one
  20270. * or more contributor license agreements. See the NOTICE file
  20271. * distributed with this work for additional information
  20272. * regarding copyright ownership. The ASF licenses this file
  20273. * to you under the Apache License, Version 2.0 (the
  20274. * "License"); you may not use this file except in compliance
  20275. * with the License. You may obtain a copy of the License at
  20276. *
  20277. * http://www.apache.org/licenses/LICENSE-2.0
  20278. *
  20279. * Unless required by applicable law or agreed to in writing,
  20280. * software distributed under the License is distributed on an
  20281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20282. * KIND, either express or implied. See the License for the
  20283. * specific language governing permissions and limitations
  20284. * under the License.
  20285. */
  20286. /**
  20287. * @param {Object} define
  20288. * @return See the return of `createTask`.
  20289. */
  20290. function createTask(define) {
  20291. return new Task(define);
  20292. }
  20293. /**
  20294. * @constructor
  20295. * @param {Object} define
  20296. * @param {Function} define.reset Custom reset
  20297. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20298. * @param {Function} [define.count] count is used to determin data task.
  20299. * @param {Function} [define.onDirty] count is used to determin data task.
  20300. */
  20301. function Task(define) {
  20302. define = define || {};
  20303. this._reset = define.reset;
  20304. this._plan = define.plan;
  20305. this._count = define.count;
  20306. this._onDirty = define.onDirty;
  20307. this._dirty = true;
  20308. // Context must be specified implicitly, to
  20309. // avoid miss update context when model changed.
  20310. this.context;
  20311. }
  20312. var taskProto = Task.prototype;
  20313. /**
  20314. * @param {Object} performArgs
  20315. * @param {number} [performArgs.step] Specified step.
  20316. * @param {number} [performArgs.skip] Skip customer perform call.
  20317. * @param {number} [performArgs.modBy] Sampling window size.
  20318. * @param {number} [performArgs.modDataCount] Sampling count.
  20319. */
  20320. taskProto.perform = function (performArgs) {
  20321. var upTask = this._upstream;
  20322. var skip = performArgs && performArgs.skip;
  20323. // TODO some refactor.
  20324. // Pull data. Must pull data each time, because context.data
  20325. // may be updated by Series.setData.
  20326. if (this._dirty && upTask) {
  20327. var context = this.context;
  20328. context.data = context.outputData = upTask.context.outputData;
  20329. }
  20330. if (this.__pipeline) {
  20331. this.__pipeline.currentTask = this;
  20332. }
  20333. var planResult;
  20334. if (this._plan && !skip) {
  20335. planResult = this._plan(this.context);
  20336. }
  20337. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20338. // elements uniformed distributed when progress, especially when moving or zooming.
  20339. var lastModBy = normalizeModBy(this._modBy);
  20340. var lastModDataCount = this._modDataCount || 0;
  20341. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20342. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20343. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20344. planResult = 'reset';
  20345. }
  20346. function normalizeModBy(val) {
  20347. !(val >= 1) && (val = 1); // jshint ignore:line
  20348. return val;
  20349. }
  20350. var forceFirstProgress;
  20351. if (this._dirty || planResult === 'reset') {
  20352. this._dirty = false;
  20353. forceFirstProgress = reset(this, skip);
  20354. }
  20355. this._modBy = modBy;
  20356. this._modDataCount = modDataCount;
  20357. var step = performArgs && performArgs.step;
  20358. if (upTask) {
  20359. if (__DEV__) {
  20360. assert$1(upTask._outputDueEnd != null);
  20361. }
  20362. this._dueEnd = upTask._outputDueEnd;
  20363. }
  20364. // DataTask or overallTask
  20365. else {
  20366. if (__DEV__) {
  20367. assert$1(!this._progress || this._count);
  20368. }
  20369. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20370. }
  20371. // Note: Stubs, that its host overall task let it has progress, has progress.
  20372. // If no progress, pass index from upstream to downstream each time plan called.
  20373. if (this._progress) {
  20374. var start = this._dueIndex;
  20375. var end = Math.min(
  20376. step != null ? this._dueIndex + step : Infinity,
  20377. this._dueEnd
  20378. );
  20379. if (!skip && (forceFirstProgress || start < end)) {
  20380. var progress = this._progress;
  20381. if (isArray(progress)) {
  20382. for (var i = 0; i < progress.length; i++) {
  20383. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20384. }
  20385. }
  20386. else {
  20387. doProgress(this, progress, start, end, modBy, modDataCount);
  20388. }
  20389. }
  20390. this._dueIndex = end;
  20391. // If no `outputDueEnd`, assume that output data and
  20392. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20393. var outputDueEnd = this._settedOutputEnd != null
  20394. ? this._settedOutputEnd : end;
  20395. if (__DEV__) {
  20396. // ??? Can not rollback.
  20397. assert$1(outputDueEnd >= this._outputDueEnd);
  20398. }
  20399. this._outputDueEnd = outputDueEnd;
  20400. }
  20401. else {
  20402. // (1) Some overall task has no progress.
  20403. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20404. // This should always be performed so it can be passed to downstream.
  20405. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20406. ? this._settedOutputEnd : this._dueEnd;
  20407. }
  20408. return this.unfinished();
  20409. };
  20410. var iterator = (function () {
  20411. var end;
  20412. var current;
  20413. var modBy;
  20414. var modDataCount;
  20415. var winCount;
  20416. var it = {
  20417. reset: function (s, e, sStep, sCount) {
  20418. current = s;
  20419. end = e;
  20420. modBy = sStep;
  20421. modDataCount = sCount;
  20422. winCount = Math.ceil(modDataCount / modBy);
  20423. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20424. }
  20425. };
  20426. return it;
  20427. function sequentialNext() {
  20428. return current < end ? current++ : null;
  20429. }
  20430. function modNext() {
  20431. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20432. var result = current >= end
  20433. ? null
  20434. : dataIndex < modDataCount
  20435. ? dataIndex
  20436. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20437. // Use normal linear rendering mode.
  20438. : current;
  20439. current++;
  20440. return result;
  20441. }
  20442. })();
  20443. taskProto.dirty = function () {
  20444. this._dirty = true;
  20445. this._onDirty && this._onDirty(this.context);
  20446. };
  20447. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20448. iterator.reset(start, end, modBy, modDataCount);
  20449. taskIns._callingProgress = progress;
  20450. taskIns._callingProgress({
  20451. start: start, end: end, count: end - start, next: iterator.next
  20452. }, taskIns.context);
  20453. }
  20454. function reset(taskIns, skip) {
  20455. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20456. taskIns._settedOutputEnd = null;
  20457. var progress;
  20458. var forceFirstProgress;
  20459. if (!skip && taskIns._reset) {
  20460. progress = taskIns._reset(taskIns.context);
  20461. if (progress && progress.progress) {
  20462. forceFirstProgress = progress.forceFirstProgress;
  20463. progress = progress.progress;
  20464. }
  20465. // To simplify no progress checking, array must has item.
  20466. if (isArray(progress) && !progress.length) {
  20467. progress = null;
  20468. }
  20469. }
  20470. taskIns._progress = progress;
  20471. taskIns._modBy = taskIns._modDataCount = null;
  20472. var downstream = taskIns._downstream;
  20473. downstream && downstream.dirty();
  20474. return forceFirstProgress;
  20475. }
  20476. /**
  20477. * @return {boolean}
  20478. */
  20479. taskProto.unfinished = function () {
  20480. return this._progress && this._dueIndex < this._dueEnd;
  20481. };
  20482. /**
  20483. * @param {Object} downTask The downstream task.
  20484. * @return {Object} The downstream task.
  20485. */
  20486. taskProto.pipe = function (downTask) {
  20487. if (__DEV__) {
  20488. assert$1(downTask && !downTask._disposed && downTask !== this);
  20489. }
  20490. // If already downstream, do not dirty downTask.
  20491. if (this._downstream !== downTask || this._dirty) {
  20492. this._downstream = downTask;
  20493. downTask._upstream = this;
  20494. downTask.dirty();
  20495. }
  20496. };
  20497. taskProto.dispose = function () {
  20498. if (this._disposed) {
  20499. return;
  20500. }
  20501. this._upstream && (this._upstream._downstream = null);
  20502. this._downstream && (this._downstream._upstream = null);
  20503. this._dirty = false;
  20504. this._disposed = true;
  20505. };
  20506. taskProto.getUpstream = function () {
  20507. return this._upstream;
  20508. };
  20509. taskProto.getDownstream = function () {
  20510. return this._downstream;
  20511. };
  20512. taskProto.setOutputEnd = function (end) {
  20513. // This only happend in dataTask, dataZoom, map, currently.
  20514. // where dataZoom do not set end each time, but only set
  20515. // when reset. So we should record the setted end, in case
  20516. // that the stub of dataZoom perform again and earse the
  20517. // setted end by upstream.
  20518. this._outputDueEnd = this._settedOutputEnd = end;
  20519. };
  20520. ///////////////////////////////////////////////////////////
  20521. // For stream debug (Should be commented out after used!)
  20522. // Usage: printTask(this, 'begin');
  20523. // Usage: printTask(this, null, {someExtraProp});
  20524. // function printTask(task, prefix, extra) {
  20525. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20526. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20527. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20528. // var props = [];
  20529. // if (task.__pipeline) {
  20530. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20531. // props.push({text: 'idx', value: val});
  20532. // } else {
  20533. // var stubCount = 0;
  20534. // task.agentStubMap.each(() => stubCount++);
  20535. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20536. // }
  20537. // props.push({text: 'uid', value: task.uidDebug});
  20538. // if (task.__pipeline) {
  20539. // props.push({text: 'pid', value: task.__pipeline.id});
  20540. // task.agent && props.push(
  20541. // {text: 'stubFor', value: task.agent.uidDebug}
  20542. // );
  20543. // }
  20544. // props.push(
  20545. // {text: 'dirty', value: task._dirty},
  20546. // {text: 'dueIndex', value: task._dueIndex},
  20547. // {text: 'dueEnd', value: task._dueEnd},
  20548. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20549. // );
  20550. // if (extra) {
  20551. // Object.keys(extra).forEach(key => {
  20552. // props.push({text: key, value: extra[key]});
  20553. // });
  20554. // }
  20555. // var args = ['color: blue'];
  20556. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20557. // args.push('color: black', 'color: red'),
  20558. // `${item.text}: %c${item.value}`
  20559. // )).join('%c, ');
  20560. // console.log.apply(console, [msg].concat(args));
  20561. // // console.log(this);
  20562. // }
  20563. /*
  20564. * Licensed to the Apache Software Foundation (ASF) under one
  20565. * or more contributor license agreements. See the NOTICE file
  20566. * distributed with this work for additional information
  20567. * regarding copyright ownership. The ASF licenses this file
  20568. * to you under the Apache License, Version 2.0 (the
  20569. * "License"); you may not use this file except in compliance
  20570. * with the License. You may obtain a copy of the License at
  20571. *
  20572. * http://www.apache.org/licenses/LICENSE-2.0
  20573. *
  20574. * Unless required by applicable law or agreed to in writing,
  20575. * software distributed under the License is distributed on an
  20576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20577. * KIND, either express or implied. See the License for the
  20578. * specific language governing permissions and limitations
  20579. * under the License.
  20580. */
  20581. var inner$4 = makeInner();
  20582. var SeriesModel = ComponentModel.extend({
  20583. type: 'series.__base__',
  20584. /**
  20585. * @readOnly
  20586. */
  20587. seriesIndex: 0,
  20588. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20589. coordinateSystem: null,
  20590. /**
  20591. * @type {Object}
  20592. * @protected
  20593. */
  20594. defaultOption: null,
  20595. /**
  20596. * Data provided for legend
  20597. * @type {Function}
  20598. */
  20599. // PENDING
  20600. legendDataProvider: null,
  20601. /**
  20602. * Access path of color for visual
  20603. */
  20604. visualColorAccessPath: 'itemStyle.color',
  20605. /**
  20606. * Support merge layout params.
  20607. * Only support 'box' now (left/right/top/bottom/width/height).
  20608. * @type {string|Object} Object can be {ignoreSize: true}
  20609. * @readOnly
  20610. */
  20611. layoutMode: null,
  20612. init: function (option, parentModel, ecModel, extraOpt) {
  20613. /**
  20614. * @type {number}
  20615. * @readOnly
  20616. */
  20617. this.seriesIndex = this.componentIndex;
  20618. this.dataTask = createTask({
  20619. count: dataTaskCount,
  20620. reset: dataTaskReset
  20621. });
  20622. this.dataTask.context = {model: this};
  20623. this.mergeDefaultAndTheme(option, ecModel);
  20624. prepareSource(this);
  20625. var data = this.getInitialData(option, ecModel);
  20626. wrapData(data, this);
  20627. this.dataTask.context.data = data;
  20628. if (__DEV__) {
  20629. assert$1(data, 'getInitialData returned invalid data.');
  20630. }
  20631. /**
  20632. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20633. * @private
  20634. */
  20635. inner$4(this).dataBeforeProcessed = data;
  20636. // If we reverse the order (make data firstly, and then make
  20637. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20638. // cause data.graph.data !== data when using
  20639. // module:echarts/data/Graph or module:echarts/data/Tree.
  20640. // See module:echarts/data/helper/linkList
  20641. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20642. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20643. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20644. // Call `seriesModel.getRawData()` instead.
  20645. // this.restoreData();
  20646. autoSeriesName(this);
  20647. },
  20648. /**
  20649. * Util for merge default and theme to option
  20650. * @param {Object} option
  20651. * @param {module:echarts/model/Global} ecModel
  20652. */
  20653. mergeDefaultAndTheme: function (option, ecModel) {
  20654. var layoutMode = this.layoutMode;
  20655. var inputPositionParams = layoutMode
  20656. ? getLayoutParams(option) : {};
  20657. // Backward compat: using subType on theme.
  20658. // But if name duplicate between series subType
  20659. // (for example: parallel) add component mainType,
  20660. // add suffix 'Series'.
  20661. var themeSubType = this.subType;
  20662. if (ComponentModel.hasClass(themeSubType)) {
  20663. themeSubType += 'Series';
  20664. }
  20665. merge(
  20666. option,
  20667. ecModel.getTheme().get(this.subType)
  20668. );
  20669. merge(option, this.getDefaultOption());
  20670. // Default label emphasis `show`
  20671. defaultEmphasis(option, 'label', ['show']);
  20672. this.fillDataTextStyle(option.data);
  20673. if (layoutMode) {
  20674. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20675. }
  20676. },
  20677. mergeOption: function (newSeriesOption, ecModel) {
  20678. // this.settingTask.dirty();
  20679. newSeriesOption = merge(this.option, newSeriesOption, true);
  20680. this.fillDataTextStyle(newSeriesOption.data);
  20681. var layoutMode = this.layoutMode;
  20682. if (layoutMode) {
  20683. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20684. }
  20685. prepareSource(this);
  20686. var data = this.getInitialData(newSeriesOption, ecModel);
  20687. wrapData(data, this);
  20688. this.dataTask.dirty();
  20689. this.dataTask.context.data = data;
  20690. inner$4(this).dataBeforeProcessed = data;
  20691. autoSeriesName(this);
  20692. },
  20693. fillDataTextStyle: function (data) {
  20694. // Default data label emphasis `show`
  20695. // FIXME Tree structure data ?
  20696. // FIXME Performance ?
  20697. if (data && !isTypedArray(data)) {
  20698. var props = ['show'];
  20699. for (var i = 0; i < data.length; i++) {
  20700. if (data[i] && data[i].label) {
  20701. defaultEmphasis(data[i], 'label', props);
  20702. }
  20703. }
  20704. }
  20705. },
  20706. /**
  20707. * Init a data structure from data related option in series
  20708. * Must be overwritten
  20709. */
  20710. getInitialData: function () {},
  20711. /**
  20712. * Append data to list
  20713. * @param {Object} params
  20714. * @param {Array|TypedArray} params.data
  20715. */
  20716. appendData: function (params) {
  20717. // FIXME ???
  20718. // (1) If data from dataset, forbidden append.
  20719. // (2) support append data of dataset.
  20720. var data = this.getRawData();
  20721. data.appendData(params.data);
  20722. },
  20723. /**
  20724. * Consider some method like `filter`, `map` need make new data,
  20725. * We should make sure that `seriesModel.getData()` get correct
  20726. * data in the stream procedure. So we fetch data from upstream
  20727. * each time `task.perform` called.
  20728. * @param {string} [dataType]
  20729. * @return {module:echarts/data/List}
  20730. */
  20731. getData: function (dataType) {
  20732. var task = getCurrentTask(this);
  20733. if (task) {
  20734. var data = task.context.data;
  20735. return dataType == null ? data : data.getLinkedData(dataType);
  20736. }
  20737. else {
  20738. // When series is not alive (that may happen when click toolbox
  20739. // restore or setOption with not merge mode), series data may
  20740. // be still need to judge animation or something when graphic
  20741. // elements want to know whether fade out.
  20742. return inner$4(this).data;
  20743. }
  20744. },
  20745. /**
  20746. * @param {module:echarts/data/List} data
  20747. */
  20748. setData: function (data) {
  20749. var task = getCurrentTask(this);
  20750. if (task) {
  20751. var context = task.context;
  20752. // Consider case: filter, data sample.
  20753. if (context.data !== data && task.modifyOutputEnd) {
  20754. task.setOutputEnd(data.count());
  20755. }
  20756. context.outputData = data;
  20757. // Caution: setData should update context.data,
  20758. // Because getData may be called multiply in a
  20759. // single stage and expect to get the data just
  20760. // set. (For example, AxisProxy, x y both call
  20761. // getData and setDate sequentially).
  20762. // So the context.data should be fetched from
  20763. // upstream each time when a stage starts to be
  20764. // performed.
  20765. if (task !== this.dataTask) {
  20766. context.data = data;
  20767. }
  20768. }
  20769. inner$4(this).data = data;
  20770. },
  20771. /**
  20772. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20773. * @return {module:echarts/data/Source} source
  20774. */
  20775. getSource: function () {
  20776. return getSource(this);
  20777. },
  20778. /**
  20779. * Get data before processed
  20780. * @return {module:echarts/data/List}
  20781. */
  20782. getRawData: function () {
  20783. return inner$4(this).dataBeforeProcessed;
  20784. },
  20785. /**
  20786. * Get base axis if has coordinate system and has axis.
  20787. * By default use coordSys.getBaseAxis();
  20788. * Can be overrided for some chart.
  20789. * @return {type} description
  20790. */
  20791. getBaseAxis: function () {
  20792. var coordSys = this.coordinateSystem;
  20793. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20794. },
  20795. // FIXME
  20796. /**
  20797. * Default tooltip formatter
  20798. *
  20799. * @param {number} dataIndex
  20800. * @param {boolean} [multipleSeries=false]
  20801. * @param {number} [dataType]
  20802. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20803. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20804. * string is used as DOM HTML content.
  20805. * 'richText' is used for rendering tooltip in rich text form, for those where
  20806. * DOM operation is not supported.
  20807. * @return {Object} formatted tooltip with `html` and `markers`
  20808. */
  20809. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20810. var series = this;
  20811. renderMode = renderMode || 'html';
  20812. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20813. var isRichText = renderMode === 'richText';
  20814. var markers = {};
  20815. var markerId = 0;
  20816. function formatArrayValue(value) {
  20817. // ??? TODO refactor these logic.
  20818. // check: category-no-encode-has-axis-data in dataset.html
  20819. var vertially = reduce(value, function (vertially, val, idx) {
  20820. var dimItem = data.getDimensionInfo(idx);
  20821. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20822. }, 0);
  20823. var result = [];
  20824. tooltipDims.length
  20825. ? each$1(tooltipDims, function (dim) {
  20826. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20827. })
  20828. // By default, all dims is used on tooltip.
  20829. : each$1(value, setEachItem);
  20830. function setEachItem(val, dim) {
  20831. var dimInfo = data.getDimensionInfo(dim);
  20832. // If `dimInfo.tooltip` is not set, show tooltip.
  20833. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20834. return;
  20835. }
  20836. var dimType = dimInfo.type;
  20837. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  20838. var dimHead = getTooltipMarker({
  20839. color: color,
  20840. type: 'subItem',
  20841. renderMode: renderMode,
  20842. markerId: markName
  20843. });
  20844. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  20845. var valStr = (vertially
  20846. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  20847. : ''
  20848. )
  20849. // FIXME should not format time for raw data?
  20850. + encodeHTML(dimType === 'ordinal'
  20851. ? val + ''
  20852. : dimType === 'time'
  20853. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20854. : addCommas(val)
  20855. );
  20856. valStr && result.push(valStr);
  20857. if (isRichText) {
  20858. markers[markName] = color;
  20859. ++markerId;
  20860. }
  20861. }
  20862. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  20863. var content = newLine + result.join(newLine || ', ');
  20864. return {
  20865. renderMode: renderMode,
  20866. content: content,
  20867. style: markers
  20868. };
  20869. }
  20870. function formatSingleValue(val) {
  20871. // return encodeHTML(addCommas(val));
  20872. return {
  20873. renderMode: renderMode,
  20874. content: encodeHTML(addCommas(val)),
  20875. style: markers
  20876. };
  20877. }
  20878. var data = this.getData();
  20879. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20880. var tooltipDimLen = tooltipDims.length;
  20881. var value = this.getRawValue(dataIndex);
  20882. var isValueArr = isArray(value);
  20883. var color = data.getItemVisual(dataIndex, 'color');
  20884. if (isObject$1(color) && color.colorStops) {
  20885. color = (color.colorStops[0] || {}).color;
  20886. }
  20887. color = color || 'transparent';
  20888. // Complicated rule for pretty tooltip.
  20889. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20890. ? formatArrayValue(value)
  20891. : tooltipDimLen
  20892. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20893. : formatSingleValue(isValueArr ? value[0] : value);
  20894. var content = formattedValue.content;
  20895. var markName = series.seriesIndex + 'at' + markerId;
  20896. var colorEl = getTooltipMarker({
  20897. color: color,
  20898. type: 'item',
  20899. renderMode: renderMode,
  20900. markerId: markName
  20901. });
  20902. markers[markName] = color;
  20903. ++markerId;
  20904. var name = data.getName(dataIndex);
  20905. var seriesName = this.name;
  20906. if (!isNameSpecified(this)) {
  20907. seriesName = '';
  20908. }
  20909. seriesName = seriesName
  20910. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  20911. : '';
  20912. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20913. var html = !multipleSeries
  20914. ? seriesName + colorStr
  20915. + (name
  20916. ? encodeHTML(name) + ': ' + content
  20917. : content
  20918. )
  20919. : colorStr + seriesName + content;
  20920. return {
  20921. html: html,
  20922. markers: markers
  20923. };
  20924. },
  20925. /**
  20926. * @return {boolean}
  20927. */
  20928. isAnimationEnabled: function () {
  20929. if (env$1.node) {
  20930. return false;
  20931. }
  20932. var animationEnabled = this.getShallow('animation');
  20933. if (animationEnabled) {
  20934. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20935. animationEnabled = false;
  20936. }
  20937. }
  20938. return animationEnabled;
  20939. },
  20940. restoreData: function () {
  20941. this.dataTask.dirty();
  20942. },
  20943. getColorFromPalette: function (name, scope, requestColorNum) {
  20944. var ecModel = this.ecModel;
  20945. // PENDING
  20946. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20947. if (!color) {
  20948. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20949. }
  20950. return color;
  20951. },
  20952. /**
  20953. * Use `data.mapDimension(coordDim, true)` instead.
  20954. * @deprecated
  20955. */
  20956. coordDimToDataDim: function (coordDim) {
  20957. return this.getRawData().mapDimension(coordDim, true);
  20958. },
  20959. /**
  20960. * Get progressive rendering count each step
  20961. * @return {number}
  20962. */
  20963. getProgressive: function () {
  20964. return this.get('progressive');
  20965. },
  20966. /**
  20967. * Get progressive rendering count each step
  20968. * @return {number}
  20969. */
  20970. getProgressiveThreshold: function () {
  20971. return this.get('progressiveThreshold');
  20972. },
  20973. /**
  20974. * Get data indices for show tooltip content. See tooltip.
  20975. * @abstract
  20976. * @param {Array.<string>|string} dim
  20977. * @param {Array.<number>} value
  20978. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20979. * @return {Object} {dataIndices, nestestValue}.
  20980. */
  20981. getAxisTooltipData: null,
  20982. /**
  20983. * See tooltip.
  20984. * @abstract
  20985. * @param {number} dataIndex
  20986. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20987. */
  20988. getTooltipPosition: null,
  20989. /**
  20990. * @see {module:echarts/stream/Scheduler}
  20991. */
  20992. pipeTask: null,
  20993. /**
  20994. * Convinient for override in extended class.
  20995. * @protected
  20996. * @type {Function}
  20997. */
  20998. preventIncremental: null,
  20999. /**
  21000. * @public
  21001. * @readOnly
  21002. * @type {Object}
  21003. */
  21004. pipelineContext: null
  21005. });
  21006. mixin(SeriesModel, dataFormatMixin);
  21007. mixin(SeriesModel, colorPaletteMixin);
  21008. /**
  21009. * MUST be called after `prepareSource` called
  21010. * Here we need to make auto series, especially for auto legend. But we
  21011. * do not modify series.name in option to avoid side effects.
  21012. */
  21013. function autoSeriesName(seriesModel) {
  21014. // User specified name has higher priority, otherwise it may cause
  21015. // series can not be queried unexpectedly.
  21016. var name = seriesModel.name;
  21017. if (!isNameSpecified(seriesModel)) {
  21018. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21019. }
  21020. }
  21021. function getSeriesAutoName(seriesModel) {
  21022. var data = seriesModel.getRawData();
  21023. var dataDims = data.mapDimension('seriesName', true);
  21024. var nameArr = [];
  21025. each$1(dataDims, function (dataDim) {
  21026. var dimInfo = data.getDimensionInfo(dataDim);
  21027. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21028. });
  21029. return nameArr.join(' ');
  21030. }
  21031. function dataTaskCount(context) {
  21032. return context.model.getRawData().count();
  21033. }
  21034. function dataTaskReset(context) {
  21035. var seriesModel = context.model;
  21036. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21037. return dataTaskProgress;
  21038. }
  21039. function dataTaskProgress(param, context) {
  21040. // Avoid repead cloneShallow when data just created in reset.
  21041. if (param.end > context.outputData.count()) {
  21042. context.model.getRawData().cloneShallow(context.outputData);
  21043. }
  21044. }
  21045. // TODO refactor
  21046. function wrapData(data, seriesModel) {
  21047. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21048. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21049. });
  21050. }
  21051. function onDataSelfChange(seriesModel) {
  21052. var task = getCurrentTask(seriesModel);
  21053. if (task) {
  21054. // Consider case: filter, selectRange
  21055. task.setOutputEnd(this.count());
  21056. }
  21057. }
  21058. function getCurrentTask(seriesModel) {
  21059. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21060. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21061. if (pipeline) {
  21062. // When pipline finished, the currrentTask keep the last
  21063. // task (renderTask).
  21064. var task = pipeline.currentTask;
  21065. if (task) {
  21066. var agentStubMap = task.agentStubMap;
  21067. if (agentStubMap) {
  21068. task = agentStubMap.get(seriesModel.uid);
  21069. }
  21070. }
  21071. return task;
  21072. }
  21073. }
  21074. /*
  21075. * Licensed to the Apache Software Foundation (ASF) under one
  21076. * or more contributor license agreements. See the NOTICE file
  21077. * distributed with this work for additional information
  21078. * regarding copyright ownership. The ASF licenses this file
  21079. * to you under the Apache License, Version 2.0 (the
  21080. * "License"); you may not use this file except in compliance
  21081. * with the License. You may obtain a copy of the License at
  21082. *
  21083. * http://www.apache.org/licenses/LICENSE-2.0
  21084. *
  21085. * Unless required by applicable law or agreed to in writing,
  21086. * software distributed under the License is distributed on an
  21087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21088. * KIND, either express or implied. See the License for the
  21089. * specific language governing permissions and limitations
  21090. * under the License.
  21091. */
  21092. var Component = function () {
  21093. /**
  21094. * @type {module:zrender/container/Group}
  21095. * @readOnly
  21096. */
  21097. this.group = new Group();
  21098. /**
  21099. * @type {string}
  21100. * @readOnly
  21101. */
  21102. this.uid = getUID('viewComponent');
  21103. };
  21104. Component.prototype = {
  21105. constructor: Component,
  21106. init: function (ecModel, api) {},
  21107. render: function (componentModel, ecModel, api, payload) {},
  21108. dispose: function () {},
  21109. /**
  21110. * @param {string} eventType
  21111. * @param {Object} query
  21112. * @param {module:zrender/Element} targetEl
  21113. * @param {Object} packedEvent
  21114. * @return {boolen} Pass only when return `true`.
  21115. */
  21116. filterForExposedEvent: null
  21117. };
  21118. var componentProto = Component.prototype;
  21119. componentProto.updateView
  21120. = componentProto.updateLayout
  21121. = componentProto.updateVisual
  21122. = function (seriesModel, ecModel, api, payload) {
  21123. // Do nothing;
  21124. };
  21125. // Enable Component.extend.
  21126. enableClassExtend(Component);
  21127. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21128. enableClassManagement(Component, {registerWhenExtend: true});
  21129. /*
  21130. * Licensed to the Apache Software Foundation (ASF) under one
  21131. * or more contributor license agreements. See the NOTICE file
  21132. * distributed with this work for additional information
  21133. * regarding copyright ownership. The ASF licenses this file
  21134. * to you under the Apache License, Version 2.0 (the
  21135. * "License"); you may not use this file except in compliance
  21136. * with the License. You may obtain a copy of the License at
  21137. *
  21138. * http://www.apache.org/licenses/LICENSE-2.0
  21139. *
  21140. * Unless required by applicable law or agreed to in writing,
  21141. * software distributed under the License is distributed on an
  21142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21143. * KIND, either express or implied. See the License for the
  21144. * specific language governing permissions and limitations
  21145. * under the License.
  21146. */
  21147. /**
  21148. * @return {string} If large mode changed, return string 'reset';
  21149. */
  21150. var createRenderPlanner = function () {
  21151. var inner = makeInner();
  21152. return function (seriesModel) {
  21153. var fields = inner(seriesModel);
  21154. var pipelineContext = seriesModel.pipelineContext;
  21155. var originalLarge = fields.large;
  21156. var originalProgressive = fields.progressiveRender;
  21157. var large = fields.large = pipelineContext.large;
  21158. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21159. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21160. };
  21161. };
  21162. /*
  21163. * Licensed to the Apache Software Foundation (ASF) under one
  21164. * or more contributor license agreements. See the NOTICE file
  21165. * distributed with this work for additional information
  21166. * regarding copyright ownership. The ASF licenses this file
  21167. * to you under the Apache License, Version 2.0 (the
  21168. * "License"); you may not use this file except in compliance
  21169. * with the License. You may obtain a copy of the License at
  21170. *
  21171. * http://www.apache.org/licenses/LICENSE-2.0
  21172. *
  21173. * Unless required by applicable law or agreed to in writing,
  21174. * software distributed under the License is distributed on an
  21175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21176. * KIND, either express or implied. See the License for the
  21177. * specific language governing permissions and limitations
  21178. * under the License.
  21179. */
  21180. var inner$5 = makeInner();
  21181. var renderPlanner = createRenderPlanner();
  21182. function Chart() {
  21183. /**
  21184. * @type {module:zrender/container/Group}
  21185. * @readOnly
  21186. */
  21187. this.group = new Group();
  21188. /**
  21189. * @type {string}
  21190. * @readOnly
  21191. */
  21192. this.uid = getUID('viewChart');
  21193. this.renderTask = createTask({
  21194. plan: renderTaskPlan,
  21195. reset: renderTaskReset
  21196. });
  21197. this.renderTask.context = {view: this};
  21198. }
  21199. Chart.prototype = {
  21200. type: 'chart',
  21201. /**
  21202. * Init the chart.
  21203. * @param {module:echarts/model/Global} ecModel
  21204. * @param {module:echarts/ExtensionAPI} api
  21205. */
  21206. init: function (ecModel, api) {},
  21207. /**
  21208. * Render the chart.
  21209. * @param {module:echarts/model/Series} seriesModel
  21210. * @param {module:echarts/model/Global} ecModel
  21211. * @param {module:echarts/ExtensionAPI} api
  21212. * @param {Object} payload
  21213. */
  21214. render: function (seriesModel, ecModel, api, payload) {},
  21215. /**
  21216. * Highlight series or specified data item.
  21217. * @param {module:echarts/model/Series} seriesModel
  21218. * @param {module:echarts/model/Global} ecModel
  21219. * @param {module:echarts/ExtensionAPI} api
  21220. * @param {Object} payload
  21221. */
  21222. highlight: function (seriesModel, ecModel, api, payload) {
  21223. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21224. },
  21225. /**
  21226. * Downplay series or specified data item.
  21227. * @param {module:echarts/model/Series} seriesModel
  21228. * @param {module:echarts/model/Global} ecModel
  21229. * @param {module:echarts/ExtensionAPI} api
  21230. * @param {Object} payload
  21231. */
  21232. downplay: function (seriesModel, ecModel, api, payload) {
  21233. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21234. },
  21235. /**
  21236. * Remove self.
  21237. * @param {module:echarts/model/Global} ecModel
  21238. * @param {module:echarts/ExtensionAPI} api
  21239. */
  21240. remove: function (ecModel, api) {
  21241. this.group.removeAll();
  21242. },
  21243. /**
  21244. * Dispose self.
  21245. * @param {module:echarts/model/Global} ecModel
  21246. * @param {module:echarts/ExtensionAPI} api
  21247. */
  21248. dispose: function () {},
  21249. /**
  21250. * Rendering preparation in progressive mode.
  21251. * @param {module:echarts/model/Series} seriesModel
  21252. * @param {module:echarts/model/Global} ecModel
  21253. * @param {module:echarts/ExtensionAPI} api
  21254. * @param {Object} payload
  21255. */
  21256. incrementalPrepareRender: null,
  21257. /**
  21258. * Render in progressive mode.
  21259. * @param {Object} params See taskParams in `stream/task.js`
  21260. * @param {module:echarts/model/Series} seriesModel
  21261. * @param {module:echarts/model/Global} ecModel
  21262. * @param {module:echarts/ExtensionAPI} api
  21263. * @param {Object} payload
  21264. */
  21265. incrementalRender: null,
  21266. /**
  21267. * Update transform directly.
  21268. * @param {module:echarts/model/Series} seriesModel
  21269. * @param {module:echarts/model/Global} ecModel
  21270. * @param {module:echarts/ExtensionAPI} api
  21271. * @param {Object} payload
  21272. * @return {Object} {update: true}
  21273. */
  21274. updateTransform: null,
  21275. /**
  21276. * The view contains the given point.
  21277. * @interface
  21278. * @param {Array.<number>} point
  21279. * @return {boolean}
  21280. */
  21281. // containPoint: function () {}
  21282. /**
  21283. * @param {string} eventType
  21284. * @param {Object} query
  21285. * @param {module:zrender/Element} targetEl
  21286. * @param {Object} packedEvent
  21287. * @return {boolen} Pass only when return `true`.
  21288. */
  21289. filterForExposedEvent: null
  21290. };
  21291. var chartProto = Chart.prototype;
  21292. chartProto.updateView
  21293. = chartProto.updateLayout
  21294. = chartProto.updateVisual
  21295. = function (seriesModel, ecModel, api, payload) {
  21296. this.render(seriesModel, ecModel, api, payload);
  21297. };
  21298. /**
  21299. * Set state of single element
  21300. * @param {module:zrender/Element} el
  21301. * @param {string} state
  21302. */
  21303. function elSetState(el, state) {
  21304. if (el) {
  21305. el.trigger(state);
  21306. if (el.type === 'group') {
  21307. for (var i = 0; i < el.childCount(); i++) {
  21308. elSetState(el.childAt(i), state);
  21309. }
  21310. }
  21311. }
  21312. }
  21313. /**
  21314. * @param {module:echarts/data/List} data
  21315. * @param {Object} payload
  21316. * @param {string} state 'normal'|'emphasis'
  21317. */
  21318. function toggleHighlight(data, payload, state) {
  21319. var dataIndex = queryDataIndex(data, payload);
  21320. if (dataIndex != null) {
  21321. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21322. elSetState(data.getItemGraphicEl(dataIdx), state);
  21323. });
  21324. }
  21325. else {
  21326. data.eachItemGraphicEl(function (el) {
  21327. elSetState(el, state);
  21328. });
  21329. }
  21330. }
  21331. // Enable Chart.extend.
  21332. enableClassExtend(Chart, ['dispose']);
  21333. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21334. enableClassManagement(Chart, {registerWhenExtend: true});
  21335. Chart.markUpdateMethod = function (payload, methodName) {
  21336. inner$5(payload).updateMethod = methodName;
  21337. };
  21338. function renderTaskPlan(context) {
  21339. return renderPlanner(context.model);
  21340. }
  21341. function renderTaskReset(context) {
  21342. var seriesModel = context.model;
  21343. var ecModel = context.ecModel;
  21344. var api = context.api;
  21345. var payload = context.payload;
  21346. // ???! remove updateView updateVisual
  21347. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21348. var view = context.view;
  21349. var updateMethod = payload && inner$5(payload).updateMethod;
  21350. var methodName = progressiveRender
  21351. ? 'incrementalPrepareRender'
  21352. : (updateMethod && view[updateMethod])
  21353. ? updateMethod
  21354. // `appendData` is also supported when data amount
  21355. // is less than progressive threshold.
  21356. : 'render';
  21357. if (methodName !== 'render') {
  21358. view[methodName](seriesModel, ecModel, api, payload);
  21359. }
  21360. return progressMethodMap[methodName];
  21361. }
  21362. var progressMethodMap = {
  21363. incrementalPrepareRender: {
  21364. progress: function (params, context) {
  21365. context.view.incrementalRender(
  21366. params, context.model, context.ecModel, context.api, context.payload
  21367. );
  21368. }
  21369. },
  21370. render: {
  21371. // Put view.render in `progress` to support appendData. But in this case
  21372. // view.render should not be called in reset, otherwise it will be called
  21373. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21374. // in any cases.
  21375. forceFirstProgress: true,
  21376. progress: function (params, context) {
  21377. context.view.render(
  21378. context.model, context.ecModel, context.api, context.payload
  21379. );
  21380. }
  21381. }
  21382. };
  21383. /*
  21384. * Licensed to the Apache Software Foundation (ASF) under one
  21385. * or more contributor license agreements. See the NOTICE file
  21386. * distributed with this work for additional information
  21387. * regarding copyright ownership. The ASF licenses this file
  21388. * to you under the Apache License, Version 2.0 (the
  21389. * "License"); you may not use this file except in compliance
  21390. * with the License. You may obtain a copy of the License at
  21391. *
  21392. * http://www.apache.org/licenses/LICENSE-2.0
  21393. *
  21394. * Unless required by applicable law or agreed to in writing,
  21395. * software distributed under the License is distributed on an
  21396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21397. * KIND, either express or implied. See the License for the
  21398. * specific language governing permissions and limitations
  21399. * under the License.
  21400. */
  21401. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  21402. var RATE = '\0__throttleRate';
  21403. var THROTTLE_TYPE = '\0__throttleType';
  21404. /**
  21405. * @public
  21406. * @param {(Function)} fn
  21407. * @param {number} [delay=0] Unit: ms.
  21408. * @param {boolean} [debounce=false]
  21409. * true: If call interval less than `delay`, only the last call works.
  21410. * false: If call interval less than `delay, call works on fixed rate.
  21411. * @return {(Function)} throttled fn.
  21412. */
  21413. function throttle(fn, delay, debounce) {
  21414. var currCall;
  21415. var lastCall = 0;
  21416. var lastExec = 0;
  21417. var timer = null;
  21418. var diff;
  21419. var scope;
  21420. var args;
  21421. var debounceNextCall;
  21422. delay = delay || 0;
  21423. function exec() {
  21424. lastExec = (new Date()).getTime();
  21425. timer = null;
  21426. fn.apply(scope, args || []);
  21427. }
  21428. var cb = function () {
  21429. currCall = (new Date()).getTime();
  21430. scope = this;
  21431. args = arguments;
  21432. var thisDelay = debounceNextCall || delay;
  21433. var thisDebounce = debounceNextCall || debounce;
  21434. debounceNextCall = null;
  21435. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21436. clearTimeout(timer);
  21437. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21438. // than a new call of `cb`, that is, preserving the command order. Consider
  21439. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21440. // happens, either the `exec` is called dierectly, or the call is delayed.
  21441. // But the delayed call should never be later than next call of `cb`. Under
  21442. // this assurance, we can simply update view state each time `dispatchAction`
  21443. // triggered by user roaming, but not need to add extra code to avoid the
  21444. // state being "rolled-back".
  21445. if (thisDebounce) {
  21446. timer = setTimeout(exec, thisDelay);
  21447. }
  21448. else {
  21449. if (diff >= 0) {
  21450. exec();
  21451. }
  21452. else {
  21453. timer = setTimeout(exec, -diff);
  21454. }
  21455. }
  21456. lastCall = currCall;
  21457. };
  21458. /**
  21459. * Clear throttle.
  21460. * @public
  21461. */
  21462. cb.clear = function () {
  21463. if (timer) {
  21464. clearTimeout(timer);
  21465. timer = null;
  21466. }
  21467. };
  21468. /**
  21469. * Enable debounce once.
  21470. */
  21471. cb.debounceNextCall = function (debounceDelay) {
  21472. debounceNextCall = debounceDelay;
  21473. };
  21474. return cb;
  21475. }
  21476. /**
  21477. * Create throttle method or update throttle rate.
  21478. *
  21479. * @example
  21480. * ComponentView.prototype.render = function () {
  21481. * ...
  21482. * throttle.createOrUpdate(
  21483. * this,
  21484. * '_dispatchAction',
  21485. * this.model.get('throttle'),
  21486. * 'fixRate'
  21487. * );
  21488. * };
  21489. * ComponentView.prototype.remove = function () {
  21490. * throttle.clear(this, '_dispatchAction');
  21491. * };
  21492. * ComponentView.prototype.dispose = function () {
  21493. * throttle.clear(this, '_dispatchAction');
  21494. * };
  21495. *
  21496. * @public
  21497. * @param {Object} obj
  21498. * @param {string} fnAttr
  21499. * @param {number} [rate]
  21500. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21501. * @return {Function} throttled function.
  21502. */
  21503. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  21504. var fn = obj[fnAttr];
  21505. if (!fn) {
  21506. return;
  21507. }
  21508. var originFn = fn[ORIGIN_METHOD] || fn;
  21509. var lastThrottleType = fn[THROTTLE_TYPE];
  21510. var lastRate = fn[RATE];
  21511. if (lastRate !== rate || lastThrottleType !== throttleType) {
  21512. if (rate == null || !throttleType) {
  21513. return (obj[fnAttr] = originFn);
  21514. }
  21515. fn = obj[fnAttr] = throttle(
  21516. originFn, rate, throttleType === 'debounce'
  21517. );
  21518. fn[ORIGIN_METHOD] = originFn;
  21519. fn[THROTTLE_TYPE] = throttleType;
  21520. fn[RATE] = rate;
  21521. }
  21522. return fn;
  21523. }
  21524. /**
  21525. * Clear throttle. Example see throttle.createOrUpdate.
  21526. *
  21527. * @public
  21528. * @param {Object} obj
  21529. * @param {string} fnAttr
  21530. */
  21531. function clear(obj, fnAttr) {
  21532. var fn = obj[fnAttr];
  21533. if (fn && fn[ORIGIN_METHOD]) {
  21534. obj[fnAttr] = fn[ORIGIN_METHOD];
  21535. }
  21536. }
  21537. /*
  21538. * Licensed to the Apache Software Foundation (ASF) under one
  21539. * or more contributor license agreements. See the NOTICE file
  21540. * distributed with this work for additional information
  21541. * regarding copyright ownership. The ASF licenses this file
  21542. * to you under the Apache License, Version 2.0 (the
  21543. * "License"); you may not use this file except in compliance
  21544. * with the License. You may obtain a copy of the License at
  21545. *
  21546. * http://www.apache.org/licenses/LICENSE-2.0
  21547. *
  21548. * Unless required by applicable law or agreed to in writing,
  21549. * software distributed under the License is distributed on an
  21550. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21551. * KIND, either express or implied. See the License for the
  21552. * specific language governing permissions and limitations
  21553. * under the License.
  21554. */
  21555. var seriesColor = {
  21556. createOnAllSeries: true,
  21557. performRawSeries: true,
  21558. reset: function (seriesModel, ecModel) {
  21559. var data = seriesModel.getData();
  21560. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21561. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  21562. || seriesModel.getColorFromPalette(
  21563. // TODO series count changed.
  21564. seriesModel.name, null, ecModel.getSeriesCount()
  21565. ); // Default color
  21566. // FIXME Set color function or use the platte color
  21567. data.setVisual('color', color);
  21568. // Only visible series has each data be visual encoded
  21569. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21570. if (typeof color === 'function' && !(color instanceof Gradient)) {
  21571. data.each(function (idx) {
  21572. data.setItemVisual(
  21573. idx, 'color', color(seriesModel.getDataParams(idx))
  21574. );
  21575. });
  21576. }
  21577. // itemStyle in each data item
  21578. var dataEach = function (data, idx) {
  21579. var itemModel = data.getItemModel(idx);
  21580. var color = itemModel.get(colorAccessPath, true);
  21581. if (color != null) {
  21582. data.setItemVisual(idx, 'color', color);
  21583. }
  21584. };
  21585. return { dataEach: data.hasItemOption ? dataEach : null };
  21586. }
  21587. }
  21588. };
  21589. /*
  21590. * Licensed to the Apache Software Foundation (ASF) under one
  21591. * or more contributor license agreements. See the NOTICE file
  21592. * distributed with this work for additional information
  21593. * regarding copyright ownership. The ASF licenses this file
  21594. * to you under the Apache License, Version 2.0 (the
  21595. * "License"); you may not use this file except in compliance
  21596. * with the License. You may obtain a copy of the License at
  21597. *
  21598. * http://www.apache.org/licenses/LICENSE-2.0
  21599. *
  21600. * Unless required by applicable law or agreed to in writing,
  21601. * software distributed under the License is distributed on an
  21602. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21603. * KIND, either express or implied. See the License for the
  21604. * specific language governing permissions and limitations
  21605. * under the License.
  21606. */
  21607. var lang = {
  21608. toolbox: {
  21609. brush: {
  21610. title: {
  21611. rect: '矩形选择',
  21612. polygon: '圈选',
  21613. lineX: '横向选择',
  21614. lineY: '纵向选择',
  21615. keep: '保持选择',
  21616. clear: '清除选择'
  21617. }
  21618. },
  21619. dataView: {
  21620. title: '数据视图',
  21621. lang: ['数据视图', '关闭', '刷新']
  21622. },
  21623. dataZoom: {
  21624. title: {
  21625. zoom: '区域缩放',
  21626. back: '区域缩放还原'
  21627. }
  21628. },
  21629. magicType: {
  21630. title: {
  21631. line: '切换为折线图',
  21632. bar: '切换为柱状图',
  21633. stack: '切换为堆叠',
  21634. tiled: '切换为平铺'
  21635. }
  21636. },
  21637. restore: {
  21638. title: '还原'
  21639. },
  21640. saveAsImage: {
  21641. title: '保存为图片',
  21642. lang: ['右键另存为图片']
  21643. }
  21644. },
  21645. series: {
  21646. typeNames: {
  21647. pie: '饼图',
  21648. bar: '柱状图',
  21649. line: '折线图',
  21650. scatter: '散点图',
  21651. effectScatter: '涟漪散点图',
  21652. radar: '雷达图',
  21653. tree: '树图',
  21654. treemap: '矩形树图',
  21655. boxplot: '箱型图',
  21656. candlestick: 'K线图',
  21657. k: 'K线图',
  21658. heatmap: '热力图',
  21659. map: '地图',
  21660. parallel: '平行坐标图',
  21661. lines: '线图',
  21662. graph: '关系图',
  21663. sankey: '桑基图',
  21664. funnel: '漏斗图',
  21665. gauge: '仪表盘图',
  21666. pictorialBar: '象形柱图',
  21667. themeRiver: '主题河流图',
  21668. sunburst: '旭日图'
  21669. }
  21670. },
  21671. aria: {
  21672. general: {
  21673. withTitle: '这是一个关于“{title}”的图表。',
  21674. withoutTitle: '这是一个图表,'
  21675. },
  21676. series: {
  21677. single: {
  21678. prefix: '',
  21679. withName: '图表类型是{seriesType},表示{seriesName}。',
  21680. withoutName: '图表类型是{seriesType}。'
  21681. },
  21682. multiple: {
  21683. prefix: '它由{seriesCount}个图表系列组成。',
  21684. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21685. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21686. separator: {
  21687. middle: ';',
  21688. end: '。'
  21689. }
  21690. }
  21691. },
  21692. data: {
  21693. allData: '其数据是——',
  21694. partialData: '其中,前{displayCnt}项是——',
  21695. withName: '{name}的数据是{value}',
  21696. withoutName: '{value}',
  21697. separator: {
  21698. middle: ',',
  21699. end: ''
  21700. }
  21701. }
  21702. }
  21703. };
  21704. /*
  21705. * Licensed to the Apache Software Foundation (ASF) under one
  21706. * or more contributor license agreements. See the NOTICE file
  21707. * distributed with this work for additional information
  21708. * regarding copyright ownership. The ASF licenses this file
  21709. * to you under the Apache License, Version 2.0 (the
  21710. * "License"); you may not use this file except in compliance
  21711. * with the License. You may obtain a copy of the License at
  21712. *
  21713. * http://www.apache.org/licenses/LICENSE-2.0
  21714. *
  21715. * Unless required by applicable law or agreed to in writing,
  21716. * software distributed under the License is distributed on an
  21717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21718. * KIND, either express or implied. See the License for the
  21719. * specific language governing permissions and limitations
  21720. * under the License.
  21721. */
  21722. var aria = function (dom, ecModel) {
  21723. var ariaModel = ecModel.getModel('aria');
  21724. if (!ariaModel.get('show')) {
  21725. return;
  21726. }
  21727. else if (ariaModel.get('description')) {
  21728. dom.setAttribute('aria-label', ariaModel.get('description'));
  21729. return;
  21730. }
  21731. var seriesCnt = 0;
  21732. ecModel.eachSeries(function (seriesModel, idx) {
  21733. ++seriesCnt;
  21734. }, this);
  21735. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21736. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21737. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21738. var ariaLabel;
  21739. if (seriesCnt < 1) {
  21740. // No series, no aria label
  21741. return;
  21742. }
  21743. else {
  21744. var title = getTitle();
  21745. if (title) {
  21746. ariaLabel = replace(getConfig('general.withTitle'), {
  21747. title: title
  21748. });
  21749. }
  21750. else {
  21751. ariaLabel = getConfig('general.withoutTitle');
  21752. }
  21753. var seriesLabels = [];
  21754. var prefix = seriesCnt > 1
  21755. ? 'series.multiple.prefix'
  21756. : 'series.single.prefix';
  21757. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21758. ecModel.eachSeries(function (seriesModel, idx) {
  21759. if (idx < displaySeriesCnt) {
  21760. var seriesLabel;
  21761. var seriesName = seriesModel.get('name');
  21762. var seriesTpl = 'series.'
  21763. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21764. seriesLabel = getConfig(seriesName
  21765. ? seriesTpl + 'withName'
  21766. : seriesTpl + 'withoutName');
  21767. seriesLabel = replace(seriesLabel, {
  21768. seriesId: seriesModel.seriesIndex,
  21769. seriesName: seriesModel.get('name'),
  21770. seriesType: getSeriesTypeName(seriesModel.subType)
  21771. });
  21772. var data = seriesModel.getData();
  21773. window.data = data;
  21774. if (data.count() > maxDataCnt) {
  21775. // Show part of data
  21776. seriesLabel += replace(getConfig('data.partialData'), {
  21777. displayCnt: maxDataCnt
  21778. });
  21779. }
  21780. else {
  21781. seriesLabel += getConfig('data.allData');
  21782. }
  21783. var dataLabels = [];
  21784. for (var i = 0; i < data.count(); i++) {
  21785. if (i < maxDataCnt) {
  21786. var name = data.getName(i);
  21787. var value = retrieveRawValue(data, i);
  21788. dataLabels.push(
  21789. replace(
  21790. name
  21791. ? getConfig('data.withName')
  21792. : getConfig('data.withoutName'),
  21793. {
  21794. name: name,
  21795. value: value
  21796. }
  21797. )
  21798. );
  21799. }
  21800. }
  21801. seriesLabel += dataLabels
  21802. .join(getConfig('data.separator.middle'))
  21803. + getConfig('data.separator.end');
  21804. seriesLabels.push(seriesLabel);
  21805. }
  21806. });
  21807. ariaLabel += seriesLabels
  21808. .join(getConfig('series.multiple.separator.middle'))
  21809. + getConfig('series.multiple.separator.end');
  21810. dom.setAttribute('aria-label', ariaLabel);
  21811. }
  21812. function replace(str, keyValues) {
  21813. if (typeof str !== 'string') {
  21814. return str;
  21815. }
  21816. var result = str;
  21817. each$1(keyValues, function (value, key) {
  21818. result = result.replace(
  21819. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21820. value
  21821. );
  21822. });
  21823. return result;
  21824. }
  21825. function getConfig(path) {
  21826. var userConfig = ariaModel.get(path);
  21827. if (userConfig == null) {
  21828. var pathArr = path.split('.');
  21829. var result = lang.aria;
  21830. for (var i = 0; i < pathArr.length; ++i) {
  21831. result = result[pathArr[i]];
  21832. }
  21833. return result;
  21834. }
  21835. else {
  21836. return userConfig;
  21837. }
  21838. }
  21839. function getTitle() {
  21840. var title = ecModel.getModel('title').option;
  21841. if (title && title.length) {
  21842. title = title[0];
  21843. }
  21844. return title && title.text;
  21845. }
  21846. function getSeriesTypeName(type) {
  21847. return lang.series.typeNames[type] || '自定义图';
  21848. }
  21849. };
  21850. /*
  21851. * Licensed to the Apache Software Foundation (ASF) under one
  21852. * or more contributor license agreements. See the NOTICE file
  21853. * distributed with this work for additional information
  21854. * regarding copyright ownership. The ASF licenses this file
  21855. * to you under the Apache License, Version 2.0 (the
  21856. * "License"); you may not use this file except in compliance
  21857. * with the License. You may obtain a copy of the License at
  21858. *
  21859. * http://www.apache.org/licenses/LICENSE-2.0
  21860. *
  21861. * Unless required by applicable law or agreed to in writing,
  21862. * software distributed under the License is distributed on an
  21863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21864. * KIND, either express or implied. See the License for the
  21865. * specific language governing permissions and limitations
  21866. * under the License.
  21867. */
  21868. var PI$1 = Math.PI;
  21869. /**
  21870. * @param {module:echarts/ExtensionAPI} api
  21871. * @param {Object} [opts]
  21872. * @param {string} [opts.text]
  21873. * @param {string} [opts.color]
  21874. * @param {string} [opts.textColor]
  21875. * @return {module:zrender/Element}
  21876. */
  21877. var loadingDefault = function (api, opts) {
  21878. opts = opts || {};
  21879. defaults(opts, {
  21880. text: 'loading',
  21881. color: '#c23531',
  21882. textColor: '#000',
  21883. maskColor: 'rgba(255, 255, 255, 0.8)',
  21884. zlevel: 0
  21885. });
  21886. var mask = new Rect({
  21887. style: {
  21888. fill: opts.maskColor
  21889. },
  21890. zlevel: opts.zlevel,
  21891. z: 10000
  21892. });
  21893. var arc = new Arc({
  21894. shape: {
  21895. startAngle: -PI$1 / 2,
  21896. endAngle: -PI$1 / 2 + 0.1,
  21897. r: 10
  21898. },
  21899. style: {
  21900. stroke: opts.color,
  21901. lineCap: 'round',
  21902. lineWidth: 5
  21903. },
  21904. zlevel: opts.zlevel,
  21905. z: 10001
  21906. });
  21907. var labelRect = new Rect({
  21908. style: {
  21909. fill: 'none',
  21910. text: opts.text,
  21911. textPosition: 'right',
  21912. textDistance: 10,
  21913. textFill: opts.textColor
  21914. },
  21915. zlevel: opts.zlevel,
  21916. z: 10001
  21917. });
  21918. arc.animateShape(true)
  21919. .when(1000, {
  21920. endAngle: PI$1 * 3 / 2
  21921. })
  21922. .start('circularInOut');
  21923. arc.animateShape(true)
  21924. .when(1000, {
  21925. startAngle: PI$1 * 3 / 2
  21926. })
  21927. .delay(300)
  21928. .start('circularInOut');
  21929. var group = new Group();
  21930. group.add(arc);
  21931. group.add(labelRect);
  21932. group.add(mask);
  21933. // Inject resize
  21934. group.resize = function () {
  21935. var cx = api.getWidth() / 2;
  21936. var cy = api.getHeight() / 2;
  21937. arc.setShape({
  21938. cx: cx,
  21939. cy: cy
  21940. });
  21941. var r = arc.shape.r;
  21942. labelRect.setShape({
  21943. x: cx - r,
  21944. y: cy - r,
  21945. width: r * 2,
  21946. height: r * 2
  21947. });
  21948. mask.setShape({
  21949. x: 0,
  21950. y: 0,
  21951. width: api.getWidth(),
  21952. height: api.getHeight()
  21953. });
  21954. };
  21955. group.resize();
  21956. return group;
  21957. };
  21958. /*
  21959. * Licensed to the Apache Software Foundation (ASF) under one
  21960. * or more contributor license agreements. See the NOTICE file
  21961. * distributed with this work for additional information
  21962. * regarding copyright ownership. The ASF licenses this file
  21963. * to you under the Apache License, Version 2.0 (the
  21964. * "License"); you may not use this file except in compliance
  21965. * with the License. You may obtain a copy of the License at
  21966. *
  21967. * http://www.apache.org/licenses/LICENSE-2.0
  21968. *
  21969. * Unless required by applicable law or agreed to in writing,
  21970. * software distributed under the License is distributed on an
  21971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21972. * KIND, either express or implied. See the License for the
  21973. * specific language governing permissions and limitations
  21974. * under the License.
  21975. */
  21976. /**
  21977. * @module echarts/stream/Scheduler
  21978. */
  21979. /**
  21980. * @constructor
  21981. */
  21982. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21983. this.ecInstance = ecInstance;
  21984. this.api = api;
  21985. this.unfinished;
  21986. // Fix current processors in case that in some rear cases that
  21987. // processors might be registered after echarts instance created.
  21988. // Register processors incrementally for a echarts instance is
  21989. // not supported by this stream architecture.
  21990. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21991. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21992. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21993. /**
  21994. * @private
  21995. * @type {
  21996. * [handlerUID: string]: {
  21997. * seriesTaskMap?: {
  21998. * [seriesUID: string]: Task
  21999. * },
  22000. * overallTask?: Task
  22001. * }
  22002. * }
  22003. */
  22004. this._stageTaskMap = createHashMap();
  22005. }
  22006. var proto = Scheduler.prototype;
  22007. /**
  22008. * @param {module:echarts/model/Global} ecModel
  22009. * @param {Object} payload
  22010. */
  22011. proto.restoreData = function (ecModel, payload) {
  22012. // TODO: Only restroe needed series and components, but not all components.
  22013. // Currently `restoreData` of all of the series and component will be called.
  22014. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22015. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22016. // and some components like coordinate system, axes, dataZoom, visualMap only
  22017. // need their target series refresh.
  22018. // (1) If we are implementing this feature some day, we should consider these cases:
  22019. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22020. // on the settings of `dataZoom`), it should be re-performed if the component
  22021. // is modified by `setOption`.
  22022. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22023. // it should be re-performed when the result array of `getTargetSeries` changed.
  22024. // We use `dependencies` to cover these issues.
  22025. // (3) How to update target series when coordinate system related components modified.
  22026. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22027. // and this case all of the tasks will be set as dirty.
  22028. ecModel.restoreData(payload);
  22029. // Theoretically an overall task not only depends on each of its target series, but also
  22030. // depends on all of the series.
  22031. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22032. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22033. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22034. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22035. // probably cause state chaos (consider `dataZoomProcessor`).
  22036. this._stageTaskMap.each(function (taskRecord) {
  22037. var overallTask = taskRecord.overallTask;
  22038. overallTask && overallTask.dirty();
  22039. });
  22040. };
  22041. // If seriesModel provided, incremental threshold is check by series data.
  22042. proto.getPerformArgs = function (task, isBlock) {
  22043. // For overall task
  22044. if (!task.__pipeline) {
  22045. return;
  22046. }
  22047. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22048. var pCtx = pipeline.context;
  22049. var incremental = !isBlock
  22050. && pipeline.progressiveEnabled
  22051. && (!pCtx || pCtx.progressiveRender)
  22052. && task.__idxInPipeline > pipeline.blockIndex;
  22053. var step = incremental ? pipeline.step : null;
  22054. var modDataCount = pCtx && pCtx.modDataCount;
  22055. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22056. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22057. };
  22058. proto.getPipeline = function (pipelineId) {
  22059. return this._pipelineMap.get(pipelineId);
  22060. };
  22061. /**
  22062. * Current, progressive rendering starts from visual and layout.
  22063. * Always detect render mode in the same stage, avoiding that incorrect
  22064. * detection caused by data filtering.
  22065. * Caution:
  22066. * `updateStreamModes` use `seriesModel.getData()`.
  22067. */
  22068. proto.updateStreamModes = function (seriesModel, view) {
  22069. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22070. var data = seriesModel.getData();
  22071. var dataLen = data.count();
  22072. // `progressiveRender` means that can render progressively in each
  22073. // animation frame. Note that some types of series do not provide
  22074. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22075. // use the term `incremental` but not `progressive` to describe the
  22076. // case that `chart.appendData`.
  22077. var progressiveRender = pipeline.progressiveEnabled
  22078. && view.incrementalPrepareRender
  22079. && dataLen >= pipeline.threshold;
  22080. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22081. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22082. // see `test/candlestick-large3.html`
  22083. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22084. seriesModel.pipelineContext = pipeline.context = {
  22085. progressiveRender: progressiveRender,
  22086. modDataCount: modDataCount,
  22087. large: large
  22088. };
  22089. };
  22090. proto.restorePipelines = function (ecModel) {
  22091. var scheduler = this;
  22092. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22093. ecModel.eachSeries(function (seriesModel) {
  22094. var progressive = seriesModel.getProgressive();
  22095. var pipelineId = seriesModel.uid;
  22096. pipelineMap.set(pipelineId, {
  22097. id: pipelineId,
  22098. head: null,
  22099. tail: null,
  22100. threshold: seriesModel.getProgressiveThreshold(),
  22101. progressiveEnabled: progressive
  22102. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22103. blockIndex: -1,
  22104. step: Math.round(progressive || 700),
  22105. count: 0
  22106. });
  22107. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22108. });
  22109. };
  22110. proto.prepareStageTasks = function () {
  22111. var stageTaskMap = this._stageTaskMap;
  22112. var ecModel = this.ecInstance.getModel();
  22113. var api = this.api;
  22114. each$1(this._allHandlers, function (handler) {
  22115. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22116. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22117. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22118. }, this);
  22119. };
  22120. proto.prepareView = function (view, model, ecModel, api) {
  22121. var renderTask = view.renderTask;
  22122. var context = renderTask.context;
  22123. context.model = model;
  22124. context.ecModel = ecModel;
  22125. context.api = api;
  22126. renderTask.__block = !view.incrementalPrepareRender;
  22127. pipe(this, model, renderTask);
  22128. };
  22129. proto.performDataProcessorTasks = function (ecModel, payload) {
  22130. // If we do not use `block` here, it should be considered when to update modes.
  22131. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22132. };
  22133. // opt
  22134. // opt.visualType: 'visual' or 'layout'
  22135. // opt.setDirty
  22136. proto.performVisualTasks = function (ecModel, payload, opt) {
  22137. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22138. };
  22139. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22140. opt = opt || {};
  22141. var unfinished;
  22142. each$1(stageHandlers, function (stageHandler, idx) {
  22143. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22144. return;
  22145. }
  22146. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22147. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22148. var overallTask = stageHandlerRecord.overallTask;
  22149. if (overallTask) {
  22150. var overallNeedDirty;
  22151. var agentStubMap = overallTask.agentStubMap;
  22152. agentStubMap.each(function (stub) {
  22153. if (needSetDirty(opt, stub)) {
  22154. stub.dirty();
  22155. overallNeedDirty = true;
  22156. }
  22157. });
  22158. overallNeedDirty && overallTask.dirty();
  22159. updatePayload(overallTask, payload);
  22160. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22161. // Execute stubs firstly, which may set the overall task dirty,
  22162. // then execute the overall task. And stub will call seriesModel.setData,
  22163. // which ensures that in the overallTask seriesModel.getData() will not
  22164. // return incorrect data.
  22165. agentStubMap.each(function (stub) {
  22166. stub.perform(performArgs);
  22167. });
  22168. unfinished |= overallTask.perform(performArgs);
  22169. }
  22170. else if (seriesTaskMap) {
  22171. seriesTaskMap.each(function (task, pipelineId) {
  22172. if (needSetDirty(opt, task)) {
  22173. task.dirty();
  22174. }
  22175. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22176. performArgs.skip = !stageHandler.performRawSeries
  22177. && ecModel.isSeriesFiltered(task.context.model);
  22178. updatePayload(task, payload);
  22179. unfinished |= task.perform(performArgs);
  22180. });
  22181. }
  22182. });
  22183. function needSetDirty(opt, task) {
  22184. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22185. }
  22186. scheduler.unfinished |= unfinished;
  22187. }
  22188. proto.performSeriesTasks = function (ecModel) {
  22189. var unfinished;
  22190. ecModel.eachSeries(function (seriesModel) {
  22191. // Progress to the end for dataInit and dataRestore.
  22192. unfinished |= seriesModel.dataTask.perform();
  22193. });
  22194. this.unfinished |= unfinished;
  22195. };
  22196. proto.plan = function () {
  22197. // Travel pipelines, check block.
  22198. this._pipelineMap.each(function (pipeline) {
  22199. var task = pipeline.tail;
  22200. do {
  22201. if (task.__block) {
  22202. pipeline.blockIndex = task.__idxInPipeline;
  22203. break;
  22204. }
  22205. task = task.getUpstream();
  22206. }
  22207. while (task);
  22208. });
  22209. };
  22210. var updatePayload = proto.updatePayload = function (task, payload) {
  22211. payload !== 'remain' && (task.context.payload = payload);
  22212. };
  22213. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22214. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22215. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22216. var seriesType = stageHandler.seriesType;
  22217. var getTargetSeries = stageHandler.getTargetSeries;
  22218. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22219. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22220. // it works but it may cause other irrelevant charts blocked.
  22221. if (stageHandler.createOnAllSeries) {
  22222. ecModel.eachRawSeries(create);
  22223. }
  22224. else if (seriesType) {
  22225. ecModel.eachRawSeriesByType(seriesType, create);
  22226. }
  22227. else if (getTargetSeries) {
  22228. getTargetSeries(ecModel, api).each(create);
  22229. }
  22230. function create(seriesModel) {
  22231. var pipelineId = seriesModel.uid;
  22232. // Init tasks for each seriesModel only once.
  22233. // Reuse original task instance.
  22234. var task = seriesTaskMap.get(pipelineId)
  22235. || seriesTaskMap.set(pipelineId, createTask({
  22236. plan: seriesTaskPlan,
  22237. reset: seriesTaskReset,
  22238. count: seriesTaskCount
  22239. }));
  22240. task.context = {
  22241. model: seriesModel,
  22242. ecModel: ecModel,
  22243. api: api,
  22244. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22245. plan: stageHandler.plan,
  22246. reset: stageHandler.reset,
  22247. scheduler: scheduler
  22248. };
  22249. pipe(scheduler, seriesModel, task);
  22250. }
  22251. // Clear unused series tasks.
  22252. var pipelineMap = scheduler._pipelineMap;
  22253. seriesTaskMap.each(function (task, pipelineId) {
  22254. if (!pipelineMap.get(pipelineId)) {
  22255. task.dispose();
  22256. seriesTaskMap.removeKey(pipelineId);
  22257. }
  22258. });
  22259. }
  22260. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22261. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22262. // For overall task, the function only be called on reset stage.
  22263. || createTask({reset: overallTaskReset});
  22264. overallTask.context = {
  22265. ecModel: ecModel,
  22266. api: api,
  22267. overallReset: stageHandler.overallReset,
  22268. scheduler: scheduler
  22269. };
  22270. // Reuse orignal stubs.
  22271. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22272. var seriesType = stageHandler.seriesType;
  22273. var getTargetSeries = stageHandler.getTargetSeries;
  22274. var overallProgress = true;
  22275. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22276. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22277. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22278. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22279. // we set the pipeline block.
  22280. if (seriesType) {
  22281. ecModel.eachRawSeriesByType(seriesType, createStub);
  22282. }
  22283. else if (getTargetSeries) {
  22284. getTargetSeries(ecModel, api).each(createStub);
  22285. }
  22286. // Otherwise, (usually it is legancy case), the overall task will only be
  22287. // executed when upstream dirty. Otherwise the progressive rendering of all
  22288. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22289. // dirty info from upsteam.
  22290. else {
  22291. overallProgress = false;
  22292. each$1(ecModel.getSeries(), createStub);
  22293. }
  22294. function createStub(seriesModel) {
  22295. var pipelineId = seriesModel.uid;
  22296. var stub = agentStubMap.get(pipelineId);
  22297. if (!stub) {
  22298. stub = agentStubMap.set(pipelineId, createTask(
  22299. {reset: stubReset, onDirty: stubOnDirty}
  22300. ));
  22301. // When the result of `getTargetSeries` changed, the overallTask
  22302. // should be set as dirty and re-performed.
  22303. overallTask.dirty();
  22304. }
  22305. stub.context = {
  22306. model: seriesModel,
  22307. overallProgress: overallProgress,
  22308. modifyOutputEnd: modifyOutputEnd
  22309. };
  22310. stub.agent = overallTask;
  22311. stub.__block = overallProgress;
  22312. pipe(scheduler, seriesModel, stub);
  22313. }
  22314. // Clear unused stubs.
  22315. var pipelineMap = scheduler._pipelineMap;
  22316. agentStubMap.each(function (stub, pipelineId) {
  22317. if (!pipelineMap.get(pipelineId)) {
  22318. stub.dispose();
  22319. // When the result of `getTargetSeries` changed, the overallTask
  22320. // should be set as dirty and re-performed.
  22321. overallTask.dirty();
  22322. agentStubMap.removeKey(pipelineId);
  22323. }
  22324. });
  22325. }
  22326. function overallTaskReset(context) {
  22327. context.overallReset(
  22328. context.ecModel, context.api, context.payload
  22329. );
  22330. }
  22331. function stubReset(context, upstreamContext) {
  22332. return context.overallProgress && stubProgress;
  22333. }
  22334. function stubProgress() {
  22335. this.agent.dirty();
  22336. this.getDownstream().dirty();
  22337. }
  22338. function stubOnDirty() {
  22339. this.agent && this.agent.dirty();
  22340. }
  22341. function seriesTaskPlan(context) {
  22342. return context.plan && context.plan(
  22343. context.model, context.ecModel, context.api, context.payload
  22344. );
  22345. }
  22346. function seriesTaskReset(context) {
  22347. if (context.useClearVisual) {
  22348. context.data.clearAllVisual();
  22349. }
  22350. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22351. context.model, context.ecModel, context.api, context.payload
  22352. ));
  22353. return resetDefines.length > 1
  22354. ? map(resetDefines, function (v, idx) {
  22355. return makeSeriesTaskProgress(idx);
  22356. })
  22357. : singleSeriesTaskProgress;
  22358. }
  22359. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22360. function makeSeriesTaskProgress(resetDefineIdx) {
  22361. return function (params, context) {
  22362. var data = context.data;
  22363. var resetDefine = context.resetDefines[resetDefineIdx];
  22364. if (resetDefine && resetDefine.dataEach) {
  22365. for (var i = params.start; i < params.end; i++) {
  22366. resetDefine.dataEach(data, i);
  22367. }
  22368. }
  22369. else if (resetDefine && resetDefine.progress) {
  22370. resetDefine.progress(params, data);
  22371. }
  22372. };
  22373. }
  22374. function seriesTaskCount(context) {
  22375. return context.data.count();
  22376. }
  22377. function pipe(scheduler, seriesModel, task) {
  22378. var pipelineId = seriesModel.uid;
  22379. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22380. !pipeline.head && (pipeline.head = task);
  22381. pipeline.tail && pipeline.tail.pipe(task);
  22382. pipeline.tail = task;
  22383. task.__idxInPipeline = pipeline.count++;
  22384. task.__pipeline = pipeline;
  22385. }
  22386. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22387. if (isFunction$1(stageHandler)) {
  22388. stageHandler = {
  22389. overallReset: stageHandler,
  22390. seriesType: detectSeriseType(stageHandler)
  22391. };
  22392. }
  22393. stageHandler.uid = getUID('stageHandler');
  22394. visualType && (stageHandler.visualType = visualType);
  22395. return stageHandler;
  22396. };
  22397. /**
  22398. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22399. * To ensure that they can work normally, they should work in block mode, that is,
  22400. * they should not be started util the previous tasks finished. So they cause the
  22401. * progressive rendering disabled. We try to detect the series type, to narrow down
  22402. * the block range to only the series type they concern, but not all series.
  22403. */
  22404. function detectSeriseType(legacyFunc) {
  22405. seriesType = null;
  22406. try {
  22407. // Assume there is no async when calling `eachSeriesByType`.
  22408. legacyFunc(ecModelMock, apiMock);
  22409. }
  22410. catch (e) {
  22411. }
  22412. return seriesType;
  22413. }
  22414. var ecModelMock = {};
  22415. var apiMock = {};
  22416. var seriesType;
  22417. mockMethods(ecModelMock, GlobalModel);
  22418. mockMethods(apiMock, ExtensionAPI);
  22419. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22420. seriesType = type;
  22421. };
  22422. ecModelMock.eachComponent = function (cond) {
  22423. if (cond.mainType === 'series' && cond.subType) {
  22424. seriesType = cond.subType;
  22425. }
  22426. };
  22427. function mockMethods(target, Clz) {
  22428. /* eslint-disable */
  22429. for (var name in Clz.prototype) {
  22430. // Do not use hasOwnProperty
  22431. target[name] = noop;
  22432. }
  22433. /* eslint-enable */
  22434. }
  22435. /*
  22436. * Licensed to the Apache Software Foundation (ASF) under one
  22437. * or more contributor license agreements. See the NOTICE file
  22438. * distributed with this work for additional information
  22439. * regarding copyright ownership. The ASF licenses this file
  22440. * to you under the Apache License, Version 2.0 (the
  22441. * "License"); you may not use this file except in compliance
  22442. * with the License. You may obtain a copy of the License at
  22443. *
  22444. * http://www.apache.org/licenses/LICENSE-2.0
  22445. *
  22446. * Unless required by applicable law or agreed to in writing,
  22447. * software distributed under the License is distributed on an
  22448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22449. * KIND, either express or implied. See the License for the
  22450. * specific language governing permissions and limitations
  22451. * under the License.
  22452. */
  22453. var colorAll = [
  22454. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22455. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22456. ];
  22457. var lightTheme = {
  22458. color: colorAll,
  22459. colorLayer: [
  22460. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22461. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22462. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22463. colorAll
  22464. ]
  22465. };
  22466. /*
  22467. * Licensed to the Apache Software Foundation (ASF) under one
  22468. * or more contributor license agreements. See the NOTICE file
  22469. * distributed with this work for additional information
  22470. * regarding copyright ownership. The ASF licenses this file
  22471. * to you under the Apache License, Version 2.0 (the
  22472. * "License"); you may not use this file except in compliance
  22473. * with the License. You may obtain a copy of the License at
  22474. *
  22475. * http://www.apache.org/licenses/LICENSE-2.0
  22476. *
  22477. * Unless required by applicable law or agreed to in writing,
  22478. * software distributed under the License is distributed on an
  22479. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22480. * KIND, either express or implied. See the License for the
  22481. * specific language governing permissions and limitations
  22482. * under the License.
  22483. */
  22484. var contrastColor = '#eee';
  22485. var axisCommon = function () {
  22486. return {
  22487. axisLine: {
  22488. lineStyle: {
  22489. color: contrastColor
  22490. }
  22491. },
  22492. axisTick: {
  22493. lineStyle: {
  22494. color: contrastColor
  22495. }
  22496. },
  22497. axisLabel: {
  22498. textStyle: {
  22499. color: contrastColor
  22500. }
  22501. },
  22502. splitLine: {
  22503. lineStyle: {
  22504. type: 'dashed',
  22505. color: '#aaa'
  22506. }
  22507. },
  22508. splitArea: {
  22509. areaStyle: {
  22510. color: contrastColor
  22511. }
  22512. }
  22513. };
  22514. };
  22515. var colorPalette = [
  22516. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22517. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22518. ];
  22519. var theme = {
  22520. color: colorPalette,
  22521. backgroundColor: '#333',
  22522. tooltip: {
  22523. axisPointer: {
  22524. lineStyle: {
  22525. color: contrastColor
  22526. },
  22527. crossStyle: {
  22528. color: contrastColor
  22529. }
  22530. }
  22531. },
  22532. legend: {
  22533. textStyle: {
  22534. color: contrastColor
  22535. }
  22536. },
  22537. textStyle: {
  22538. color: contrastColor
  22539. },
  22540. title: {
  22541. textStyle: {
  22542. color: contrastColor
  22543. }
  22544. },
  22545. toolbox: {
  22546. iconStyle: {
  22547. normal: {
  22548. borderColor: contrastColor
  22549. }
  22550. }
  22551. },
  22552. dataZoom: {
  22553. textStyle: {
  22554. color: contrastColor
  22555. }
  22556. },
  22557. visualMap: {
  22558. textStyle: {
  22559. color: contrastColor
  22560. }
  22561. },
  22562. timeline: {
  22563. lineStyle: {
  22564. color: contrastColor
  22565. },
  22566. itemStyle: {
  22567. normal: {
  22568. color: colorPalette[1]
  22569. }
  22570. },
  22571. label: {
  22572. normal: {
  22573. textStyle: {
  22574. color: contrastColor
  22575. }
  22576. }
  22577. },
  22578. controlStyle: {
  22579. normal: {
  22580. color: contrastColor,
  22581. borderColor: contrastColor
  22582. }
  22583. }
  22584. },
  22585. timeAxis: axisCommon(),
  22586. logAxis: axisCommon(),
  22587. valueAxis: axisCommon(),
  22588. categoryAxis: axisCommon(),
  22589. line: {
  22590. symbol: 'circle'
  22591. },
  22592. graph: {
  22593. color: colorPalette
  22594. },
  22595. gauge: {
  22596. title: {
  22597. textStyle: {
  22598. color: contrastColor
  22599. }
  22600. }
  22601. },
  22602. candlestick: {
  22603. itemStyle: {
  22604. normal: {
  22605. color: '#FD1050',
  22606. color0: '#0CF49B',
  22607. borderColor: '#FD1050',
  22608. borderColor0: '#0CF49B'
  22609. }
  22610. }
  22611. }
  22612. };
  22613. theme.categoryAxis.splitLine.show = false;
  22614. /*
  22615. * Licensed to the Apache Software Foundation (ASF) under one
  22616. * or more contributor license agreements. See the NOTICE file
  22617. * distributed with this work for additional information
  22618. * regarding copyright ownership. The ASF licenses this file
  22619. * to you under the Apache License, Version 2.0 (the
  22620. * "License"); you may not use this file except in compliance
  22621. * with the License. You may obtain a copy of the License at
  22622. *
  22623. * http://www.apache.org/licenses/LICENSE-2.0
  22624. *
  22625. * Unless required by applicable law or agreed to in writing,
  22626. * software distributed under the License is distributed on an
  22627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22628. * KIND, either express or implied. See the License for the
  22629. * specific language governing permissions and limitations
  22630. * under the License.
  22631. */
  22632. /**
  22633. * This module is imported by echarts directly.
  22634. *
  22635. * Notice:
  22636. * Always keep this file exists for backward compatibility.
  22637. * Because before 4.1.0, dataset is an optional component,
  22638. * some users may import this module manually.
  22639. */
  22640. ComponentModel.extend({
  22641. type: 'dataset',
  22642. /**
  22643. * @protected
  22644. */
  22645. defaultOption: {
  22646. // 'row', 'column'
  22647. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22648. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22649. sourceHeader: null,
  22650. dimensions: null,
  22651. source: null
  22652. },
  22653. optionUpdated: function () {
  22654. detectSourceFormat(this);
  22655. }
  22656. });
  22657. Component.extend({
  22658. type: 'dataset'
  22659. });
  22660. /**
  22661. * 椭圆形状
  22662. * @module zrender/graphic/shape/Ellipse
  22663. */
  22664. var Ellipse = Path.extend({
  22665. type: 'ellipse',
  22666. shape: {
  22667. cx: 0, cy: 0,
  22668. rx: 0, ry: 0
  22669. },
  22670. buildPath: function (ctx, shape) {
  22671. var k = 0.5522848;
  22672. var x = shape.cx;
  22673. var y = shape.cy;
  22674. var a = shape.rx;
  22675. var b = shape.ry;
  22676. var ox = a * k; // 水平控制点偏移量
  22677. var oy = b * k; // 垂直控制点偏移量
  22678. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22679. ctx.moveTo(x - a, y);
  22680. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22681. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22682. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22683. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22684. ctx.closePath();
  22685. }
  22686. });
  22687. // import RadialGradient from '../graphic/RadialGradient';
  22688. // import Pattern from '../graphic/Pattern';
  22689. // import * as vector from '../core/vector';
  22690. // Most of the values can be separated by comma and/or white space.
  22691. var DILIMITER_REG = /[\s,]+/;
  22692. /**
  22693. * For big svg string, this method might be time consuming.
  22694. *
  22695. * @param {string} svg xml string
  22696. * @return {Object} xml root.
  22697. */
  22698. function parseXML(svg) {
  22699. if (isString(svg)) {
  22700. var parser = new DOMParser();
  22701. svg = parser.parseFromString(svg, 'text/xml');
  22702. }
  22703. // Document node. If using $.get, doc node may be input.
  22704. if (svg.nodeType === 9) {
  22705. svg = svg.firstChild;
  22706. }
  22707. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22708. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22709. svg = svg.nextSibling;
  22710. }
  22711. return svg;
  22712. }
  22713. function SVGParser() {
  22714. this._defs = {};
  22715. this._root = null;
  22716. this._isDefine = false;
  22717. this._isText = false;
  22718. }
  22719. SVGParser.prototype.parse = function (xml, opt) {
  22720. opt = opt || {};
  22721. var svg = parseXML(xml);
  22722. if (!svg) {
  22723. throw new Error('Illegal svg');
  22724. }
  22725. var root = new Group();
  22726. this._root = root;
  22727. // parse view port
  22728. var viewBox = svg.getAttribute('viewBox') || '';
  22729. // If width/height not specified, means "100%" of `opt.width/height`.
  22730. // TODO: Other percent value not supported yet.
  22731. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22732. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22733. // If width/height not specified, set as null for output.
  22734. isNaN(width) && (width = null);
  22735. isNaN(height) && (height = null);
  22736. // Apply inline style on svg element.
  22737. parseAttributes(svg, root, null, true);
  22738. var child = svg.firstChild;
  22739. while (child) {
  22740. this._parseNode(child, root);
  22741. child = child.nextSibling;
  22742. }
  22743. var viewBoxRect;
  22744. var viewBoxTransform;
  22745. if (viewBox) {
  22746. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22747. // Some invalid case like viewBox: 'none'.
  22748. if (viewBoxArr.length >= 4) {
  22749. viewBoxRect = {
  22750. x: parseFloat(viewBoxArr[0] || 0),
  22751. y: parseFloat(viewBoxArr[1] || 0),
  22752. width: parseFloat(viewBoxArr[2]),
  22753. height: parseFloat(viewBoxArr[3])
  22754. };
  22755. }
  22756. }
  22757. if (viewBoxRect && width != null && height != null) {
  22758. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22759. if (!opt.ignoreViewBox) {
  22760. // If set transform on the output group, it probably bring trouble when
  22761. // some users only intend to show the clipped content inside the viewBox,
  22762. // but not intend to transform the output group. So we keep the output
  22763. // group no transform. If the user intend to use the viewBox as a
  22764. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22765. // manually according to the viewBox info in the output of this method.
  22766. var elRoot = root;
  22767. root = new Group();
  22768. root.add(elRoot);
  22769. elRoot.scale = viewBoxTransform.scale.slice();
  22770. elRoot.position = viewBoxTransform.position.slice();
  22771. }
  22772. }
  22773. // Some shapes might be overflow the viewport, which should be
  22774. // clipped despite whether the viewBox is used, as the SVG does.
  22775. if (!opt.ignoreRootClip && width != null && height != null) {
  22776. root.setClipPath(new Rect({
  22777. shape: {x: 0, y: 0, width: width, height: height}
  22778. }));
  22779. }
  22780. // Set width/height on group just for output the viewport size.
  22781. return {
  22782. root: root,
  22783. width: width,
  22784. height: height,
  22785. viewBoxRect: viewBoxRect,
  22786. viewBoxTransform: viewBoxTransform
  22787. };
  22788. };
  22789. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22790. var nodeName = xmlNode.nodeName.toLowerCase();
  22791. // TODO
  22792. // support <style>...</style> in svg, where nodeName is 'style',
  22793. // CSS classes is defined globally wherever the style tags are declared.
  22794. if (nodeName === 'defs') {
  22795. // define flag
  22796. this._isDefine = true;
  22797. }
  22798. else if (nodeName === 'text') {
  22799. this._isText = true;
  22800. }
  22801. var el;
  22802. if (this._isDefine) {
  22803. var parser = defineParsers[nodeName];
  22804. if (parser) {
  22805. var def = parser.call(this, xmlNode);
  22806. var id = xmlNode.getAttribute('id');
  22807. if (id) {
  22808. this._defs[id] = def;
  22809. }
  22810. }
  22811. }
  22812. else {
  22813. var parser = nodeParsers[nodeName];
  22814. if (parser) {
  22815. el = parser.call(this, xmlNode, parentGroup);
  22816. parentGroup.add(el);
  22817. }
  22818. }
  22819. var child = xmlNode.firstChild;
  22820. while (child) {
  22821. if (child.nodeType === 1) {
  22822. this._parseNode(child, el);
  22823. }
  22824. // Is text
  22825. if (child.nodeType === 3 && this._isText) {
  22826. this._parseText(child, el);
  22827. }
  22828. child = child.nextSibling;
  22829. }
  22830. // Quit define
  22831. if (nodeName === 'defs') {
  22832. this._isDefine = false;
  22833. }
  22834. else if (nodeName === 'text') {
  22835. this._isText = false;
  22836. }
  22837. };
  22838. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22839. if (xmlNode.nodeType === 1) {
  22840. var dx = xmlNode.getAttribute('dx') || 0;
  22841. var dy = xmlNode.getAttribute('dy') || 0;
  22842. this._textX += parseFloat(dx);
  22843. this._textY += parseFloat(dy);
  22844. }
  22845. var text = new Text({
  22846. style: {
  22847. text: xmlNode.textContent,
  22848. transformText: true
  22849. },
  22850. position: [this._textX || 0, this._textY || 0]
  22851. });
  22852. inheritStyle(parentGroup, text);
  22853. parseAttributes(xmlNode, text, this._defs);
  22854. var fontSize = text.style.fontSize;
  22855. if (fontSize && fontSize < 9) {
  22856. // PENDING
  22857. text.style.fontSize = 9;
  22858. text.scale = text.scale || [1, 1];
  22859. text.scale[0] *= fontSize / 9;
  22860. text.scale[1] *= fontSize / 9;
  22861. }
  22862. var rect = text.getBoundingRect();
  22863. this._textX += rect.width;
  22864. parentGroup.add(text);
  22865. return text;
  22866. };
  22867. var nodeParsers = {
  22868. 'g': function (xmlNode, parentGroup) {
  22869. var g = new Group();
  22870. inheritStyle(parentGroup, g);
  22871. parseAttributes(xmlNode, g, this._defs);
  22872. return g;
  22873. },
  22874. 'rect': function (xmlNode, parentGroup) {
  22875. var rect = new Rect();
  22876. inheritStyle(parentGroup, rect);
  22877. parseAttributes(xmlNode, rect, this._defs);
  22878. rect.setShape({
  22879. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22880. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22881. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22882. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22883. });
  22884. // console.log(xmlNode.getAttribute('transform'));
  22885. // console.log(rect.transform);
  22886. return rect;
  22887. },
  22888. 'circle': function (xmlNode, parentGroup) {
  22889. var circle = new Circle();
  22890. inheritStyle(parentGroup, circle);
  22891. parseAttributes(xmlNode, circle, this._defs);
  22892. circle.setShape({
  22893. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22894. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22895. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22896. });
  22897. return circle;
  22898. },
  22899. 'line': function (xmlNode, parentGroup) {
  22900. var line = new Line();
  22901. inheritStyle(parentGroup, line);
  22902. parseAttributes(xmlNode, line, this._defs);
  22903. line.setShape({
  22904. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22905. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22906. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22907. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22908. });
  22909. return line;
  22910. },
  22911. 'ellipse': function (xmlNode, parentGroup) {
  22912. var ellipse = new Ellipse();
  22913. inheritStyle(parentGroup, ellipse);
  22914. parseAttributes(xmlNode, ellipse, this._defs);
  22915. ellipse.setShape({
  22916. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22917. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22918. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22919. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22920. });
  22921. return ellipse;
  22922. },
  22923. 'polygon': function (xmlNode, parentGroup) {
  22924. var points = xmlNode.getAttribute('points');
  22925. if (points) {
  22926. points = parsePoints(points);
  22927. }
  22928. var polygon = new Polygon({
  22929. shape: {
  22930. points: points || []
  22931. }
  22932. });
  22933. inheritStyle(parentGroup, polygon);
  22934. parseAttributes(xmlNode, polygon, this._defs);
  22935. return polygon;
  22936. },
  22937. 'polyline': function (xmlNode, parentGroup) {
  22938. var path = new Path();
  22939. inheritStyle(parentGroup, path);
  22940. parseAttributes(xmlNode, path, this._defs);
  22941. var points = xmlNode.getAttribute('points');
  22942. if (points) {
  22943. points = parsePoints(points);
  22944. }
  22945. var polyline = new Polyline({
  22946. shape: {
  22947. points: points || []
  22948. }
  22949. });
  22950. return polyline;
  22951. },
  22952. 'image': function (xmlNode, parentGroup) {
  22953. var img = new ZImage();
  22954. inheritStyle(parentGroup, img);
  22955. parseAttributes(xmlNode, img, this._defs);
  22956. img.setStyle({
  22957. image: xmlNode.getAttribute('xlink:href'),
  22958. x: xmlNode.getAttribute('x'),
  22959. y: xmlNode.getAttribute('y'),
  22960. width: xmlNode.getAttribute('width'),
  22961. height: xmlNode.getAttribute('height')
  22962. });
  22963. return img;
  22964. },
  22965. 'text': function (xmlNode, parentGroup) {
  22966. var x = xmlNode.getAttribute('x') || 0;
  22967. var y = xmlNode.getAttribute('y') || 0;
  22968. var dx = xmlNode.getAttribute('dx') || 0;
  22969. var dy = xmlNode.getAttribute('dy') || 0;
  22970. this._textX = parseFloat(x) + parseFloat(dx);
  22971. this._textY = parseFloat(y) + parseFloat(dy);
  22972. var g = new Group();
  22973. inheritStyle(parentGroup, g);
  22974. parseAttributes(xmlNode, g, this._defs);
  22975. return g;
  22976. },
  22977. 'tspan': function (xmlNode, parentGroup) {
  22978. var x = xmlNode.getAttribute('x');
  22979. var y = xmlNode.getAttribute('y');
  22980. if (x != null) {
  22981. // new offset x
  22982. this._textX = parseFloat(x);
  22983. }
  22984. if (y != null) {
  22985. // new offset y
  22986. this._textY = parseFloat(y);
  22987. }
  22988. var dx = xmlNode.getAttribute('dx') || 0;
  22989. var dy = xmlNode.getAttribute('dy') || 0;
  22990. var g = new Group();
  22991. inheritStyle(parentGroup, g);
  22992. parseAttributes(xmlNode, g, this._defs);
  22993. this._textX += dx;
  22994. this._textY += dy;
  22995. return g;
  22996. },
  22997. 'path': function (xmlNode, parentGroup) {
  22998. // TODO svg fill rule
  22999. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23000. // path.style.globalCompositeOperation = 'xor';
  23001. var d = xmlNode.getAttribute('d') || '';
  23002. // Performance sensitive.
  23003. var path = createFromString(d);
  23004. inheritStyle(parentGroup, path);
  23005. parseAttributes(xmlNode, path, this._defs);
  23006. return path;
  23007. }
  23008. };
  23009. var defineParsers = {
  23010. 'lineargradient': function (xmlNode) {
  23011. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23012. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23013. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23014. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23015. var gradient = new LinearGradient(x1, y1, x2, y2);
  23016. _parseGradientColorStops(xmlNode, gradient);
  23017. return gradient;
  23018. },
  23019. 'radialgradient': function (xmlNode) {
  23020. }
  23021. };
  23022. function _parseGradientColorStops(xmlNode, gradient) {
  23023. var stop = xmlNode.firstChild;
  23024. while (stop) {
  23025. if (stop.nodeType === 1) {
  23026. var offset = stop.getAttribute('offset');
  23027. if (offset.indexOf('%') > 0) { // percentage
  23028. offset = parseInt(offset, 10) / 100;
  23029. }
  23030. else if (offset) { // number from 0 to 1
  23031. offset = parseFloat(offset);
  23032. }
  23033. else {
  23034. offset = 0;
  23035. }
  23036. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23037. gradient.addColorStop(offset, stopColor);
  23038. }
  23039. stop = stop.nextSibling;
  23040. }
  23041. }
  23042. function inheritStyle(parent, child) {
  23043. if (parent && parent.__inheritedStyle) {
  23044. if (!child.__inheritedStyle) {
  23045. child.__inheritedStyle = {};
  23046. }
  23047. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23048. }
  23049. }
  23050. function parsePoints(pointsString) {
  23051. var list = trim(pointsString).split(DILIMITER_REG);
  23052. var points = [];
  23053. for (var i = 0; i < list.length; i += 2) {
  23054. var x = parseFloat(list[i]);
  23055. var y = parseFloat(list[i + 1]);
  23056. points.push([x, y]);
  23057. }
  23058. return points;
  23059. }
  23060. var attributesMap = {
  23061. 'fill': 'fill',
  23062. 'stroke': 'stroke',
  23063. 'stroke-width': 'lineWidth',
  23064. 'opacity': 'opacity',
  23065. 'fill-opacity': 'fillOpacity',
  23066. 'stroke-opacity': 'strokeOpacity',
  23067. 'stroke-dasharray': 'lineDash',
  23068. 'stroke-dashoffset': 'lineDashOffset',
  23069. 'stroke-linecap': 'lineCap',
  23070. 'stroke-linejoin': 'lineJoin',
  23071. 'stroke-miterlimit': 'miterLimit',
  23072. 'font-family': 'fontFamily',
  23073. 'font-size': 'fontSize',
  23074. 'font-style': 'fontStyle',
  23075. 'font-weight': 'fontWeight',
  23076. 'text-align': 'textAlign',
  23077. 'alignment-baseline': 'textBaseline'
  23078. };
  23079. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23080. var zrStyle = el.__inheritedStyle || {};
  23081. var isTextEl = el.type === 'text';
  23082. // TODO Shadow
  23083. if (xmlNode.nodeType === 1) {
  23084. parseTransformAttribute(xmlNode, el);
  23085. extend(zrStyle, parseStyleAttribute(xmlNode));
  23086. if (!onlyInlineStyle) {
  23087. for (var svgAttrName in attributesMap) {
  23088. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23089. var attrValue = xmlNode.getAttribute(svgAttrName);
  23090. if (attrValue != null) {
  23091. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23092. }
  23093. }
  23094. }
  23095. }
  23096. }
  23097. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23098. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23099. el.style = el.style || new Style();
  23100. var elStyle = el.style;
  23101. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23102. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23103. each$1([
  23104. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23105. ], function (propName) {
  23106. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23107. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23108. });
  23109. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23110. zrStyle.textBaseline = 'alphabetic';
  23111. }
  23112. if (zrStyle.textBaseline === 'alphabetic') {
  23113. zrStyle.textBaseline = 'bottom';
  23114. }
  23115. if (zrStyle.textAlign === 'start') {
  23116. zrStyle.textAlign = 'left';
  23117. }
  23118. if (zrStyle.textAlign === 'end') {
  23119. zrStyle.textAlign = 'right';
  23120. }
  23121. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23122. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23123. ], function (propName) {
  23124. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23125. });
  23126. if (zrStyle.lineDash) {
  23127. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23128. }
  23129. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23130. // enable stroke
  23131. el[elStrokeProp] = true;
  23132. }
  23133. el.__inheritedStyle = zrStyle;
  23134. }
  23135. var urlRegex = /url\(\s*#(.*?)\)/;
  23136. function getPaint(str, defs) {
  23137. // if (str === 'none') {
  23138. // return;
  23139. // }
  23140. var urlMatch = defs && str && str.match(urlRegex);
  23141. if (urlMatch) {
  23142. var url = trim(urlMatch[1]);
  23143. var def = defs[url];
  23144. return def;
  23145. }
  23146. return str;
  23147. }
  23148. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23149. function parseTransformAttribute(xmlNode, node) {
  23150. var transform = xmlNode.getAttribute('transform');
  23151. if (transform) {
  23152. transform = transform.replace(/,/g, ' ');
  23153. var m = null;
  23154. var transformOps = [];
  23155. transform.replace(transformRegex, function (str, type, value) {
  23156. transformOps.push(type, value);
  23157. });
  23158. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23159. var value = transformOps[i];
  23160. var type = transformOps[i - 1];
  23161. m = m || create$1();
  23162. switch (type) {
  23163. case 'translate':
  23164. value = trim(value).split(DILIMITER_REG);
  23165. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23166. break;
  23167. case 'scale':
  23168. value = trim(value).split(DILIMITER_REG);
  23169. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23170. break;
  23171. case 'rotate':
  23172. value = trim(value).split(DILIMITER_REG);
  23173. rotate(m, m, parseFloat(value[0]));
  23174. break;
  23175. case 'skew':
  23176. value = trim(value).split(DILIMITER_REG);
  23177. console.warn('Skew transform is not supported yet');
  23178. break;
  23179. case 'matrix':
  23180. var value = trim(value).split(DILIMITER_REG);
  23181. m[0] = parseFloat(value[0]);
  23182. m[1] = parseFloat(value[1]);
  23183. m[2] = parseFloat(value[2]);
  23184. m[3] = parseFloat(value[3]);
  23185. m[4] = parseFloat(value[4]);
  23186. m[5] = parseFloat(value[5]);
  23187. break;
  23188. }
  23189. }
  23190. node.setLocalTransform(m);
  23191. }
  23192. }
  23193. // Value may contain space.
  23194. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23195. function parseStyleAttribute(xmlNode) {
  23196. var style = xmlNode.getAttribute('style');
  23197. var result = {};
  23198. if (!style) {
  23199. return result;
  23200. }
  23201. var styleList = {};
  23202. styleRegex.lastIndex = 0;
  23203. var styleRegResult;
  23204. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23205. styleList[styleRegResult[1]] = styleRegResult[2];
  23206. }
  23207. for (var svgAttrName in attributesMap) {
  23208. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23209. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23210. }
  23211. }
  23212. return result;
  23213. }
  23214. /**
  23215. * @param {Array.<number>} viewBoxRect
  23216. * @param {number} width
  23217. * @param {number} height
  23218. * @return {Object} {scale, position}
  23219. */
  23220. function makeViewBoxTransform(viewBoxRect, width, height) {
  23221. var scaleX = width / viewBoxRect.width;
  23222. var scaleY = height / viewBoxRect.height;
  23223. var scale = Math.min(scaleX, scaleY);
  23224. // preserveAspectRatio 'xMidYMid'
  23225. var viewBoxScale = [scale, scale];
  23226. var viewBoxPosition = [
  23227. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23228. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23229. ];
  23230. return {
  23231. scale: viewBoxScale,
  23232. position: viewBoxPosition
  23233. };
  23234. }
  23235. /**
  23236. * @param {string|XMLElement} xml
  23237. * @param {Object} [opt]
  23238. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23239. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23240. * @param {boolean} [opt.ignoreViewBox]
  23241. * @param {boolean} [opt.ignoreRootClip]
  23242. * @return {Object} result:
  23243. * {
  23244. * root: Group, The root of the the result tree of zrender shapes,
  23245. * width: number, the viewport width of the SVG,
  23246. * height: number, the viewport height of the SVG,
  23247. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23248. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23249. * }
  23250. */
  23251. function parseSVG(xml, opt) {
  23252. var parser = new SVGParser();
  23253. return parser.parse(xml, opt);
  23254. }
  23255. /*
  23256. * Licensed to the Apache Software Foundation (ASF) under one
  23257. * or more contributor license agreements. See the NOTICE file
  23258. * distributed with this work for additional information
  23259. * regarding copyright ownership. The ASF licenses this file
  23260. * to you under the Apache License, Version 2.0 (the
  23261. * "License"); you may not use this file except in compliance
  23262. * with the License. You may obtain a copy of the License at
  23263. *
  23264. * http://www.apache.org/licenses/LICENSE-2.0
  23265. *
  23266. * Unless required by applicable law or agreed to in writing,
  23267. * software distributed under the License is distributed on an
  23268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23269. * KIND, either express or implied. See the License for the
  23270. * specific language governing permissions and limitations
  23271. * under the License.
  23272. */
  23273. var storage = createHashMap();
  23274. // For minimize the code size of common echarts package,
  23275. // do not put too much logic in this module.
  23276. var mapDataStorage = {
  23277. // The format of record: see `echarts.registerMap`.
  23278. // Compatible with previous `echarts.registerMap`.
  23279. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23280. var records;
  23281. if (isArray(rawGeoJson)) {
  23282. records = rawGeoJson;
  23283. }
  23284. else if (rawGeoJson.svg) {
  23285. records = [{
  23286. type: 'svg',
  23287. source: rawGeoJson.svg,
  23288. specialAreas: rawGeoJson.specialAreas
  23289. }];
  23290. }
  23291. else {
  23292. // Backward compatibility.
  23293. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23294. rawSpecialAreas = rawGeoJson.specialAreas;
  23295. rawGeoJson = rawGeoJson.geoJson;
  23296. }
  23297. records = [{
  23298. type: 'geoJSON',
  23299. source: rawGeoJson,
  23300. specialAreas: rawSpecialAreas
  23301. }];
  23302. }
  23303. each$1(records, function (record) {
  23304. var type = record.type;
  23305. type === 'geoJson' && (type = record.type = 'geoJSON');
  23306. var parse = parsers[type];
  23307. if (__DEV__) {
  23308. assert$1(parse, 'Illegal map type: ' + type);
  23309. }
  23310. parse(record);
  23311. });
  23312. return storage.set(mapName, records);
  23313. },
  23314. retrieveMap: function (mapName) {
  23315. return storage.get(mapName);
  23316. }
  23317. };
  23318. var parsers = {
  23319. geoJSON: function (record) {
  23320. var source = record.source;
  23321. record.geoJSON = !isString(source)
  23322. ? source
  23323. : (typeof JSON !== 'undefined' && JSON.parse)
  23324. ? JSON.parse(source)
  23325. : (new Function('return (' + source + ');'))();
  23326. },
  23327. // Only perform parse to XML object here, which might be time
  23328. // consiming for large SVG.
  23329. // Although convert XML to zrender element is also time consiming,
  23330. // if we do it here, the clone of zrender elements has to be
  23331. // required. So we do it once for each geo instance, util real
  23332. // performance issues call for optimizing it.
  23333. svg: function (record) {
  23334. record.svgXML = parseXML(record.source);
  23335. }
  23336. };
  23337. /*
  23338. * Licensed to the Apache Software Foundation (ASF) under one
  23339. * or more contributor license agreements. See the NOTICE file
  23340. * distributed with this work for additional information
  23341. * regarding copyright ownership. The ASF licenses this file
  23342. * to you under the Apache License, Version 2.0 (the
  23343. * "License"); you may not use this file except in compliance
  23344. * with the License. You may obtain a copy of the License at
  23345. *
  23346. * http://www.apache.org/licenses/LICENSE-2.0
  23347. *
  23348. * Unless required by applicable law or agreed to in writing,
  23349. * software distributed under the License is distributed on an
  23350. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23351. * KIND, either express or implied. See the License for the
  23352. * specific language governing permissions and limitations
  23353. * under the License.
  23354. */
  23355. var assert = assert$1;
  23356. var each = each$1;
  23357. var isFunction = isFunction$1;
  23358. var isObject = isObject$1;
  23359. var parseClassType = ComponentModel.parseClassType;
  23360. var version = '4.2.1';
  23361. var dependencies = {
  23362. zrender: '4.0.6'
  23363. };
  23364. var TEST_FRAME_REMAIN_TIME = 1;
  23365. var PRIORITY_PROCESSOR_FILTER = 1000;
  23366. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23367. var PRIORITY_VISUAL_LAYOUT = 1000;
  23368. var PRIORITY_VISUAL_GLOBAL = 2000;
  23369. var PRIORITY_VISUAL_CHART = 3000;
  23370. var PRIORITY_VISUAL_COMPONENT = 4000;
  23371. // FIXME
  23372. // necessary?
  23373. var PRIORITY_VISUAL_BRUSH = 5000;
  23374. var PRIORITY = {
  23375. PROCESSOR: {
  23376. FILTER: PRIORITY_PROCESSOR_FILTER,
  23377. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23378. },
  23379. VISUAL: {
  23380. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23381. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23382. CHART: PRIORITY_VISUAL_CHART,
  23383. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23384. BRUSH: PRIORITY_VISUAL_BRUSH
  23385. }
  23386. };
  23387. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23388. // where they must not be invoked nestedly, except the only case: invoke
  23389. // dispatchAction with updateMethod "none" in main process.
  23390. // This flag is used to carry out this rule.
  23391. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23392. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23393. var OPTION_UPDATED = '__optionUpdated';
  23394. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23395. function createRegisterEventWithLowercaseName(method) {
  23396. return function (eventName, handler, context) {
  23397. // Event name is all lowercase
  23398. eventName = eventName && eventName.toLowerCase();
  23399. Eventful.prototype[method].call(this, eventName, handler, context);
  23400. };
  23401. }
  23402. /**
  23403. * @module echarts~MessageCenter
  23404. */
  23405. function MessageCenter() {
  23406. Eventful.call(this);
  23407. }
  23408. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  23409. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  23410. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  23411. mixin(MessageCenter, Eventful);
  23412. /**
  23413. * @module echarts~ECharts
  23414. */
  23415. function ECharts(dom, theme$$1, opts) {
  23416. opts = opts || {};
  23417. // Get theme by name
  23418. if (typeof theme$$1 === 'string') {
  23419. theme$$1 = themeStorage[theme$$1];
  23420. }
  23421. /**
  23422. * @type {string}
  23423. */
  23424. this.id;
  23425. /**
  23426. * Group id
  23427. * @type {string}
  23428. */
  23429. this.group;
  23430. /**
  23431. * @type {HTMLElement}
  23432. * @private
  23433. */
  23434. this._dom = dom;
  23435. var defaultRenderer = 'canvas';
  23436. if (__DEV__) {
  23437. defaultRenderer = (
  23438. typeof window === 'undefined' ? global : window
  23439. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23440. }
  23441. /**
  23442. * @type {module:zrender/ZRender}
  23443. * @private
  23444. */
  23445. var zr = this._zr = init$1(dom, {
  23446. renderer: opts.renderer || defaultRenderer,
  23447. devicePixelRatio: opts.devicePixelRatio,
  23448. width: opts.width,
  23449. height: opts.height
  23450. });
  23451. /**
  23452. * Expect 60 pfs.
  23453. * @type {Function}
  23454. * @private
  23455. */
  23456. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23457. var theme$$1 = clone(theme$$1);
  23458. theme$$1 && backwardCompat(theme$$1, true);
  23459. /**
  23460. * @type {Object}
  23461. * @private
  23462. */
  23463. this._theme = theme$$1;
  23464. /**
  23465. * @type {Array.<module:echarts/view/Chart>}
  23466. * @private
  23467. */
  23468. this._chartsViews = [];
  23469. /**
  23470. * @type {Object.<string, module:echarts/view/Chart>}
  23471. * @private
  23472. */
  23473. this._chartsMap = {};
  23474. /**
  23475. * @type {Array.<module:echarts/view/Component>}
  23476. * @private
  23477. */
  23478. this._componentsViews = [];
  23479. /**
  23480. * @type {Object.<string, module:echarts/view/Component>}
  23481. * @private
  23482. */
  23483. this._componentsMap = {};
  23484. /**
  23485. * @type {module:echarts/CoordinateSystem}
  23486. * @private
  23487. */
  23488. this._coordSysMgr = new CoordinateSystemManager();
  23489. /**
  23490. * @type {module:echarts/ExtensionAPI}
  23491. * @private
  23492. */
  23493. var api = this._api = createExtensionAPI(this);
  23494. // Sort on demand
  23495. function prioritySortFunc(a, b) {
  23496. return a.__prio - b.__prio;
  23497. }
  23498. sort(visualFuncs, prioritySortFunc);
  23499. sort(dataProcessorFuncs, prioritySortFunc);
  23500. /**
  23501. * @type {module:echarts/stream/Scheduler}
  23502. */
  23503. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23504. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23505. /**
  23506. * @type {module:echarts~MessageCenter}
  23507. * @private
  23508. */
  23509. this._messageCenter = new MessageCenter();
  23510. // Init mouse events
  23511. this._initEvents();
  23512. // In case some people write `window.onresize = chart.resize`
  23513. this.resize = bind(this.resize, this);
  23514. // Can't dispatch action during rendering procedure
  23515. this._pendingActions = [];
  23516. zr.animation.on('frame', this._onframe, this);
  23517. bindRenderedEvent(zr, this);
  23518. // ECharts instance can be used as value.
  23519. setAsPrimitive(this);
  23520. }
  23521. var echartsProto = ECharts.prototype;
  23522. echartsProto._onframe = function () {
  23523. if (this._disposed) {
  23524. return;
  23525. }
  23526. var scheduler = this._scheduler;
  23527. // Lazy update
  23528. if (this[OPTION_UPDATED]) {
  23529. var silent = this[OPTION_UPDATED].silent;
  23530. this[IN_MAIN_PROCESS] = true;
  23531. prepare(this);
  23532. updateMethods.update.call(this);
  23533. this[IN_MAIN_PROCESS] = false;
  23534. this[OPTION_UPDATED] = false;
  23535. flushPendingActions.call(this, silent);
  23536. triggerUpdatedEvent.call(this, silent);
  23537. }
  23538. // Avoid do both lazy update and progress in one frame.
  23539. else if (scheduler.unfinished) {
  23540. // Stream progress.
  23541. var remainTime = TEST_FRAME_REMAIN_TIME;
  23542. var ecModel = this._model;
  23543. var api = this._api;
  23544. scheduler.unfinished = false;
  23545. do {
  23546. var startTime = +new Date();
  23547. scheduler.performSeriesTasks(ecModel);
  23548. // Currently dataProcessorFuncs do not check threshold.
  23549. scheduler.performDataProcessorTasks(ecModel);
  23550. updateStreamModes(this, ecModel);
  23551. // Do not update coordinate system here. Because that coord system update in
  23552. // each frame is not a good user experience. So we follow the rule that
  23553. // the extent of the coordinate system is determin in the first frame (the
  23554. // frame is executed immedietely after task reset.
  23555. // this._coordSysMgr.update(ecModel, api);
  23556. // console.log('--- ec frame visual ---', remainTime);
  23557. scheduler.performVisualTasks(ecModel);
  23558. renderSeries(this, this._model, api, 'remain');
  23559. remainTime -= (+new Date() - startTime);
  23560. }
  23561. while (remainTime > 0 && scheduler.unfinished);
  23562. // Call flush explicitly for trigger finished event.
  23563. if (!scheduler.unfinished) {
  23564. this._zr.flush();
  23565. }
  23566. // Else, zr flushing be ensue within the same frame,
  23567. // because zr flushing is after onframe event.
  23568. }
  23569. };
  23570. /**
  23571. * @return {HTMLElement}
  23572. */
  23573. echartsProto.getDom = function () {
  23574. return this._dom;
  23575. };
  23576. /**
  23577. * @return {module:zrender~ZRender}
  23578. */
  23579. echartsProto.getZr = function () {
  23580. return this._zr;
  23581. };
  23582. /**
  23583. * Usage:
  23584. * chart.setOption(option, notMerge, lazyUpdate);
  23585. * chart.setOption(option, {
  23586. * notMerge: ...,
  23587. * lazyUpdate: ...,
  23588. * silent: ...
  23589. * });
  23590. *
  23591. * @param {Object} option
  23592. * @param {Object|boolean} [opts] opts or notMerge.
  23593. * @param {boolean} [opts.notMerge=false]
  23594. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23595. */
  23596. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23597. if (__DEV__) {
  23598. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23599. }
  23600. var silent;
  23601. if (isObject(notMerge)) {
  23602. lazyUpdate = notMerge.lazyUpdate;
  23603. silent = notMerge.silent;
  23604. notMerge = notMerge.notMerge;
  23605. }
  23606. this[IN_MAIN_PROCESS] = true;
  23607. if (!this._model || notMerge) {
  23608. var optionManager = new OptionManager(this._api);
  23609. var theme$$1 = this._theme;
  23610. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  23611. ecModel.scheduler = this._scheduler;
  23612. ecModel.init(null, null, theme$$1, optionManager);
  23613. }
  23614. this._model.setOption(option, optionPreprocessorFuncs);
  23615. if (lazyUpdate) {
  23616. this[OPTION_UPDATED] = {silent: silent};
  23617. this[IN_MAIN_PROCESS] = false;
  23618. }
  23619. else {
  23620. prepare(this);
  23621. updateMethods.update.call(this);
  23622. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23623. // fetched after `setOption`.
  23624. this._zr.flush();
  23625. this[OPTION_UPDATED] = false;
  23626. this[IN_MAIN_PROCESS] = false;
  23627. flushPendingActions.call(this, silent);
  23628. triggerUpdatedEvent.call(this, silent);
  23629. }
  23630. };
  23631. /**
  23632. * @DEPRECATED
  23633. */
  23634. echartsProto.setTheme = function () {
  23635. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23636. };
  23637. /**
  23638. * @return {module:echarts/model/Global}
  23639. */
  23640. echartsProto.getModel = function () {
  23641. return this._model;
  23642. };
  23643. /**
  23644. * @return {Object}
  23645. */
  23646. echartsProto.getOption = function () {
  23647. return this._model && this._model.getOption();
  23648. };
  23649. /**
  23650. * @return {number}
  23651. */
  23652. echartsProto.getWidth = function () {
  23653. return this._zr.getWidth();
  23654. };
  23655. /**
  23656. * @return {number}
  23657. */
  23658. echartsProto.getHeight = function () {
  23659. return this._zr.getHeight();
  23660. };
  23661. /**
  23662. * @return {number}
  23663. */
  23664. echartsProto.getDevicePixelRatio = function () {
  23665. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23666. };
  23667. /**
  23668. * Get canvas which has all thing rendered
  23669. * @param {Object} opts
  23670. * @param {string} [opts.backgroundColor]
  23671. * @return {string}
  23672. */
  23673. echartsProto.getRenderedCanvas = function (opts) {
  23674. if (!env$1.canvasSupported) {
  23675. return;
  23676. }
  23677. opts = opts || {};
  23678. opts.pixelRatio = opts.pixelRatio || 1;
  23679. opts.backgroundColor = opts.backgroundColor
  23680. || this._model.get('backgroundColor');
  23681. var zr = this._zr;
  23682. // var list = zr.storage.getDisplayList();
  23683. // Stop animations
  23684. // Never works before in init animation, so remove it.
  23685. // zrUtil.each(list, function (el) {
  23686. // el.stopAnimation(true);
  23687. // });
  23688. return zr.painter.getRenderedCanvas(opts);
  23689. };
  23690. /**
  23691. * Get svg data url
  23692. * @return {string}
  23693. */
  23694. echartsProto.getSvgDataUrl = function () {
  23695. if (!env$1.svgSupported) {
  23696. return;
  23697. }
  23698. var zr = this._zr;
  23699. var list = zr.storage.getDisplayList();
  23700. // Stop animations
  23701. each$1(list, function (el) {
  23702. el.stopAnimation(true);
  23703. });
  23704. return zr.painter.pathToDataUrl();
  23705. };
  23706. /**
  23707. * @return {string}
  23708. * @param {Object} opts
  23709. * @param {string} [opts.type='png']
  23710. * @param {string} [opts.pixelRatio=1]
  23711. * @param {string} [opts.backgroundColor]
  23712. * @param {string} [opts.excludeComponents]
  23713. */
  23714. echartsProto.getDataURL = function (opts) {
  23715. opts = opts || {};
  23716. var excludeComponents = opts.excludeComponents;
  23717. var ecModel = this._model;
  23718. var excludesComponentViews = [];
  23719. var self = this;
  23720. each(excludeComponents, function (componentType) {
  23721. ecModel.eachComponent({
  23722. mainType: componentType
  23723. }, function (component) {
  23724. var view = self._componentsMap[component.__viewId];
  23725. if (!view.group.ignore) {
  23726. excludesComponentViews.push(view);
  23727. view.group.ignore = true;
  23728. }
  23729. });
  23730. });
  23731. var url = this._zr.painter.getType() === 'svg'
  23732. ? this.getSvgDataUrl()
  23733. : this.getRenderedCanvas(opts).toDataURL(
  23734. 'image/' + (opts && opts.type || 'png')
  23735. );
  23736. each(excludesComponentViews, function (view) {
  23737. view.group.ignore = false;
  23738. });
  23739. return url;
  23740. };
  23741. /**
  23742. * @return {string}
  23743. * @param {Object} opts
  23744. * @param {string} [opts.type='png']
  23745. * @param {string} [opts.pixelRatio=1]
  23746. * @param {string} [opts.backgroundColor]
  23747. */
  23748. echartsProto.getConnectedDataURL = function (opts) {
  23749. if (!env$1.canvasSupported) {
  23750. return;
  23751. }
  23752. var groupId = this.group;
  23753. var mathMin = Math.min;
  23754. var mathMax = Math.max;
  23755. var MAX_NUMBER = Infinity;
  23756. if (connectedGroups[groupId]) {
  23757. var left = MAX_NUMBER;
  23758. var top = MAX_NUMBER;
  23759. var right = -MAX_NUMBER;
  23760. var bottom = -MAX_NUMBER;
  23761. var canvasList = [];
  23762. var dpr = (opts && opts.pixelRatio) || 1;
  23763. each$1(instances, function (chart, id) {
  23764. if (chart.group === groupId) {
  23765. var canvas = chart.getRenderedCanvas(
  23766. clone(opts)
  23767. );
  23768. var boundingRect = chart.getDom().getBoundingClientRect();
  23769. left = mathMin(boundingRect.left, left);
  23770. top = mathMin(boundingRect.top, top);
  23771. right = mathMax(boundingRect.right, right);
  23772. bottom = mathMax(boundingRect.bottom, bottom);
  23773. canvasList.push({
  23774. dom: canvas,
  23775. left: boundingRect.left,
  23776. top: boundingRect.top
  23777. });
  23778. }
  23779. });
  23780. left *= dpr;
  23781. top *= dpr;
  23782. right *= dpr;
  23783. bottom *= dpr;
  23784. var width = right - left;
  23785. var height = bottom - top;
  23786. var targetCanvas = createCanvas();
  23787. targetCanvas.width = width;
  23788. targetCanvas.height = height;
  23789. var zr = init$1(targetCanvas);
  23790. each(canvasList, function (item) {
  23791. var img = new ZImage({
  23792. style: {
  23793. x: item.left * dpr - left,
  23794. y: item.top * dpr - top,
  23795. image: item.dom
  23796. }
  23797. });
  23798. zr.add(img);
  23799. });
  23800. zr.refreshImmediately();
  23801. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23802. }
  23803. else {
  23804. return this.getDataURL(opts);
  23805. }
  23806. };
  23807. /**
  23808. * Convert from logical coordinate system to pixel coordinate system.
  23809. * See CoordinateSystem#convertToPixel.
  23810. * @param {string|Object} finder
  23811. * If string, e.g., 'geo', means {geoIndex: 0}.
  23812. * If Object, could contain some of these properties below:
  23813. * {
  23814. * seriesIndex / seriesId / seriesName,
  23815. * geoIndex / geoId, geoName,
  23816. * bmapIndex / bmapId / bmapName,
  23817. * xAxisIndex / xAxisId / xAxisName,
  23818. * yAxisIndex / yAxisId / yAxisName,
  23819. * gridIndex / gridId / gridName,
  23820. * ... (can be extended)
  23821. * }
  23822. * @param {Array|number} value
  23823. * @return {Array|number} result
  23824. */
  23825. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23826. /**
  23827. * Convert from pixel coordinate system to logical coordinate system.
  23828. * See CoordinateSystem#convertFromPixel.
  23829. * @param {string|Object} finder
  23830. * If string, e.g., 'geo', means {geoIndex: 0}.
  23831. * If Object, could contain some of these properties below:
  23832. * {
  23833. * seriesIndex / seriesId / seriesName,
  23834. * geoIndex / geoId / geoName,
  23835. * bmapIndex / bmapId / bmapName,
  23836. * xAxisIndex / xAxisId / xAxisName,
  23837. * yAxisIndex / yAxisId / yAxisName
  23838. * gridIndex / gridId / gridName,
  23839. * ... (can be extended)
  23840. * }
  23841. * @param {Array|number} value
  23842. * @return {Array|number} result
  23843. */
  23844. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23845. function doConvertPixel(methodName, finder, value) {
  23846. var ecModel = this._model;
  23847. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23848. var result;
  23849. finder = parseFinder(ecModel, finder);
  23850. for (var i = 0; i < coordSysList.length; i++) {
  23851. var coordSys = coordSysList[i];
  23852. if (coordSys[methodName]
  23853. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23854. ) {
  23855. return result;
  23856. }
  23857. }
  23858. if (__DEV__) {
  23859. console.warn(
  23860. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23861. );
  23862. }
  23863. }
  23864. /**
  23865. * Is the specified coordinate systems or components contain the given pixel point.
  23866. * @param {string|Object} finder
  23867. * If string, e.g., 'geo', means {geoIndex: 0}.
  23868. * If Object, could contain some of these properties below:
  23869. * {
  23870. * seriesIndex / seriesId / seriesName,
  23871. * geoIndex / geoId / geoName,
  23872. * bmapIndex / bmapId / bmapName,
  23873. * xAxisIndex / xAxisId / xAxisName,
  23874. * yAxisIndex / yAxisId / yAxisName,
  23875. * gridIndex / gridId / gridName,
  23876. * ... (can be extended)
  23877. * }
  23878. * @param {Array|number} value
  23879. * @return {boolean} result
  23880. */
  23881. echartsProto.containPixel = function (finder, value) {
  23882. var ecModel = this._model;
  23883. var result;
  23884. finder = parseFinder(ecModel, finder);
  23885. each$1(finder, function (models, key) {
  23886. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23887. var coordSys = model.coordinateSystem;
  23888. if (coordSys && coordSys.containPoint) {
  23889. result |= !!coordSys.containPoint(value);
  23890. }
  23891. else if (key === 'seriesModels') {
  23892. var view = this._chartsMap[model.__viewId];
  23893. if (view && view.containPoint) {
  23894. result |= view.containPoint(value, model);
  23895. }
  23896. else {
  23897. if (__DEV__) {
  23898. console.warn(key + ': ' + (view
  23899. ? 'The found component do not support containPoint.'
  23900. : 'No view mapping to the found component.'
  23901. ));
  23902. }
  23903. }
  23904. }
  23905. else {
  23906. if (__DEV__) {
  23907. console.warn(key + ': containPoint is not supported');
  23908. }
  23909. }
  23910. }, this);
  23911. }, this);
  23912. return !!result;
  23913. };
  23914. /**
  23915. * Get visual from series or data.
  23916. * @param {string|Object} finder
  23917. * If string, e.g., 'series', means {seriesIndex: 0}.
  23918. * If Object, could contain some of these properties below:
  23919. * {
  23920. * seriesIndex / seriesId / seriesName,
  23921. * dataIndex / dataIndexInside
  23922. * }
  23923. * If dataIndex is not specified, series visual will be fetched,
  23924. * but not data item visual.
  23925. * If all of seriesIndex, seriesId, seriesName are not specified,
  23926. * visual will be fetched from first series.
  23927. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23928. */
  23929. echartsProto.getVisual = function (finder, visualType) {
  23930. var ecModel = this._model;
  23931. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23932. var seriesModel = finder.seriesModel;
  23933. if (__DEV__) {
  23934. if (!seriesModel) {
  23935. console.warn('There is no specified seires model');
  23936. }
  23937. }
  23938. var data = seriesModel.getData();
  23939. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23940. ? finder.dataIndexInside
  23941. : finder.hasOwnProperty('dataIndex')
  23942. ? data.indexOfRawIndex(finder.dataIndex)
  23943. : null;
  23944. return dataIndexInside != null
  23945. ? data.getItemVisual(dataIndexInside, visualType)
  23946. : data.getVisual(visualType);
  23947. };
  23948. /**
  23949. * Get view of corresponding component model
  23950. * @param {module:echarts/model/Component} componentModel
  23951. * @return {module:echarts/view/Component}
  23952. */
  23953. echartsProto.getViewOfComponentModel = function (componentModel) {
  23954. return this._componentsMap[componentModel.__viewId];
  23955. };
  23956. /**
  23957. * Get view of corresponding series model
  23958. * @param {module:echarts/model/Series} seriesModel
  23959. * @return {module:echarts/view/Chart}
  23960. */
  23961. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23962. return this._chartsMap[seriesModel.__viewId];
  23963. };
  23964. var updateMethods = {
  23965. prepareAndUpdate: function (payload) {
  23966. prepare(this);
  23967. updateMethods.update.call(this, payload);
  23968. },
  23969. /**
  23970. * @param {Object} payload
  23971. * @private
  23972. */
  23973. update: function (payload) {
  23974. // console.profile && console.profile('update');
  23975. var ecModel = this._model;
  23976. var api = this._api;
  23977. var zr = this._zr;
  23978. var coordSysMgr = this._coordSysMgr;
  23979. var scheduler = this._scheduler;
  23980. // update before setOption
  23981. if (!ecModel) {
  23982. return;
  23983. }
  23984. scheduler.restoreData(ecModel, payload);
  23985. scheduler.performSeriesTasks(ecModel);
  23986. // TODO
  23987. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23988. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23989. // Create new coordinate system each update
  23990. // In LineView may save the old coordinate system and use it to get the orignal point
  23991. coordSysMgr.create(ecModel, api);
  23992. scheduler.performDataProcessorTasks(ecModel, payload);
  23993. // Current stream render is not supported in data process. So we can update
  23994. // stream modes after data processing, where the filtered data is used to
  23995. // deteming whether use progressive rendering.
  23996. updateStreamModes(this, ecModel);
  23997. // We update stream modes before coordinate system updated, then the modes info
  23998. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23999. // the drawback is the full coord info can not be fetched. Fortunately this full
  24000. // coord is not requied in stream mode updater currently.
  24001. coordSysMgr.update(ecModel, api);
  24002. clearColorPalette(ecModel);
  24003. scheduler.performVisualTasks(ecModel, payload);
  24004. render(this, ecModel, api, payload);
  24005. // Set background
  24006. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24007. // In IE8
  24008. if (!env$1.canvasSupported) {
  24009. var colorArr = parse(backgroundColor);
  24010. backgroundColor = stringify(colorArr, 'rgb');
  24011. if (colorArr[3] === 0) {
  24012. backgroundColor = 'transparent';
  24013. }
  24014. }
  24015. else {
  24016. zr.setBackgroundColor(backgroundColor);
  24017. }
  24018. performPostUpdateFuncs(ecModel, api);
  24019. // console.profile && console.profileEnd('update');
  24020. },
  24021. /**
  24022. * @param {Object} payload
  24023. * @private
  24024. */
  24025. updateTransform: function (payload) {
  24026. var ecModel = this._model;
  24027. var ecIns = this;
  24028. var api = this._api;
  24029. // update before setOption
  24030. if (!ecModel) {
  24031. return;
  24032. }
  24033. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24034. var componentDirtyList = [];
  24035. ecModel.eachComponent(function (componentType, componentModel) {
  24036. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24037. if (componentView && componentView.__alive) {
  24038. if (componentView.updateTransform) {
  24039. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24040. result && result.update && componentDirtyList.push(componentView);
  24041. }
  24042. else {
  24043. componentDirtyList.push(componentView);
  24044. }
  24045. }
  24046. });
  24047. var seriesDirtyMap = createHashMap();
  24048. ecModel.eachSeries(function (seriesModel) {
  24049. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24050. if (chartView.updateTransform) {
  24051. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24052. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24053. }
  24054. else {
  24055. seriesDirtyMap.set(seriesModel.uid, 1);
  24056. }
  24057. });
  24058. clearColorPalette(ecModel);
  24059. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24060. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24061. this._scheduler.performVisualTasks(
  24062. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24063. );
  24064. // Currently, not call render of components. Geo render cost a lot.
  24065. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24066. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24067. performPostUpdateFuncs(ecModel, this._api);
  24068. },
  24069. /**
  24070. * @param {Object} payload
  24071. * @private
  24072. */
  24073. updateView: function (payload) {
  24074. var ecModel = this._model;
  24075. // update before setOption
  24076. if (!ecModel) {
  24077. return;
  24078. }
  24079. Chart.markUpdateMethod(payload, 'updateView');
  24080. clearColorPalette(ecModel);
  24081. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24082. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24083. render(this, this._model, this._api, payload);
  24084. performPostUpdateFuncs(ecModel, this._api);
  24085. },
  24086. /**
  24087. * @param {Object} payload
  24088. * @private
  24089. */
  24090. updateVisual: function (payload) {
  24091. updateMethods.update.call(this, payload);
  24092. // var ecModel = this._model;
  24093. // // update before setOption
  24094. // if (!ecModel) {
  24095. // return;
  24096. // }
  24097. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24098. // clearColorPalette(ecModel);
  24099. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24100. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24101. // render(this, this._model, this._api, payload);
  24102. // performPostUpdateFuncs(ecModel, this._api);
  24103. },
  24104. /**
  24105. * @param {Object} payload
  24106. * @private
  24107. */
  24108. updateLayout: function (payload) {
  24109. updateMethods.update.call(this, payload);
  24110. // var ecModel = this._model;
  24111. // // update before setOption
  24112. // if (!ecModel) {
  24113. // return;
  24114. // }
  24115. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24116. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24117. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24118. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24119. // render(this, this._model, this._api, payload);
  24120. // performPostUpdateFuncs(ecModel, this._api);
  24121. }
  24122. };
  24123. function prepare(ecIns) {
  24124. var ecModel = ecIns._model;
  24125. var scheduler = ecIns._scheduler;
  24126. scheduler.restorePipelines(ecModel);
  24127. scheduler.prepareStageTasks();
  24128. prepareView(ecIns, 'component', ecModel, scheduler);
  24129. prepareView(ecIns, 'chart', ecModel, scheduler);
  24130. scheduler.plan();
  24131. }
  24132. /**
  24133. * @private
  24134. */
  24135. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24136. var ecModel = ecIns._model;
  24137. // broadcast
  24138. if (!mainType) {
  24139. // FIXME
  24140. // Chart will not be update directly here, except set dirty.
  24141. // But there is no such scenario now.
  24142. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24143. return;
  24144. }
  24145. var query = {};
  24146. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24147. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24148. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24149. var condition = {mainType: mainType, query: query};
  24150. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24151. var excludeSeriesId = payload.excludeSeriesId;
  24152. if (excludeSeriesId != null) {
  24153. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24154. }
  24155. // If dispatchAction before setOption, do nothing.
  24156. ecModel && ecModel.eachComponent(condition, function (model) {
  24157. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24158. callView(ecIns[
  24159. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24160. ][model.__viewId]);
  24161. }
  24162. }, ecIns);
  24163. function callView(view) {
  24164. view && view.__alive && view[method] && view[method](
  24165. view.__model, ecModel, ecIns._api, payload
  24166. );
  24167. }
  24168. }
  24169. /**
  24170. * Resize the chart
  24171. * @param {Object} opts
  24172. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24173. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24174. * @param {boolean} [opts.silent=false]
  24175. */
  24176. echartsProto.resize = function (opts) {
  24177. if (__DEV__) {
  24178. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24179. }
  24180. this._zr.resize(opts);
  24181. var ecModel = this._model;
  24182. // Resize loading effect
  24183. this._loadingFX && this._loadingFX.resize();
  24184. if (!ecModel) {
  24185. return;
  24186. }
  24187. var optionChanged = ecModel.resetOption('media');
  24188. var silent = opts && opts.silent;
  24189. this[IN_MAIN_PROCESS] = true;
  24190. optionChanged && prepare(this);
  24191. updateMethods.update.call(this);
  24192. this[IN_MAIN_PROCESS] = false;
  24193. flushPendingActions.call(this, silent);
  24194. triggerUpdatedEvent.call(this, silent);
  24195. };
  24196. function updateStreamModes(ecIns, ecModel) {
  24197. var chartsMap = ecIns._chartsMap;
  24198. var scheduler = ecIns._scheduler;
  24199. ecModel.eachSeries(function (seriesModel) {
  24200. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24201. });
  24202. }
  24203. /**
  24204. * Show loading effect
  24205. * @param {string} [name='default']
  24206. * @param {Object} [cfg]
  24207. */
  24208. echartsProto.showLoading = function (name, cfg) {
  24209. if (isObject(name)) {
  24210. cfg = name;
  24211. name = '';
  24212. }
  24213. name = name || 'default';
  24214. this.hideLoading();
  24215. if (!loadingEffects[name]) {
  24216. if (__DEV__) {
  24217. console.warn('Loading effects ' + name + ' not exists.');
  24218. }
  24219. return;
  24220. }
  24221. var el = loadingEffects[name](this._api, cfg);
  24222. var zr = this._zr;
  24223. this._loadingFX = el;
  24224. zr.add(el);
  24225. };
  24226. /**
  24227. * Hide loading effect
  24228. */
  24229. echartsProto.hideLoading = function () {
  24230. this._loadingFX && this._zr.remove(this._loadingFX);
  24231. this._loadingFX = null;
  24232. };
  24233. /**
  24234. * @param {Object} eventObj
  24235. * @return {Object}
  24236. */
  24237. echartsProto.makeActionFromEvent = function (eventObj) {
  24238. var payload = extend({}, eventObj);
  24239. payload.type = eventActionMap[eventObj.type];
  24240. return payload;
  24241. };
  24242. /**
  24243. * @pubilc
  24244. * @param {Object} payload
  24245. * @param {string} [payload.type] Action type
  24246. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24247. * @param {boolean} [opt.silent=false] Whether trigger events.
  24248. * @param {boolean} [opt.flush=undefined]
  24249. * true: Flush immediately, and then pixel in canvas can be fetched
  24250. * immediately. Caution: it might affect performance.
  24251. * false: Not not flush.
  24252. * undefined: Auto decide whether perform flush.
  24253. */
  24254. echartsProto.dispatchAction = function (payload, opt) {
  24255. if (!isObject(opt)) {
  24256. opt = {silent: !!opt};
  24257. }
  24258. if (!actions[payload.type]) {
  24259. return;
  24260. }
  24261. // Avoid dispatch action before setOption. Especially in `connect`.
  24262. if (!this._model) {
  24263. return;
  24264. }
  24265. // May dispatchAction in rendering procedure
  24266. if (this[IN_MAIN_PROCESS]) {
  24267. this._pendingActions.push(payload);
  24268. return;
  24269. }
  24270. doDispatchAction.call(this, payload, opt.silent);
  24271. if (opt.flush) {
  24272. this._zr.flush(true);
  24273. }
  24274. else if (opt.flush !== false && env$1.browser.weChat) {
  24275. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24276. // hang when sliding page (on touch event), which cause that zr does not
  24277. // refresh util user interaction finished, which is not expected.
  24278. // But `dispatchAction` may be called too frequently when pan on touch
  24279. // screen, which impacts performance if do not throttle them.
  24280. this._throttledZrFlush();
  24281. }
  24282. flushPendingActions.call(this, opt.silent);
  24283. triggerUpdatedEvent.call(this, opt.silent);
  24284. };
  24285. function doDispatchAction(payload, silent) {
  24286. var payloadType = payload.type;
  24287. var escapeConnect = payload.escapeConnect;
  24288. var actionWrap = actions[payloadType];
  24289. var actionInfo = actionWrap.actionInfo;
  24290. var cptType = (actionInfo.update || 'update').split(':');
  24291. var updateMethod = cptType.pop();
  24292. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24293. this[IN_MAIN_PROCESS] = true;
  24294. var payloads = [payload];
  24295. var batched = false;
  24296. // Batch action
  24297. if (payload.batch) {
  24298. batched = true;
  24299. payloads = map(payload.batch, function (item) {
  24300. item = defaults(extend({}, item), payload);
  24301. item.batch = null;
  24302. return item;
  24303. });
  24304. }
  24305. var eventObjBatch = [];
  24306. var eventObj;
  24307. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24308. each(payloads, function (batchItem) {
  24309. // Action can specify the event by return it.
  24310. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24311. // Emit event outside
  24312. eventObj = eventObj || extend({}, batchItem);
  24313. // Convert type to eventType
  24314. eventObj.type = actionInfo.event || eventObj.type;
  24315. eventObjBatch.push(eventObj);
  24316. // light update does not perform data process, layout and visual.
  24317. if (isHighDown) {
  24318. // method, payload, mainType, subType
  24319. updateDirectly(this, updateMethod, batchItem, 'series');
  24320. }
  24321. else if (cptType) {
  24322. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24323. }
  24324. }, this);
  24325. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24326. // Still dirty
  24327. if (this[OPTION_UPDATED]) {
  24328. // FIXME Pass payload ?
  24329. prepare(this);
  24330. updateMethods.update.call(this, payload);
  24331. this[OPTION_UPDATED] = false;
  24332. }
  24333. else {
  24334. updateMethods[updateMethod].call(this, payload);
  24335. }
  24336. }
  24337. // Follow the rule of action batch
  24338. if (batched) {
  24339. eventObj = {
  24340. type: actionInfo.event || payloadType,
  24341. escapeConnect: escapeConnect,
  24342. batch: eventObjBatch
  24343. };
  24344. }
  24345. else {
  24346. eventObj = eventObjBatch[0];
  24347. }
  24348. this[IN_MAIN_PROCESS] = false;
  24349. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24350. }
  24351. function flushPendingActions(silent) {
  24352. var pendingActions = this._pendingActions;
  24353. while (pendingActions.length) {
  24354. var payload = pendingActions.shift();
  24355. doDispatchAction.call(this, payload, silent);
  24356. }
  24357. }
  24358. function triggerUpdatedEvent(silent) {
  24359. !silent && this.trigger('updated');
  24360. }
  24361. /**
  24362. * Event `rendered` is triggered when zr
  24363. * rendered. It is useful for realtime
  24364. * snapshot (reflect animation).
  24365. *
  24366. * Event `finished` is triggered when:
  24367. * (1) zrender rendering finished.
  24368. * (2) initial animation finished.
  24369. * (3) progressive rendering finished.
  24370. * (4) no pending action.
  24371. * (5) no delayed setOption needs to be processed.
  24372. */
  24373. function bindRenderedEvent(zr, ecIns) {
  24374. zr.on('rendered', function () {
  24375. ecIns.trigger('rendered');
  24376. // The `finished` event should not be triggered repeatly,
  24377. // so it should only be triggered when rendering indeed happend
  24378. // in zrender. (Consider the case that dipatchAction is keep
  24379. // triggering when mouse move).
  24380. if (
  24381. // Although zr is dirty if initial animation is not finished
  24382. // and this checking is called on frame, we also check
  24383. // animation finished for robustness.
  24384. zr.animation.isFinished()
  24385. && !ecIns[OPTION_UPDATED]
  24386. && !ecIns._scheduler.unfinished
  24387. && !ecIns._pendingActions.length
  24388. ) {
  24389. ecIns.trigger('finished');
  24390. }
  24391. });
  24392. }
  24393. /**
  24394. * @param {Object} params
  24395. * @param {number} params.seriesIndex
  24396. * @param {Array|TypedArray} params.data
  24397. */
  24398. echartsProto.appendData = function (params) {
  24399. var seriesIndex = params.seriesIndex;
  24400. var ecModel = this.getModel();
  24401. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24402. if (__DEV__) {
  24403. assert(params.data && seriesModel);
  24404. }
  24405. seriesModel.appendData(params);
  24406. // Note: `appendData` does not support that update extent of coordinate
  24407. // system, util some scenario require that. In the expected usage of
  24408. // `appendData`, the initial extent of coordinate system should better
  24409. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24410. // the extent changed while `appendData`, the location of the painted
  24411. // graphic elements have to be changed, which make the usage of
  24412. // `appendData` meaningless.
  24413. this._scheduler.unfinished = true;
  24414. };
  24415. /**
  24416. * Register event
  24417. * @method
  24418. */
  24419. echartsProto.on = createRegisterEventWithLowercaseName('on');
  24420. echartsProto.off = createRegisterEventWithLowercaseName('off');
  24421. echartsProto.one = createRegisterEventWithLowercaseName('one');
  24422. /**
  24423. * Prepare view instances of charts and components
  24424. * @param {module:echarts/model/Global} ecModel
  24425. * @private
  24426. */
  24427. function prepareView(ecIns, type, ecModel, scheduler) {
  24428. var isComponent = type === 'component';
  24429. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24430. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24431. var zr = ecIns._zr;
  24432. var api = ecIns._api;
  24433. for (var i = 0; i < viewList.length; i++) {
  24434. viewList[i].__alive = false;
  24435. }
  24436. isComponent
  24437. ? ecModel.eachComponent(function (componentType, model) {
  24438. componentType !== 'series' && doPrepare(model);
  24439. })
  24440. : ecModel.eachSeries(doPrepare);
  24441. function doPrepare(model) {
  24442. // Consider: id same and type changed.
  24443. var viewId = '_ec_' + model.id + '_' + model.type;
  24444. var view = viewMap[viewId];
  24445. if (!view) {
  24446. var classType = parseClassType(model.type);
  24447. var Clazz = isComponent
  24448. ? Component.getClass(classType.main, classType.sub)
  24449. : Chart.getClass(classType.sub);
  24450. if (__DEV__) {
  24451. assert(Clazz, classType.sub + ' does not exist.');
  24452. }
  24453. view = new Clazz();
  24454. view.init(ecModel, api);
  24455. viewMap[viewId] = view;
  24456. viewList.push(view);
  24457. zr.add(view.group);
  24458. }
  24459. model.__viewId = view.__id = viewId;
  24460. view.__alive = true;
  24461. view.__model = model;
  24462. view.group.__ecComponentInfo = {
  24463. mainType: model.mainType,
  24464. index: model.componentIndex
  24465. };
  24466. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24467. }
  24468. for (var i = 0; i < viewList.length;) {
  24469. var view = viewList[i];
  24470. if (!view.__alive) {
  24471. !isComponent && view.renderTask.dispose();
  24472. zr.remove(view.group);
  24473. view.dispose(ecModel, api);
  24474. viewList.splice(i, 1);
  24475. delete viewMap[view.__id];
  24476. view.__id = view.group.__ecComponentInfo = null;
  24477. }
  24478. else {
  24479. i++;
  24480. }
  24481. }
  24482. }
  24483. // /**
  24484. // * Encode visual infomation from data after data processing
  24485. // *
  24486. // * @param {module:echarts/model/Global} ecModel
  24487. // * @param {object} layout
  24488. // * @param {boolean} [layoutFilter] `true`: only layout,
  24489. // * `false`: only not layout,
  24490. // * `null`/`undefined`: all.
  24491. // * @param {string} taskBaseTag
  24492. // * @private
  24493. // */
  24494. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24495. // each(visualFuncs, function (visual, index) {
  24496. // var isLayout = visual.isLayout;
  24497. // if (layoutFilter == null
  24498. // || (layoutFilter === false && !isLayout)
  24499. // || (layoutFilter === true && isLayout)
  24500. // ) {
  24501. // visual.func(ecModel, api, payload);
  24502. // }
  24503. // });
  24504. // }
  24505. function clearColorPalette(ecModel) {
  24506. ecModel.clearColorPalette();
  24507. ecModel.eachSeries(function (seriesModel) {
  24508. seriesModel.clearColorPalette();
  24509. });
  24510. }
  24511. function render(ecIns, ecModel, api, payload) {
  24512. renderComponents(ecIns, ecModel, api, payload);
  24513. each(ecIns._chartsViews, function (chart) {
  24514. chart.__alive = false;
  24515. });
  24516. renderSeries(ecIns, ecModel, api, payload);
  24517. // Remove groups of unrendered charts
  24518. each(ecIns._chartsViews, function (chart) {
  24519. if (!chart.__alive) {
  24520. chart.remove(ecModel, api);
  24521. }
  24522. });
  24523. }
  24524. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24525. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24526. var componentModel = componentView.__model;
  24527. componentView.render(componentModel, ecModel, api, payload);
  24528. updateZ(componentModel, componentView);
  24529. });
  24530. }
  24531. /**
  24532. * Render each chart and component
  24533. * @private
  24534. */
  24535. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24536. // Render all charts
  24537. var scheduler = ecIns._scheduler;
  24538. var unfinished;
  24539. ecModel.eachSeries(function (seriesModel) {
  24540. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24541. chartView.__alive = true;
  24542. var renderTask = chartView.renderTask;
  24543. scheduler.updatePayload(renderTask, payload);
  24544. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24545. renderTask.dirty();
  24546. }
  24547. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24548. chartView.group.silent = !!seriesModel.get('silent');
  24549. updateZ(seriesModel, chartView);
  24550. updateBlend(seriesModel, chartView);
  24551. });
  24552. scheduler.unfinished |= unfinished;
  24553. // If use hover layer
  24554. updateHoverLayerStatus(ecIns._zr, ecModel);
  24555. // Add aria
  24556. aria(ecIns._zr.dom, ecModel);
  24557. }
  24558. function performPostUpdateFuncs(ecModel, api) {
  24559. each(postUpdateFuncs, function (func) {
  24560. func(ecModel, api);
  24561. });
  24562. }
  24563. var MOUSE_EVENT_NAMES = [
  24564. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24565. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24566. ];
  24567. /**
  24568. * @private
  24569. */
  24570. echartsProto._initEvents = function () {
  24571. each(MOUSE_EVENT_NAMES, function (eveName) {
  24572. var handler = function (e) {
  24573. var ecModel = this.getModel();
  24574. var el = e.target;
  24575. var params;
  24576. var isGlobalOut = eveName === 'globalout';
  24577. // no e.target when 'globalout'.
  24578. if (isGlobalOut) {
  24579. params = {};
  24580. }
  24581. else if (el && el.dataIndex != null) {
  24582. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24583. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24584. }
  24585. // If element has custom eventData of components
  24586. else if (el && el.eventData) {
  24587. params = extend({}, el.eventData);
  24588. }
  24589. // Contract: if params prepared in mouse event,
  24590. // these properties must be specified:
  24591. // {
  24592. // componentType: string (component main type)
  24593. // componentIndex: number
  24594. // }
  24595. // Otherwise event query can not work.
  24596. if (params) {
  24597. var componentType = params.componentType;
  24598. var componentIndex = params.componentIndex;
  24599. // Special handling for historic reason: when trigger by
  24600. // markLine/markPoint/markArea, the componentType is
  24601. // 'markLine'/'markPoint'/'markArea', but we should better
  24602. // enable them to be queried by seriesIndex, since their
  24603. // option is set in each series.
  24604. if (componentType === 'markLine'
  24605. || componentType === 'markPoint'
  24606. || componentType === 'markArea'
  24607. ) {
  24608. componentType = 'series';
  24609. componentIndex = params.seriesIndex;
  24610. }
  24611. var model = componentType && componentIndex != null
  24612. && ecModel.getComponent(componentType, componentIndex);
  24613. var view = model && this[
  24614. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24615. ][model.__viewId];
  24616. if (__DEV__) {
  24617. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24618. // be missed, otherwise there is no way to distinguish source component.
  24619. // See `dataFormat.getDataParams`.
  24620. if (!isGlobalOut && !(model && view)) {
  24621. console.warn('model or view can not be found by params');
  24622. }
  24623. }
  24624. params.event = e;
  24625. params.type = eveName;
  24626. this._ecEventProcessor.eventInfo = {
  24627. targetEl: el,
  24628. packedEvent: params,
  24629. model: model,
  24630. view: view
  24631. };
  24632. this.trigger(eveName, params);
  24633. }
  24634. };
  24635. // Consider that some component (like tooltip, brush, ...)
  24636. // register zr event handler, but user event handler might
  24637. // do anything, such as call `setOption` or `dispatchAction`,
  24638. // which probably update any of the content and probably
  24639. // cause problem if it is called previous other inner handlers.
  24640. handler.zrEventfulCallAtLast = true;
  24641. this._zr.on(eveName, handler, this);
  24642. }, this);
  24643. each(eventActionMap, function (actionType, eventType) {
  24644. this._messageCenter.on(eventType, function (event) {
  24645. this.trigger(eventType, event);
  24646. }, this);
  24647. }, this);
  24648. };
  24649. /**
  24650. * @return {boolean}
  24651. */
  24652. echartsProto.isDisposed = function () {
  24653. return this._disposed;
  24654. };
  24655. /**
  24656. * Clear
  24657. */
  24658. echartsProto.clear = function () {
  24659. this.setOption({ series: [] }, true);
  24660. };
  24661. /**
  24662. * Dispose instance
  24663. */
  24664. echartsProto.dispose = function () {
  24665. if (this._disposed) {
  24666. if (__DEV__) {
  24667. console.warn('Instance ' + this.id + ' has been disposed');
  24668. }
  24669. return;
  24670. }
  24671. this._disposed = true;
  24672. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24673. var api = this._api;
  24674. var ecModel = this._model;
  24675. each(this._componentsViews, function (component) {
  24676. component.dispose(ecModel, api);
  24677. });
  24678. each(this._chartsViews, function (chart) {
  24679. chart.dispose(ecModel, api);
  24680. });
  24681. // Dispose after all views disposed
  24682. this._zr.dispose();
  24683. delete instances[this.id];
  24684. };
  24685. mixin(ECharts, Eventful);
  24686. function updateHoverLayerStatus(zr, ecModel) {
  24687. var storage = zr.storage;
  24688. var elCount = 0;
  24689. storage.traverse(function (el) {
  24690. if (!el.isGroup) {
  24691. elCount++;
  24692. }
  24693. });
  24694. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24695. storage.traverse(function (el) {
  24696. if (!el.isGroup) {
  24697. // Don't switch back.
  24698. el.useHoverLayer = true;
  24699. }
  24700. });
  24701. }
  24702. }
  24703. /**
  24704. * Update chart progressive and blend.
  24705. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24706. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24707. */
  24708. function updateBlend(seriesModel, chartView) {
  24709. var blendMode = seriesModel.get('blendMode') || null;
  24710. if (__DEV__) {
  24711. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24712. console.warn('Only canvas support blendMode');
  24713. }
  24714. }
  24715. chartView.group.traverse(function (el) {
  24716. // FIXME marker and other components
  24717. if (!el.isGroup) {
  24718. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24719. if (el.style.blend !== blendMode) {
  24720. el.setStyle('blend', blendMode);
  24721. }
  24722. }
  24723. if (el.eachPendingDisplayable) {
  24724. el.eachPendingDisplayable(function (displayable) {
  24725. displayable.setStyle('blend', blendMode);
  24726. });
  24727. }
  24728. });
  24729. }
  24730. /**
  24731. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24732. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24733. */
  24734. function updateZ(model, view) {
  24735. var z = model.get('z');
  24736. var zlevel = model.get('zlevel');
  24737. // Set z and zlevel
  24738. view.group.traverse(function (el) {
  24739. if (el.type !== 'group') {
  24740. z != null && (el.z = z);
  24741. zlevel != null && (el.zlevel = zlevel);
  24742. }
  24743. });
  24744. }
  24745. function createExtensionAPI(ecInstance) {
  24746. var coordSysMgr = ecInstance._coordSysMgr;
  24747. return extend(new ExtensionAPI(ecInstance), {
  24748. // Inject methods
  24749. getCoordinateSystems: bind(
  24750. coordSysMgr.getCoordinateSystems, coordSysMgr
  24751. ),
  24752. getComponentByElement: function (el) {
  24753. while (el) {
  24754. var modelInfo = el.__ecComponentInfo;
  24755. if (modelInfo != null) {
  24756. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24757. }
  24758. el = el.parent;
  24759. }
  24760. }
  24761. });
  24762. }
  24763. /**
  24764. * @class
  24765. * Usage of query:
  24766. * `chart.on('click', query, handler);`
  24767. * The `query` can be:
  24768. * + The component type query string, only `mainType` or `mainType.subType`,
  24769. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24770. * + The component query object, like:
  24771. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24772. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24773. * + The data query object, like:
  24774. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24775. * + The other query object (cmponent customized query), like:
  24776. * `{element: 'some'}` (only available in custom series).
  24777. *
  24778. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24779. * same as there is no such prop in the `query` object.
  24780. */
  24781. function EventProcessor() {
  24782. // These info required: targetEl, packedEvent, model, view
  24783. this.eventInfo;
  24784. }
  24785. EventProcessor.prototype = {
  24786. constructor: EventProcessor,
  24787. normalizeQuery: function (query) {
  24788. var cptQuery = {};
  24789. var dataQuery = {};
  24790. var otherQuery = {};
  24791. // `query` is `mainType` or `mainType.subType` of component.
  24792. if (isString(query)) {
  24793. var condCptType = parseClassType(query);
  24794. // `.main` and `.sub` may be ''.
  24795. cptQuery.mainType = condCptType.main || null;
  24796. cptQuery.subType = condCptType.sub || null;
  24797. }
  24798. // `query` is an object, convert to {mainType, index, name, id}.
  24799. else {
  24800. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24801. // can not be used in `compomentModel.filterForExposedEvent`.
  24802. var suffixes = ['Index', 'Name', 'Id'];
  24803. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24804. each$1(query, function (val, key) {
  24805. var reserved = false;
  24806. for (var i = 0; i < suffixes.length; i++) {
  24807. var propSuffix = suffixes[i];
  24808. var suffixPos = key.lastIndexOf(propSuffix);
  24809. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24810. var mainType = key.slice(0, suffixPos);
  24811. // Consider `dataIndex`.
  24812. if (mainType !== 'data') {
  24813. cptQuery.mainType = mainType;
  24814. cptQuery[propSuffix.toLowerCase()] = val;
  24815. reserved = true;
  24816. }
  24817. }
  24818. }
  24819. if (dataKeys.hasOwnProperty(key)) {
  24820. dataQuery[key] = val;
  24821. reserved = true;
  24822. }
  24823. if (!reserved) {
  24824. otherQuery[key] = val;
  24825. }
  24826. });
  24827. }
  24828. return {
  24829. cptQuery: cptQuery,
  24830. dataQuery: dataQuery,
  24831. otherQuery: otherQuery
  24832. };
  24833. },
  24834. filter: function (eventType, query, args) {
  24835. // They should be assigned before each trigger call.
  24836. var eventInfo = this.eventInfo;
  24837. if (!eventInfo) {
  24838. return true;
  24839. }
  24840. var targetEl = eventInfo.targetEl;
  24841. var packedEvent = eventInfo.packedEvent;
  24842. var model = eventInfo.model;
  24843. var view = eventInfo.view;
  24844. // For event like 'globalout'.
  24845. if (!model || !view) {
  24846. return true;
  24847. }
  24848. var cptQuery = query.cptQuery;
  24849. var dataQuery = query.dataQuery;
  24850. return check(cptQuery, model, 'mainType')
  24851. && check(cptQuery, model, 'subType')
  24852. && check(cptQuery, model, 'index', 'componentIndex')
  24853. && check(cptQuery, model, 'name')
  24854. && check(cptQuery, model, 'id')
  24855. && check(dataQuery, packedEvent, 'name')
  24856. && check(dataQuery, packedEvent, 'dataIndex')
  24857. && check(dataQuery, packedEvent, 'dataType')
  24858. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24859. eventType, query.otherQuery, targetEl, packedEvent
  24860. ));
  24861. function check(query, host, prop, propOnHost) {
  24862. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24863. }
  24864. },
  24865. afterTrigger: function () {
  24866. // Make sure the eventInfo wont be used in next trigger.
  24867. this.eventInfo = null;
  24868. }
  24869. };
  24870. /**
  24871. * @type {Object} key: actionType.
  24872. * @inner
  24873. */
  24874. var actions = {};
  24875. /**
  24876. * Map eventType to actionType
  24877. * @type {Object}
  24878. */
  24879. var eventActionMap = {};
  24880. /**
  24881. * Data processor functions of each stage
  24882. * @type {Array.<Object.<string, Function>>}
  24883. * @inner
  24884. */
  24885. var dataProcessorFuncs = [];
  24886. /**
  24887. * @type {Array.<Function>}
  24888. * @inner
  24889. */
  24890. var optionPreprocessorFuncs = [];
  24891. /**
  24892. * @type {Array.<Function>}
  24893. * @inner
  24894. */
  24895. var postUpdateFuncs = [];
  24896. /**
  24897. * Visual encoding functions of each stage
  24898. * @type {Array.<Object.<string, Function>>}
  24899. */
  24900. var visualFuncs = [];
  24901. /**
  24902. * Theme storage
  24903. * @type {Object.<key, Object>}
  24904. */
  24905. var themeStorage = {};
  24906. /**
  24907. * Loading effects
  24908. */
  24909. var loadingEffects = {};
  24910. var instances = {};
  24911. var connectedGroups = {};
  24912. var idBase = new Date() - 0;
  24913. var groupIdBase = new Date() - 0;
  24914. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24915. function enableConnect(chart) {
  24916. var STATUS_PENDING = 0;
  24917. var STATUS_UPDATING = 1;
  24918. var STATUS_UPDATED = 2;
  24919. var STATUS_KEY = '__connectUpdateStatus';
  24920. function updateConnectedChartsStatus(charts, status) {
  24921. for (var i = 0; i < charts.length; i++) {
  24922. var otherChart = charts[i];
  24923. otherChart[STATUS_KEY] = status;
  24924. }
  24925. }
  24926. each(eventActionMap, function (actionType, eventType) {
  24927. chart._messageCenter.on(eventType, function (event) {
  24928. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24929. if (event && event.escapeConnect) {
  24930. return;
  24931. }
  24932. var action = chart.makeActionFromEvent(event);
  24933. var otherCharts = [];
  24934. each(instances, function (otherChart) {
  24935. if (otherChart !== chart && otherChart.group === chart.group) {
  24936. otherCharts.push(otherChart);
  24937. }
  24938. });
  24939. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24940. each(otherCharts, function (otherChart) {
  24941. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24942. otherChart.dispatchAction(action);
  24943. }
  24944. });
  24945. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24946. }
  24947. });
  24948. });
  24949. }
  24950. /**
  24951. * @param {HTMLElement} dom
  24952. * @param {Object} [theme]
  24953. * @param {Object} opts
  24954. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24955. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24956. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24957. * Can be 'auto' (the same as null/undefined)
  24958. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24959. * Can be 'auto' (the same as null/undefined)
  24960. */
  24961. function init(dom, theme$$1, opts) {
  24962. if (__DEV__) {
  24963. // Check version
  24964. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24965. throw new Error(
  24966. 'zrender/src ' + version$1
  24967. + ' is too old for ECharts ' + version
  24968. + '. Current version need ZRender '
  24969. + dependencies.zrender + '+'
  24970. );
  24971. }
  24972. if (!dom) {
  24973. throw new Error('Initialize failed: invalid dom.');
  24974. }
  24975. }
  24976. var existInstance = getInstanceByDom(dom);
  24977. if (existInstance) {
  24978. if (__DEV__) {
  24979. console.warn('There is a chart instance already initialized on the dom.');
  24980. }
  24981. return existInstance;
  24982. }
  24983. if (__DEV__) {
  24984. if (isDom(dom)
  24985. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24986. && (
  24987. (!dom.clientWidth && (!opts || opts.width == null))
  24988. || (!dom.clientHeight && (!opts || opts.height == null))
  24989. )
  24990. ) {
  24991. console.warn('Can\'t get dom width or height');
  24992. }
  24993. }
  24994. var chart = new ECharts(dom, theme$$1, opts);
  24995. chart.id = 'ec_' + idBase++;
  24996. instances[chart.id] = chart;
  24997. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24998. enableConnect(chart);
  24999. return chart;
  25000. }
  25001. /**
  25002. * @return {string|Array.<module:echarts~ECharts>} groupId
  25003. */
  25004. function connect(groupId) {
  25005. // Is array of charts
  25006. if (isArray(groupId)) {
  25007. var charts = groupId;
  25008. groupId = null;
  25009. // If any chart has group
  25010. each(charts, function (chart) {
  25011. if (chart.group != null) {
  25012. groupId = chart.group;
  25013. }
  25014. });
  25015. groupId = groupId || ('g_' + groupIdBase++);
  25016. each(charts, function (chart) {
  25017. chart.group = groupId;
  25018. });
  25019. }
  25020. connectedGroups[groupId] = true;
  25021. return groupId;
  25022. }
  25023. /**
  25024. * @DEPRECATED
  25025. * @return {string} groupId
  25026. */
  25027. function disConnect(groupId) {
  25028. connectedGroups[groupId] = false;
  25029. }
  25030. /**
  25031. * @return {string} groupId
  25032. */
  25033. var disconnect = disConnect;
  25034. /**
  25035. * Dispose a chart instance
  25036. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25037. */
  25038. function dispose(chart) {
  25039. if (typeof chart === 'string') {
  25040. chart = instances[chart];
  25041. }
  25042. else if (!(chart instanceof ECharts)) {
  25043. // Try to treat as dom
  25044. chart = getInstanceByDom(chart);
  25045. }
  25046. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25047. chart.dispose();
  25048. }
  25049. }
  25050. /**
  25051. * @param {HTMLElement} dom
  25052. * @return {echarts~ECharts}
  25053. */
  25054. function getInstanceByDom(dom) {
  25055. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25056. }
  25057. /**
  25058. * @param {string} key
  25059. * @return {echarts~ECharts}
  25060. */
  25061. function getInstanceById(key) {
  25062. return instances[key];
  25063. }
  25064. /**
  25065. * Register theme
  25066. */
  25067. function registerTheme(name, theme$$1) {
  25068. themeStorage[name] = theme$$1;
  25069. }
  25070. /**
  25071. * Register option preprocessor
  25072. * @param {Function} preprocessorFunc
  25073. */
  25074. function registerPreprocessor(preprocessorFunc) {
  25075. optionPreprocessorFuncs.push(preprocessorFunc);
  25076. }
  25077. /**
  25078. * @param {number} [priority=1000]
  25079. * @param {Object|Function} processor
  25080. */
  25081. function registerProcessor(priority, processor) {
  25082. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25083. }
  25084. /**
  25085. * Register postUpdater
  25086. * @param {Function} postUpdateFunc
  25087. */
  25088. function registerPostUpdate(postUpdateFunc) {
  25089. postUpdateFuncs.push(postUpdateFunc);
  25090. }
  25091. /**
  25092. * Usage:
  25093. * registerAction('someAction', 'someEvent', function () { ... });
  25094. * registerAction('someAction', function () { ... });
  25095. * registerAction(
  25096. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25097. * function () { ... }
  25098. * );
  25099. *
  25100. * @param {(string|Object)} actionInfo
  25101. * @param {string} actionInfo.type
  25102. * @param {string} [actionInfo.event]
  25103. * @param {string} [actionInfo.update]
  25104. * @param {string} [eventName]
  25105. * @param {Function} action
  25106. */
  25107. function registerAction(actionInfo, eventName, action) {
  25108. if (typeof eventName === 'function') {
  25109. action = eventName;
  25110. eventName = '';
  25111. }
  25112. var actionType = isObject(actionInfo)
  25113. ? actionInfo.type
  25114. : ([actionInfo, actionInfo = {
  25115. event: eventName
  25116. }][0]);
  25117. // Event name is all lowercase
  25118. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25119. eventName = actionInfo.event;
  25120. // Validate action type and event name.
  25121. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25122. if (!actions[actionType]) {
  25123. actions[actionType] = {action: action, actionInfo: actionInfo};
  25124. }
  25125. eventActionMap[eventName] = actionType;
  25126. }
  25127. /**
  25128. * @param {string} type
  25129. * @param {*} CoordinateSystem
  25130. */
  25131. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25132. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25133. }
  25134. /**
  25135. * Get dimensions of specified coordinate system.
  25136. * @param {string} type
  25137. * @return {Array.<string|Object>}
  25138. */
  25139. function getCoordinateSystemDimensions(type) {
  25140. var coordSysCreator = CoordinateSystemManager.get(type);
  25141. if (coordSysCreator) {
  25142. return coordSysCreator.getDimensionsInfo
  25143. ? coordSysCreator.getDimensionsInfo()
  25144. : coordSysCreator.dimensions.slice();
  25145. }
  25146. }
  25147. /**
  25148. * Layout is a special stage of visual encoding
  25149. * Most visual encoding like color are common for different chart
  25150. * But each chart has it's own layout algorithm
  25151. *
  25152. * @param {number} [priority=1000]
  25153. * @param {Function} layoutTask
  25154. */
  25155. function registerLayout(priority, layoutTask) {
  25156. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25157. }
  25158. /**
  25159. * @param {number} [priority=3000]
  25160. * @param {module:echarts/stream/Task} visualTask
  25161. */
  25162. function registerVisual(priority, visualTask) {
  25163. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25164. }
  25165. /**
  25166. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25167. */
  25168. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25169. if (isFunction(priority) || isObject(priority)) {
  25170. fn = priority;
  25171. priority = defaultPriority;
  25172. }
  25173. if (__DEV__) {
  25174. if (isNaN(priority) || priority == null) {
  25175. throw new Error('Illegal priority');
  25176. }
  25177. // Check duplicate
  25178. each(targetList, function (wrap) {
  25179. assert(wrap.__raw !== fn);
  25180. });
  25181. }
  25182. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25183. stageHandler.__prio = priority;
  25184. stageHandler.__raw = fn;
  25185. targetList.push(stageHandler);
  25186. return stageHandler;
  25187. }
  25188. /**
  25189. * @param {string} name
  25190. */
  25191. function registerLoading(name, loadingFx) {
  25192. loadingEffects[name] = loadingFx;
  25193. }
  25194. /**
  25195. * @param {Object} opts
  25196. * @param {string} [superClass]
  25197. */
  25198. function extendComponentModel(opts/*, superClass*/) {
  25199. // var Clazz = ComponentModel;
  25200. // if (superClass) {
  25201. // var classType = parseClassType(superClass);
  25202. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25203. // }
  25204. return ComponentModel.extend(opts);
  25205. }
  25206. /**
  25207. * @param {Object} opts
  25208. * @param {string} [superClass]
  25209. */
  25210. function extendComponentView(opts/*, superClass*/) {
  25211. // var Clazz = ComponentView;
  25212. // if (superClass) {
  25213. // var classType = parseClassType(superClass);
  25214. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25215. // }
  25216. return Component.extend(opts);
  25217. }
  25218. /**
  25219. * @param {Object} opts
  25220. * @param {string} [superClass]
  25221. */
  25222. function extendSeriesModel(opts/*, superClass*/) {
  25223. // var Clazz = SeriesModel;
  25224. // if (superClass) {
  25225. // superClass = 'series.' + superClass.replace('series.', '');
  25226. // var classType = parseClassType(superClass);
  25227. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25228. // }
  25229. return SeriesModel.extend(opts);
  25230. }
  25231. /**
  25232. * @param {Object} opts
  25233. * @param {string} [superClass]
  25234. */
  25235. function extendChartView(opts/*, superClass*/) {
  25236. // var Clazz = ChartView;
  25237. // if (superClass) {
  25238. // superClass = superClass.replace('series.', '');
  25239. // var classType = parseClassType(superClass);
  25240. // Clazz = ChartView.getClass(classType.main, true);
  25241. // }
  25242. return Chart.extend(opts);
  25243. }
  25244. /**
  25245. * ZRender need a canvas context to do measureText.
  25246. * But in node environment canvas may be created by node-canvas.
  25247. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25248. *
  25249. * Be careful of using it in the browser.
  25250. *
  25251. * @param {Function} creator
  25252. * @example
  25253. * var Canvas = require('canvas');
  25254. * var echarts = require('echarts');
  25255. * echarts.setCanvasCreator(function () {
  25256. * // Small size is enough.
  25257. * return new Canvas(32, 32);
  25258. * });
  25259. */
  25260. function setCanvasCreator(creator) {
  25261. $override('createCanvas', creator);
  25262. }
  25263. /**
  25264. * @param {string} mapName
  25265. * @param {Array.<Object>|Object|string} geoJson
  25266. * @param {Object} [specialAreas]
  25267. *
  25268. * @example GeoJSON
  25269. * $.get('USA.json', function (geoJson) {
  25270. * echarts.registerMap('USA', geoJson);
  25271. * // Or
  25272. * echarts.registerMap('USA', {
  25273. * geoJson: geoJson,
  25274. * specialAreas: {}
  25275. * })
  25276. * });
  25277. *
  25278. * $.get('airport.svg', function (svg) {
  25279. * echarts.registerMap('airport', {
  25280. * svg: svg
  25281. * }
  25282. * });
  25283. *
  25284. * echarts.registerMap('eu', [
  25285. * {svg: eu-topographic.svg},
  25286. * {geoJSON: eu.json}
  25287. * ])
  25288. */
  25289. function registerMap(mapName, geoJson, specialAreas) {
  25290. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25291. }
  25292. /**
  25293. * @param {string} mapName
  25294. * @return {Object}
  25295. */
  25296. function getMap(mapName) {
  25297. // For backward compatibility, only return the first one.
  25298. var records = mapDataStorage.retrieveMap(mapName);
  25299. return records && records[0] && {
  25300. geoJson: records[0].geoJSON,
  25301. specialAreas: records[0].specialAreas
  25302. };
  25303. }
  25304. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25305. registerPreprocessor(backwardCompat);
  25306. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  25307. registerLoading('default', loadingDefault);
  25308. // Default actions
  25309. registerAction({
  25310. type: 'highlight',
  25311. event: 'highlight',
  25312. update: 'highlight'
  25313. }, noop);
  25314. registerAction({
  25315. type: 'downplay',
  25316. event: 'downplay',
  25317. update: 'downplay'
  25318. }, noop);
  25319. // Default theme
  25320. registerTheme('light', lightTheme);
  25321. registerTheme('dark', theme);
  25322. // For backward compatibility, where the namespace `dataTool` will
  25323. // be mounted on `echarts` is the extension `dataTool` is imported.
  25324. var dataTool = {};
  25325. /*
  25326. * Licensed to the Apache Software Foundation (ASF) under one
  25327. * or more contributor license agreements. See the NOTICE file
  25328. * distributed with this work for additional information
  25329. * regarding copyright ownership. The ASF licenses this file
  25330. * to you under the Apache License, Version 2.0 (the
  25331. * "License"); you may not use this file except in compliance
  25332. * with the License. You may obtain a copy of the License at
  25333. *
  25334. * http://www.apache.org/licenses/LICENSE-2.0
  25335. *
  25336. * Unless required by applicable law or agreed to in writing,
  25337. * software distributed under the License is distributed on an
  25338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25339. * KIND, either express or implied. See the License for the
  25340. * specific language governing permissions and limitations
  25341. * under the License.
  25342. */
  25343. function defaultKeyGetter(item) {
  25344. return item;
  25345. }
  25346. /**
  25347. * @param {Array} oldArr
  25348. * @param {Array} newArr
  25349. * @param {Function} oldKeyGetter
  25350. * @param {Function} newKeyGetter
  25351. * @param {Object} [context] Can be visited by this.context in callback.
  25352. */
  25353. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25354. this._old = oldArr;
  25355. this._new = newArr;
  25356. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25357. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25358. this.context = context;
  25359. }
  25360. DataDiffer.prototype = {
  25361. constructor: DataDiffer,
  25362. /**
  25363. * Callback function when add a data
  25364. */
  25365. add: function (func) {
  25366. this._add = func;
  25367. return this;
  25368. },
  25369. /**
  25370. * Callback function when update a data
  25371. */
  25372. update: function (func) {
  25373. this._update = func;
  25374. return this;
  25375. },
  25376. /**
  25377. * Callback function when remove a data
  25378. */
  25379. remove: function (func) {
  25380. this._remove = func;
  25381. return this;
  25382. },
  25383. execute: function () {
  25384. var oldArr = this._old;
  25385. var newArr = this._new;
  25386. var oldDataIndexMap = {};
  25387. var newDataIndexMap = {};
  25388. var oldDataKeyArr = [];
  25389. var newDataKeyArr = [];
  25390. var i;
  25391. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25392. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25393. // Travel by inverted order to make sure order consistency
  25394. // when duplicate keys exists (consider newDataIndex.pop() below).
  25395. // For performance consideration, these code below do not look neat.
  25396. for (i = 0; i < oldArr.length; i++) {
  25397. var key = oldDataKeyArr[i];
  25398. var idx = newDataIndexMap[key];
  25399. // idx can never be empty array here. see 'set null' logic below.
  25400. if (idx != null) {
  25401. // Consider there is duplicate key (for example, use dataItem.name as key).
  25402. // We should make sure every item in newArr and oldArr can be visited.
  25403. var len = idx.length;
  25404. if (len) {
  25405. len === 1 && (newDataIndexMap[key] = null);
  25406. idx = idx.unshift();
  25407. }
  25408. else {
  25409. newDataIndexMap[key] = null;
  25410. }
  25411. this._update && this._update(idx, i);
  25412. }
  25413. else {
  25414. this._remove && this._remove(i);
  25415. }
  25416. }
  25417. for (var i = 0; i < newDataKeyArr.length; i++) {
  25418. var key = newDataKeyArr[i];
  25419. if (newDataIndexMap.hasOwnProperty(key)) {
  25420. var idx = newDataIndexMap[key];
  25421. if (idx == null) {
  25422. continue;
  25423. }
  25424. // idx can never be empty array here. see 'set null' logic above.
  25425. if (!idx.length) {
  25426. this._add && this._add(idx);
  25427. }
  25428. else {
  25429. for (var j = 0, len = idx.length; j < len; j++) {
  25430. this._add && this._add(idx[j]);
  25431. }
  25432. }
  25433. }
  25434. }
  25435. }
  25436. };
  25437. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25438. for (var i = 0; i < arr.length; i++) {
  25439. // Add prefix to avoid conflict with Object.prototype.
  25440. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25441. var existence = map[key];
  25442. if (existence == null) {
  25443. keyArr.push(key);
  25444. map[key] = i;
  25445. }
  25446. else {
  25447. if (!existence.length) {
  25448. map[key] = existence = [existence];
  25449. }
  25450. existence.push(i);
  25451. }
  25452. }
  25453. }
  25454. /*
  25455. * Licensed to the Apache Software Foundation (ASF) under one
  25456. * or more contributor license agreements. See the NOTICE file
  25457. * distributed with this work for additional information
  25458. * regarding copyright ownership. The ASF licenses this file
  25459. * to you under the Apache License, Version 2.0 (the
  25460. * "License"); you may not use this file except in compliance
  25461. * with the License. You may obtain a copy of the License at
  25462. *
  25463. * http://www.apache.org/licenses/LICENSE-2.0
  25464. *
  25465. * Unless required by applicable law or agreed to in writing,
  25466. * software distributed under the License is distributed on an
  25467. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25468. * KIND, either express or implied. See the License for the
  25469. * specific language governing permissions and limitations
  25470. * under the License.
  25471. */
  25472. var OTHER_DIMENSIONS = createHashMap([
  25473. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25474. ]);
  25475. function summarizeDimensions(data) {
  25476. var summary = {};
  25477. var encode = summary.encode = {};
  25478. var notExtraCoordDimMap = createHashMap();
  25479. var defaultedLabel = [];
  25480. var defaultedTooltip = [];
  25481. each$1(data.dimensions, function (dimName) {
  25482. var dimItem = data.getDimensionInfo(dimName);
  25483. var coordDim = dimItem.coordDim;
  25484. if (coordDim) {
  25485. if (__DEV__) {
  25486. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25487. }
  25488. var coordDimArr = encode[coordDim];
  25489. if (!encode.hasOwnProperty(coordDim)) {
  25490. coordDimArr = encode[coordDim] = [];
  25491. }
  25492. coordDimArr[dimItem.coordDimIndex] = dimName;
  25493. if (!dimItem.isExtraCoord) {
  25494. notExtraCoordDimMap.set(coordDim, 1);
  25495. // Use the last coord dim (and label friendly) as default label,
  25496. // because when dataset is used, it is hard to guess which dimension
  25497. // can be value dimension. If both show x, y on label is not look good,
  25498. // and conventionally y axis is focused more.
  25499. if (mayLabelDimType(dimItem.type)) {
  25500. defaultedLabel[0] = dimName;
  25501. }
  25502. }
  25503. if (dimItem.defaultTooltip) {
  25504. defaultedTooltip.push(dimName);
  25505. }
  25506. }
  25507. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25508. var otherDimArr = encode[otherDim];
  25509. if (!encode.hasOwnProperty(otherDim)) {
  25510. otherDimArr = encode[otherDim] = [];
  25511. }
  25512. var dimIndex = dimItem.otherDims[otherDim];
  25513. if (dimIndex != null && dimIndex !== false) {
  25514. otherDimArr[dimIndex] = dimItem.name;
  25515. }
  25516. });
  25517. });
  25518. var dataDimsOnCoord = [];
  25519. var encodeFirstDimNotExtra = {};
  25520. notExtraCoordDimMap.each(function (v, coordDim) {
  25521. var dimArr = encode[coordDim];
  25522. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25523. // But should fix the case that radar axes: simplify the logic
  25524. // of `completeDimension`, remove `extraPrefix`.
  25525. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25526. // Not necessary to remove duplicate, because a data
  25527. // dim canot on more than one coordDim.
  25528. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25529. });
  25530. summary.dataDimsOnCoord = dataDimsOnCoord;
  25531. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25532. var encodeLabel = encode.label;
  25533. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25534. // in this way. Use label.formatter instead. May be remove this approach someday.
  25535. if (encodeLabel && encodeLabel.length) {
  25536. defaultedLabel = encodeLabel.slice();
  25537. }
  25538. var encodeTooltip = encode.tooltip;
  25539. if (encodeTooltip && encodeTooltip.length) {
  25540. defaultedTooltip = encodeTooltip.slice();
  25541. }
  25542. else if (!defaultedTooltip.length) {
  25543. defaultedTooltip = defaultedLabel.slice();
  25544. }
  25545. encode.defaultedLabel = defaultedLabel;
  25546. encode.defaultedTooltip = defaultedTooltip;
  25547. return summary;
  25548. }
  25549. function getDimensionTypeByAxis(axisType) {
  25550. return axisType === 'category'
  25551. ? 'ordinal'
  25552. : axisType === 'time'
  25553. ? 'time'
  25554. : 'float';
  25555. }
  25556. function mayLabelDimType(dimType) {
  25557. // In most cases, ordinal and time do not suitable for label.
  25558. // Ordinal info can be displayed on axis. Time is too long.
  25559. return !(dimType === 'ordinal' || dimType === 'time');
  25560. }
  25561. // function findTheLastDimMayLabel(data) {
  25562. // // Get last value dim
  25563. // var dimensions = data.dimensions.slice();
  25564. // var valueType;
  25565. // var valueDim;
  25566. // while (dimensions.length && (
  25567. // valueDim = dimensions.pop(),
  25568. // valueType = data.getDimensionInfo(valueDim).type,
  25569. // valueType === 'ordinal' || valueType === 'time'
  25570. // )) {} // jshint ignore:line
  25571. // return valueDim;
  25572. // }
  25573. /*
  25574. * Licensed to the Apache Software Foundation (ASF) under one
  25575. * or more contributor license agreements. See the NOTICE file
  25576. * distributed with this work for additional information
  25577. * regarding copyright ownership. The ASF licenses this file
  25578. * to you under the Apache License, Version 2.0 (the
  25579. * "License"); you may not use this file except in compliance
  25580. * with the License. You may obtain a copy of the License at
  25581. *
  25582. * http://www.apache.org/licenses/LICENSE-2.0
  25583. *
  25584. * Unless required by applicable law or agreed to in writing,
  25585. * software distributed under the License is distributed on an
  25586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25587. * KIND, either express or implied. See the License for the
  25588. * specific language governing permissions and limitations
  25589. * under the License.
  25590. */
  25591. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25592. /**
  25593. * List for data storage
  25594. * @module echarts/data/List
  25595. */
  25596. var isObject$4 = isObject$1;
  25597. var UNDEFINED = 'undefined';
  25598. var INDEX_NOT_FOUND = -1;
  25599. // Use prefix to avoid index to be the same as otherIdList[idx],
  25600. // which will cause weird udpate animation.
  25601. var ID_PREFIX = 'e\0\0';
  25602. var dataCtors = {
  25603. 'float': typeof Float64Array === UNDEFINED
  25604. ? Array : Float64Array,
  25605. 'int': typeof Int32Array === UNDEFINED
  25606. ? Array : Int32Array,
  25607. // Ordinal data type can be string or int
  25608. 'ordinal': Array,
  25609. 'number': Array,
  25610. 'time': Array
  25611. };
  25612. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25613. // different from the Ctor of typed array.
  25614. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25615. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25616. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25617. function getIndicesCtor(list) {
  25618. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25619. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25620. }
  25621. function cloneChunk(originalChunk) {
  25622. var Ctor = originalChunk.constructor;
  25623. // Only shallow clone is enough when Array.
  25624. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25625. }
  25626. var TRANSFERABLE_PROPERTIES = [
  25627. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25628. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25629. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25630. ];
  25631. var CLONE_PROPERTIES = [
  25632. '_extent', '_approximateExtent', '_rawExtent'
  25633. ];
  25634. function transferProperties(target, source) {
  25635. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25636. if (source.hasOwnProperty(propName)) {
  25637. target[propName] = source[propName];
  25638. }
  25639. });
  25640. target.__wrappedMethods = source.__wrappedMethods;
  25641. each$1(CLONE_PROPERTIES, function (propName) {
  25642. target[propName] = clone(source[propName]);
  25643. });
  25644. target._calculationInfo = extend(source._calculationInfo);
  25645. }
  25646. /**
  25647. * @constructor
  25648. * @alias module:echarts/data/List
  25649. *
  25650. * @param {Array.<string|Object>} dimensions
  25651. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25652. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25653. * Spetial fields: {
  25654. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25655. * createInvertedIndices: <boolean>
  25656. * }
  25657. * @param {module:echarts/model/Model} hostModel
  25658. */
  25659. var List = function (dimensions, hostModel) {
  25660. dimensions = dimensions || ['x', 'y'];
  25661. var dimensionInfos = {};
  25662. var dimensionNames = [];
  25663. var invertedIndicesMap = {};
  25664. for (var i = 0; i < dimensions.length; i++) {
  25665. // Use the original dimensions[i], where other flag props may exists.
  25666. var dimensionInfo = dimensions[i];
  25667. if (isString(dimensionInfo)) {
  25668. dimensionInfo = {name: dimensionInfo};
  25669. }
  25670. var dimensionName = dimensionInfo.name;
  25671. dimensionInfo.type = dimensionInfo.type || 'float';
  25672. if (!dimensionInfo.coordDim) {
  25673. dimensionInfo.coordDim = dimensionName;
  25674. dimensionInfo.coordDimIndex = 0;
  25675. }
  25676. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25677. dimensionNames.push(dimensionName);
  25678. dimensionInfos[dimensionName] = dimensionInfo;
  25679. dimensionInfo.index = i;
  25680. if (dimensionInfo.createInvertedIndices) {
  25681. invertedIndicesMap[dimensionName] = [];
  25682. }
  25683. }
  25684. /**
  25685. * @readOnly
  25686. * @type {Array.<string>}
  25687. */
  25688. this.dimensions = dimensionNames;
  25689. /**
  25690. * Infomation of each data dimension, like data type.
  25691. * @type {Object}
  25692. */
  25693. this._dimensionInfos = dimensionInfos;
  25694. /**
  25695. * @type {module:echarts/model/Model}
  25696. */
  25697. this.hostModel = hostModel;
  25698. /**
  25699. * @type {module:echarts/model/Model}
  25700. */
  25701. this.dataType;
  25702. /**
  25703. * Indices stores the indices of data subset after filtered.
  25704. * This data subset will be used in chart.
  25705. * @type {Array.<number>}
  25706. * @readOnly
  25707. */
  25708. this._indices = null;
  25709. this._count = 0;
  25710. this._rawCount = 0;
  25711. /**
  25712. * Data storage
  25713. * @type {Object.<key, Array.<TypedArray|Array>>}
  25714. * @private
  25715. */
  25716. this._storage = {};
  25717. /**
  25718. * @type {Array.<string>}
  25719. */
  25720. this._nameList = [];
  25721. /**
  25722. * @type {Array.<string>}
  25723. */
  25724. this._idList = [];
  25725. /**
  25726. * Models of data option is stored sparse for optimizing memory cost
  25727. * @type {Array.<module:echarts/model/Model>}
  25728. * @private
  25729. */
  25730. this._optionModels = [];
  25731. /**
  25732. * Global visual properties after visual coding
  25733. * @type {Object}
  25734. * @private
  25735. */
  25736. this._visual = {};
  25737. /**
  25738. * Globel layout properties.
  25739. * @type {Object}
  25740. * @private
  25741. */
  25742. this._layout = {};
  25743. /**
  25744. * Item visual properties after visual coding
  25745. * @type {Array.<Object>}
  25746. * @private
  25747. */
  25748. this._itemVisuals = [];
  25749. /**
  25750. * Key: visual type, Value: boolean
  25751. * @type {Object}
  25752. * @readOnly
  25753. */
  25754. this.hasItemVisual = {};
  25755. /**
  25756. * Item layout properties after layout
  25757. * @type {Array.<Object>}
  25758. * @private
  25759. */
  25760. this._itemLayouts = [];
  25761. /**
  25762. * Graphic elemnents
  25763. * @type {Array.<module:zrender/Element>}
  25764. * @private
  25765. */
  25766. this._graphicEls = [];
  25767. /**
  25768. * Max size of each chunk.
  25769. * @type {number}
  25770. * @private
  25771. */
  25772. this._chunkSize = 1e5;
  25773. /**
  25774. * @type {number}
  25775. * @private
  25776. */
  25777. this._chunkCount = 0;
  25778. /**
  25779. * @type {Array.<Array|Object>}
  25780. * @private
  25781. */
  25782. this._rawData;
  25783. /**
  25784. * Raw extent will not be cloned, but only transfered.
  25785. * It will not be calculated util needed.
  25786. * key: dim,
  25787. * value: {end: number, extent: Array.<number>}
  25788. * @type {Object}
  25789. * @private
  25790. */
  25791. this._rawExtent = {};
  25792. /**
  25793. * @type {Object}
  25794. * @private
  25795. */
  25796. this._extent = {};
  25797. /**
  25798. * key: dim
  25799. * value: extent
  25800. * @type {Object}
  25801. * @private
  25802. */
  25803. this._approximateExtent = {};
  25804. /**
  25805. * Cache summary info for fast visit. See "dimensionHelper".
  25806. * @type {Object}
  25807. * @private
  25808. */
  25809. this._dimensionsSummary = summarizeDimensions(this);
  25810. /**
  25811. * @type {Object.<Array|TypedArray>}
  25812. * @private
  25813. */
  25814. this._invertedIndicesMap = invertedIndicesMap;
  25815. /**
  25816. * @type {Object}
  25817. * @private
  25818. */
  25819. this._calculationInfo = {};
  25820. };
  25821. var listProto = List.prototype;
  25822. listProto.type = 'list';
  25823. /**
  25824. * If each data item has it's own option
  25825. * @type {boolean}
  25826. */
  25827. listProto.hasItemOption = true;
  25828. /**
  25829. * Get dimension name
  25830. * @param {string|number} dim
  25831. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25832. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25833. * @return {string} Concrete dim name.
  25834. */
  25835. listProto.getDimension = function (dim) {
  25836. if (!isNaN(dim)) {
  25837. dim = this.dimensions[dim] || dim;
  25838. }
  25839. return dim;
  25840. };
  25841. /**
  25842. * Get type and calculation info of particular dimension
  25843. * @param {string|number} dim
  25844. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25845. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25846. */
  25847. listProto.getDimensionInfo = function (dim) {
  25848. // Do not clone, because there may be categories in dimInfo.
  25849. return this._dimensionInfos[this.getDimension(dim)];
  25850. };
  25851. /**
  25852. * @return {Array.<string>} concrete dimension name list on coord.
  25853. */
  25854. listProto.getDimensionsOnCoord = function () {
  25855. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25856. };
  25857. /**
  25858. * @param {string} coordDim
  25859. * @param {number} [idx] A coordDim may map to more than one data dim.
  25860. * If idx is `true`, return a array of all mapped dims.
  25861. * If idx is not specified, return the first dim not extra.
  25862. * @return {string|Array.<string>} concrete data dim.
  25863. * If idx is number, and not found, return null/undefined.
  25864. * If idx is `true`, and not found, return empty array (always return array).
  25865. */
  25866. listProto.mapDimension = function (coordDim, idx) {
  25867. var dimensionsSummary = this._dimensionsSummary;
  25868. if (idx == null) {
  25869. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25870. }
  25871. var dims = dimensionsSummary.encode[coordDim];
  25872. return idx === true
  25873. // always return array if idx is `true`
  25874. ? (dims || []).slice()
  25875. : (dims && dims[idx]);
  25876. };
  25877. /**
  25878. * Initialize from data
  25879. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25880. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25881. * defualt label/tooltip.
  25882. * A name can be specified in encode.itemName,
  25883. * or dataItem.name (only for series option data),
  25884. * or provided in nameList from outside.
  25885. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25886. */
  25887. listProto.initData = function (data, nameList, dimValueGetter) {
  25888. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25889. if (notProvider) {
  25890. data = new DefaultDataProvider(data, this.dimensions.length);
  25891. }
  25892. if (__DEV__) {
  25893. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25894. throw new Error('Inavlid data provider.');
  25895. }
  25896. }
  25897. this._rawData = data;
  25898. // Clear
  25899. this._storage = {};
  25900. this._indices = null;
  25901. this._nameList = nameList || [];
  25902. this._idList = [];
  25903. this._nameRepeatCount = {};
  25904. if (!dimValueGetter) {
  25905. this.hasItemOption = false;
  25906. }
  25907. /**
  25908. * @readOnly
  25909. */
  25910. this.defaultDimValueGetter = defaultDimValueGetters[
  25911. this._rawData.getSource().sourceFormat
  25912. ];
  25913. // Default dim value getter
  25914. this._dimValueGetter = dimValueGetter = dimValueGetter
  25915. || this.defaultDimValueGetter;
  25916. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  25917. // Reset raw extent.
  25918. this._rawExtent = {};
  25919. this._initDataFromProvider(0, data.count());
  25920. // If data has no item option.
  25921. if (data.pure) {
  25922. this.hasItemOption = false;
  25923. }
  25924. };
  25925. listProto.getProvider = function () {
  25926. return this._rawData;
  25927. };
  25928. /**
  25929. * Caution: Can be only called on raw data (before `this._indices` created).
  25930. */
  25931. listProto.appendData = function (data) {
  25932. if (__DEV__) {
  25933. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25934. }
  25935. var rawData = this._rawData;
  25936. var start = this.count();
  25937. rawData.appendData(data);
  25938. var end = rawData.count();
  25939. if (!rawData.persistent) {
  25940. end += start;
  25941. }
  25942. this._initDataFromProvider(start, end);
  25943. };
  25944. /**
  25945. * Caution: Can be only called on raw data (before `this._indices` created).
  25946. * This method does not modify `rawData` (`dataProvider`), but only
  25947. * add values to storage.
  25948. *
  25949. * The final count will be increased by `Math.max(values.length, names.length)`.
  25950. *
  25951. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  25952. * [
  25953. * [12, 33, 44],
  25954. * [NaN, 43, 1],
  25955. * ['-', 'asdf', 0]
  25956. * ]
  25957. * Each item is exaclty cooresponding to a dimension.
  25958. * @param {Array.<string>} [names]
  25959. */
  25960. listProto.appendValues = function (values, names) {
  25961. var chunkSize = this._chunkSize;
  25962. var storage = this._storage;
  25963. var dimensions = this.dimensions;
  25964. var dimLen = dimensions.length;
  25965. var rawExtent = this._rawExtent;
  25966. var start = this.count();
  25967. var end = start + Math.max(values.length, names ? names.length : 0);
  25968. var originalChunkCount = this._chunkCount;
  25969. for (var i = 0; i < dimLen; i++) {
  25970. var dim = dimensions[i];
  25971. if (!rawExtent[dim]) {
  25972. rawExtent[dim] = getInitialExtent();
  25973. }
  25974. if (!storage[dim]) {
  25975. storage[dim] = [];
  25976. }
  25977. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25978. this._chunkCount = storage[dim].length;
  25979. }
  25980. var emptyDataItem = new Array(dimLen);
  25981. for (var idx = start; idx < end; idx++) {
  25982. var sourceIdx = idx - start;
  25983. var chunkIndex = Math.floor(idx / chunkSize);
  25984. var chunkOffset = idx % chunkSize;
  25985. // Store the data by dimensions
  25986. for (var k = 0; k < dimLen; k++) {
  25987. var dim = dimensions[k];
  25988. var val = this._dimValueGetterArrayRows(
  25989. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  25990. );
  25991. storage[dim][chunkIndex][chunkOffset] = val;
  25992. var dimRawExtent = rawExtent[dim];
  25993. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25994. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25995. }
  25996. if (names) {
  25997. this._nameList[idx] = names[sourceIdx];
  25998. }
  25999. }
  26000. this._rawCount = this._count = end;
  26001. // Reset data extent
  26002. this._extent = {};
  26003. prepareInvertedIndex(this);
  26004. };
  26005. listProto._initDataFromProvider = function (start, end) {
  26006. // Optimize.
  26007. if (start >= end) {
  26008. return;
  26009. }
  26010. var chunkSize = this._chunkSize;
  26011. var rawData = this._rawData;
  26012. var storage = this._storage;
  26013. var dimensions = this.dimensions;
  26014. var dimLen = dimensions.length;
  26015. var dimensionInfoMap = this._dimensionInfos;
  26016. var nameList = this._nameList;
  26017. var idList = this._idList;
  26018. var rawExtent = this._rawExtent;
  26019. var nameRepeatCount = this._nameRepeatCount = {};
  26020. var nameDimIdx;
  26021. var originalChunkCount = this._chunkCount;
  26022. for (var i = 0; i < dimLen; i++) {
  26023. var dim = dimensions[i];
  26024. if (!rawExtent[dim]) {
  26025. rawExtent[dim] = getInitialExtent();
  26026. }
  26027. var dimInfo = dimensionInfoMap[dim];
  26028. if (dimInfo.otherDims.itemName === 0) {
  26029. nameDimIdx = this._nameDimIdx = i;
  26030. }
  26031. if (dimInfo.otherDims.itemId === 0) {
  26032. this._idDimIdx = i;
  26033. }
  26034. if (!storage[dim]) {
  26035. storage[dim] = [];
  26036. }
  26037. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26038. this._chunkCount = storage[dim].length;
  26039. }
  26040. var dataItem = new Array(dimLen);
  26041. for (var idx = start; idx < end; idx++) {
  26042. // NOTICE: Try not to write things into dataItem
  26043. dataItem = rawData.getItem(idx, dataItem);
  26044. // Each data item is value
  26045. // [1, 2]
  26046. // 2
  26047. // Bar chart, line chart which uses category axis
  26048. // only gives the 'y' value. 'x' value is the indices of category
  26049. // Use a tempValue to normalize the value to be a (x, y) value
  26050. var chunkIndex = Math.floor(idx / chunkSize);
  26051. var chunkOffset = idx % chunkSize;
  26052. // Store the data by dimensions
  26053. for (var k = 0; k < dimLen; k++) {
  26054. var dim = dimensions[k];
  26055. var dimStorage = storage[dim][chunkIndex];
  26056. // PENDING NULL is empty or zero
  26057. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26058. dimStorage[chunkOffset] = val;
  26059. var dimRawExtent = rawExtent[dim];
  26060. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26061. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26062. }
  26063. // ??? FIXME not check by pure but sourceFormat?
  26064. // TODO refactor these logic.
  26065. if (!rawData.pure) {
  26066. var name = nameList[idx];
  26067. if (dataItem && name == null) {
  26068. // If dataItem is {name: ...}, it has highest priority.
  26069. // That is appropriate for many common cases.
  26070. if (dataItem.name != null) {
  26071. // There is no other place to persistent dataItem.name,
  26072. // so save it to nameList.
  26073. nameList[idx] = name = dataItem.name;
  26074. }
  26075. else if (nameDimIdx != null) {
  26076. var nameDim = dimensions[nameDimIdx];
  26077. var nameDimChunk = storage[nameDim][chunkIndex];
  26078. if (nameDimChunk) {
  26079. name = nameDimChunk[chunkOffset];
  26080. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26081. if (ordinalMeta && ordinalMeta.categories.length) {
  26082. name = ordinalMeta.categories[name];
  26083. }
  26084. }
  26085. }
  26086. }
  26087. // Try using the id in option
  26088. // id or name is used on dynamical data, mapping old and new items.
  26089. var id = dataItem == null ? null : dataItem.id;
  26090. if (id == null && name != null) {
  26091. // Use name as id and add counter to avoid same name
  26092. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26093. id = name;
  26094. if (nameRepeatCount[name] > 0) {
  26095. id += '__ec__' + nameRepeatCount[name];
  26096. }
  26097. nameRepeatCount[name]++;
  26098. }
  26099. id != null && (idList[idx] = id);
  26100. }
  26101. }
  26102. if (!rawData.persistent && rawData.clean) {
  26103. // Clean unused data if data source is typed array.
  26104. rawData.clean();
  26105. }
  26106. this._rawCount = this._count = end;
  26107. // Reset data extent
  26108. this._extent = {};
  26109. prepareInvertedIndex(this);
  26110. };
  26111. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26112. var DataCtor = dataCtors[dimInfo.type];
  26113. var lastChunkIndex = chunkCount - 1;
  26114. var dim = dimInfo.name;
  26115. var resizeChunkArray = storage[dim][lastChunkIndex];
  26116. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26117. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26118. // The cost of the copy is probably inconsiderable
  26119. // within the initial chunkSize.
  26120. for (var j = 0; j < resizeChunkArray.length; j++) {
  26121. newStore[j] = resizeChunkArray[j];
  26122. }
  26123. storage[dim][lastChunkIndex] = newStore;
  26124. }
  26125. // Create new chunks.
  26126. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26127. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26128. }
  26129. }
  26130. function prepareInvertedIndex(list) {
  26131. var invertedIndicesMap = list._invertedIndicesMap;
  26132. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26133. var dimInfo = list._dimensionInfos[dim];
  26134. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26135. var ordinalMeta = dimInfo.ordinalMeta;
  26136. if (ordinalMeta) {
  26137. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26138. ordinalMeta.categories.length
  26139. );
  26140. // The default value of TypedArray is 0. To avoid miss
  26141. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26142. for (var i = 0; i < invertedIndices.length; i++) {
  26143. invertedIndices[i] = INDEX_NOT_FOUND;
  26144. }
  26145. for (var i = 0; i < list._count; i++) {
  26146. // Only support the case that all values are distinct.
  26147. invertedIndices[list.get(dim, i)] = i;
  26148. }
  26149. }
  26150. });
  26151. }
  26152. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26153. var val;
  26154. if (dimIndex != null) {
  26155. var chunkSize = list._chunkSize;
  26156. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26157. var chunkOffset = rawIndex % chunkSize;
  26158. var dim = list.dimensions[dimIndex];
  26159. var chunk = list._storage[dim][chunkIndex];
  26160. if (chunk) {
  26161. val = chunk[chunkOffset];
  26162. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26163. if (ordinalMeta && ordinalMeta.categories.length) {
  26164. val = ordinalMeta.categories[val];
  26165. }
  26166. }
  26167. }
  26168. return val;
  26169. }
  26170. /**
  26171. * @return {number}
  26172. */
  26173. listProto.count = function () {
  26174. return this._count;
  26175. };
  26176. listProto.getIndices = function () {
  26177. var newIndices;
  26178. var indices = this._indices;
  26179. if (indices) {
  26180. var Ctor = indices.constructor;
  26181. var thisCount = this._count;
  26182. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26183. if (Ctor === Array) {
  26184. newIndices = new Ctor(thisCount);
  26185. for (var i = 0; i < thisCount; i++) {
  26186. newIndices[i] = indices[i];
  26187. }
  26188. }
  26189. else {
  26190. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26191. }
  26192. }
  26193. else {
  26194. var Ctor = getIndicesCtor(this);
  26195. var newIndices = new Ctor(this.count());
  26196. for (var i = 0; i < newIndices.length; i++) {
  26197. newIndices[i] = i;
  26198. }
  26199. }
  26200. return newIndices;
  26201. };
  26202. /**
  26203. * Get value. Return NaN if idx is out of range.
  26204. * @param {string} dim Dim must be concrete name.
  26205. * @param {number} idx
  26206. * @param {boolean} stack
  26207. * @return {number}
  26208. */
  26209. listProto.get = function (dim, idx /*, stack */) {
  26210. if (!(idx >= 0 && idx < this._count)) {
  26211. return NaN;
  26212. }
  26213. var storage = this._storage;
  26214. if (!storage[dim]) {
  26215. // TODO Warn ?
  26216. return NaN;
  26217. }
  26218. idx = this.getRawIndex(idx);
  26219. var chunkIndex = Math.floor(idx / this._chunkSize);
  26220. var chunkOffset = idx % this._chunkSize;
  26221. var chunkStore = storage[dim][chunkIndex];
  26222. var value = chunkStore[chunkOffset];
  26223. // FIXME ordinal data type is not stackable
  26224. // if (stack) {
  26225. // var dimensionInfo = this._dimensionInfos[dim];
  26226. // if (dimensionInfo && dimensionInfo.stackable) {
  26227. // var stackedOn = this.stackedOn;
  26228. // while (stackedOn) {
  26229. // // Get no stacked data of stacked on
  26230. // var stackedValue = stackedOn.get(dim, idx);
  26231. // // Considering positive stack, negative stack and empty data
  26232. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26233. // || (value <= 0 && stackedValue < 0) // Negative stack
  26234. // ) {
  26235. // value += stackedValue;
  26236. // }
  26237. // stackedOn = stackedOn.stackedOn;
  26238. // }
  26239. // }
  26240. // }
  26241. return value;
  26242. };
  26243. /**
  26244. * @param {string} dim concrete dim
  26245. * @param {number} rawIndex
  26246. * @return {number|string}
  26247. */
  26248. listProto.getByRawIndex = function (dim, rawIdx) {
  26249. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26250. return NaN;
  26251. }
  26252. var dimStore = this._storage[dim];
  26253. if (!dimStore) {
  26254. // TODO Warn ?
  26255. return NaN;
  26256. }
  26257. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26258. var chunkOffset = rawIdx % this._chunkSize;
  26259. var chunkStore = dimStore[chunkIndex];
  26260. return chunkStore[chunkOffset];
  26261. };
  26262. /**
  26263. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26264. * Hack a much simpler _getFast
  26265. * @private
  26266. */
  26267. listProto._getFast = function (dim, rawIdx) {
  26268. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26269. var chunkOffset = rawIdx % this._chunkSize;
  26270. var chunkStore = this._storage[dim][chunkIndex];
  26271. return chunkStore[chunkOffset];
  26272. };
  26273. /**
  26274. * Get value for multi dimensions.
  26275. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26276. * @param {number} idx
  26277. * @return {number}
  26278. */
  26279. listProto.getValues = function (dimensions, idx /*, stack */) {
  26280. var values = [];
  26281. if (!isArray(dimensions)) {
  26282. // stack = idx;
  26283. idx = dimensions;
  26284. dimensions = this.dimensions;
  26285. }
  26286. for (var i = 0, len = dimensions.length; i < len; i++) {
  26287. values.push(this.get(dimensions[i], idx /*, stack */));
  26288. }
  26289. return values;
  26290. };
  26291. /**
  26292. * If value is NaN. Inlcuding '-'
  26293. * Only check the coord dimensions.
  26294. * @param {string} dim
  26295. * @param {number} idx
  26296. * @return {number}
  26297. */
  26298. listProto.hasValue = function (idx) {
  26299. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26300. var dimensionInfos = this._dimensionInfos;
  26301. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26302. if (
  26303. // Ordinal type can be string or number
  26304. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  26305. // FIXME check ordinal when using index?
  26306. && isNaN(this.get(dataDimsOnCoord[i], idx))
  26307. ) {
  26308. return false;
  26309. }
  26310. }
  26311. return true;
  26312. };
  26313. /**
  26314. * Get extent of data in one dimension
  26315. * @param {string} dim
  26316. * @param {boolean} stack
  26317. */
  26318. listProto.getDataExtent = function (dim /*, stack */) {
  26319. // Make sure use concrete dim as cache name.
  26320. dim = this.getDimension(dim);
  26321. var dimData = this._storage[dim];
  26322. var initialExtent = getInitialExtent();
  26323. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26324. if (!dimData) {
  26325. return initialExtent;
  26326. }
  26327. // Make more strict checkings to ensure hitting cache.
  26328. var currEnd = this.count();
  26329. // var cacheName = [dim, !!stack].join('_');
  26330. // var cacheName = dim;
  26331. // Consider the most cases when using data zoom, `getDataExtent`
  26332. // happened before filtering. We cache raw extent, which is not
  26333. // necessary to be cleared and recalculated when restore data.
  26334. var useRaw = !this._indices; // && !stack;
  26335. var dimExtent;
  26336. if (useRaw) {
  26337. return this._rawExtent[dim].slice();
  26338. }
  26339. dimExtent = this._extent[dim];
  26340. if (dimExtent) {
  26341. return dimExtent.slice();
  26342. }
  26343. dimExtent = initialExtent;
  26344. var min = dimExtent[0];
  26345. var max = dimExtent[1];
  26346. for (var i = 0; i < currEnd; i++) {
  26347. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26348. var value = this._getFast(dim, this.getRawIndex(i));
  26349. value < min && (min = value);
  26350. value > max && (max = value);
  26351. }
  26352. dimExtent = [min, max];
  26353. this._extent[dim] = dimExtent;
  26354. return dimExtent;
  26355. };
  26356. /**
  26357. * Optimize for the scenario that data is filtered by a given extent.
  26358. * Consider that if data amount is more than hundreds of thousand,
  26359. * extent calculation will cost more than 10ms and the cache will
  26360. * be erased because of the filtering.
  26361. */
  26362. listProto.getApproximateExtent = function (dim /*, stack */) {
  26363. dim = this.getDimension(dim);
  26364. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26365. };
  26366. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26367. dim = this.getDimension(dim);
  26368. this._approximateExtent[dim] = extent.slice();
  26369. };
  26370. /**
  26371. * @param {string} key
  26372. * @return {*}
  26373. */
  26374. listProto.getCalculationInfo = function (key) {
  26375. return this._calculationInfo[key];
  26376. };
  26377. /**
  26378. * @param {string|Object} key or k-v object
  26379. * @param {*} [value]
  26380. */
  26381. listProto.setCalculationInfo = function (key, value) {
  26382. isObject$4(key)
  26383. ? extend(this._calculationInfo, key)
  26384. : (this._calculationInfo[key] = value);
  26385. };
  26386. /**
  26387. * Get sum of data in one dimension
  26388. * @param {string} dim
  26389. */
  26390. listProto.getSum = function (dim /*, stack */) {
  26391. var dimData = this._storage[dim];
  26392. var sum = 0;
  26393. if (dimData) {
  26394. for (var i = 0, len = this.count(); i < len; i++) {
  26395. var value = this.get(dim, i /*, stack */);
  26396. if (!isNaN(value)) {
  26397. sum += value;
  26398. }
  26399. }
  26400. }
  26401. return sum;
  26402. };
  26403. /**
  26404. * Get median of data in one dimension
  26405. * @param {string} dim
  26406. */
  26407. listProto.getMedian = function (dim /*, stack */) {
  26408. var dimDataArray = [];
  26409. // map all data of one dimension
  26410. this.each(dim, function (val, idx) {
  26411. if (!isNaN(val)) {
  26412. dimDataArray.push(val);
  26413. }
  26414. });
  26415. // TODO
  26416. // Use quick select?
  26417. // immutability & sort
  26418. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26419. return a - b;
  26420. });
  26421. var len = this.count();
  26422. // calculate median
  26423. return len === 0
  26424. ? 0
  26425. : len % 2 === 1
  26426. ? sortedDimDataArray[(len - 1) / 2]
  26427. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26428. };
  26429. // /**
  26430. // * Retreive the index with given value
  26431. // * @param {string} dim Concrete dimension.
  26432. // * @param {number} value
  26433. // * @return {number}
  26434. // */
  26435. // Currently incorrect: should return dataIndex but not rawIndex.
  26436. // Do not fix it until this method is to be used somewhere.
  26437. // FIXME Precision of float value
  26438. // listProto.indexOf = function (dim, value) {
  26439. // var storage = this._storage;
  26440. // var dimData = storage[dim];
  26441. // var chunkSize = this._chunkSize;
  26442. // if (dimData) {
  26443. // for (var i = 0, len = this.count(); i < len; i++) {
  26444. // var chunkIndex = Math.floor(i / chunkSize);
  26445. // var chunkOffset = i % chunkSize;
  26446. // if (dimData[chunkIndex][chunkOffset] === value) {
  26447. // return i;
  26448. // }
  26449. // }
  26450. // }
  26451. // return -1;
  26452. // };
  26453. /**
  26454. * Only support the dimension which inverted index created.
  26455. * Do not support other cases until required.
  26456. * @param {string} concrete dim
  26457. * @param {number|string} value
  26458. * @return {number} rawIndex
  26459. */
  26460. listProto.rawIndexOf = function (dim, value) {
  26461. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26462. if (__DEV__) {
  26463. if (!invertedIndices) {
  26464. throw new Error('Do not supported yet');
  26465. }
  26466. }
  26467. var rawIndex = invertedIndices[value];
  26468. if (rawIndex == null || isNaN(rawIndex)) {
  26469. return INDEX_NOT_FOUND;
  26470. }
  26471. return rawIndex;
  26472. };
  26473. /**
  26474. * Retreive the index with given name
  26475. * @param {number} idx
  26476. * @param {number} name
  26477. * @return {number}
  26478. */
  26479. listProto.indexOfName = function (name) {
  26480. for (var i = 0, len = this.count(); i < len; i++) {
  26481. if (this.getName(i) === name) {
  26482. return i;
  26483. }
  26484. }
  26485. return -1;
  26486. };
  26487. /**
  26488. * Retreive the index with given raw data index
  26489. * @param {number} idx
  26490. * @param {number} name
  26491. * @return {number}
  26492. */
  26493. listProto.indexOfRawIndex = function (rawIndex) {
  26494. if (!this._indices) {
  26495. return rawIndex;
  26496. }
  26497. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26498. return -1;
  26499. }
  26500. // Indices are ascending
  26501. var indices = this._indices;
  26502. // If rawIndex === dataIndex
  26503. var rawDataIndex = indices[rawIndex];
  26504. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26505. return rawIndex;
  26506. }
  26507. var left = 0;
  26508. var right = this._count - 1;
  26509. while (left <= right) {
  26510. var mid = (left + right) / 2 | 0;
  26511. if (indices[mid] < rawIndex) {
  26512. left = mid + 1;
  26513. }
  26514. else if (indices[mid] > rawIndex) {
  26515. right = mid - 1;
  26516. }
  26517. else {
  26518. return mid;
  26519. }
  26520. }
  26521. return -1;
  26522. };
  26523. /**
  26524. * Retreive the index of nearest value
  26525. * @param {string} dim
  26526. * @param {number} value
  26527. * @param {number} [maxDistance=Infinity]
  26528. * @return {Array.<number>} Considere multiple points has the same value.
  26529. */
  26530. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26531. var storage = this._storage;
  26532. var dimData = storage[dim];
  26533. var nearestIndices = [];
  26534. if (!dimData) {
  26535. return nearestIndices;
  26536. }
  26537. if (maxDistance == null) {
  26538. maxDistance = Infinity;
  26539. }
  26540. var minDist = Number.MAX_VALUE;
  26541. var minDiff = -1;
  26542. for (var i = 0, len = this.count(); i < len; i++) {
  26543. var diff = value - this.get(dim, i /*, stack */);
  26544. var dist = Math.abs(diff);
  26545. if (diff <= maxDistance && dist <= minDist) {
  26546. // For the case of two data are same on xAxis, which has sequence data.
  26547. // Show the nearest index
  26548. // https://github.com/ecomfe/echarts/issues/2869
  26549. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  26550. minDist = dist;
  26551. minDiff = diff;
  26552. nearestIndices.length = 0;
  26553. }
  26554. nearestIndices.push(i);
  26555. }
  26556. }
  26557. return nearestIndices;
  26558. };
  26559. /**
  26560. * Get raw data index
  26561. * @param {number} idx
  26562. * @return {number}
  26563. */
  26564. listProto.getRawIndex = getRawIndexWithoutIndices;
  26565. function getRawIndexWithoutIndices(idx) {
  26566. return idx;
  26567. }
  26568. function getRawIndexWithIndices(idx) {
  26569. if (idx < this._count && idx >= 0) {
  26570. return this._indices[idx];
  26571. }
  26572. return -1;
  26573. }
  26574. /**
  26575. * Get raw data item
  26576. * @param {number} idx
  26577. * @return {number}
  26578. */
  26579. listProto.getRawDataItem = function (idx) {
  26580. if (!this._rawData.persistent) {
  26581. var val = [];
  26582. for (var i = 0; i < this.dimensions.length; i++) {
  26583. var dim = this.dimensions[i];
  26584. val.push(this.get(dim, idx));
  26585. }
  26586. return val;
  26587. }
  26588. else {
  26589. return this._rawData.getItem(this.getRawIndex(idx));
  26590. }
  26591. };
  26592. /**
  26593. * @param {number} idx
  26594. * @param {boolean} [notDefaultIdx=false]
  26595. * @return {string}
  26596. */
  26597. listProto.getName = function (idx) {
  26598. var rawIndex = this.getRawIndex(idx);
  26599. return this._nameList[rawIndex]
  26600. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26601. || '';
  26602. };
  26603. /**
  26604. * @param {number} idx
  26605. * @param {boolean} [notDefaultIdx=false]
  26606. * @return {string}
  26607. */
  26608. listProto.getId = function (idx) {
  26609. return getId(this, this.getRawIndex(idx));
  26610. };
  26611. function getId(list, rawIndex) {
  26612. var id = list._idList[rawIndex];
  26613. if (id == null) {
  26614. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26615. }
  26616. if (id == null) {
  26617. // FIXME Check the usage in graph, should not use prefix.
  26618. id = ID_PREFIX + rawIndex;
  26619. }
  26620. return id;
  26621. }
  26622. function normalizeDimensions(dimensions) {
  26623. if (!isArray(dimensions)) {
  26624. dimensions = [dimensions];
  26625. }
  26626. return dimensions;
  26627. }
  26628. function validateDimensions(list, dims) {
  26629. for (var i = 0; i < dims.length; i++) {
  26630. // stroage may be empty when no data, so use
  26631. // dimensionInfos to check.
  26632. if (!list._dimensionInfos[dims[i]]) {
  26633. console.error('Unkown dimension ' + dims[i]);
  26634. }
  26635. }
  26636. }
  26637. /**
  26638. * Data iteration
  26639. * @param {string|Array.<string>}
  26640. * @param {Function} cb
  26641. * @param {*} [context=this]
  26642. *
  26643. * @example
  26644. * list.each('x', function (x, idx) {});
  26645. * list.each(['x', 'y'], function (x, y, idx) {});
  26646. * list.each(function (idx) {})
  26647. */
  26648. listProto.each = function (dims, cb, context, contextCompat) {
  26649. 'use strict';
  26650. if (!this._count) {
  26651. return;
  26652. }
  26653. if (typeof dims === 'function') {
  26654. contextCompat = context;
  26655. context = cb;
  26656. cb = dims;
  26657. dims = [];
  26658. }
  26659. // contextCompat just for compat echarts3
  26660. context = context || contextCompat || this;
  26661. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26662. if (__DEV__) {
  26663. validateDimensions(this, dims);
  26664. }
  26665. var dimSize = dims.length;
  26666. for (var i = 0; i < this.count(); i++) {
  26667. // Simple optimization
  26668. switch (dimSize) {
  26669. case 0:
  26670. cb.call(context, i);
  26671. break;
  26672. case 1:
  26673. cb.call(context, this.get(dims[0], i), i);
  26674. break;
  26675. case 2:
  26676. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26677. break;
  26678. default:
  26679. var k = 0;
  26680. var value = [];
  26681. for (; k < dimSize; k++) {
  26682. value[k] = this.get(dims[k], i);
  26683. }
  26684. // Index
  26685. value[k] = i;
  26686. cb.apply(context, value);
  26687. }
  26688. }
  26689. };
  26690. /**
  26691. * Data filter
  26692. * @param {string|Array.<string>}
  26693. * @param {Function} cb
  26694. * @param {*} [context=this]
  26695. */
  26696. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26697. 'use strict';
  26698. if (!this._count) {
  26699. return;
  26700. }
  26701. if (typeof dimensions === 'function') {
  26702. contextCompat = context;
  26703. context = cb;
  26704. cb = dimensions;
  26705. dimensions = [];
  26706. }
  26707. // contextCompat just for compat echarts3
  26708. context = context || contextCompat || this;
  26709. dimensions = map(
  26710. normalizeDimensions(dimensions), this.getDimension, this
  26711. );
  26712. if (__DEV__) {
  26713. validateDimensions(this, dimensions);
  26714. }
  26715. var count = this.count();
  26716. var Ctor = getIndicesCtor(this);
  26717. var newIndices = new Ctor(count);
  26718. var value = [];
  26719. var dimSize = dimensions.length;
  26720. var offset = 0;
  26721. var dim0 = dimensions[0];
  26722. for (var i = 0; i < count; i++) {
  26723. var keep;
  26724. var rawIdx = this.getRawIndex(i);
  26725. // Simple optimization
  26726. if (dimSize === 0) {
  26727. keep = cb.call(context, i);
  26728. }
  26729. else if (dimSize === 1) {
  26730. var val = this._getFast(dim0, rawIdx);
  26731. keep = cb.call(context, val, i);
  26732. }
  26733. else {
  26734. for (var k = 0; k < dimSize; k++) {
  26735. value[k] = this._getFast(dim0, rawIdx);
  26736. }
  26737. value[k] = i;
  26738. keep = cb.apply(context, value);
  26739. }
  26740. if (keep) {
  26741. newIndices[offset++] = rawIdx;
  26742. }
  26743. }
  26744. // Set indices after filtered.
  26745. if (offset < count) {
  26746. this._indices = newIndices;
  26747. }
  26748. this._count = offset;
  26749. // Reset data extent
  26750. this._extent = {};
  26751. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26752. return this;
  26753. };
  26754. /**
  26755. * Select data in range. (For optimization of filter)
  26756. * (Manually inline code, support 5 million data filtering in data zoom.)
  26757. */
  26758. listProto.selectRange = function (range) {
  26759. 'use strict';
  26760. if (!this._count) {
  26761. return;
  26762. }
  26763. var dimensions = [];
  26764. for (var dim in range) {
  26765. if (range.hasOwnProperty(dim)) {
  26766. dimensions.push(dim);
  26767. }
  26768. }
  26769. if (__DEV__) {
  26770. validateDimensions(this, dimensions);
  26771. }
  26772. var dimSize = dimensions.length;
  26773. if (!dimSize) {
  26774. return;
  26775. }
  26776. var originalCount = this.count();
  26777. var Ctor = getIndicesCtor(this);
  26778. var newIndices = new Ctor(originalCount);
  26779. var offset = 0;
  26780. var dim0 = dimensions[0];
  26781. var min = range[dim0][0];
  26782. var max = range[dim0][1];
  26783. var quickFinished = false;
  26784. if (!this._indices) {
  26785. // Extreme optimization for common case. About 2x faster in chrome.
  26786. var idx = 0;
  26787. if (dimSize === 1) {
  26788. var dimStorage = this._storage[dimensions[0]];
  26789. for (var k = 0; k < this._chunkCount; k++) {
  26790. var chunkStorage = dimStorage[k];
  26791. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26792. for (var i = 0; i < len; i++) {
  26793. var val = chunkStorage[i];
  26794. // NaN will not be filtered. Consider the case, in line chart, empty
  26795. // value indicates the line should be broken. But for the case like
  26796. // scatter plot, a data item with empty value will not be rendered,
  26797. // but the axis extent may be effected if some other dim of the data
  26798. // item has value. Fortunately it is not a significant negative effect.
  26799. if (
  26800. (val >= min && val <= max) || isNaN(val)
  26801. ) {
  26802. newIndices[offset++] = idx;
  26803. }
  26804. idx++;
  26805. }
  26806. }
  26807. quickFinished = true;
  26808. }
  26809. else if (dimSize === 2) {
  26810. var dimStorage = this._storage[dim0];
  26811. var dimStorage2 = this._storage[dimensions[1]];
  26812. var min2 = range[dimensions[1]][0];
  26813. var max2 = range[dimensions[1]][1];
  26814. for (var k = 0; k < this._chunkCount; k++) {
  26815. var chunkStorage = dimStorage[k];
  26816. var chunkStorage2 = dimStorage2[k];
  26817. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26818. for (var i = 0; i < len; i++) {
  26819. var val = chunkStorage[i];
  26820. var val2 = chunkStorage2[i];
  26821. // Do not filter NaN, see comment above.
  26822. if ((
  26823. (val >= min && val <= max) || isNaN(val)
  26824. )
  26825. && (
  26826. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26827. )
  26828. ) {
  26829. newIndices[offset++] = idx;
  26830. }
  26831. idx++;
  26832. }
  26833. }
  26834. quickFinished = true;
  26835. }
  26836. }
  26837. if (!quickFinished) {
  26838. if (dimSize === 1) {
  26839. for (var i = 0; i < originalCount; i++) {
  26840. var rawIndex = this.getRawIndex(i);
  26841. var val = this._getFast(dim0, rawIndex);
  26842. // Do not filter NaN, see comment above.
  26843. if (
  26844. (val >= min && val <= max) || isNaN(val)
  26845. ) {
  26846. newIndices[offset++] = rawIndex;
  26847. }
  26848. }
  26849. }
  26850. else {
  26851. for (var i = 0; i < originalCount; i++) {
  26852. var keep = true;
  26853. var rawIndex = this.getRawIndex(i);
  26854. for (var k = 0; k < dimSize; k++) {
  26855. var dimk = dimensions[k];
  26856. var val = this._getFast(dim, rawIndex);
  26857. // Do not filter NaN, see comment above.
  26858. if (val < range[dimk][0] || val > range[dimk][1]) {
  26859. keep = false;
  26860. }
  26861. }
  26862. if (keep) {
  26863. newIndices[offset++] = this.getRawIndex(i);
  26864. }
  26865. }
  26866. }
  26867. }
  26868. // Set indices after filtered.
  26869. if (offset < originalCount) {
  26870. this._indices = newIndices;
  26871. }
  26872. this._count = offset;
  26873. // Reset data extent
  26874. this._extent = {};
  26875. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26876. return this;
  26877. };
  26878. /**
  26879. * Data mapping to a plain array
  26880. * @param {string|Array.<string>} [dimensions]
  26881. * @param {Function} cb
  26882. * @param {*} [context=this]
  26883. * @return {Array}
  26884. */
  26885. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26886. 'use strict';
  26887. if (typeof dimensions === 'function') {
  26888. contextCompat = context;
  26889. context = cb;
  26890. cb = dimensions;
  26891. dimensions = [];
  26892. }
  26893. // contextCompat just for compat echarts3
  26894. context = context || contextCompat || this;
  26895. var result = [];
  26896. this.each(dimensions, function () {
  26897. result.push(cb && cb.apply(this, arguments));
  26898. }, context);
  26899. return result;
  26900. };
  26901. // Data in excludeDimensions is copied, otherwise transfered.
  26902. function cloneListForMapAndSample(original, excludeDimensions) {
  26903. var allDimensions = original.dimensions;
  26904. var list = new List(
  26905. map(allDimensions, original.getDimensionInfo, original),
  26906. original.hostModel
  26907. );
  26908. // FIXME If needs stackedOn, value may already been stacked
  26909. transferProperties(list, original);
  26910. var storage = list._storage = {};
  26911. var originalStorage = original._storage;
  26912. // Init storage
  26913. for (var i = 0; i < allDimensions.length; i++) {
  26914. var dim = allDimensions[i];
  26915. if (originalStorage[dim]) {
  26916. // Notice that we do not reset invertedIndicesMap here, becuase
  26917. // there is no scenario of mapping or sampling ordinal dimension.
  26918. if (indexOf(excludeDimensions, dim) >= 0) {
  26919. storage[dim] = cloneDimStore(originalStorage[dim]);
  26920. list._rawExtent[dim] = getInitialExtent();
  26921. list._extent[dim] = null;
  26922. }
  26923. else {
  26924. // Direct reference for other dimensions
  26925. storage[dim] = originalStorage[dim];
  26926. }
  26927. }
  26928. }
  26929. return list;
  26930. }
  26931. function cloneDimStore(originalDimStore) {
  26932. var newDimStore = new Array(originalDimStore.length);
  26933. for (var j = 0; j < originalDimStore.length; j++) {
  26934. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26935. }
  26936. return newDimStore;
  26937. }
  26938. function getInitialExtent() {
  26939. return [Infinity, -Infinity];
  26940. }
  26941. /**
  26942. * Data mapping to a new List with given dimensions
  26943. * @param {string|Array.<string>} dimensions
  26944. * @param {Function} cb
  26945. * @param {*} [context=this]
  26946. * @return {Array}
  26947. */
  26948. listProto.map = function (dimensions, cb, context, contextCompat) {
  26949. 'use strict';
  26950. // contextCompat just for compat echarts3
  26951. context = context || contextCompat || this;
  26952. dimensions = map(
  26953. normalizeDimensions(dimensions), this.getDimension, this
  26954. );
  26955. if (__DEV__) {
  26956. validateDimensions(this, dimensions);
  26957. }
  26958. var list = cloneListForMapAndSample(this, dimensions);
  26959. // Following properties are all immutable.
  26960. // So we can reference to the same value
  26961. list._indices = this._indices;
  26962. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26963. var storage = list._storage;
  26964. var tmpRetValue = [];
  26965. var chunkSize = this._chunkSize;
  26966. var dimSize = dimensions.length;
  26967. var dataCount = this.count();
  26968. var values = [];
  26969. var rawExtent = list._rawExtent;
  26970. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26971. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26972. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26973. }
  26974. values[dimSize] = dataIndex;
  26975. var retValue = cb && cb.apply(context, values);
  26976. if (retValue != null) {
  26977. // a number or string (in oridinal dimension)?
  26978. if (typeof retValue !== 'object') {
  26979. tmpRetValue[0] = retValue;
  26980. retValue = tmpRetValue;
  26981. }
  26982. var rawIndex = this.getRawIndex(dataIndex);
  26983. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26984. var chunkOffset = rawIndex % chunkSize;
  26985. for (var i = 0; i < retValue.length; i++) {
  26986. var dim = dimensions[i];
  26987. var val = retValue[i];
  26988. var rawExtentOnDim = rawExtent[dim];
  26989. var dimStore = storage[dim];
  26990. if (dimStore) {
  26991. dimStore[chunkIndex][chunkOffset] = val;
  26992. }
  26993. if (val < rawExtentOnDim[0]) {
  26994. rawExtentOnDim[0] = val;
  26995. }
  26996. if (val > rawExtentOnDim[1]) {
  26997. rawExtentOnDim[1] = val;
  26998. }
  26999. }
  27000. }
  27001. }
  27002. return list;
  27003. };
  27004. /**
  27005. * Large data down sampling on given dimension
  27006. * @param {string} dimension
  27007. * @param {number} rate
  27008. * @param {Function} sampleValue
  27009. * @param {Function} sampleIndex Sample index for name and id
  27010. */
  27011. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27012. var list = cloneListForMapAndSample(this, [dimension]);
  27013. var targetStorage = list._storage;
  27014. var frameValues = [];
  27015. var frameSize = Math.floor(1 / rate);
  27016. var dimStore = targetStorage[dimension];
  27017. var len = this.count();
  27018. var chunkSize = this._chunkSize;
  27019. var rawExtentOnDim = list._rawExtent[dimension];
  27020. var newIndices = new (getIndicesCtor(this))(len);
  27021. var offset = 0;
  27022. for (var i = 0; i < len; i += frameSize) {
  27023. // Last frame
  27024. if (frameSize > len - i) {
  27025. frameSize = len - i;
  27026. frameValues.length = frameSize;
  27027. }
  27028. for (var k = 0; k < frameSize; k++) {
  27029. var dataIdx = this.getRawIndex(i + k);
  27030. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27031. var originalChunkOffset = dataIdx % chunkSize;
  27032. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27033. }
  27034. var value = sampleValue(frameValues);
  27035. var sampleFrameIdx = this.getRawIndex(
  27036. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27037. );
  27038. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27039. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27040. // Only write value on the filtered data
  27041. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27042. if (value < rawExtentOnDim[0]) {
  27043. rawExtentOnDim[0] = value;
  27044. }
  27045. if (value > rawExtentOnDim[1]) {
  27046. rawExtentOnDim[1] = value;
  27047. }
  27048. newIndices[offset++] = sampleFrameIdx;
  27049. }
  27050. list._count = offset;
  27051. list._indices = newIndices;
  27052. list.getRawIndex = getRawIndexWithIndices;
  27053. return list;
  27054. };
  27055. /**
  27056. * Get model of one data item.
  27057. *
  27058. * @param {number} idx
  27059. */
  27060. // FIXME Model proxy ?
  27061. listProto.getItemModel = function (idx) {
  27062. var hostModel = this.hostModel;
  27063. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27064. };
  27065. /**
  27066. * Create a data differ
  27067. * @param {module:echarts/data/List} otherList
  27068. * @return {module:echarts/data/DataDiffer}
  27069. */
  27070. listProto.diff = function (otherList) {
  27071. var thisList = this;
  27072. return new DataDiffer(
  27073. otherList ? otherList.getIndices() : [],
  27074. this.getIndices(),
  27075. function (idx) {
  27076. return getId(otherList, idx);
  27077. },
  27078. function (idx) {
  27079. return getId(thisList, idx);
  27080. }
  27081. );
  27082. };
  27083. /**
  27084. * Get visual property.
  27085. * @param {string} key
  27086. */
  27087. listProto.getVisual = function (key) {
  27088. var visual = this._visual;
  27089. return visual && visual[key];
  27090. };
  27091. /**
  27092. * Set visual property
  27093. * @param {string|Object} key
  27094. * @param {*} [value]
  27095. *
  27096. * @example
  27097. * setVisual('color', color);
  27098. * setVisual({
  27099. * 'color': color
  27100. * });
  27101. */
  27102. listProto.setVisual = function (key, val) {
  27103. if (isObject$4(key)) {
  27104. for (var name in key) {
  27105. if (key.hasOwnProperty(name)) {
  27106. this.setVisual(name, key[name]);
  27107. }
  27108. }
  27109. return;
  27110. }
  27111. this._visual = this._visual || {};
  27112. this._visual[key] = val;
  27113. };
  27114. /**
  27115. * Set layout property.
  27116. * @param {string|Object} key
  27117. * @param {*} [val]
  27118. */
  27119. listProto.setLayout = function (key, val) {
  27120. if (isObject$4(key)) {
  27121. for (var name in key) {
  27122. if (key.hasOwnProperty(name)) {
  27123. this.setLayout(name, key[name]);
  27124. }
  27125. }
  27126. return;
  27127. }
  27128. this._layout[key] = val;
  27129. };
  27130. /**
  27131. * Get layout property.
  27132. * @param {string} key.
  27133. * @return {*}
  27134. */
  27135. listProto.getLayout = function (key) {
  27136. return this._layout[key];
  27137. };
  27138. /**
  27139. * Get layout of single data item
  27140. * @param {number} idx
  27141. */
  27142. listProto.getItemLayout = function (idx) {
  27143. return this._itemLayouts[idx];
  27144. };
  27145. /**
  27146. * Set layout of single data item
  27147. * @param {number} idx
  27148. * @param {Object} layout
  27149. * @param {boolean=} [merge=false]
  27150. */
  27151. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27152. this._itemLayouts[idx] = merge$$1
  27153. ? extend(this._itemLayouts[idx] || {}, layout)
  27154. : layout;
  27155. };
  27156. /**
  27157. * Clear all layout of single data item
  27158. */
  27159. listProto.clearItemLayouts = function () {
  27160. this._itemLayouts.length = 0;
  27161. };
  27162. /**
  27163. * Get visual property of single data item
  27164. * @param {number} idx
  27165. * @param {string} key
  27166. * @param {boolean} [ignoreParent=false]
  27167. */
  27168. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27169. var itemVisual = this._itemVisuals[idx];
  27170. var val = itemVisual && itemVisual[key];
  27171. if (val == null && !ignoreParent) {
  27172. // Use global visual property
  27173. return this.getVisual(key);
  27174. }
  27175. return val;
  27176. };
  27177. /**
  27178. * Set visual property of single data item
  27179. *
  27180. * @param {number} idx
  27181. * @param {string|Object} key
  27182. * @param {*} [value]
  27183. *
  27184. * @example
  27185. * setItemVisual(0, 'color', color);
  27186. * setItemVisual(0, {
  27187. * 'color': color
  27188. * });
  27189. */
  27190. listProto.setItemVisual = function (idx, key, value) {
  27191. var itemVisual = this._itemVisuals[idx] || {};
  27192. var hasItemVisual = this.hasItemVisual;
  27193. this._itemVisuals[idx] = itemVisual;
  27194. if (isObject$4(key)) {
  27195. for (var name in key) {
  27196. if (key.hasOwnProperty(name)) {
  27197. itemVisual[name] = key[name];
  27198. hasItemVisual[name] = true;
  27199. }
  27200. }
  27201. return;
  27202. }
  27203. itemVisual[key] = value;
  27204. hasItemVisual[key] = true;
  27205. };
  27206. /**
  27207. * Clear itemVisuals and list visual.
  27208. */
  27209. listProto.clearAllVisual = function () {
  27210. this._visual = {};
  27211. this._itemVisuals = [];
  27212. this.hasItemVisual = {};
  27213. };
  27214. var setItemDataAndSeriesIndex = function (child) {
  27215. child.seriesIndex = this.seriesIndex;
  27216. child.dataIndex = this.dataIndex;
  27217. child.dataType = this.dataType;
  27218. };
  27219. /**
  27220. * Set graphic element relative to data. It can be set as null
  27221. * @param {number} idx
  27222. * @param {module:zrender/Element} [el]
  27223. */
  27224. listProto.setItemGraphicEl = function (idx, el) {
  27225. var hostModel = this.hostModel;
  27226. if (el) {
  27227. // Add data index and series index for indexing the data by element
  27228. // Useful in tooltip
  27229. el.dataIndex = idx;
  27230. el.dataType = this.dataType;
  27231. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27232. if (el.type === 'group') {
  27233. el.traverse(setItemDataAndSeriesIndex, el);
  27234. }
  27235. }
  27236. this._graphicEls[idx] = el;
  27237. };
  27238. /**
  27239. * @param {number} idx
  27240. * @return {module:zrender/Element}
  27241. */
  27242. listProto.getItemGraphicEl = function (idx) {
  27243. return this._graphicEls[idx];
  27244. };
  27245. /**
  27246. * @param {Function} cb
  27247. * @param {*} context
  27248. */
  27249. listProto.eachItemGraphicEl = function (cb, context) {
  27250. each$1(this._graphicEls, function (el, idx) {
  27251. if (el) {
  27252. cb && cb.call(context, el, idx);
  27253. }
  27254. });
  27255. };
  27256. /**
  27257. * Shallow clone a new list except visual and layout properties, and graph elements.
  27258. * New list only change the indices.
  27259. */
  27260. listProto.cloneShallow = function (list) {
  27261. if (!list) {
  27262. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27263. list = new List(dimensionInfoList, this.hostModel);
  27264. }
  27265. // FIXME
  27266. list._storage = this._storage;
  27267. transferProperties(list, this);
  27268. // Clone will not change the data extent and indices
  27269. if (this._indices) {
  27270. var Ctor = this._indices.constructor;
  27271. list._indices = new Ctor(this._indices);
  27272. }
  27273. else {
  27274. list._indices = null;
  27275. }
  27276. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27277. return list;
  27278. };
  27279. /**
  27280. * Wrap some method to add more feature
  27281. * @param {string} methodName
  27282. * @param {Function} injectFunction
  27283. */
  27284. listProto.wrapMethod = function (methodName, injectFunction) {
  27285. var originalMethod = this[methodName];
  27286. if (typeof originalMethod !== 'function') {
  27287. return;
  27288. }
  27289. this.__wrappedMethods = this.__wrappedMethods || [];
  27290. this.__wrappedMethods.push(methodName);
  27291. this[methodName] = function () {
  27292. var res = originalMethod.apply(this, arguments);
  27293. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27294. };
  27295. };
  27296. // Methods that create a new list based on this list should be listed here.
  27297. // Notice that those method should `RETURN` the new list.
  27298. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27299. // Methods that change indices of this list should be listed here.
  27300. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27301. /*
  27302. * Licensed to the Apache Software Foundation (ASF) under one
  27303. * or more contributor license agreements. See the NOTICE file
  27304. * distributed with this work for additional information
  27305. * regarding copyright ownership. The ASF licenses this file
  27306. * to you under the Apache License, Version 2.0 (the
  27307. * "License"); you may not use this file except in compliance
  27308. * with the License. You may obtain a copy of the License at
  27309. *
  27310. * http://www.apache.org/licenses/LICENSE-2.0
  27311. *
  27312. * Unless required by applicable law or agreed to in writing,
  27313. * software distributed under the License is distributed on an
  27314. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27315. * KIND, either express or implied. See the License for the
  27316. * specific language governing permissions and limitations
  27317. * under the License.
  27318. */
  27319. /**
  27320. * @deprecated
  27321. * Use `echarts/data/helper/createDimensions` instead.
  27322. */
  27323. /**
  27324. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27325. *
  27326. * Complete the dimensions array, by user defined `dimension` and `encode`,
  27327. * and guessing from the data structure.
  27328. * If no 'value' dimension specified, the first no-named dimension will be
  27329. * named as 'value'.
  27330. *
  27331. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27332. * provides not only dim template, but also default order.
  27333. * properties: 'name', 'type', 'displayName'.
  27334. * `name` of each item provides default coord name.
  27335. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27336. * provide dims count that the sysDim required.
  27337. * [{ordinalMeta}] can be specified.
  27338. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27339. * @param {Object} [opt]
  27340. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27341. * For example: ['asdf', {name, type}, ...].
  27342. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27343. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27344. * If not specified, extra dim names will be:
  27345. * 'value', 'value0', 'value1', ...
  27346. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27347. * If `generateCoordCount` specified, the generated dim names will be:
  27348. * `generateCoord` + 0, `generateCoord` + 1, ...
  27349. * can be Infinity, indicate that use all of the remain columns.
  27350. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27351. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  27352. * @return {Array.<Object>} [{
  27353. * name: string mandatory,
  27354. * displayName: string, the origin name in dimsDef, see source helper.
  27355. * If displayName given, the tooltip will displayed vertically.
  27356. * coordDim: string mandatory,
  27357. * coordDimIndex: number mandatory,
  27358. * type: string optional,
  27359. * otherDims: { never null/undefined
  27360. * tooltip: number optional,
  27361. * label: number optional,
  27362. * itemName: number optional,
  27363. * seriesName: number optional,
  27364. * },
  27365. * isExtraCoord: boolean true if coord is generated
  27366. * (not specified in encode and not series specified)
  27367. * other props ...
  27368. * }]
  27369. */
  27370. function completeDimensions(sysDims, source, opt) {
  27371. if (!Source.isInstance(source)) {
  27372. source = Source.seriesDataToSource(source);
  27373. }
  27374. opt = opt || {};
  27375. sysDims = (sysDims || []).slice();
  27376. var dimsDef = (opt.dimsDef || []).slice();
  27377. var encodeDef = createHashMap(opt.encodeDef);
  27378. var dataDimNameMap = createHashMap();
  27379. var coordDimNameMap = createHashMap();
  27380. // var valueCandidate;
  27381. var result = [];
  27382. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27383. // Apply user defined dims (`name` and `type`) and init result.
  27384. for (var i = 0; i < dimCount; i++) {
  27385. var dimDefItem = dimsDef[i] = extend(
  27386. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27387. );
  27388. var userDimName = dimDefItem.name;
  27389. var resultItem = result[i] = {otherDims: {}};
  27390. // Name will be applied later for avoiding duplication.
  27391. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27392. // Only if `series.dimensions` is defined in option
  27393. // displayName, will be set, and dimension will be diplayed vertically in
  27394. // tooltip by default.
  27395. resultItem.name = resultItem.displayName = userDimName;
  27396. dataDimNameMap.set(userDimName, i);
  27397. }
  27398. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27399. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27400. }
  27401. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27402. encodeDef.each(function (dataDims, coordDim) {
  27403. dataDims = normalizeToArray(dataDims).slice();
  27404. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27405. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27406. // this case.
  27407. if (dataDims.length === 1 && dataDims[0] < 0) {
  27408. encodeDef.set(coordDim, false);
  27409. return;
  27410. }
  27411. var validDataDims = encodeDef.set(coordDim, []);
  27412. each$1(dataDims, function (resultDimIdx, idx) {
  27413. // The input resultDimIdx can be dim name or index.
  27414. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27415. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27416. validDataDims[idx] = resultDimIdx;
  27417. applyDim(result[resultDimIdx], coordDim, idx);
  27418. }
  27419. });
  27420. });
  27421. // Apply templetes and default order from `sysDims`.
  27422. var availDimIdx = 0;
  27423. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27424. var coordDim;
  27425. var sysDimItem;
  27426. var sysDimItemDimsDef;
  27427. var sysDimItemOtherDims;
  27428. if (isString(sysDimItem)) {
  27429. coordDim = sysDimItem;
  27430. sysDimItem = {};
  27431. }
  27432. else {
  27433. coordDim = sysDimItem.name;
  27434. var ordinalMeta = sysDimItem.ordinalMeta;
  27435. sysDimItem.ordinalMeta = null;
  27436. sysDimItem = clone(sysDimItem);
  27437. sysDimItem.ordinalMeta = ordinalMeta;
  27438. // `coordDimIndex` should not be set directly.
  27439. sysDimItemDimsDef = sysDimItem.dimsDef;
  27440. sysDimItemOtherDims = sysDimItem.otherDims;
  27441. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  27442. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27443. }
  27444. var dataDims = encodeDef.get(coordDim);
  27445. // negative resultDimIdx means no need to mapping.
  27446. if (dataDims === false) {
  27447. return;
  27448. }
  27449. var dataDims = normalizeToArray(dataDims);
  27450. // dimensions provides default dim sequences.
  27451. if (!dataDims.length) {
  27452. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27453. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27454. availDimIdx++;
  27455. }
  27456. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27457. }
  27458. }
  27459. // Apply templates.
  27460. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27461. var resultItem = result[resultDimIdx];
  27462. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27463. if (resultItem.name == null && sysDimItemDimsDef) {
  27464. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27465. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27466. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27467. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27468. }
  27469. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27470. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27471. });
  27472. });
  27473. function applyDim(resultItem, coordDim, coordDimIndex) {
  27474. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27475. resultItem.otherDims[coordDim] = coordDimIndex;
  27476. }
  27477. else {
  27478. resultItem.coordDim = coordDim;
  27479. resultItem.coordDimIndex = coordDimIndex;
  27480. coordDimNameMap.set(coordDim, true);
  27481. }
  27482. }
  27483. // Make sure the first extra dim is 'value'.
  27484. var generateCoord = opt.generateCoord;
  27485. var generateCoordCount = opt.generateCoordCount;
  27486. var fromZero = generateCoordCount != null;
  27487. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27488. var extra = generateCoord || 'value';
  27489. // Set dim `name` and other `coordDim` and other props.
  27490. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27491. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  27492. var coordDim = resultItem.coordDim;
  27493. if (coordDim == null) {
  27494. resultItem.coordDim = genName(
  27495. extra, coordDimNameMap, fromZero
  27496. );
  27497. resultItem.coordDimIndex = 0;
  27498. if (!generateCoord || generateCoordCount <= 0) {
  27499. resultItem.isExtraCoord = true;
  27500. }
  27501. generateCoordCount--;
  27502. }
  27503. resultItem.name == null && (resultItem.name = genName(
  27504. resultItem.coordDim,
  27505. dataDimNameMap
  27506. ));
  27507. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  27508. resultItem.type = 'ordinal';
  27509. }
  27510. }
  27511. return result;
  27512. }
  27513. // ??? TODO
  27514. // Originally detect dimCount by data[0]. Should we
  27515. // optimize it to only by sysDims and dimensions and encode.
  27516. // So only necessary dims will be initialized.
  27517. // But
  27518. // (1) custom series should be considered. where other dims
  27519. // may be visited.
  27520. // (2) sometimes user need to calcualte bubble size or use visualMap
  27521. // on other dimensions besides coordSys needed.
  27522. // So, dims that is not used by system, should be shared in storage?
  27523. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27524. // Note that the result dimCount should not small than columns count
  27525. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27526. var dimCount = Math.max(
  27527. source.dimensionsDetectCount || 1,
  27528. sysDims.length,
  27529. dimsDef.length,
  27530. optDimCount || 0
  27531. );
  27532. each$1(sysDims, function (sysDimItem) {
  27533. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27534. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27535. });
  27536. return dimCount;
  27537. }
  27538. function genName(name, map$$1, fromZero) {
  27539. if (fromZero || map$$1.get(name) != null) {
  27540. var i = 0;
  27541. while (map$$1.get(name + i) != null) {
  27542. i++;
  27543. }
  27544. name += i;
  27545. }
  27546. map$$1.set(name, true);
  27547. return name;
  27548. }
  27549. /*
  27550. * Licensed to the Apache Software Foundation (ASF) under one
  27551. * or more contributor license agreements. See the NOTICE file
  27552. * distributed with this work for additional information
  27553. * regarding copyright ownership. The ASF licenses this file
  27554. * to you under the Apache License, Version 2.0 (the
  27555. * "License"); you may not use this file except in compliance
  27556. * with the License. You may obtain a copy of the License at
  27557. *
  27558. * http://www.apache.org/licenses/LICENSE-2.0
  27559. *
  27560. * Unless required by applicable law or agreed to in writing,
  27561. * software distributed under the License is distributed on an
  27562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27563. * KIND, either express or implied. See the License for the
  27564. * specific language governing permissions and limitations
  27565. * under the License.
  27566. */
  27567. /**
  27568. * Substitute `completeDimensions`.
  27569. * `completeDimensions` is to be deprecated.
  27570. */
  27571. /**
  27572. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27573. * @param {Object|Array} [opt]
  27574. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27575. * @param {number} [opt.dimensionsCount]
  27576. * @param {string} [opt.generateCoord]
  27577. * @param {string} [opt.generateCoordCount]
  27578. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27579. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27580. * @return {Array.<Object>} dimensionsInfo
  27581. */
  27582. var createDimensions = function (source, opt) {
  27583. opt = opt || {};
  27584. return completeDimensions(opt.coordDimensions || [], source, {
  27585. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  27586. encodeDef: opt.encodeDefine || source.encodeDefine,
  27587. dimCount: opt.dimensionsCount,
  27588. generateCoord: opt.generateCoord,
  27589. generateCoordCount: opt.generateCoordCount
  27590. });
  27591. };
  27592. /*
  27593. * Licensed to the Apache Software Foundation (ASF) under one
  27594. * or more contributor license agreements. See the NOTICE file
  27595. * distributed with this work for additional information
  27596. * regarding copyright ownership. The ASF licenses this file
  27597. * to you under the Apache License, Version 2.0 (the
  27598. * "License"); you may not use this file except in compliance
  27599. * with the License. You may obtain a copy of the License at
  27600. *
  27601. * http://www.apache.org/licenses/LICENSE-2.0
  27602. *
  27603. * Unless required by applicable law or agreed to in writing,
  27604. * software distributed under the License is distributed on an
  27605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27606. * KIND, either express or implied. See the License for the
  27607. * specific language governing permissions and limitations
  27608. * under the License.
  27609. */
  27610. /**
  27611. * Note that it is too complicated to support 3d stack by value
  27612. * (have to create two-dimension inverted index), so in 3d case
  27613. * we just support that stacked by index.
  27614. *
  27615. * @param {module:echarts/model/Series} seriesModel
  27616. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  27617. * The input dimensionInfoList will be modified.
  27618. * @param {Object} [opt]
  27619. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  27620. * @param {boolean} [opt.byIndex=false]
  27621. * @return {Object} calculationInfo
  27622. * {
  27623. * stackedDimension: string
  27624. * stackedByDimension: string
  27625. * isStackedByIndex: boolean
  27626. * stackedOverDimension: string
  27627. * stackResultDimension: string
  27628. * }
  27629. */
  27630. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  27631. opt = opt || {};
  27632. var byIndex = opt.byIndex;
  27633. var stackedCoordDimension = opt.stackedCoordDimension;
  27634. // Compatibal: when `stack` is set as '', do not stack.
  27635. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  27636. var stackedByDimInfo;
  27637. var stackedDimInfo;
  27638. var stackResultDimension;
  27639. var stackedOverDimension;
  27640. each$1(dimensionInfoList, function (dimensionInfo, index) {
  27641. if (isString(dimensionInfo)) {
  27642. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  27643. }
  27644. if (mayStack && !dimensionInfo.isExtraCoord) {
  27645. // Find the first ordinal dimension as the stackedByDimInfo.
  27646. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  27647. stackedByDimInfo = dimensionInfo;
  27648. }
  27649. // Find the first stackable dimension as the stackedDimInfo.
  27650. if (!stackedDimInfo
  27651. && dimensionInfo.type !== 'ordinal'
  27652. && dimensionInfo.type !== 'time'
  27653. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27654. ) {
  27655. stackedDimInfo = dimensionInfo;
  27656. }
  27657. }
  27658. });
  27659. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27660. // Compatible with previous design, value axis (time axis) only stack by index.
  27661. // It may make sense if the user provides elaborately constructed data.
  27662. byIndex = true;
  27663. }
  27664. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27665. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27666. // might not be a good way.
  27667. if (stackedDimInfo) {
  27668. // Use a weird name that not duplicated with other names.
  27669. stackResultDimension = '__\0ecstackresult';
  27670. stackedOverDimension = '__\0ecstackedover';
  27671. // Create inverted index to fast query index by value.
  27672. if (stackedByDimInfo) {
  27673. stackedByDimInfo.createInvertedIndices = true;
  27674. }
  27675. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27676. var stackedDimType = stackedDimInfo.type;
  27677. var stackedDimCoordIndex = 0;
  27678. each$1(dimensionInfoList, function (dimensionInfo) {
  27679. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27680. stackedDimCoordIndex++;
  27681. }
  27682. });
  27683. dimensionInfoList.push({
  27684. name: stackResultDimension,
  27685. coordDim: stackedDimCoordDim,
  27686. coordDimIndex: stackedDimCoordIndex,
  27687. type: stackedDimType,
  27688. isExtraCoord: true,
  27689. isCalculationCoord: true
  27690. });
  27691. stackedDimCoordIndex++;
  27692. dimensionInfoList.push({
  27693. name: stackedOverDimension,
  27694. // This dimension contains stack base (generally, 0), so do not set it as
  27695. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27696. coordDim: stackedOverDimension,
  27697. coordDimIndex: stackedDimCoordIndex,
  27698. type: stackedDimType,
  27699. isExtraCoord: true,
  27700. isCalculationCoord: true
  27701. });
  27702. }
  27703. return {
  27704. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27705. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27706. isStackedByIndex: byIndex,
  27707. stackedOverDimension: stackedOverDimension,
  27708. stackResultDimension: stackResultDimension
  27709. };
  27710. }
  27711. /**
  27712. * @param {module:echarts/data/List} data
  27713. * @param {string} stackedDim
  27714. */
  27715. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27716. // Each single series only maps to one pair of axis. So we do not need to
  27717. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27718. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27719. // && (
  27720. // stackedByDim != null
  27721. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27722. // : data.getCalculationInfo('isStackedByIndex')
  27723. // );
  27724. }
  27725. /**
  27726. * @param {module:echarts/data/List} data
  27727. * @param {string} targetDim
  27728. * @param {string} [stackedByDim] If not input this parameter, check whether
  27729. * stacked by index.
  27730. * @return {string} dimension
  27731. */
  27732. function getStackedDimension(data, targetDim) {
  27733. return isDimensionStacked(data, targetDim)
  27734. ? data.getCalculationInfo('stackResultDimension')
  27735. : targetDim;
  27736. }
  27737. /*
  27738. * Licensed to the Apache Software Foundation (ASF) under one
  27739. * or more contributor license agreements. See the NOTICE file
  27740. * distributed with this work for additional information
  27741. * regarding copyright ownership. The ASF licenses this file
  27742. * to you under the Apache License, Version 2.0 (the
  27743. * "License"); you may not use this file except in compliance
  27744. * with the License. You may obtain a copy of the License at
  27745. *
  27746. * http://www.apache.org/licenses/LICENSE-2.0
  27747. *
  27748. * Unless required by applicable law or agreed to in writing,
  27749. * software distributed under the License is distributed on an
  27750. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27751. * KIND, either express or implied. See the License for the
  27752. * specific language governing permissions and limitations
  27753. * under the License.
  27754. */
  27755. /**
  27756. * @param {module:echarts/data/Source|Array} source Or raw data.
  27757. * @param {module:echarts/model/Series} seriesModel
  27758. * @param {Object} [opt]
  27759. * @param {string} [opt.generateCoord]
  27760. */
  27761. function createListFromArray(source, seriesModel, opt) {
  27762. opt = opt || {};
  27763. if (!Source.isInstance(source)) {
  27764. source = Source.seriesDataToSource(source);
  27765. }
  27766. var coordSysName = seriesModel.get('coordinateSystem');
  27767. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27768. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27769. var coordSysDimDefs;
  27770. if (coordSysDefine) {
  27771. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27772. var dimInfo = {name: dim};
  27773. var axisModel = coordSysDefine.axisMap.get(dim);
  27774. if (axisModel) {
  27775. var axisType = axisModel.get('type');
  27776. dimInfo.type = getDimensionTypeByAxis(axisType);
  27777. // dimInfo.stackable = isStackable(axisType);
  27778. }
  27779. return dimInfo;
  27780. });
  27781. }
  27782. if (!coordSysDimDefs) {
  27783. // Get dimensions from registered coordinate system
  27784. coordSysDimDefs = (registeredCoordSys && (
  27785. registeredCoordSys.getDimensionsInfo
  27786. ? registeredCoordSys.getDimensionsInfo()
  27787. : registeredCoordSys.dimensions.slice()
  27788. )) || ['x', 'y'];
  27789. }
  27790. var dimInfoList = createDimensions(source, {
  27791. coordDimensions: coordSysDimDefs,
  27792. generateCoord: opt.generateCoord
  27793. });
  27794. var firstCategoryDimIndex;
  27795. var hasNameEncode;
  27796. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27797. var coordDim = dimInfo.coordDim;
  27798. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27799. if (categoryAxisModel) {
  27800. if (firstCategoryDimIndex == null) {
  27801. firstCategoryDimIndex = dimIndex;
  27802. }
  27803. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27804. }
  27805. if (dimInfo.otherDims.itemName != null) {
  27806. hasNameEncode = true;
  27807. }
  27808. });
  27809. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27810. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27811. }
  27812. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27813. var list = new List(dimInfoList, seriesModel);
  27814. list.setCalculationInfo(stackCalculationInfo);
  27815. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27816. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27817. // Use dataIndex as ordinal value in categoryAxis
  27818. return dimIndex === firstCategoryDimIndex
  27819. ? dataIndex
  27820. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27821. }
  27822. : null;
  27823. list.hasItemOption = false;
  27824. list.initData(source, null, dimValueGetter);
  27825. return list;
  27826. }
  27827. function isNeedCompleteOrdinalData(source) {
  27828. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27829. var sampleItem = firstDataNotNull(source.data || []);
  27830. return sampleItem != null
  27831. && !isArray(getDataItemValue(sampleItem));
  27832. }
  27833. }
  27834. function firstDataNotNull(data) {
  27835. var i = 0;
  27836. while (i < data.length && data[i] == null) {
  27837. i++;
  27838. }
  27839. return data[i];
  27840. }
  27841. /*
  27842. * Licensed to the Apache Software Foundation (ASF) under one
  27843. * or more contributor license agreements. See the NOTICE file
  27844. * distributed with this work for additional information
  27845. * regarding copyright ownership. The ASF licenses this file
  27846. * to you under the Apache License, Version 2.0 (the
  27847. * "License"); you may not use this file except in compliance
  27848. * with the License. You may obtain a copy of the License at
  27849. *
  27850. * http://www.apache.org/licenses/LICENSE-2.0
  27851. *
  27852. * Unless required by applicable law or agreed to in writing,
  27853. * software distributed under the License is distributed on an
  27854. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27855. * KIND, either express or implied. See the License for the
  27856. * specific language governing permissions and limitations
  27857. * under the License.
  27858. */
  27859. /**
  27860. * // Scale class management
  27861. * @module echarts/scale/Scale
  27862. */
  27863. /**
  27864. * @param {Object} [setting]
  27865. */
  27866. function Scale(setting) {
  27867. this._setting = setting || {};
  27868. /**
  27869. * Extent
  27870. * @type {Array.<number>}
  27871. * @protected
  27872. */
  27873. this._extent = [Infinity, -Infinity];
  27874. /**
  27875. * Step is calculated in adjustExtent
  27876. * @type {Array.<number>}
  27877. * @protected
  27878. */
  27879. this._interval = 0;
  27880. this.init && this.init.apply(this, arguments);
  27881. }
  27882. /**
  27883. * Parse input val to valid inner number.
  27884. * @param {*} val
  27885. * @return {number}
  27886. */
  27887. Scale.prototype.parse = function (val) {
  27888. // Notice: This would be a trap here, If the implementation
  27889. // of this method depends on extent, and this method is used
  27890. // before extent set (like in dataZoom), it would be wrong.
  27891. // Nevertheless, parse does not depend on extent generally.
  27892. return val;
  27893. };
  27894. Scale.prototype.getSetting = function (name) {
  27895. return this._setting[name];
  27896. };
  27897. Scale.prototype.contain = function (val) {
  27898. var extent = this._extent;
  27899. return val >= extent[0] && val <= extent[1];
  27900. };
  27901. /**
  27902. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  27903. * @param {number} val
  27904. * @return {number}
  27905. */
  27906. Scale.prototype.normalize = function (val) {
  27907. var extent = this._extent;
  27908. if (extent[1] === extent[0]) {
  27909. return 0.5;
  27910. }
  27911. return (val - extent[0]) / (extent[1] - extent[0]);
  27912. };
  27913. /**
  27914. * Scale normalized value
  27915. * @param {number} val
  27916. * @return {number}
  27917. */
  27918. Scale.prototype.scale = function (val) {
  27919. var extent = this._extent;
  27920. return val * (extent[1] - extent[0]) + extent[0];
  27921. };
  27922. /**
  27923. * Set extent from data
  27924. * @param {Array.<number>} other
  27925. */
  27926. Scale.prototype.unionExtent = function (other) {
  27927. var extent = this._extent;
  27928. other[0] < extent[0] && (extent[0] = other[0]);
  27929. other[1] > extent[1] && (extent[1] = other[1]);
  27930. // not setExtent because in log axis it may transformed to power
  27931. // this.setExtent(extent[0], extent[1]);
  27932. };
  27933. /**
  27934. * Set extent from data
  27935. * @param {module:echarts/data/List} data
  27936. * @param {string} dim
  27937. */
  27938. Scale.prototype.unionExtentFromData = function (data, dim) {
  27939. this.unionExtent(data.getApproximateExtent(dim));
  27940. };
  27941. /**
  27942. * Get extent
  27943. * @return {Array.<number>}
  27944. */
  27945. Scale.prototype.getExtent = function () {
  27946. return this._extent.slice();
  27947. };
  27948. /**
  27949. * Set extent
  27950. * @param {number} start
  27951. * @param {number} end
  27952. */
  27953. Scale.prototype.setExtent = function (start, end) {
  27954. var thisExtent = this._extent;
  27955. if (!isNaN(start)) {
  27956. thisExtent[0] = start;
  27957. }
  27958. if (!isNaN(end)) {
  27959. thisExtent[1] = end;
  27960. }
  27961. };
  27962. /**
  27963. * When axis extent depends on data and no data exists,
  27964. * axis ticks should not be drawn, which is named 'blank'.
  27965. */
  27966. Scale.prototype.isBlank = function () {
  27967. return this._isBlank;
  27968. },
  27969. /**
  27970. * When axis extent depends on data and no data exists,
  27971. * axis ticks should not be drawn, which is named 'blank'.
  27972. */
  27973. Scale.prototype.setBlank = function (isBlank) {
  27974. this._isBlank = isBlank;
  27975. };
  27976. /**
  27977. * @abstract
  27978. * @param {*} tick
  27979. * @return {string} label of the tick.
  27980. */
  27981. Scale.prototype.getLabel = null;
  27982. enableClassExtend(Scale);
  27983. enableClassManagement(Scale, {
  27984. registerWhenExtend: true
  27985. });
  27986. /*
  27987. * Licensed to the Apache Software Foundation (ASF) under one
  27988. * or more contributor license agreements. See the NOTICE file
  27989. * distributed with this work for additional information
  27990. * regarding copyright ownership. The ASF licenses this file
  27991. * to you under the Apache License, Version 2.0 (the
  27992. * "License"); you may not use this file except in compliance
  27993. * with the License. You may obtain a copy of the License at
  27994. *
  27995. * http://www.apache.org/licenses/LICENSE-2.0
  27996. *
  27997. * Unless required by applicable law or agreed to in writing,
  27998. * software distributed under the License is distributed on an
  27999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28000. * KIND, either express or implied. See the License for the
  28001. * specific language governing permissions and limitations
  28002. * under the License.
  28003. */
  28004. /**
  28005. * @constructor
  28006. * @param {Object} [opt]
  28007. * @param {Object} [opt.categories=[]]
  28008. * @param {Object} [opt.needCollect=false]
  28009. * @param {Object} [opt.deduplication=false]
  28010. */
  28011. function OrdinalMeta(opt) {
  28012. /**
  28013. * @readOnly
  28014. * @type {Array.<string>}
  28015. */
  28016. this.categories = opt.categories || [];
  28017. /**
  28018. * @private
  28019. * @type {boolean}
  28020. */
  28021. this._needCollect = opt.needCollect;
  28022. /**
  28023. * @private
  28024. * @type {boolean}
  28025. */
  28026. this._deduplication = opt.deduplication;
  28027. /**
  28028. * @private
  28029. * @type {boolean}
  28030. */
  28031. this._map;
  28032. }
  28033. /**
  28034. * @param {module:echarts/model/Model} axisModel
  28035. * @return {module:echarts/data/OrdinalMeta}
  28036. */
  28037. OrdinalMeta.createByAxisModel = function (axisModel) {
  28038. var option = axisModel.option;
  28039. var data = option.data;
  28040. var categories = data && map(data, getName);
  28041. return new OrdinalMeta({
  28042. categories: categories,
  28043. needCollect: !categories,
  28044. // deduplication is default in axis.
  28045. deduplication: option.dedplication !== false
  28046. });
  28047. };
  28048. var proto$1 = OrdinalMeta.prototype;
  28049. /**
  28050. * @param {string} category
  28051. * @return {number} ordinal
  28052. */
  28053. proto$1.getOrdinal = function (category) {
  28054. return getOrCreateMap(this).get(category);
  28055. };
  28056. /**
  28057. * @param {*} category
  28058. * @return {number} The ordinal. If not found, return NaN.
  28059. */
  28060. proto$1.parseAndCollect = function (category) {
  28061. var index;
  28062. var needCollect = this._needCollect;
  28063. // The value of category dim can be the index of the given category set.
  28064. // This feature is only supported when !needCollect, because we should
  28065. // consider a common case: a value is 2017, which is a number but is
  28066. // expected to be tread as a category. This case usually happen in dataset,
  28067. // where it happent to be no need of the index feature.
  28068. if (typeof category !== 'string' && !needCollect) {
  28069. return category;
  28070. }
  28071. // Optimize for the scenario:
  28072. // category is ['2012-01-01', '2012-01-02', ...], where the input
  28073. // data has been ensured not duplicate and is large data.
  28074. // Notice, if a dataset dimension provide categroies, usually echarts
  28075. // should remove duplication except user tell echarts dont do that
  28076. // (set axis.deduplication = false), because echarts do not know whether
  28077. // the values in the category dimension has duplication (consider the
  28078. // parallel-aqi example)
  28079. if (needCollect && !this._deduplication) {
  28080. index = this.categories.length;
  28081. this.categories[index] = category;
  28082. return index;
  28083. }
  28084. var map$$1 = getOrCreateMap(this);
  28085. index = map$$1.get(category);
  28086. if (index == null) {
  28087. if (needCollect) {
  28088. index = this.categories.length;
  28089. this.categories[index] = category;
  28090. map$$1.set(category, index);
  28091. }
  28092. else {
  28093. index = NaN;
  28094. }
  28095. }
  28096. return index;
  28097. };
  28098. // Consider big data, do not create map until needed.
  28099. function getOrCreateMap(ordinalMeta) {
  28100. return ordinalMeta._map || (
  28101. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  28102. );
  28103. }
  28104. function getName(obj) {
  28105. if (isObject$1(obj) && obj.value != null) {
  28106. return obj.value;
  28107. }
  28108. else {
  28109. return obj + '';
  28110. }
  28111. }
  28112. /*
  28113. * Licensed to the Apache Software Foundation (ASF) under one
  28114. * or more contributor license agreements. See the NOTICE file
  28115. * distributed with this work for additional information
  28116. * regarding copyright ownership. The ASF licenses this file
  28117. * to you under the Apache License, Version 2.0 (the
  28118. * "License"); you may not use this file except in compliance
  28119. * with the License. You may obtain a copy of the License at
  28120. *
  28121. * http://www.apache.org/licenses/LICENSE-2.0
  28122. *
  28123. * Unless required by applicable law or agreed to in writing,
  28124. * software distributed under the License is distributed on an
  28125. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28126. * KIND, either express or implied. See the License for the
  28127. * specific language governing permissions and limitations
  28128. * under the License.
  28129. */
  28130. /**
  28131. * Linear continuous scale
  28132. * @module echarts/coord/scale/Ordinal
  28133. *
  28134. * http://en.wikipedia.org/wiki/Level_of_measurement
  28135. */
  28136. // FIXME only one data
  28137. var scaleProto = Scale.prototype;
  28138. var OrdinalScale = Scale.extend({
  28139. type: 'ordinal',
  28140. /**
  28141. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  28142. */
  28143. init: function (ordinalMeta, extent) {
  28144. // Caution: Should not use instanceof, consider ec-extensions using
  28145. // import approach to get OrdinalMeta class.
  28146. if (!ordinalMeta || isArray(ordinalMeta)) {
  28147. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  28148. }
  28149. this._ordinalMeta = ordinalMeta;
  28150. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  28151. },
  28152. parse: function (val) {
  28153. return typeof val === 'string'
  28154. ? this._ordinalMeta.getOrdinal(val)
  28155. // val might be float.
  28156. : Math.round(val);
  28157. },
  28158. contain: function (rank) {
  28159. rank = this.parse(rank);
  28160. return scaleProto.contain.call(this, rank)
  28161. && this._ordinalMeta.categories[rank] != null;
  28162. },
  28163. /**
  28164. * Normalize given rank or name to linear [0, 1]
  28165. * @param {number|string} [val]
  28166. * @return {number}
  28167. */
  28168. normalize: function (val) {
  28169. return scaleProto.normalize.call(this, this.parse(val));
  28170. },
  28171. scale: function (val) {
  28172. return Math.round(scaleProto.scale.call(this, val));
  28173. },
  28174. /**
  28175. * @return {Array}
  28176. */
  28177. getTicks: function () {
  28178. var ticks = [];
  28179. var extent = this._extent;
  28180. var rank = extent[0];
  28181. while (rank <= extent[1]) {
  28182. ticks.push(rank);
  28183. rank++;
  28184. }
  28185. return ticks;
  28186. },
  28187. /**
  28188. * Get item on rank n
  28189. * @param {number} n
  28190. * @return {string}
  28191. */
  28192. getLabel: function (n) {
  28193. if (!this.isBlank()) {
  28194. // Note that if no data, ordinalMeta.categories is an empty array.
  28195. return this._ordinalMeta.categories[n];
  28196. }
  28197. },
  28198. /**
  28199. * @return {number}
  28200. */
  28201. count: function () {
  28202. return this._extent[1] - this._extent[0] + 1;
  28203. },
  28204. /**
  28205. * @override
  28206. */
  28207. unionExtentFromData: function (data, dim) {
  28208. this.unionExtent(data.getApproximateExtent(dim));
  28209. },
  28210. getOrdinalMeta: function () {
  28211. return this._ordinalMeta;
  28212. },
  28213. niceTicks: noop,
  28214. niceExtent: noop
  28215. });
  28216. /**
  28217. * @return {module:echarts/scale/Time}
  28218. */
  28219. OrdinalScale.create = function () {
  28220. return new OrdinalScale();
  28221. };
  28222. /*
  28223. * Licensed to the Apache Software Foundation (ASF) under one
  28224. * or more contributor license agreements. See the NOTICE file
  28225. * distributed with this work for additional information
  28226. * regarding copyright ownership. The ASF licenses this file
  28227. * to you under the Apache License, Version 2.0 (the
  28228. * "License"); you may not use this file except in compliance
  28229. * with the License. You may obtain a copy of the License at
  28230. *
  28231. * http://www.apache.org/licenses/LICENSE-2.0
  28232. *
  28233. * Unless required by applicable law or agreed to in writing,
  28234. * software distributed under the License is distributed on an
  28235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28236. * KIND, either express or implied. See the License for the
  28237. * specific language governing permissions and limitations
  28238. * under the License.
  28239. */
  28240. /**
  28241. * For testable.
  28242. */
  28243. var roundNumber$1 = round$2;
  28244. /**
  28245. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  28246. * Should be extent[0] < extent[1].
  28247. * @param {number} splitNumber splitNumber should be >= 1.
  28248. * @param {number} [minInterval]
  28249. * @param {number} [maxInterval]
  28250. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  28251. */
  28252. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  28253. var result = {};
  28254. var span = extent[1] - extent[0];
  28255. var interval = result.interval = nice(span / splitNumber, true);
  28256. if (minInterval != null && interval < minInterval) {
  28257. interval = result.interval = minInterval;
  28258. }
  28259. if (maxInterval != null && interval > maxInterval) {
  28260. interval = result.interval = maxInterval;
  28261. }
  28262. // Tow more digital for tick.
  28263. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  28264. // Niced extent inside original extent
  28265. var niceTickExtent = result.niceTickExtent = [
  28266. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  28267. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  28268. ];
  28269. fixExtent(niceTickExtent, extent);
  28270. return result;
  28271. }
  28272. /**
  28273. * @param {number} interval
  28274. * @return {number} interval precision
  28275. */
  28276. function getIntervalPrecision(interval) {
  28277. // Tow more digital for tick.
  28278. return getPrecisionSafe(interval) + 2;
  28279. }
  28280. function clamp(niceTickExtent, idx, extent) {
  28281. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  28282. }
  28283. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  28284. function fixExtent(niceTickExtent, extent) {
  28285. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  28286. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  28287. clamp(niceTickExtent, 0, extent);
  28288. clamp(niceTickExtent, 1, extent);
  28289. if (niceTickExtent[0] > niceTickExtent[1]) {
  28290. niceTickExtent[0] = niceTickExtent[1];
  28291. }
  28292. }
  28293. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  28294. var ticks = [];
  28295. // If interval is 0, return [];
  28296. if (!interval) {
  28297. return ticks;
  28298. }
  28299. // Consider this case: using dataZoom toolbox, zoom and zoom.
  28300. var safeLimit = 10000;
  28301. if (extent[0] < niceTickExtent[0]) {
  28302. ticks.push(extent[0]);
  28303. }
  28304. var tick = niceTickExtent[0];
  28305. while (tick <= niceTickExtent[1]) {
  28306. ticks.push(tick);
  28307. // Avoid rounding error
  28308. tick = roundNumber$1(tick + interval, intervalPrecision);
  28309. if (tick === ticks[ticks.length - 1]) {
  28310. // Consider out of safe float point, e.g.,
  28311. // -3711126.9907707 + 2e-10 === -3711126.9907707
  28312. break;
  28313. }
  28314. if (ticks.length > safeLimit) {
  28315. return [];
  28316. }
  28317. }
  28318. // Consider this case: the last item of ticks is smaller
  28319. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  28320. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  28321. ticks.push(extent[1]);
  28322. }
  28323. return ticks;
  28324. }
  28325. /*
  28326. * Licensed to the Apache Software Foundation (ASF) under one
  28327. * or more contributor license agreements. See the NOTICE file
  28328. * distributed with this work for additional information
  28329. * regarding copyright ownership. The ASF licenses this file
  28330. * to you under the Apache License, Version 2.0 (the
  28331. * "License"); you may not use this file except in compliance
  28332. * with the License. You may obtain a copy of the License at
  28333. *
  28334. * http://www.apache.org/licenses/LICENSE-2.0
  28335. *
  28336. * Unless required by applicable law or agreed to in writing,
  28337. * software distributed under the License is distributed on an
  28338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28339. * KIND, either express or implied. See the License for the
  28340. * specific language governing permissions and limitations
  28341. * under the License.
  28342. */
  28343. /**
  28344. * Interval scale
  28345. * @module echarts/scale/Interval
  28346. */
  28347. var roundNumber = round$2;
  28348. /**
  28349. * @alias module:echarts/coord/scale/Interval
  28350. * @constructor
  28351. */
  28352. var IntervalScale = Scale.extend({
  28353. type: 'interval',
  28354. _interval: 0,
  28355. _intervalPrecision: 2,
  28356. setExtent: function (start, end) {
  28357. var thisExtent = this._extent;
  28358. //start,end may be a Number like '25',so...
  28359. if (!isNaN(start)) {
  28360. thisExtent[0] = parseFloat(start);
  28361. }
  28362. if (!isNaN(end)) {
  28363. thisExtent[1] = parseFloat(end);
  28364. }
  28365. },
  28366. unionExtent: function (other) {
  28367. var extent = this._extent;
  28368. other[0] < extent[0] && (extent[0] = other[0]);
  28369. other[1] > extent[1] && (extent[1] = other[1]);
  28370. // unionExtent may called by it's sub classes
  28371. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  28372. },
  28373. /**
  28374. * Get interval
  28375. */
  28376. getInterval: function () {
  28377. return this._interval;
  28378. },
  28379. /**
  28380. * Set interval
  28381. */
  28382. setInterval: function (interval) {
  28383. this._interval = interval;
  28384. // Dropped auto calculated niceExtent and use user setted extent
  28385. // We assume user wan't to set both interval, min, max to get a better result
  28386. this._niceExtent = this._extent.slice();
  28387. this._intervalPrecision = getIntervalPrecision(interval);
  28388. },
  28389. /**
  28390. * @return {Array.<number>}
  28391. */
  28392. getTicks: function () {
  28393. return intervalScaleGetTicks(
  28394. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  28395. );
  28396. },
  28397. /**
  28398. * @param {number} data
  28399. * @param {Object} [opt]
  28400. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  28401. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  28402. * @return {string}
  28403. */
  28404. getLabel: function (data, opt) {
  28405. if (data == null) {
  28406. return '';
  28407. }
  28408. var precision = opt && opt.precision;
  28409. if (precision == null) {
  28410. precision = getPrecisionSafe(data) || 0;
  28411. }
  28412. else if (precision === 'auto') {
  28413. // Should be more precise then tick.
  28414. precision = this._intervalPrecision;
  28415. }
  28416. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  28417. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  28418. data = roundNumber(data, precision, true);
  28419. return addCommas(data);
  28420. },
  28421. /**
  28422. * Update interval and extent of intervals for nice ticks
  28423. *
  28424. * @param {number} [splitNumber = 5] Desired number of ticks
  28425. * @param {number} [minInterval]
  28426. * @param {number} [maxInterval]
  28427. */
  28428. niceTicks: function (splitNumber, minInterval, maxInterval) {
  28429. splitNumber = splitNumber || 5;
  28430. var extent = this._extent;
  28431. var span = extent[1] - extent[0];
  28432. if (!isFinite(span)) {
  28433. return;
  28434. }
  28435. // User may set axis min 0 and data are all negative
  28436. // FIXME If it needs to reverse ?
  28437. if (span < 0) {
  28438. span = -span;
  28439. extent.reverse();
  28440. }
  28441. var result = intervalScaleNiceTicks(
  28442. extent, splitNumber, minInterval, maxInterval
  28443. );
  28444. this._intervalPrecision = result.intervalPrecision;
  28445. this._interval = result.interval;
  28446. this._niceExtent = result.niceTickExtent;
  28447. },
  28448. /**
  28449. * Nice extent.
  28450. * @param {Object} opt
  28451. * @param {number} [opt.splitNumber = 5] Given approx tick number
  28452. * @param {boolean} [opt.fixMin=false]
  28453. * @param {boolean} [opt.fixMax=false]
  28454. * @param {boolean} [opt.minInterval]
  28455. * @param {boolean} [opt.maxInterval]
  28456. */
  28457. niceExtent: function (opt) {
  28458. var extent = this._extent;
  28459. // If extent start and end are same, expand them
  28460. if (extent[0] === extent[1]) {
  28461. if (extent[0] !== 0) {
  28462. // Expand extent
  28463. var expandSize = extent[0];
  28464. // In the fowllowing case
  28465. // Axis has been fixed max 100
  28466. // Plus data are all 100 and axis extent are [100, 100].
  28467. // Extend to the both side will cause expanded max is larger than fixed max.
  28468. // So only expand to the smaller side.
  28469. if (!opt.fixMax) {
  28470. extent[1] += expandSize / 2;
  28471. extent[0] -= expandSize / 2;
  28472. }
  28473. else {
  28474. extent[0] -= expandSize / 2;
  28475. }
  28476. }
  28477. else {
  28478. extent[1] = 1;
  28479. }
  28480. }
  28481. var span = extent[1] - extent[0];
  28482. // If there are no data and extent are [Infinity, -Infinity]
  28483. if (!isFinite(span)) {
  28484. extent[0] = 0;
  28485. extent[1] = 1;
  28486. }
  28487. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28488. // var extent = this._extent;
  28489. var interval = this._interval;
  28490. if (!opt.fixMin) {
  28491. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  28492. }
  28493. if (!opt.fixMax) {
  28494. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  28495. }
  28496. }
  28497. });
  28498. /**
  28499. * @return {module:echarts/scale/Time}
  28500. */
  28501. IntervalScale.create = function () {
  28502. return new IntervalScale();
  28503. };
  28504. /*
  28505. * Licensed to the Apache Software Foundation (ASF) under one
  28506. * or more contributor license agreements. See the NOTICE file
  28507. * distributed with this work for additional information
  28508. * regarding copyright ownership. The ASF licenses this file
  28509. * to you under the Apache License, Version 2.0 (the
  28510. * "License"); you may not use this file except in compliance
  28511. * with the License. You may obtain a copy of the License at
  28512. *
  28513. * http://www.apache.org/licenses/LICENSE-2.0
  28514. *
  28515. * Unless required by applicable law or agreed to in writing,
  28516. * software distributed under the License is distributed on an
  28517. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28518. * KIND, either express or implied. See the License for the
  28519. * specific language governing permissions and limitations
  28520. * under the License.
  28521. */
  28522. /* global Float32Array */
  28523. var STACK_PREFIX = '__ec_stack_';
  28524. var LARGE_BAR_MIN_WIDTH = 0.5;
  28525. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  28526. function getSeriesStackId(seriesModel) {
  28527. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  28528. }
  28529. function getAxisKey(axis) {
  28530. return axis.dim + axis.index;
  28531. }
  28532. /**
  28533. * @param {Object} opt
  28534. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  28535. * @param {number} opt.count Positive interger.
  28536. * @param {number} [opt.barWidth]
  28537. * @param {number} [opt.barMaxWidth]
  28538. * @param {number} [opt.barGap]
  28539. * @param {number} [opt.barCategoryGap]
  28540. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  28541. */
  28542. function getLayoutOnAxis(opt) {
  28543. var params = [];
  28544. var baseAxis = opt.axis;
  28545. var axisKey = 'axis0';
  28546. if (baseAxis.type !== 'category') {
  28547. return;
  28548. }
  28549. var bandWidth = baseAxis.getBandWidth();
  28550. for (var i = 0; i < opt.count || 0; i++) {
  28551. params.push(defaults({
  28552. bandWidth: bandWidth,
  28553. axisKey: axisKey,
  28554. stackId: STACK_PREFIX + i
  28555. }, opt));
  28556. }
  28557. var widthAndOffsets = doCalBarWidthAndOffset(params);
  28558. var result = [];
  28559. for (var i = 0; i < opt.count; i++) {
  28560. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  28561. item.offsetCenter = item.offset + item.width / 2;
  28562. result.push(item);
  28563. }
  28564. return result;
  28565. }
  28566. function prepareLayoutBarSeries(seriesType, ecModel) {
  28567. var seriesModels = [];
  28568. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28569. // Check series coordinate, do layout for cartesian2d only
  28570. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  28571. seriesModels.push(seriesModel);
  28572. }
  28573. });
  28574. return seriesModels;
  28575. }
  28576. function makeColumnLayout(barSeries) {
  28577. var seriesInfoList = [];
  28578. each$1(barSeries, function (seriesModel) {
  28579. var data = seriesModel.getData();
  28580. var cartesian = seriesModel.coordinateSystem;
  28581. var baseAxis = cartesian.getBaseAxis();
  28582. var axisExtent = baseAxis.getExtent();
  28583. var bandWidth = baseAxis.type === 'category'
  28584. ? baseAxis.getBandWidth()
  28585. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  28586. var barWidth = parsePercent$1(
  28587. seriesModel.get('barWidth'), bandWidth
  28588. );
  28589. var barMaxWidth = parsePercent$1(
  28590. seriesModel.get('barMaxWidth'), bandWidth
  28591. );
  28592. var barGap = seriesModel.get('barGap');
  28593. var barCategoryGap = seriesModel.get('barCategoryGap');
  28594. seriesInfoList.push({
  28595. bandWidth: bandWidth,
  28596. barWidth: barWidth,
  28597. barMaxWidth: barMaxWidth,
  28598. barGap: barGap,
  28599. barCategoryGap: barCategoryGap,
  28600. axisKey: getAxisKey(baseAxis),
  28601. stackId: getSeriesStackId(seriesModel)
  28602. });
  28603. });
  28604. return doCalBarWidthAndOffset(seriesInfoList);
  28605. }
  28606. function doCalBarWidthAndOffset(seriesInfoList) {
  28607. // Columns info on each category axis. Key is cartesian name
  28608. var columnsMap = {};
  28609. each$1(seriesInfoList, function (seriesInfo, idx) {
  28610. var axisKey = seriesInfo.axisKey;
  28611. var bandWidth = seriesInfo.bandWidth;
  28612. var columnsOnAxis = columnsMap[axisKey] || {
  28613. bandWidth: bandWidth,
  28614. remainedWidth: bandWidth,
  28615. autoWidthCount: 0,
  28616. categoryGap: '20%',
  28617. gap: '30%',
  28618. stacks: {}
  28619. };
  28620. var stacks = columnsOnAxis.stacks;
  28621. columnsMap[axisKey] = columnsOnAxis;
  28622. var stackId = seriesInfo.stackId;
  28623. if (!stacks[stackId]) {
  28624. columnsOnAxis.autoWidthCount++;
  28625. }
  28626. stacks[stackId] = stacks[stackId] || {
  28627. width: 0,
  28628. maxWidth: 0
  28629. };
  28630. // Caution: In a single coordinate system, these barGrid attributes
  28631. // will be shared by series. Consider that they have default values,
  28632. // only the attributes set on the last series will work.
  28633. // Do not change this fact unless there will be a break change.
  28634. // TODO
  28635. var barWidth = seriesInfo.barWidth;
  28636. if (barWidth && !stacks[stackId].width) {
  28637. // See #6312, do not restrict width.
  28638. stacks[stackId].width = barWidth;
  28639. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  28640. columnsOnAxis.remainedWidth -= barWidth;
  28641. }
  28642. var barMaxWidth = seriesInfo.barMaxWidth;
  28643. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  28644. var barGap = seriesInfo.barGap;
  28645. (barGap != null) && (columnsOnAxis.gap = barGap);
  28646. var barCategoryGap = seriesInfo.barCategoryGap;
  28647. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  28648. });
  28649. var result = {};
  28650. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  28651. result[coordSysName] = {};
  28652. var stacks = columnsOnAxis.stacks;
  28653. var bandWidth = columnsOnAxis.bandWidth;
  28654. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  28655. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  28656. var remainedWidth = columnsOnAxis.remainedWidth;
  28657. var autoWidthCount = columnsOnAxis.autoWidthCount;
  28658. var autoWidth = (remainedWidth - categoryGap)
  28659. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28660. autoWidth = Math.max(autoWidth, 0);
  28661. // Find if any auto calculated bar exceeded maxBarWidth
  28662. each$1(stacks, function (column, stack) {
  28663. var maxWidth = column.maxWidth;
  28664. if (maxWidth && maxWidth < autoWidth) {
  28665. maxWidth = Math.min(maxWidth, remainedWidth);
  28666. if (column.width) {
  28667. maxWidth = Math.min(maxWidth, column.width);
  28668. }
  28669. remainedWidth -= maxWidth;
  28670. column.width = maxWidth;
  28671. autoWidthCount--;
  28672. }
  28673. });
  28674. // Recalculate width again
  28675. autoWidth = (remainedWidth - categoryGap)
  28676. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28677. autoWidth = Math.max(autoWidth, 0);
  28678. var widthSum = 0;
  28679. var lastColumn;
  28680. each$1(stacks, function (column, idx) {
  28681. if (!column.width) {
  28682. column.width = autoWidth;
  28683. }
  28684. lastColumn = column;
  28685. widthSum += column.width * (1 + barGapPercent);
  28686. });
  28687. if (lastColumn) {
  28688. widthSum -= lastColumn.width * barGapPercent;
  28689. }
  28690. var offset = -widthSum / 2;
  28691. each$1(stacks, function (column, stackId) {
  28692. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  28693. offset: offset,
  28694. width: column.width
  28695. };
  28696. offset += column.width * (1 + barGapPercent);
  28697. });
  28698. });
  28699. return result;
  28700. }
  28701. /**
  28702. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  28703. * @param {module:echarts/coord/Axis} axis
  28704. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  28705. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  28706. */
  28707. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  28708. if (barWidthAndOffset && axis) {
  28709. var result = barWidthAndOffset[getAxisKey(axis)];
  28710. if (result != null && seriesModel != null) {
  28711. result = result[getSeriesStackId(seriesModel)];
  28712. }
  28713. return result;
  28714. }
  28715. }
  28716. /**
  28717. * @param {string} seriesType
  28718. * @param {module:echarts/model/Global} ecModel
  28719. */
  28720. function layout(seriesType, ecModel) {
  28721. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  28722. var barWidthAndOffset = makeColumnLayout(seriesModels);
  28723. var lastStackCoords = {};
  28724. each$1(seriesModels, function (seriesModel) {
  28725. var data = seriesModel.getData();
  28726. var cartesian = seriesModel.coordinateSystem;
  28727. var baseAxis = cartesian.getBaseAxis();
  28728. var stackId = getSeriesStackId(seriesModel);
  28729. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  28730. var columnOffset = columnLayoutInfo.offset;
  28731. var columnWidth = columnLayoutInfo.width;
  28732. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28733. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  28734. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  28735. data.setLayout({
  28736. offset: columnOffset,
  28737. size: columnWidth
  28738. });
  28739. var valueDim = data.mapDimension(valueAxis.dim);
  28740. var baseDim = data.mapDimension(baseAxis.dim);
  28741. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  28742. var isValueAxisH = valueAxis.isHorizontal();
  28743. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  28744. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28745. var value = data.get(valueDim, idx);
  28746. var baseValue = data.get(baseDim, idx);
  28747. if (isNaN(value)) {
  28748. continue;
  28749. }
  28750. var sign = value >= 0 ? 'p' : 'n';
  28751. var baseCoord = valueAxisStart;
  28752. // Because of the barMinHeight, we can not use the value in
  28753. // stackResultDimension directly.
  28754. if (stacked) {
  28755. // Only ordinal axis can be stacked.
  28756. if (!lastStackCoords[stackId][baseValue]) {
  28757. lastStackCoords[stackId][baseValue] = {
  28758. p: valueAxisStart, // Positive stack
  28759. n: valueAxisStart // Negative stack
  28760. };
  28761. }
  28762. // Should also consider #4243
  28763. baseCoord = lastStackCoords[stackId][baseValue][sign];
  28764. }
  28765. var x;
  28766. var y;
  28767. var width;
  28768. var height;
  28769. if (isValueAxisH) {
  28770. var coord = cartesian.dataToPoint([value, baseValue]);
  28771. x = baseCoord;
  28772. y = coord[1] + columnOffset;
  28773. width = coord[0] - valueAxisStart;
  28774. height = columnWidth;
  28775. if (Math.abs(width) < barMinHeight) {
  28776. width = (width < 0 ? -1 : 1) * barMinHeight;
  28777. }
  28778. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  28779. }
  28780. else {
  28781. var coord = cartesian.dataToPoint([baseValue, value]);
  28782. x = coord[0] + columnOffset;
  28783. y = baseCoord;
  28784. width = columnWidth;
  28785. height = coord[1] - valueAxisStart;
  28786. if (Math.abs(height) < barMinHeight) {
  28787. // Include zero to has a positive bar
  28788. height = (height <= 0 ? -1 : 1) * barMinHeight;
  28789. }
  28790. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  28791. }
  28792. data.setItemLayout(idx, {
  28793. x: x,
  28794. y: y,
  28795. width: width,
  28796. height: height
  28797. });
  28798. }
  28799. }, this);
  28800. }
  28801. // TODO: Do not support stack in large mode yet.
  28802. var largeLayout = {
  28803. seriesType: 'bar',
  28804. plan: createRenderPlanner(),
  28805. reset: function (seriesModel) {
  28806. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  28807. return;
  28808. }
  28809. var data = seriesModel.getData();
  28810. var cartesian = seriesModel.coordinateSystem;
  28811. var baseAxis = cartesian.getBaseAxis();
  28812. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28813. var valueDim = data.mapDimension(valueAxis.dim);
  28814. var baseDim = data.mapDimension(baseAxis.dim);
  28815. var valueAxisHorizontal = valueAxis.isHorizontal();
  28816. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  28817. var barWidth = retrieveColumnLayout(
  28818. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  28819. ).width;
  28820. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  28821. barWidth = LARGE_BAR_MIN_WIDTH;
  28822. }
  28823. return {progress: progress};
  28824. function progress(params, data) {
  28825. var largePoints = new LargeArr(params.count * 2);
  28826. var dataIndex;
  28827. var coord = [];
  28828. var valuePair = [];
  28829. var offset = 0;
  28830. while ((dataIndex = params.next()) != null) {
  28831. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  28832. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  28833. coord = cartesian.dataToPoint(valuePair, null, coord);
  28834. largePoints[offset++] = coord[0];
  28835. largePoints[offset++] = coord[1];
  28836. }
  28837. data.setLayout({
  28838. largePoints: largePoints,
  28839. barWidth: barWidth,
  28840. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  28841. valueAxisHorizontal: valueAxisHorizontal
  28842. });
  28843. }
  28844. }
  28845. };
  28846. function isOnCartesian(seriesModel) {
  28847. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  28848. }
  28849. function isInLargeMode(seriesModel) {
  28850. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  28851. }
  28852. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  28853. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  28854. var extent = valueAxis.getGlobalExtent();
  28855. var min;
  28856. var max;
  28857. if (extent[0] > extent[1]) {
  28858. min = extent[1];
  28859. max = extent[0];
  28860. }
  28861. else {
  28862. min = extent[0];
  28863. max = extent[1];
  28864. }
  28865. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  28866. valueStart < min && (valueStart = min);
  28867. valueStart > max && (valueStart = max);
  28868. return valueStart;
  28869. }
  28870. /*
  28871. * Licensed to the Apache Software Foundation (ASF) under one
  28872. * or more contributor license agreements. See the NOTICE file
  28873. * distributed with this work for additional information
  28874. * regarding copyright ownership. The ASF licenses this file
  28875. * to you under the Apache License, Version 2.0 (the
  28876. * "License"); you may not use this file except in compliance
  28877. * with the License. You may obtain a copy of the License at
  28878. *
  28879. * http://www.apache.org/licenses/LICENSE-2.0
  28880. *
  28881. * Unless required by applicable law or agreed to in writing,
  28882. * software distributed under the License is distributed on an
  28883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28884. * KIND, either express or implied. See the License for the
  28885. * specific language governing permissions and limitations
  28886. * under the License.
  28887. */
  28888. /*
  28889. * The `scaleLevels` references to d3.js. The use of the source
  28890. * code of this file is also subject to the terms and consitions
  28891. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  28892. */
  28893. // [About UTC and local time zone]:
  28894. // In most cases, `number.parseDate` will treat input data string as local time
  28895. // (except time zone is specified in time string). And `format.formateTime` returns
  28896. // local time by default. option.useUTC is false by default. This design have
  28897. // concidered these common case:
  28898. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  28899. // in local time by default.
  28900. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  28901. // as its original time, without any time difference.
  28902. var intervalScaleProto = IntervalScale.prototype;
  28903. var mathCeil = Math.ceil;
  28904. var mathFloor = Math.floor;
  28905. var ONE_SECOND = 1000;
  28906. var ONE_MINUTE = ONE_SECOND * 60;
  28907. var ONE_HOUR = ONE_MINUTE * 60;
  28908. var ONE_DAY = ONE_HOUR * 24;
  28909. // FIXME 公用?
  28910. var bisect = function (a, x, lo, hi) {
  28911. while (lo < hi) {
  28912. var mid = lo + hi >>> 1;
  28913. if (a[mid][1] < x) {
  28914. lo = mid + 1;
  28915. }
  28916. else {
  28917. hi = mid;
  28918. }
  28919. }
  28920. return lo;
  28921. };
  28922. /**
  28923. * @alias module:echarts/coord/scale/Time
  28924. * @constructor
  28925. */
  28926. var TimeScale = IntervalScale.extend({
  28927. type: 'time',
  28928. /**
  28929. * @override
  28930. */
  28931. getLabel: function (val) {
  28932. var stepLvl = this._stepLvl;
  28933. var date = new Date(val);
  28934. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  28935. },
  28936. /**
  28937. * @override
  28938. */
  28939. niceExtent: function (opt) {
  28940. var extent = this._extent;
  28941. // If extent start and end are same, expand them
  28942. if (extent[0] === extent[1]) {
  28943. // Expand extent
  28944. extent[0] -= ONE_DAY;
  28945. extent[1] += ONE_DAY;
  28946. }
  28947. // If there are no data and extent are [Infinity, -Infinity]
  28948. if (extent[1] === -Infinity && extent[0] === Infinity) {
  28949. var d = new Date();
  28950. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  28951. extent[0] = extent[1] - ONE_DAY;
  28952. }
  28953. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28954. // var extent = this._extent;
  28955. var interval = this._interval;
  28956. if (!opt.fixMin) {
  28957. extent[0] = round$2(mathFloor(extent[0] / interval) * interval);
  28958. }
  28959. if (!opt.fixMax) {
  28960. extent[1] = round$2(mathCeil(extent[1] / interval) * interval);
  28961. }
  28962. },
  28963. /**
  28964. * @override
  28965. */
  28966. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  28967. approxTickNum = approxTickNum || 10;
  28968. var extent = this._extent;
  28969. var span = extent[1] - extent[0];
  28970. var approxInterval = span / approxTickNum;
  28971. if (minInterval != null && approxInterval < minInterval) {
  28972. approxInterval = minInterval;
  28973. }
  28974. if (maxInterval != null && approxInterval > maxInterval) {
  28975. approxInterval = maxInterval;
  28976. }
  28977. var scaleLevelsLen = scaleLevels.length;
  28978. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  28979. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  28980. var interval = level[1];
  28981. // Same with interval scale if span is much larger than 1 year
  28982. if (level[0] === 'year') {
  28983. var yearSpan = span / interval;
  28984. // From "Nice Numbers for Graph Labels" of Graphic Gems
  28985. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  28986. var yearStep = nice(yearSpan / approxTickNum, true);
  28987. interval *= yearStep;
  28988. }
  28989. var timezoneOffset = this.getSetting('useUTC')
  28990. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  28991. var niceExtent = [
  28992. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  28993. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  28994. ];
  28995. fixExtent(niceExtent, extent);
  28996. this._stepLvl = level;
  28997. // Interval will be used in getTicks
  28998. this._interval = interval;
  28999. this._niceExtent = niceExtent;
  29000. },
  29001. parse: function (val) {
  29002. // val might be float.
  29003. return +parseDate(val);
  29004. }
  29005. });
  29006. each$1(['contain', 'normalize'], function (methodName) {
  29007. TimeScale.prototype[methodName] = function (val) {
  29008. return intervalScaleProto[methodName].call(this, this.parse(val));
  29009. };
  29010. });
  29011. // Steps from d3, see the license statement at the top of this file.
  29012. var scaleLevels = [
  29013. // Format interval
  29014. ['hh:mm:ss', ONE_SECOND], // 1s
  29015. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  29016. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  29017. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  29018. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  29019. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  29020. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  29021. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  29022. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  29023. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  29024. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  29025. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  29026. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  29027. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  29028. ['MM-dd\nyyyy', ONE_DAY], // 1d
  29029. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  29030. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  29031. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  29032. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  29033. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  29034. ['week', ONE_DAY * 7], // 7d
  29035. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  29036. ['week', ONE_DAY * 14], // 2w
  29037. ['week', ONE_DAY * 21], // 3w
  29038. ['month', ONE_DAY * 31], // 1M
  29039. ['week', ONE_DAY * 42], // 6w
  29040. ['month', ONE_DAY * 62], // 2M
  29041. ['week', ONE_DAY * 70], // 10w
  29042. ['quarter', ONE_DAY * 95], // 3M
  29043. ['month', ONE_DAY * 31 * 4], // 4M
  29044. ['month', ONE_DAY * 31 * 5], // 5M
  29045. ['half-year', ONE_DAY * 380 / 2], // 6M
  29046. ['month', ONE_DAY * 31 * 8], // 8M
  29047. ['month', ONE_DAY * 31 * 10], // 10M
  29048. ['year', ONE_DAY * 380] // 1Y
  29049. ];
  29050. /**
  29051. * @param {module:echarts/model/Model}
  29052. * @return {module:echarts/scale/Time}
  29053. */
  29054. TimeScale.create = function (model) {
  29055. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  29056. };
  29057. /*
  29058. * Licensed to the Apache Software Foundation (ASF) under one
  29059. * or more contributor license agreements. See the NOTICE file
  29060. * distributed with this work for additional information
  29061. * regarding copyright ownership. The ASF licenses this file
  29062. * to you under the Apache License, Version 2.0 (the
  29063. * "License"); you may not use this file except in compliance
  29064. * with the License. You may obtain a copy of the License at
  29065. *
  29066. * http://www.apache.org/licenses/LICENSE-2.0
  29067. *
  29068. * Unless required by applicable law or agreed to in writing,
  29069. * software distributed under the License is distributed on an
  29070. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29071. * KIND, either express or implied. See the License for the
  29072. * specific language governing permissions and limitations
  29073. * under the License.
  29074. */
  29075. /**
  29076. * Log scale
  29077. * @module echarts/scale/Log
  29078. */
  29079. // Use some method of IntervalScale
  29080. var scaleProto$1 = Scale.prototype;
  29081. var intervalScaleProto$1 = IntervalScale.prototype;
  29082. var getPrecisionSafe$1 = getPrecisionSafe;
  29083. var roundingErrorFix = round$2;
  29084. var mathFloor$1 = Math.floor;
  29085. var mathCeil$1 = Math.ceil;
  29086. var mathPow$1 = Math.pow;
  29087. var mathLog = Math.log;
  29088. var LogScale = Scale.extend({
  29089. type: 'log',
  29090. base: 10,
  29091. $constructor: function () {
  29092. Scale.apply(this, arguments);
  29093. this._originalScale = new IntervalScale();
  29094. },
  29095. /**
  29096. * @return {Array.<number>}
  29097. */
  29098. getTicks: function () {
  29099. var originalScale = this._originalScale;
  29100. var extent = this._extent;
  29101. var originalExtent = originalScale.getExtent();
  29102. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  29103. var powVal = round$2(mathPow$1(this.base, val));
  29104. // Fix #4158
  29105. powVal = (val === extent[0] && originalScale.__fixMin)
  29106. ? fixRoundingError(powVal, originalExtent[0])
  29107. : powVal;
  29108. powVal = (val === extent[1] && originalScale.__fixMax)
  29109. ? fixRoundingError(powVal, originalExtent[1])
  29110. : powVal;
  29111. return powVal;
  29112. }, this);
  29113. },
  29114. /**
  29115. * @param {number} val
  29116. * @return {string}
  29117. */
  29118. getLabel: intervalScaleProto$1.getLabel,
  29119. /**
  29120. * @param {number} val
  29121. * @return {number}
  29122. */
  29123. scale: function (val) {
  29124. val = scaleProto$1.scale.call(this, val);
  29125. return mathPow$1(this.base, val);
  29126. },
  29127. /**
  29128. * @param {number} start
  29129. * @param {number} end
  29130. */
  29131. setExtent: function (start, end) {
  29132. var base = this.base;
  29133. start = mathLog(start) / mathLog(base);
  29134. end = mathLog(end) / mathLog(base);
  29135. intervalScaleProto$1.setExtent.call(this, start, end);
  29136. },
  29137. /**
  29138. * @return {number} end
  29139. */
  29140. getExtent: function () {
  29141. var base = this.base;
  29142. var extent = scaleProto$1.getExtent.call(this);
  29143. extent[0] = mathPow$1(base, extent[0]);
  29144. extent[1] = mathPow$1(base, extent[1]);
  29145. // Fix #4158
  29146. var originalScale = this._originalScale;
  29147. var originalExtent = originalScale.getExtent();
  29148. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  29149. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  29150. return extent;
  29151. },
  29152. /**
  29153. * @param {Array.<number>} extent
  29154. */
  29155. unionExtent: function (extent) {
  29156. this._originalScale.unionExtent(extent);
  29157. var base = this.base;
  29158. extent[0] = mathLog(extent[0]) / mathLog(base);
  29159. extent[1] = mathLog(extent[1]) / mathLog(base);
  29160. scaleProto$1.unionExtent.call(this, extent);
  29161. },
  29162. /**
  29163. * @override
  29164. */
  29165. unionExtentFromData: function (data, dim) {
  29166. // TODO
  29167. // filter value that <= 0
  29168. this.unionExtent(data.getApproximateExtent(dim));
  29169. },
  29170. /**
  29171. * Update interval and extent of intervals for nice ticks
  29172. * @param {number} [approxTickNum = 10] Given approx tick number
  29173. */
  29174. niceTicks: function (approxTickNum) {
  29175. approxTickNum = approxTickNum || 10;
  29176. var extent = this._extent;
  29177. var span = extent[1] - extent[0];
  29178. if (span === Infinity || span <= 0) {
  29179. return;
  29180. }
  29181. var interval = quantity(span);
  29182. var err = approxTickNum / span * interval;
  29183. // Filter ticks to get closer to the desired count.
  29184. if (err <= 0.5) {
  29185. interval *= 10;
  29186. }
  29187. // Interval should be integer
  29188. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  29189. interval *= 10;
  29190. }
  29191. var niceExtent = [
  29192. round$2(mathCeil$1(extent[0] / interval) * interval),
  29193. round$2(mathFloor$1(extent[1] / interval) * interval)
  29194. ];
  29195. this._interval = interval;
  29196. this._niceExtent = niceExtent;
  29197. },
  29198. /**
  29199. * Nice extent.
  29200. * @override
  29201. */
  29202. niceExtent: function (opt) {
  29203. intervalScaleProto$1.niceExtent.call(this, opt);
  29204. var originalScale = this._originalScale;
  29205. originalScale.__fixMin = opt.fixMin;
  29206. originalScale.__fixMax = opt.fixMax;
  29207. }
  29208. });
  29209. each$1(['contain', 'normalize'], function (methodName) {
  29210. LogScale.prototype[methodName] = function (val) {
  29211. val = mathLog(val) / mathLog(this.base);
  29212. return scaleProto$1[methodName].call(this, val);
  29213. };
  29214. });
  29215. LogScale.create = function () {
  29216. return new LogScale();
  29217. };
  29218. function fixRoundingError(val, originalVal) {
  29219. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  29220. }
  29221. /*
  29222. * Licensed to the Apache Software Foundation (ASF) under one
  29223. * or more contributor license agreements. See the NOTICE file
  29224. * distributed with this work for additional information
  29225. * regarding copyright ownership. The ASF licenses this file
  29226. * to you under the Apache License, Version 2.0 (the
  29227. * "License"); you may not use this file except in compliance
  29228. * with the License. You may obtain a copy of the License at
  29229. *
  29230. * http://www.apache.org/licenses/LICENSE-2.0
  29231. *
  29232. * Unless required by applicable law or agreed to in writing,
  29233. * software distributed under the License is distributed on an
  29234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29235. * KIND, either express or implied. See the License for the
  29236. * specific language governing permissions and limitations
  29237. * under the License.
  29238. */
  29239. /**
  29240. * Get axis scale extent before niced.
  29241. * Item of returned array can only be number (including Infinity and NaN).
  29242. */
  29243. function getScaleExtent(scale, model) {
  29244. var scaleType = scale.type;
  29245. var min = model.getMin();
  29246. var max = model.getMax();
  29247. var fixMin = min != null;
  29248. var fixMax = max != null;
  29249. var originalExtent = scale.getExtent();
  29250. var axisDataLen;
  29251. var boundaryGap;
  29252. var span;
  29253. if (scaleType === 'ordinal') {
  29254. axisDataLen = model.getCategories().length;
  29255. }
  29256. else {
  29257. boundaryGap = model.get('boundaryGap');
  29258. if (!isArray(boundaryGap)) {
  29259. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  29260. }
  29261. if (typeof boundaryGap[0] === 'boolean') {
  29262. if (__DEV__) {
  29263. console.warn('Boolean type for boundaryGap is only '
  29264. + 'allowed for ordinal axis. Please use string in '
  29265. + 'percentage instead, e.g., "20%". Currently, '
  29266. + 'boundaryGap is set to be 0.');
  29267. }
  29268. boundaryGap = [0, 0];
  29269. }
  29270. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  29271. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  29272. span = (originalExtent[1] - originalExtent[0])
  29273. || Math.abs(originalExtent[0]);
  29274. }
  29275. // Notice: When min/max is not set (that is, when there are null/undefined,
  29276. // which is the most common case), these cases should be ensured:
  29277. // (1) For 'ordinal', show all axis.data.
  29278. // (2) For others:
  29279. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  29280. // disabled).
  29281. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  29282. // be the result that originalExtent enlarged by boundaryGap.
  29283. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  29284. // FIXME
  29285. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  29286. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  29287. // that the results processed by boundaryGap are positive/negative?
  29288. if (min == null) {
  29289. min = scaleType === 'ordinal'
  29290. ? (axisDataLen ? 0 : NaN)
  29291. : originalExtent[0] - boundaryGap[0] * span;
  29292. }
  29293. if (max == null) {
  29294. max = scaleType === 'ordinal'
  29295. ? (axisDataLen ? axisDataLen - 1 : NaN)
  29296. : originalExtent[1] + boundaryGap[1] * span;
  29297. }
  29298. if (min === 'dataMin') {
  29299. min = originalExtent[0];
  29300. }
  29301. else if (typeof min === 'function') {
  29302. min = min({
  29303. min: originalExtent[0],
  29304. max: originalExtent[1]
  29305. });
  29306. }
  29307. if (max === 'dataMax') {
  29308. max = originalExtent[1];
  29309. }
  29310. else if (typeof max === 'function') {
  29311. max = max({
  29312. min: originalExtent[0],
  29313. max: originalExtent[1]
  29314. });
  29315. }
  29316. (min == null || !isFinite(min)) && (min = NaN);
  29317. (max == null || !isFinite(max)) && (max = NaN);
  29318. scale.setBlank(
  29319. eqNaN(min)
  29320. || eqNaN(max)
  29321. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  29322. );
  29323. // Evaluate if axis needs cross zero
  29324. if (model.getNeedCrossZero()) {
  29325. // Axis is over zero and min is not set
  29326. if (min > 0 && max > 0 && !fixMin) {
  29327. min = 0;
  29328. }
  29329. // Axis is under zero and max is not set
  29330. if (min < 0 && max < 0 && !fixMax) {
  29331. max = 0;
  29332. }
  29333. }
  29334. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  29335. // is base axis
  29336. // FIXME
  29337. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  29338. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  29339. // Should not depend on series type `bar`?
  29340. // (3) Fix that might overlap when using dataZoom.
  29341. // (4) Consider other chart types using `barGrid`?
  29342. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  29343. var ecModel = model.ecModel;
  29344. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  29345. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  29346. var isBaseAxisAndHasBarSeries;
  29347. each$1(barSeriesModels, function (seriesModel) {
  29348. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  29349. });
  29350. if (isBaseAxisAndHasBarSeries) {
  29351. // Calculate placement of bars on axis
  29352. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  29353. // Adjust axis min and max to account for overflow
  29354. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  29355. min = adjustedScale.min;
  29356. max = adjustedScale.max;
  29357. }
  29358. }
  29359. return [min, max];
  29360. }
  29361. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  29362. // Get Axis Length
  29363. var axisExtent = model.axis.getExtent();
  29364. var axisLength = axisExtent[1] - axisExtent[0];
  29365. // Get bars on current base axis and calculate min and max overflow
  29366. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  29367. if (barsOnCurrentAxis === undefined) {
  29368. return {min: min, max: max};
  29369. }
  29370. var minOverflow = Infinity;
  29371. each$1(barsOnCurrentAxis, function (item) {
  29372. minOverflow = Math.min(item.offset, minOverflow);
  29373. });
  29374. var maxOverflow = -Infinity;
  29375. each$1(barsOnCurrentAxis, function (item) {
  29376. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  29377. });
  29378. minOverflow = Math.abs(minOverflow);
  29379. maxOverflow = Math.abs(maxOverflow);
  29380. var totalOverFlow = minOverflow + maxOverflow;
  29381. // Calulate required buffer based on old range and overflow
  29382. var oldRange = max - min;
  29383. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  29384. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  29385. max += overflowBuffer * (maxOverflow / totalOverFlow);
  29386. min -= overflowBuffer * (minOverflow / totalOverFlow);
  29387. return {min: min, max: max};
  29388. }
  29389. function niceScaleExtent(scale, model) {
  29390. var extent = getScaleExtent(scale, model);
  29391. var fixMin = model.getMin() != null;
  29392. var fixMax = model.getMax() != null;
  29393. var splitNumber = model.get('splitNumber');
  29394. if (scale.type === 'log') {
  29395. scale.base = model.get('logBase');
  29396. }
  29397. var scaleType = scale.type;
  29398. scale.setExtent(extent[0], extent[1]);
  29399. scale.niceExtent({
  29400. splitNumber: splitNumber,
  29401. fixMin: fixMin,
  29402. fixMax: fixMax,
  29403. minInterval: (scaleType === 'interval' || scaleType === 'time')
  29404. ? model.get('minInterval') : null,
  29405. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  29406. ? model.get('maxInterval') : null
  29407. });
  29408. // If some one specified the min, max. And the default calculated interval
  29409. // is not good enough. He can specify the interval. It is often appeared
  29410. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  29411. // to be 60.
  29412. // FIXME
  29413. var interval = model.get('interval');
  29414. if (interval != null) {
  29415. scale.setInterval && scale.setInterval(interval);
  29416. }
  29417. }
  29418. /**
  29419. * @param {module:echarts/model/Model} model
  29420. * @param {string} [axisType] Default retrieve from model.type
  29421. * @return {module:echarts/scale/*}
  29422. */
  29423. function createScaleByModel(model, axisType) {
  29424. axisType = axisType || model.get('type');
  29425. if (axisType) {
  29426. switch (axisType) {
  29427. // Buildin scale
  29428. case 'category':
  29429. return new OrdinalScale(
  29430. model.getOrdinalMeta
  29431. ? model.getOrdinalMeta()
  29432. : model.getCategories(),
  29433. [Infinity, -Infinity]
  29434. );
  29435. case 'value':
  29436. return new IntervalScale();
  29437. // Extended scale, like time and log
  29438. default:
  29439. return (Scale.getClass(axisType) || IntervalScale).create(model);
  29440. }
  29441. }
  29442. }
  29443. /**
  29444. * Check if the axis corss 0
  29445. */
  29446. function ifAxisCrossZero(axis) {
  29447. var dataExtent = axis.scale.getExtent();
  29448. var min = dataExtent[0];
  29449. var max = dataExtent[1];
  29450. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  29451. }
  29452. /**
  29453. * @param {module:echarts/coord/Axis} axis
  29454. * @return {Function} Label formatter function.
  29455. * param: {number} tickValue,
  29456. * param: {number} idx, the index in all ticks.
  29457. * If category axis, this param is not requied.
  29458. * return: {string} label string.
  29459. */
  29460. function makeLabelFormatter(axis) {
  29461. var labelFormatter = axis.getLabelModel().get('formatter');
  29462. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  29463. if (typeof labelFormatter === 'string') {
  29464. labelFormatter = (function (tpl) {
  29465. return function (val) {
  29466. // For category axis, get raw value; for numeric axis,
  29467. // get foramtted label like '1,333,444'.
  29468. val = axis.scale.getLabel(val);
  29469. return tpl.replace('{value}', val != null ? val : '');
  29470. };
  29471. })(labelFormatter);
  29472. // Consider empty array
  29473. return labelFormatter;
  29474. }
  29475. else if (typeof labelFormatter === 'function') {
  29476. return function (tickValue, idx) {
  29477. // The original intention of `idx` is "the index of the tick in all ticks".
  29478. // But the previous implementation of category axis do not consider the
  29479. // `axisLabel.interval`, which cause that, for example, the `interval` is
  29480. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  29481. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  29482. // the definition here for back compatibility.
  29483. if (categoryTickStart != null) {
  29484. idx = tickValue - categoryTickStart;
  29485. }
  29486. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  29487. };
  29488. }
  29489. else {
  29490. return function (tick) {
  29491. return axis.scale.getLabel(tick);
  29492. };
  29493. }
  29494. }
  29495. function getAxisRawValue(axis, value) {
  29496. // In category axis with data zoom, tick is not the original
  29497. // index of axis.data. So tick should not be exposed to user
  29498. // in category axis.
  29499. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  29500. }
  29501. /**
  29502. * @param {module:echarts/coord/Axis} axis
  29503. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  29504. */
  29505. function estimateLabelUnionRect(axis) {
  29506. var axisModel = axis.model;
  29507. var scale = axis.scale;
  29508. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  29509. return;
  29510. }
  29511. var isCategory = axis.type === 'category';
  29512. var realNumberScaleTicks;
  29513. var tickCount;
  29514. var categoryScaleExtent = scale.getExtent();
  29515. // Optimize for large category data, avoid call `getTicks()`.
  29516. if (isCategory) {
  29517. tickCount = scale.count();
  29518. }
  29519. else {
  29520. realNumberScaleTicks = scale.getTicks();
  29521. tickCount = realNumberScaleTicks.length;
  29522. }
  29523. var axisLabelModel = axis.getLabelModel();
  29524. var labelFormatter = makeLabelFormatter(axis);
  29525. var rect;
  29526. var step = 1;
  29527. // Simple optimization for large amount of labels
  29528. if (tickCount > 40) {
  29529. step = Math.ceil(tickCount / 40);
  29530. }
  29531. for (var i = 0; i < tickCount; i += step) {
  29532. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  29533. var label = labelFormatter(tickValue);
  29534. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  29535. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29536. rect ? rect.union(singleRect) : (rect = singleRect);
  29537. }
  29538. return rect;
  29539. }
  29540. function rotateTextRect(textRect, rotate) {
  29541. var rotateRadians = rotate * Math.PI / 180;
  29542. var boundingBox = textRect.plain();
  29543. var beforeWidth = boundingBox.width;
  29544. var beforeHeight = boundingBox.height;
  29545. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29546. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29547. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29548. return rotatedRect;
  29549. }
  29550. /**
  29551. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  29552. * @return {number|String} Can be null|'auto'|number|function
  29553. */
  29554. function getOptionCategoryInterval(model) {
  29555. var interval = model.get('interval');
  29556. return interval == null ? 'auto' : interval;
  29557. }
  29558. /**
  29559. * Set `categoryInterval` as 0 implicitly indicates that
  29560. * show all labels reguardless of overlap.
  29561. * @param {Object} axis axisModel.axis
  29562. * @return {boolean}
  29563. */
  29564. function shouldShowAllLabels(axis) {
  29565. return axis.type === 'category'
  29566. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  29567. }
  29568. /*
  29569. * Licensed to the Apache Software Foundation (ASF) under one
  29570. * or more contributor license agreements. See the NOTICE file
  29571. * distributed with this work for additional information
  29572. * regarding copyright ownership. The ASF licenses this file
  29573. * to you under the Apache License, Version 2.0 (the
  29574. * "License"); you may not use this file except in compliance
  29575. * with the License. You may obtain a copy of the License at
  29576. *
  29577. * http://www.apache.org/licenses/LICENSE-2.0
  29578. *
  29579. * Unless required by applicable law or agreed to in writing,
  29580. * software distributed under the License is distributed on an
  29581. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29582. * KIND, either express or implied. See the License for the
  29583. * specific language governing permissions and limitations
  29584. * under the License.
  29585. */
  29586. // import * as axisHelper from './axisHelper';
  29587. var axisModelCommonMixin = {
  29588. /**
  29589. * @param {boolean} origin
  29590. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  29591. */
  29592. getMin: function (origin) {
  29593. var option = this.option;
  29594. var min = (!origin && option.rangeStart != null)
  29595. ? option.rangeStart : option.min;
  29596. if (this.axis
  29597. && min != null
  29598. && min !== 'dataMin'
  29599. && typeof min !== 'function'
  29600. && !eqNaN(min)
  29601. ) {
  29602. min = this.axis.scale.parse(min);
  29603. }
  29604. return min;
  29605. },
  29606. /**
  29607. * @param {boolean} origin
  29608. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  29609. */
  29610. getMax: function (origin) {
  29611. var option = this.option;
  29612. var max = (!origin && option.rangeEnd != null)
  29613. ? option.rangeEnd : option.max;
  29614. if (this.axis
  29615. && max != null
  29616. && max !== 'dataMax'
  29617. && typeof max !== 'function'
  29618. && !eqNaN(max)
  29619. ) {
  29620. max = this.axis.scale.parse(max);
  29621. }
  29622. return max;
  29623. },
  29624. /**
  29625. * @return {boolean}
  29626. */
  29627. getNeedCrossZero: function () {
  29628. var option = this.option;
  29629. return (option.rangeStart != null || option.rangeEnd != null)
  29630. ? false : !option.scale;
  29631. },
  29632. /**
  29633. * Should be implemented by each axis model if necessary.
  29634. * @return {module:echarts/model/Component} coordinate system model
  29635. */
  29636. getCoordSysModel: noop,
  29637. /**
  29638. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  29639. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  29640. */
  29641. setRange: function (rangeStart, rangeEnd) {
  29642. this.option.rangeStart = rangeStart;
  29643. this.option.rangeEnd = rangeEnd;
  29644. },
  29645. /**
  29646. * Reset range
  29647. */
  29648. resetRange: function () {
  29649. // rangeStart and rangeEnd is readonly.
  29650. this.option.rangeStart = this.option.rangeEnd = null;
  29651. }
  29652. };
  29653. /*
  29654. * Licensed to the Apache Software Foundation (ASF) under one
  29655. * or more contributor license agreements. See the NOTICE file
  29656. * distributed with this work for additional information
  29657. * regarding copyright ownership. The ASF licenses this file
  29658. * to you under the Apache License, Version 2.0 (the
  29659. * "License"); you may not use this file except in compliance
  29660. * with the License. You may obtain a copy of the License at
  29661. *
  29662. * http://www.apache.org/licenses/LICENSE-2.0
  29663. *
  29664. * Unless required by applicable law or agreed to in writing,
  29665. * software distributed under the License is distributed on an
  29666. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29667. * KIND, either express or implied. See the License for the
  29668. * specific language governing permissions and limitations
  29669. * under the License.
  29670. */
  29671. // Symbol factory
  29672. /**
  29673. * Triangle shape
  29674. * @inner
  29675. */
  29676. var Triangle = extendShape({
  29677. type: 'triangle',
  29678. shape: {
  29679. cx: 0,
  29680. cy: 0,
  29681. width: 0,
  29682. height: 0
  29683. },
  29684. buildPath: function (path, shape) {
  29685. var cx = shape.cx;
  29686. var cy = shape.cy;
  29687. var width = shape.width / 2;
  29688. var height = shape.height / 2;
  29689. path.moveTo(cx, cy - height);
  29690. path.lineTo(cx + width, cy + height);
  29691. path.lineTo(cx - width, cy + height);
  29692. path.closePath();
  29693. }
  29694. });
  29695. /**
  29696. * Diamond shape
  29697. * @inner
  29698. */
  29699. var Diamond = extendShape({
  29700. type: 'diamond',
  29701. shape: {
  29702. cx: 0,
  29703. cy: 0,
  29704. width: 0,
  29705. height: 0
  29706. },
  29707. buildPath: function (path, shape) {
  29708. var cx = shape.cx;
  29709. var cy = shape.cy;
  29710. var width = shape.width / 2;
  29711. var height = shape.height / 2;
  29712. path.moveTo(cx, cy - height);
  29713. path.lineTo(cx + width, cy);
  29714. path.lineTo(cx, cy + height);
  29715. path.lineTo(cx - width, cy);
  29716. path.closePath();
  29717. }
  29718. });
  29719. /**
  29720. * Pin shape
  29721. * @inner
  29722. */
  29723. var Pin = extendShape({
  29724. type: 'pin',
  29725. shape: {
  29726. // x, y on the cusp
  29727. x: 0,
  29728. y: 0,
  29729. width: 0,
  29730. height: 0
  29731. },
  29732. buildPath: function (path, shape) {
  29733. var x = shape.x;
  29734. var y = shape.y;
  29735. var w = shape.width / 5 * 3;
  29736. // Height must be larger than width
  29737. var h = Math.max(w, shape.height);
  29738. var r = w / 2;
  29739. // Dist on y with tangent point and circle center
  29740. var dy = r * r / (h - r);
  29741. var cy = y - h + r + dy;
  29742. var angle = Math.asin(dy / r);
  29743. // Dist on x with tangent point and circle center
  29744. var dx = Math.cos(angle) * r;
  29745. var tanX = Math.sin(angle);
  29746. var tanY = Math.cos(angle);
  29747. var cpLen = r * 0.6;
  29748. var cpLen2 = r * 0.7;
  29749. path.moveTo(x - dx, cy + dy);
  29750. path.arc(
  29751. x, cy, r,
  29752. Math.PI - angle,
  29753. Math.PI * 2 + angle
  29754. );
  29755. path.bezierCurveTo(
  29756. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  29757. x, y - cpLen2,
  29758. x, y
  29759. );
  29760. path.bezierCurveTo(
  29761. x, y - cpLen2,
  29762. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  29763. x - dx, cy + dy
  29764. );
  29765. path.closePath();
  29766. }
  29767. });
  29768. /**
  29769. * Arrow shape
  29770. * @inner
  29771. */
  29772. var Arrow = extendShape({
  29773. type: 'arrow',
  29774. shape: {
  29775. x: 0,
  29776. y: 0,
  29777. width: 0,
  29778. height: 0
  29779. },
  29780. buildPath: function (ctx, shape) {
  29781. var height = shape.height;
  29782. var width = shape.width;
  29783. var x = shape.x;
  29784. var y = shape.y;
  29785. var dx = width / 3 * 2;
  29786. ctx.moveTo(x, y);
  29787. ctx.lineTo(x + dx, y + height);
  29788. ctx.lineTo(x, y + height / 4 * 3);
  29789. ctx.lineTo(x - dx, y + height);
  29790. ctx.lineTo(x, y);
  29791. ctx.closePath();
  29792. }
  29793. });
  29794. /**
  29795. * Map of path contructors
  29796. * @type {Object.<string, module:zrender/graphic/Path>}
  29797. */
  29798. var symbolCtors = {
  29799. line: Line,
  29800. rect: Rect,
  29801. roundRect: Rect,
  29802. square: Rect,
  29803. circle: Circle,
  29804. diamond: Diamond,
  29805. pin: Pin,
  29806. arrow: Arrow,
  29807. triangle: Triangle
  29808. };
  29809. var symbolShapeMakers = {
  29810. line: function (x, y, w, h, shape) {
  29811. // FIXME
  29812. shape.x1 = x;
  29813. shape.y1 = y + h / 2;
  29814. shape.x2 = x + w;
  29815. shape.y2 = y + h / 2;
  29816. },
  29817. rect: function (x, y, w, h, shape) {
  29818. shape.x = x;
  29819. shape.y = y;
  29820. shape.width = w;
  29821. shape.height = h;
  29822. },
  29823. roundRect: function (x, y, w, h, shape) {
  29824. shape.x = x;
  29825. shape.y = y;
  29826. shape.width = w;
  29827. shape.height = h;
  29828. shape.r = Math.min(w, h) / 4;
  29829. },
  29830. square: function (x, y, w, h, shape) {
  29831. var size = Math.min(w, h);
  29832. shape.x = x;
  29833. shape.y = y;
  29834. shape.width = size;
  29835. shape.height = size;
  29836. },
  29837. circle: function (x, y, w, h, shape) {
  29838. // Put circle in the center of square
  29839. shape.cx = x + w / 2;
  29840. shape.cy = y + h / 2;
  29841. shape.r = Math.min(w, h) / 2;
  29842. },
  29843. diamond: function (x, y, w, h, shape) {
  29844. shape.cx = x + w / 2;
  29845. shape.cy = y + h / 2;
  29846. shape.width = w;
  29847. shape.height = h;
  29848. },
  29849. pin: function (x, y, w, h, shape) {
  29850. shape.x = x + w / 2;
  29851. shape.y = y + h / 2;
  29852. shape.width = w;
  29853. shape.height = h;
  29854. },
  29855. arrow: function (x, y, w, h, shape) {
  29856. shape.x = x + w / 2;
  29857. shape.y = y + h / 2;
  29858. shape.width = w;
  29859. shape.height = h;
  29860. },
  29861. triangle: function (x, y, w, h, shape) {
  29862. shape.cx = x + w / 2;
  29863. shape.cy = y + h / 2;
  29864. shape.width = w;
  29865. shape.height = h;
  29866. }
  29867. };
  29868. var symbolBuildProxies = {};
  29869. each$1(symbolCtors, function (Ctor, name) {
  29870. symbolBuildProxies[name] = new Ctor();
  29871. });
  29872. var SymbolClz = extendShape({
  29873. type: 'symbol',
  29874. shape: {
  29875. symbolType: '',
  29876. x: 0,
  29877. y: 0,
  29878. width: 0,
  29879. height: 0
  29880. },
  29881. beforeBrush: function () {
  29882. var style = this.style;
  29883. var shape = this.shape;
  29884. // FIXME
  29885. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  29886. style.textPosition = ['50%', '40%'];
  29887. style.textAlign = 'center';
  29888. style.textVerticalAlign = 'middle';
  29889. }
  29890. },
  29891. buildPath: function (ctx, shape, inBundle) {
  29892. var symbolType = shape.symbolType;
  29893. var proxySymbol = symbolBuildProxies[symbolType];
  29894. if (shape.symbolType !== 'none') {
  29895. if (!proxySymbol) {
  29896. // Default rect
  29897. symbolType = 'rect';
  29898. proxySymbol = symbolBuildProxies[symbolType];
  29899. }
  29900. symbolShapeMakers[symbolType](
  29901. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  29902. );
  29903. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  29904. }
  29905. }
  29906. });
  29907. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  29908. function symbolPathSetColor(color, innerColor) {
  29909. if (this.type !== 'image') {
  29910. var symbolStyle = this.style;
  29911. var symbolShape = this.shape;
  29912. if (symbolShape && symbolShape.symbolType === 'line') {
  29913. symbolStyle.stroke = color;
  29914. }
  29915. else if (this.__isEmptyBrush) {
  29916. symbolStyle.stroke = color;
  29917. symbolStyle.fill = innerColor || '#fff';
  29918. }
  29919. else {
  29920. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  29921. symbolStyle.fill && (symbolStyle.fill = color);
  29922. symbolStyle.stroke && (symbolStyle.stroke = color);
  29923. }
  29924. this.dirty(false);
  29925. }
  29926. }
  29927. /**
  29928. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  29929. * @param {string} symbolType
  29930. * @param {number} x
  29931. * @param {number} y
  29932. * @param {number} w
  29933. * @param {number} h
  29934. * @param {string} color
  29935. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  29936. * for path and image only.
  29937. */
  29938. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  29939. // TODO Support image object, DynamicImage.
  29940. var isEmpty = symbolType.indexOf('empty') === 0;
  29941. if (isEmpty) {
  29942. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  29943. }
  29944. var symbolPath;
  29945. if (symbolType.indexOf('image://') === 0) {
  29946. symbolPath = makeImage(
  29947. symbolType.slice(8),
  29948. new BoundingRect(x, y, w, h),
  29949. keepAspect ? 'center' : 'cover'
  29950. );
  29951. }
  29952. else if (symbolType.indexOf('path://') === 0) {
  29953. symbolPath = makePath(
  29954. symbolType.slice(7),
  29955. {},
  29956. new BoundingRect(x, y, w, h),
  29957. keepAspect ? 'center' : 'cover'
  29958. );
  29959. }
  29960. else {
  29961. symbolPath = new SymbolClz({
  29962. shape: {
  29963. symbolType: symbolType,
  29964. x: x,
  29965. y: y,
  29966. width: w,
  29967. height: h
  29968. }
  29969. });
  29970. }
  29971. symbolPath.__isEmptyBrush = isEmpty;
  29972. symbolPath.setColor = symbolPathSetColor;
  29973. symbolPath.setColor(color);
  29974. return symbolPath;
  29975. }
  29976. /*
  29977. * Licensed to the Apache Software Foundation (ASF) under one
  29978. * or more contributor license agreements. See the NOTICE file
  29979. * distributed with this work for additional information
  29980. * regarding copyright ownership. The ASF licenses this file
  29981. * to you under the Apache License, Version 2.0 (the
  29982. * "License"); you may not use this file except in compliance
  29983. * with the License. You may obtain a copy of the License at
  29984. *
  29985. * http://www.apache.org/licenses/LICENSE-2.0
  29986. *
  29987. * Unless required by applicable law or agreed to in writing,
  29988. * software distributed under the License is distributed on an
  29989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29990. * KIND, either express or implied. See the License for the
  29991. * specific language governing permissions and limitations
  29992. * under the License.
  29993. */
  29994. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  29995. /**
  29996. * Create a muti dimension List structure from seriesModel.
  29997. * @param {module:echarts/model/Model} seriesModel
  29998. * @return {module:echarts/data/List} list
  29999. */
  30000. function createList(seriesModel) {
  30001. return createListFromArray(seriesModel.getSource(), seriesModel);
  30002. }
  30003. var dataStack$1 = {
  30004. isDimensionStacked: isDimensionStacked,
  30005. enableDataStack: enableDataStack,
  30006. getStackedDimension: getStackedDimension
  30007. };
  30008. /**
  30009. * Create scale
  30010. * @param {Array.<number>} dataExtent
  30011. * @param {Object|module:echarts/Model} option
  30012. */
  30013. function createScale(dataExtent, option) {
  30014. var axisModel = option;
  30015. if (!Model.isInstance(option)) {
  30016. axisModel = new Model(option);
  30017. mixin(axisModel, axisModelCommonMixin);
  30018. }
  30019. var scale = createScaleByModel(axisModel);
  30020. scale.setExtent(dataExtent[0], dataExtent[1]);
  30021. niceScaleExtent(scale, axisModel);
  30022. return scale;
  30023. }
  30024. /**
  30025. * Mixin common methods to axis model,
  30026. *
  30027. * Inlcude methods
  30028. * `getFormattedLabels() => Array.<string>`
  30029. * `getCategories() => Array.<string>`
  30030. * `getMin(origin: boolean) => number`
  30031. * `getMax(origin: boolean) => number`
  30032. * `getNeedCrossZero() => boolean`
  30033. * `setRange(start: number, end: number)`
  30034. * `resetRange()`
  30035. */
  30036. function mixinAxisModelCommonMethods(Model$$1) {
  30037. mixin(Model$$1, axisModelCommonMixin);
  30038. }
  30039. var helper = (Object.freeze || Object)({
  30040. createList: createList,
  30041. getLayoutRect: getLayoutRect,
  30042. dataStack: dataStack$1,
  30043. createScale: createScale,
  30044. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  30045. completeDimensions: completeDimensions,
  30046. createDimensions: createDimensions,
  30047. createSymbol: createSymbol
  30048. });
  30049. var EPSILON$3 = 1e-8;
  30050. function isAroundEqual$1(a, b) {
  30051. return Math.abs(a - b) < EPSILON$3;
  30052. }
  30053. function contain$1(points, x, y) {
  30054. var w = 0;
  30055. var p = points[0];
  30056. if (!p) {
  30057. return false;
  30058. }
  30059. for (var i = 1; i < points.length; i++) {
  30060. var p2 = points[i];
  30061. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  30062. p = p2;
  30063. }
  30064. // Close polygon
  30065. var p0 = points[0];
  30066. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  30067. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  30068. }
  30069. return w !== 0;
  30070. }
  30071. /*
  30072. * Licensed to the Apache Software Foundation (ASF) under one
  30073. * or more contributor license agreements. See the NOTICE file
  30074. * distributed with this work for additional information
  30075. * regarding copyright ownership. The ASF licenses this file
  30076. * to you under the Apache License, Version 2.0 (the
  30077. * "License"); you may not use this file except in compliance
  30078. * with the License. You may obtain a copy of the License at
  30079. *
  30080. * http://www.apache.org/licenses/LICENSE-2.0
  30081. *
  30082. * Unless required by applicable law or agreed to in writing,
  30083. * software distributed under the License is distributed on an
  30084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30085. * KIND, either express or implied. See the License for the
  30086. * specific language governing permissions and limitations
  30087. * under the License.
  30088. */
  30089. /**
  30090. * @module echarts/coord/geo/Region
  30091. */
  30092. /**
  30093. * @param {string|Region} name
  30094. * @param {Array} geometries
  30095. * @param {Array.<number>} cp
  30096. */
  30097. function Region(name, geometries, cp) {
  30098. /**
  30099. * @type {string}
  30100. * @readOnly
  30101. */
  30102. this.name = name;
  30103. /**
  30104. * @type {Array.<Array>}
  30105. * @readOnly
  30106. */
  30107. this.geometries = geometries;
  30108. if (!cp) {
  30109. var rect = this.getBoundingRect();
  30110. cp = [
  30111. rect.x + rect.width / 2,
  30112. rect.y + rect.height / 2
  30113. ];
  30114. }
  30115. else {
  30116. cp = [cp[0], cp[1]];
  30117. }
  30118. /**
  30119. * @type {Array.<number>}
  30120. */
  30121. this.center = cp;
  30122. }
  30123. Region.prototype = {
  30124. constructor: Region,
  30125. properties: null,
  30126. /**
  30127. * @return {module:zrender/core/BoundingRect}
  30128. */
  30129. getBoundingRect: function () {
  30130. var rect = this._rect;
  30131. if (rect) {
  30132. return rect;
  30133. }
  30134. var MAX_NUMBER = Number.MAX_VALUE;
  30135. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  30136. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  30137. var min2 = [];
  30138. var max2 = [];
  30139. var geometries = this.geometries;
  30140. for (var i = 0; i < geometries.length; i++) {
  30141. // Only support polygon
  30142. if (geometries[i].type !== 'polygon') {
  30143. continue;
  30144. }
  30145. // Doesn't consider hole
  30146. var exterior = geometries[i].exterior;
  30147. fromPoints(exterior, min2, max2);
  30148. min(min$$1, min$$1, min2);
  30149. max(max$$1, max$$1, max2);
  30150. }
  30151. // No data
  30152. if (i === 0) {
  30153. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  30154. }
  30155. return (this._rect = new BoundingRect(
  30156. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  30157. ));
  30158. },
  30159. /**
  30160. * @param {<Array.<number>} coord
  30161. * @return {boolean}
  30162. */
  30163. contain: function (coord) {
  30164. var rect = this.getBoundingRect();
  30165. var geometries = this.geometries;
  30166. if (!rect.contain(coord[0], coord[1])) {
  30167. return false;
  30168. }
  30169. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  30170. // Only support polygon.
  30171. if (geometries[i].type !== 'polygon') {
  30172. continue;
  30173. }
  30174. var exterior = geometries[i].exterior;
  30175. var interiors = geometries[i].interiors;
  30176. if (contain$1(exterior, coord[0], coord[1])) {
  30177. // Not in the region if point is in the hole.
  30178. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  30179. if (contain$1(interiors[k])) {
  30180. continue loopGeo;
  30181. }
  30182. }
  30183. return true;
  30184. }
  30185. }
  30186. return false;
  30187. },
  30188. transformTo: function (x, y, width, height) {
  30189. var rect = this.getBoundingRect();
  30190. var aspect = rect.width / rect.height;
  30191. if (!width) {
  30192. width = aspect * height;
  30193. }
  30194. else if (!height) {
  30195. height = width / aspect;
  30196. }
  30197. var target = new BoundingRect(x, y, width, height);
  30198. var transform = rect.calculateTransform(target);
  30199. var geometries = this.geometries;
  30200. for (var i = 0; i < geometries.length; i++) {
  30201. // Only support polygon.
  30202. if (geometries[i].type !== 'polygon') {
  30203. continue;
  30204. }
  30205. var exterior = geometries[i].exterior;
  30206. var interiors = geometries[i].interiors;
  30207. for (var p = 0; p < exterior.length; p++) {
  30208. applyTransform(exterior[p], exterior[p], transform);
  30209. }
  30210. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  30211. for (var p = 0; p < interiors[h].length; p++) {
  30212. applyTransform(interiors[h][p], interiors[h][p], transform);
  30213. }
  30214. }
  30215. }
  30216. rect = this._rect;
  30217. rect.copy(target);
  30218. // Update center
  30219. this.center = [
  30220. rect.x + rect.width / 2,
  30221. rect.y + rect.height / 2
  30222. ];
  30223. },
  30224. cloneShallow: function (name) {
  30225. name == null && (name = this.name);
  30226. var newRegion = new Region(name, this.geometries, this.center);
  30227. newRegion._rect = this._rect;
  30228. newRegion.transformTo = null; // Simply avoid to be called.
  30229. return newRegion;
  30230. }
  30231. };
  30232. /*
  30233. * Licensed to the Apache Software Foundation (ASF) under one
  30234. * or more contributor license agreements. See the NOTICE file
  30235. * distributed with this work for additional information
  30236. * regarding copyright ownership. The ASF licenses this file
  30237. * to you under the Apache License, Version 2.0 (the
  30238. * "License"); you may not use this file except in compliance
  30239. * with the License. You may obtain a copy of the License at
  30240. *
  30241. * http://www.apache.org/licenses/LICENSE-2.0
  30242. *
  30243. * Unless required by applicable law or agreed to in writing,
  30244. * software distributed under the License is distributed on an
  30245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30246. * KIND, either express or implied. See the License for the
  30247. * specific language governing permissions and limitations
  30248. * under the License.
  30249. */
  30250. /**
  30251. * Parse and decode geo json
  30252. * @module echarts/coord/geo/parseGeoJson
  30253. */
  30254. function decode(json) {
  30255. if (!json.UTF8Encoding) {
  30256. return json;
  30257. }
  30258. var encodeScale = json.UTF8Scale;
  30259. if (encodeScale == null) {
  30260. encodeScale = 1024;
  30261. }
  30262. var features = json.features;
  30263. for (var f = 0; f < features.length; f++) {
  30264. var feature = features[f];
  30265. var geometry = feature.geometry;
  30266. var coordinates = geometry.coordinates;
  30267. var encodeOffsets = geometry.encodeOffsets;
  30268. for (var c = 0; c < coordinates.length; c++) {
  30269. var coordinate = coordinates[c];
  30270. if (geometry.type === 'Polygon') {
  30271. coordinates[c] = decodePolygon(
  30272. coordinate,
  30273. encodeOffsets[c],
  30274. encodeScale
  30275. );
  30276. }
  30277. else if (geometry.type === 'MultiPolygon') {
  30278. for (var c2 = 0; c2 < coordinate.length; c2++) {
  30279. var polygon = coordinate[c2];
  30280. coordinate[c2] = decodePolygon(
  30281. polygon,
  30282. encodeOffsets[c][c2],
  30283. encodeScale
  30284. );
  30285. }
  30286. }
  30287. }
  30288. }
  30289. // Has been decoded
  30290. json.UTF8Encoding = false;
  30291. return json;
  30292. }
  30293. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  30294. var result = [];
  30295. var prevX = encodeOffsets[0];
  30296. var prevY = encodeOffsets[1];
  30297. for (var i = 0; i < coordinate.length; i += 2) {
  30298. var x = coordinate.charCodeAt(i) - 64;
  30299. var y = coordinate.charCodeAt(i + 1) - 64;
  30300. // ZigZag decoding
  30301. x = (x >> 1) ^ (-(x & 1));
  30302. y = (y >> 1) ^ (-(y & 1));
  30303. // Delta deocding
  30304. x += prevX;
  30305. y += prevY;
  30306. prevX = x;
  30307. prevY = y;
  30308. // Dequantize
  30309. result.push([x / encodeScale, y / encodeScale]);
  30310. }
  30311. return result;
  30312. }
  30313. /**
  30314. * @alias module:echarts/coord/geo/parseGeoJson
  30315. * @param {Object} geoJson
  30316. * @return {module:zrender/container/Group}
  30317. */
  30318. var parseGeoJson$1 = function (geoJson) {
  30319. decode(geoJson);
  30320. return map(filter(geoJson.features, function (featureObj) {
  30321. // Output of mapshaper may have geometry null
  30322. return featureObj.geometry
  30323. && featureObj.properties
  30324. && featureObj.geometry.coordinates.length > 0;
  30325. }), function (featureObj) {
  30326. var properties = featureObj.properties;
  30327. var geo = featureObj.geometry;
  30328. var coordinates = geo.coordinates;
  30329. var geometries = [];
  30330. if (geo.type === 'Polygon') {
  30331. geometries.push({
  30332. type: 'polygon',
  30333. // According to the GeoJSON specification.
  30334. // First must be exterior, and the rest are all interior(holes).
  30335. exterior: coordinates[0],
  30336. interiors: coordinates.slice(1)
  30337. });
  30338. }
  30339. if (geo.type === 'MultiPolygon') {
  30340. each$1(coordinates, function (item) {
  30341. if (item[0]) {
  30342. geometries.push({
  30343. type: 'polygon',
  30344. exterior: item[0],
  30345. interiors: item.slice(1)
  30346. });
  30347. }
  30348. });
  30349. }
  30350. var region = new Region(
  30351. properties.name,
  30352. geometries,
  30353. properties.cp
  30354. );
  30355. region.properties = properties;
  30356. return region;
  30357. });
  30358. };
  30359. /*
  30360. * Licensed to the Apache Software Foundation (ASF) under one
  30361. * or more contributor license agreements. See the NOTICE file
  30362. * distributed with this work for additional information
  30363. * regarding copyright ownership. The ASF licenses this file
  30364. * to you under the Apache License, Version 2.0 (the
  30365. * "License"); you may not use this file except in compliance
  30366. * with the License. You may obtain a copy of the License at
  30367. *
  30368. * http://www.apache.org/licenses/LICENSE-2.0
  30369. *
  30370. * Unless required by applicable law or agreed to in writing,
  30371. * software distributed under the License is distributed on an
  30372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30373. * KIND, either express or implied. See the License for the
  30374. * specific language governing permissions and limitations
  30375. * under the License.
  30376. */
  30377. var inner$6 = makeInner();
  30378. /**
  30379. * @param {module:echats/coord/Axis} axis
  30380. * @return {Object} {
  30381. * labels: [{
  30382. * formattedLabel: string,
  30383. * rawLabel: string,
  30384. * tickValue: number
  30385. * }, ...],
  30386. * labelCategoryInterval: number
  30387. * }
  30388. */
  30389. function createAxisLabels(axis) {
  30390. // Only ordinal scale support tick interval
  30391. return axis.type === 'category'
  30392. ? makeCategoryLabels(axis)
  30393. : makeRealNumberLabels(axis);
  30394. }
  30395. /**
  30396. * @param {module:echats/coord/Axis} axis
  30397. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  30398. * @return {Object} {
  30399. * ticks: Array.<number>
  30400. * tickCategoryInterval: number
  30401. * }
  30402. */
  30403. function createAxisTicks(axis, tickModel) {
  30404. // Only ordinal scale support tick interval
  30405. return axis.type === 'category'
  30406. ? makeCategoryTicks(axis, tickModel)
  30407. : {ticks: axis.scale.getTicks()};
  30408. }
  30409. function makeCategoryLabels(axis) {
  30410. var labelModel = axis.getLabelModel();
  30411. var result = makeCategoryLabelsActually(axis, labelModel);
  30412. return (!labelModel.get('show') || axis.scale.isBlank())
  30413. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  30414. : result;
  30415. }
  30416. function makeCategoryLabelsActually(axis, labelModel) {
  30417. var labelsCache = getListCache(axis, 'labels');
  30418. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  30419. var result = listCacheGet(labelsCache, optionLabelInterval);
  30420. if (result) {
  30421. return result;
  30422. }
  30423. var labels;
  30424. var numericLabelInterval;
  30425. if (isFunction$1(optionLabelInterval)) {
  30426. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  30427. }
  30428. else {
  30429. numericLabelInterval = optionLabelInterval === 'auto'
  30430. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  30431. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  30432. }
  30433. // Cache to avoid calling interval function repeatly.
  30434. return listCacheSet(labelsCache, optionLabelInterval, {
  30435. labels: labels, labelCategoryInterval: numericLabelInterval
  30436. });
  30437. }
  30438. function makeCategoryTicks(axis, tickModel) {
  30439. var ticksCache = getListCache(axis, 'ticks');
  30440. var optionTickInterval = getOptionCategoryInterval(tickModel);
  30441. var result = listCacheGet(ticksCache, optionTickInterval);
  30442. if (result) {
  30443. return result;
  30444. }
  30445. var ticks;
  30446. var tickCategoryInterval;
  30447. // Optimize for the case that large category data and no label displayed,
  30448. // we should not return all ticks.
  30449. if (!tickModel.get('show') || axis.scale.isBlank()) {
  30450. ticks = [];
  30451. }
  30452. if (isFunction$1(optionTickInterval)) {
  30453. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  30454. }
  30455. // Always use label interval by default despite label show. Consider this
  30456. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  30457. // labels. `splitLine` and `axisTick` should be consistent in this case.
  30458. else if (optionTickInterval === 'auto') {
  30459. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  30460. tickCategoryInterval = labelsResult.labelCategoryInterval;
  30461. ticks = map(labelsResult.labels, function (labelItem) {
  30462. return labelItem.tickValue;
  30463. });
  30464. }
  30465. else {
  30466. tickCategoryInterval = optionTickInterval;
  30467. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  30468. }
  30469. // Cache to avoid calling interval function repeatly.
  30470. return listCacheSet(ticksCache, optionTickInterval, {
  30471. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  30472. });
  30473. }
  30474. function makeRealNumberLabels(axis) {
  30475. var ticks = axis.scale.getTicks();
  30476. var labelFormatter = makeLabelFormatter(axis);
  30477. return {
  30478. labels: map(ticks, function (tickValue, idx) {
  30479. return {
  30480. formattedLabel: labelFormatter(tickValue, idx),
  30481. rawLabel: axis.scale.getLabel(tickValue),
  30482. tickValue: tickValue
  30483. };
  30484. })
  30485. };
  30486. }
  30487. // Large category data calculation is performence sensitive, and ticks and label
  30488. // probably be fetched by multiple times. So we cache the result.
  30489. // axis is created each time during a ec process, so we do not need to clear cache.
  30490. function getListCache(axis, prop) {
  30491. // Because key can be funciton, and cache size always be small, we use array cache.
  30492. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  30493. }
  30494. function listCacheGet(cache, key) {
  30495. for (var i = 0; i < cache.length; i++) {
  30496. if (cache[i].key === key) {
  30497. return cache[i].value;
  30498. }
  30499. }
  30500. }
  30501. function listCacheSet(cache, key, value) {
  30502. cache.push({key: key, value: value});
  30503. return value;
  30504. }
  30505. function makeAutoCategoryInterval(axis) {
  30506. var result = inner$6(axis).autoInterval;
  30507. return result != null
  30508. ? result
  30509. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  30510. }
  30511. /**
  30512. * Calculate interval for category axis ticks and labels.
  30513. * To get precise result, at least one of `getRotate` and `isHorizontal`
  30514. * should be implemented in axis.
  30515. */
  30516. function calculateCategoryInterval(axis) {
  30517. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  30518. var labelFormatter = makeLabelFormatter(axis);
  30519. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  30520. var ordinalScale = axis.scale;
  30521. var ordinalExtent = ordinalScale.getExtent();
  30522. // Providing this method is for optimization:
  30523. // avoid generating a long array by `getTicks`
  30524. // in large category data case.
  30525. var tickCount = ordinalScale.count();
  30526. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  30527. return 0;
  30528. }
  30529. var step = 1;
  30530. // Simple optimization. Empirical value: tick count should less than 40.
  30531. if (tickCount > 40) {
  30532. step = Math.max(1, Math.floor(tickCount / 40));
  30533. }
  30534. var tickValue = ordinalExtent[0];
  30535. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  30536. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  30537. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  30538. var maxW = 0;
  30539. var maxH = 0;
  30540. // Caution: Performance sensitive for large category data.
  30541. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  30542. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30543. var width = 0;
  30544. var height = 0;
  30545. // Not precise, do not consider align and vertical align
  30546. // and each distance from axis line yet.
  30547. var rect = getBoundingRect(
  30548. labelFormatter(tickValue), params.font, 'center', 'top'
  30549. );
  30550. // Magic number
  30551. width = rect.width * 1.3;
  30552. height = rect.height * 1.3;
  30553. // Min size, void long loop.
  30554. maxW = Math.max(maxW, width, 7);
  30555. maxH = Math.max(maxH, height, 7);
  30556. }
  30557. var dw = maxW / unitW;
  30558. var dh = maxH / unitH;
  30559. // 0/0 is NaN, 1/0 is Infinity.
  30560. isNaN(dw) && (dw = Infinity);
  30561. isNaN(dh) && (dh = Infinity);
  30562. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  30563. var cache = inner$6(axis.model);
  30564. var lastAutoInterval = cache.lastAutoInterval;
  30565. var lastTickCount = cache.lastTickCount;
  30566. // Use cache to keep interval stable while moving zoom window,
  30567. // otherwise the calculated interval might jitter when the zoom
  30568. // window size is close to the interval-changing size.
  30569. if (lastAutoInterval != null
  30570. && lastTickCount != null
  30571. && Math.abs(lastAutoInterval - interval) <= 1
  30572. && Math.abs(lastTickCount - tickCount) <= 1
  30573. // Always choose the bigger one, otherwise the critical
  30574. // point is not the same when zooming in or zooming out.
  30575. && lastAutoInterval > interval
  30576. ) {
  30577. interval = lastAutoInterval;
  30578. }
  30579. // Only update cache if cache not used, otherwise the
  30580. // changing of interval is too insensitive.
  30581. else {
  30582. cache.lastTickCount = tickCount;
  30583. cache.lastAutoInterval = interval;
  30584. }
  30585. return interval;
  30586. }
  30587. function fetchAutoCategoryIntervalCalculationParams(axis) {
  30588. var labelModel = axis.getLabelModel();
  30589. return {
  30590. axisRotate: axis.getRotate
  30591. ? axis.getRotate()
  30592. : (axis.isHorizontal && !axis.isHorizontal())
  30593. ? 90
  30594. : 0,
  30595. labelRotate: labelModel.get('rotate') || 0,
  30596. font: labelModel.getFont()
  30597. };
  30598. }
  30599. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  30600. var labelFormatter = makeLabelFormatter(axis);
  30601. var ordinalScale = axis.scale;
  30602. var ordinalExtent = ordinalScale.getExtent();
  30603. var labelModel = axis.getLabelModel();
  30604. var result = [];
  30605. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  30606. var step = Math.max((categoryInterval || 0) + 1, 1);
  30607. var startTick = ordinalExtent[0];
  30608. var tickCount = ordinalScale.count();
  30609. // Calculate start tick based on zero if possible to keep label consistent
  30610. // while zooming and moving while interval > 0. Otherwise the selection
  30611. // of displayable ticks and symbols probably keep changing.
  30612. // 3 is empirical value.
  30613. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  30614. startTick = Math.round(Math.ceil(startTick / step) * step);
  30615. }
  30616. // (1) Only add min max label here but leave overlap checking
  30617. // to render stage, which also ensure the returned list
  30618. // suitable for splitLine and splitArea rendering.
  30619. // (2) Scales except category always contain min max label so
  30620. // do not need to perform this process.
  30621. var showAllLabel = shouldShowAllLabels(axis);
  30622. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  30623. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  30624. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  30625. addItem(ordinalExtent[0]);
  30626. }
  30627. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  30628. var tickValue = startTick;
  30629. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30630. addItem(tickValue);
  30631. }
  30632. if (includeMaxLabel && tickValue !== ordinalExtent[1]) {
  30633. addItem(ordinalExtent[1]);
  30634. }
  30635. function addItem(tVal) {
  30636. result.push(onlyTick
  30637. ? tVal
  30638. : {
  30639. formattedLabel: labelFormatter(tVal),
  30640. rawLabel: ordinalScale.getLabel(tVal),
  30641. tickValue: tVal
  30642. }
  30643. );
  30644. }
  30645. return result;
  30646. }
  30647. // When interval is function, the result `false` means ignore the tick.
  30648. // It is time consuming for large category data.
  30649. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  30650. var ordinalScale = axis.scale;
  30651. var labelFormatter = makeLabelFormatter(axis);
  30652. var result = [];
  30653. each$1(ordinalScale.getTicks(), function (tickValue) {
  30654. var rawLabel = ordinalScale.getLabel(tickValue);
  30655. if (categoryInterval(tickValue, rawLabel)) {
  30656. result.push(onlyTick
  30657. ? tickValue
  30658. : {
  30659. formattedLabel: labelFormatter(tickValue),
  30660. rawLabel: rawLabel,
  30661. tickValue: tickValue
  30662. }
  30663. );
  30664. }
  30665. });
  30666. return result;
  30667. }
  30668. /*
  30669. * Licensed to the Apache Software Foundation (ASF) under one
  30670. * or more contributor license agreements. See the NOTICE file
  30671. * distributed with this work for additional information
  30672. * regarding copyright ownership. The ASF licenses this file
  30673. * to you under the Apache License, Version 2.0 (the
  30674. * "License"); you may not use this file except in compliance
  30675. * with the License. You may obtain a copy of the License at
  30676. *
  30677. * http://www.apache.org/licenses/LICENSE-2.0
  30678. *
  30679. * Unless required by applicable law or agreed to in writing,
  30680. * software distributed under the License is distributed on an
  30681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30682. * KIND, either express or implied. See the License for the
  30683. * specific language governing permissions and limitations
  30684. * under the License.
  30685. */
  30686. var NORMALIZED_EXTENT = [0, 1];
  30687. /**
  30688. * Base class of Axis.
  30689. * @constructor
  30690. */
  30691. var Axis = function (dim, scale, extent) {
  30692. /**
  30693. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  30694. * @type {string}
  30695. */
  30696. this.dim = dim;
  30697. /**
  30698. * Axis scale
  30699. * @type {module:echarts/coord/scale/*}
  30700. */
  30701. this.scale = scale;
  30702. /**
  30703. * @type {Array.<number>}
  30704. * @private
  30705. */
  30706. this._extent = extent || [0, 0];
  30707. /**
  30708. * @type {boolean}
  30709. */
  30710. this.inverse = false;
  30711. /**
  30712. * Usually true when axis has a ordinal scale
  30713. * @type {boolean}
  30714. */
  30715. this.onBand = false;
  30716. };
  30717. Axis.prototype = {
  30718. constructor: Axis,
  30719. /**
  30720. * If axis extent contain given coord
  30721. * @param {number} coord
  30722. * @return {boolean}
  30723. */
  30724. contain: function (coord) {
  30725. var extent = this._extent;
  30726. var min = Math.min(extent[0], extent[1]);
  30727. var max = Math.max(extent[0], extent[1]);
  30728. return coord >= min && coord <= max;
  30729. },
  30730. /**
  30731. * If axis extent contain given data
  30732. * @param {number} data
  30733. * @return {boolean}
  30734. */
  30735. containData: function (data) {
  30736. return this.contain(this.dataToCoord(data));
  30737. },
  30738. /**
  30739. * Get coord extent.
  30740. * @return {Array.<number>}
  30741. */
  30742. getExtent: function () {
  30743. return this._extent.slice();
  30744. },
  30745. /**
  30746. * Get precision used for formatting
  30747. * @param {Array.<number>} [dataExtent]
  30748. * @return {number}
  30749. */
  30750. getPixelPrecision: function (dataExtent) {
  30751. return getPixelPrecision(
  30752. dataExtent || this.scale.getExtent(),
  30753. this._extent
  30754. );
  30755. },
  30756. /**
  30757. * Set coord extent
  30758. * @param {number} start
  30759. * @param {number} end
  30760. */
  30761. setExtent: function (start, end) {
  30762. var extent = this._extent;
  30763. extent[0] = start;
  30764. extent[1] = end;
  30765. },
  30766. /**
  30767. * Convert data to coord. Data is the rank if it has an ordinal scale
  30768. * @param {number} data
  30769. * @param {boolean} clamp
  30770. * @return {number}
  30771. */
  30772. dataToCoord: function (data, clamp) {
  30773. var extent = this._extent;
  30774. var scale = this.scale;
  30775. data = scale.normalize(data);
  30776. if (this.onBand && scale.type === 'ordinal') {
  30777. extent = extent.slice();
  30778. fixExtentWithBands(extent, scale.count());
  30779. }
  30780. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  30781. },
  30782. /**
  30783. * Convert coord to data. Data is the rank if it has an ordinal scale
  30784. * @param {number} coord
  30785. * @param {boolean} clamp
  30786. * @return {number}
  30787. */
  30788. coordToData: function (coord, clamp) {
  30789. var extent = this._extent;
  30790. var scale = this.scale;
  30791. if (this.onBand && scale.type === 'ordinal') {
  30792. extent = extent.slice();
  30793. fixExtentWithBands(extent, scale.count());
  30794. }
  30795. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  30796. return this.scale.scale(t);
  30797. },
  30798. /**
  30799. * Convert pixel point to data in axis
  30800. * @param {Array.<number>} point
  30801. * @param {boolean} clamp
  30802. * @return {number} data
  30803. */
  30804. pointToData: function (point, clamp) {
  30805. // Should be implemented in derived class if necessary.
  30806. },
  30807. /**
  30808. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  30809. * `axis.getTicksCoords` considers `onBand`, which is used by
  30810. * `boundaryGap:true` of category axis and splitLine and splitArea.
  30811. * @param {Object} [opt]
  30812. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  30813. * @param {boolean} [opt.clamp] If `true`, the first and the last
  30814. * tick must be at the axis end points. Otherwise, clip ticks
  30815. * that outside the axis extent.
  30816. * @return {Array.<Object>} [{
  30817. * coord: ...,
  30818. * tickValue: ...
  30819. * }, ...]
  30820. */
  30821. getTicksCoords: function (opt) {
  30822. opt = opt || {};
  30823. var tickModel = opt.tickModel || this.getTickModel();
  30824. var result = createAxisTicks(this, tickModel);
  30825. var ticks = result.ticks;
  30826. var ticksCoords = map(ticks, function (tickValue) {
  30827. return {
  30828. coord: this.dataToCoord(tickValue),
  30829. tickValue: tickValue
  30830. };
  30831. }, this);
  30832. var alignWithLabel = tickModel.get('alignWithLabel');
  30833. fixOnBandTicksCoords(
  30834. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  30835. );
  30836. return ticksCoords;
  30837. },
  30838. /**
  30839. * @return {Array.<Object>} [{
  30840. * formattedLabel: string,
  30841. * rawLabel: axis.scale.getLabel(tickValue)
  30842. * tickValue: number
  30843. * }, ...]
  30844. */
  30845. getViewLabels: function () {
  30846. return createAxisLabels(this).labels;
  30847. },
  30848. /**
  30849. * @return {module:echarts/coord/model/Model}
  30850. */
  30851. getLabelModel: function () {
  30852. return this.model.getModel('axisLabel');
  30853. },
  30854. /**
  30855. * Notice here we only get the default tick model. For splitLine
  30856. * or splitArea, we should pass the splitLineModel or splitAreaModel
  30857. * manually when calling `getTicksCoords`.
  30858. * In GL, this method may be overrided to:
  30859. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  30860. * @return {module:echarts/coord/model/Model}
  30861. */
  30862. getTickModel: function () {
  30863. return this.model.getModel('axisTick');
  30864. },
  30865. /**
  30866. * Get width of band
  30867. * @return {number}
  30868. */
  30869. getBandWidth: function () {
  30870. var axisExtent = this._extent;
  30871. var dataExtent = this.scale.getExtent();
  30872. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  30873. // Fix #2728, avoid NaN when only one data.
  30874. len === 0 && (len = 1);
  30875. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  30876. return Math.abs(size) / len;
  30877. },
  30878. /**
  30879. * @abstract
  30880. * @return {boolean} Is horizontal
  30881. */
  30882. isHorizontal: null,
  30883. /**
  30884. * @abstract
  30885. * @return {number} Get axis rotate, by degree.
  30886. */
  30887. getRotate: null,
  30888. /**
  30889. * Only be called in category axis.
  30890. * Can be overrided, consider other axes like in 3D.
  30891. * @return {number} Auto interval for cateogry axis tick and label
  30892. */
  30893. calculateCategoryInterval: function () {
  30894. return calculateCategoryInterval(this);
  30895. }
  30896. };
  30897. function fixExtentWithBands(extent, nTick) {
  30898. var size = extent[1] - extent[0];
  30899. var len = nTick;
  30900. var margin = size / len / 2;
  30901. extent[0] += margin;
  30902. extent[1] -= margin;
  30903. }
  30904. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  30905. // |---1---|---2---|---3---|---4---|.
  30906. // So the displayed ticks and splitLine/splitArea should between
  30907. // each data item, otherwise cause misleading (e.g., split tow bars
  30908. // of a single data item when there are two bar series).
  30909. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  30910. // splitLine/spliteArea should layout appropriately corresponding
  30911. // to displayed labels. (So we should not use `getBandWidth` in this
  30912. // case).
  30913. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  30914. var ticksLen = ticksCoords.length;
  30915. if (!axis.onBand || alignWithLabel || !ticksLen) {
  30916. return;
  30917. }
  30918. var axisExtent = axis.getExtent();
  30919. var last;
  30920. if (ticksLen === 1) {
  30921. ticksCoords[0].coord = axisExtent[0];
  30922. last = ticksCoords[1] = {coord: axisExtent[0]};
  30923. }
  30924. else {
  30925. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  30926. each$1(ticksCoords, function (ticksItem) {
  30927. ticksItem.coord -= shift / 2;
  30928. var tickCategoryInterval = tickCategoryInterval || 0;
  30929. // Avoid split a single data item when odd interval.
  30930. if (tickCategoryInterval % 2 > 0) {
  30931. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  30932. }
  30933. });
  30934. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  30935. ticksCoords.push(last);
  30936. }
  30937. var inverse = axisExtent[0] > axisExtent[1];
  30938. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  30939. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  30940. }
  30941. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  30942. ticksCoords.unshift({coord: axisExtent[0]});
  30943. }
  30944. if (littleThan(axisExtent[1], last.coord)) {
  30945. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  30946. }
  30947. if (clamp && littleThan(last.coord, axisExtent[1])) {
  30948. ticksCoords.push({coord: axisExtent[1]});
  30949. }
  30950. function littleThan(a, b) {
  30951. return inverse ? a > b : a < b;
  30952. }
  30953. }
  30954. /*
  30955. * Licensed to the Apache Software Foundation (ASF) under one
  30956. * or more contributor license agreements. See the NOTICE file
  30957. * distributed with this work for additional information
  30958. * regarding copyright ownership. The ASF licenses this file
  30959. * to you under the Apache License, Version 2.0 (the
  30960. * "License"); you may not use this file except in compliance
  30961. * with the License. You may obtain a copy of the License at
  30962. *
  30963. * http://www.apache.org/licenses/LICENSE-2.0
  30964. *
  30965. * Unless required by applicable law or agreed to in writing,
  30966. * software distributed under the License is distributed on an
  30967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30968. * KIND, either express or implied. See the License for the
  30969. * specific language governing permissions and limitations
  30970. * under the License.
  30971. */
  30972. /**
  30973. * Do not mount those modules on 'src/echarts' for better tree shaking.
  30974. */
  30975. var parseGeoJson = parseGeoJson$1;
  30976. var ecUtil = {};
  30977. each$1(
  30978. [
  30979. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  30980. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  30981. 'extend', 'defaults', 'clone', 'merge'
  30982. ],
  30983. function (name) {
  30984. ecUtil[name] = zrUtil[name];
  30985. }
  30986. );
  30987. var graphic$1 = {};
  30988. each$1(
  30989. [
  30990. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  30991. 'mergePath', 'resizePath', 'createIcon',
  30992. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  30993. 'getFont', 'updateProps', 'initProps', 'getTransform',
  30994. 'clipPointsByRect', 'clipRectByRect',
  30995. 'Group',
  30996. 'Image',
  30997. 'Text',
  30998. 'Circle',
  30999. 'Sector',
  31000. 'Ring',
  31001. 'Polygon',
  31002. 'Polyline',
  31003. 'Rect',
  31004. 'Line',
  31005. 'BezierCurve',
  31006. 'Arc',
  31007. 'IncrementalDisplayable',
  31008. 'CompoundPath',
  31009. 'LinearGradient',
  31010. 'RadialGradient',
  31011. 'BoundingRect'
  31012. ],
  31013. function (name) {
  31014. graphic$1[name] = graphic[name];
  31015. }
  31016. );
  31017. /*
  31018. * Licensed to the Apache Software Foundation (ASF) under one
  31019. * or more contributor license agreements. See the NOTICE file
  31020. * distributed with this work for additional information
  31021. * regarding copyright ownership. The ASF licenses this file
  31022. * to you under the Apache License, Version 2.0 (the
  31023. * "License"); you may not use this file except in compliance
  31024. * with the License. You may obtain a copy of the License at
  31025. *
  31026. * http://www.apache.org/licenses/LICENSE-2.0
  31027. *
  31028. * Unless required by applicable law or agreed to in writing,
  31029. * software distributed under the License is distributed on an
  31030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31031. * KIND, either express or implied. See the License for the
  31032. * specific language governing permissions and limitations
  31033. * under the License.
  31034. */
  31035. SeriesModel.extend({
  31036. type: 'series.line',
  31037. dependencies: ['grid', 'polar'],
  31038. getInitialData: function (option, ecModel) {
  31039. if (__DEV__) {
  31040. var coordSys = option.coordinateSystem;
  31041. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  31042. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  31043. }
  31044. }
  31045. return createListFromArray(this.getSource(), this);
  31046. },
  31047. defaultOption: {
  31048. zlevel: 0,
  31049. z: 2,
  31050. coordinateSystem: 'cartesian2d',
  31051. legendHoverLink: true,
  31052. hoverAnimation: true,
  31053. // stack: null
  31054. // xAxisIndex: 0,
  31055. // yAxisIndex: 0,
  31056. // polarIndex: 0,
  31057. // If clip the overflow value
  31058. clipOverflow: true,
  31059. // cursor: null,
  31060. label: {
  31061. position: 'top'
  31062. },
  31063. // itemStyle: {
  31064. // },
  31065. lineStyle: {
  31066. width: 2,
  31067. type: 'solid'
  31068. },
  31069. // areaStyle: {
  31070. // origin of areaStyle. Valid values:
  31071. // `'auto'/null/undefined`: from axisLine to data
  31072. // `'start'`: from min to data
  31073. // `'end'`: from data to max
  31074. // origin: 'auto'
  31075. // },
  31076. // false, 'start', 'end', 'middle'
  31077. step: false,
  31078. // Disabled if step is true
  31079. smooth: false,
  31080. smoothMonotone: null,
  31081. symbol: 'emptyCircle',
  31082. symbolSize: 4,
  31083. symbolRotate: null,
  31084. showSymbol: true,
  31085. // `false`: follow the label interval strategy.
  31086. // `true`: show all symbols.
  31087. // `'auto'`: If possible, show all symbols, otherwise
  31088. // follow the label interval strategy.
  31089. showAllSymbol: 'auto',
  31090. // Whether to connect break point.
  31091. connectNulls: false,
  31092. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  31093. sampling: 'none',
  31094. animationEasing: 'linear',
  31095. // Disable progressive
  31096. progressive: 0,
  31097. hoverLayerThreshold: Infinity
  31098. }
  31099. });
  31100. /*
  31101. * Licensed to the Apache Software Foundation (ASF) under one
  31102. * or more contributor license agreements. See the NOTICE file
  31103. * distributed with this work for additional information
  31104. * regarding copyright ownership. The ASF licenses this file
  31105. * to you under the Apache License, Version 2.0 (the
  31106. * "License"); you may not use this file except in compliance
  31107. * with the License. You may obtain a copy of the License at
  31108. *
  31109. * http://www.apache.org/licenses/LICENSE-2.0
  31110. *
  31111. * Unless required by applicable law or agreed to in writing,
  31112. * software distributed under the License is distributed on an
  31113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31114. * KIND, either express or implied. See the License for the
  31115. * specific language governing permissions and limitations
  31116. * under the License.
  31117. */
  31118. /**
  31119. * @param {module:echarts/data/List} data
  31120. * @param {number} dataIndex
  31121. * @return {string} label string. Not null/undefined
  31122. */
  31123. function getDefaultLabel(data, dataIndex) {
  31124. var labelDims = data.mapDimension('defaultedLabel', true);
  31125. var len = labelDims.length;
  31126. // Simple optimization (in lots of cases, label dims length is 1)
  31127. if (len === 1) {
  31128. return retrieveRawValue(data, dataIndex, labelDims[0]);
  31129. }
  31130. else if (len) {
  31131. var vals = [];
  31132. for (var i = 0; i < labelDims.length; i++) {
  31133. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  31134. vals.push(val);
  31135. }
  31136. return vals.join(' ');
  31137. }
  31138. }
  31139. /*
  31140. * Licensed to the Apache Software Foundation (ASF) under one
  31141. * or more contributor license agreements. See the NOTICE file
  31142. * distributed with this work for additional information
  31143. * regarding copyright ownership. The ASF licenses this file
  31144. * to you under the Apache License, Version 2.0 (the
  31145. * "License"); you may not use this file except in compliance
  31146. * with the License. You may obtain a copy of the License at
  31147. *
  31148. * http://www.apache.org/licenses/LICENSE-2.0
  31149. *
  31150. * Unless required by applicable law or agreed to in writing,
  31151. * software distributed under the License is distributed on an
  31152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31153. * KIND, either express or implied. See the License for the
  31154. * specific language governing permissions and limitations
  31155. * under the License.
  31156. */
  31157. /**
  31158. * @module echarts/chart/helper/Symbol
  31159. */
  31160. /**
  31161. * @constructor
  31162. * @alias {module:echarts/chart/helper/Symbol}
  31163. * @param {module:echarts/data/List} data
  31164. * @param {number} idx
  31165. * @extends {module:zrender/graphic/Group}
  31166. */
  31167. function SymbolClz$1(data, idx, seriesScope) {
  31168. Group.call(this);
  31169. this.updateData(data, idx, seriesScope);
  31170. }
  31171. var symbolProto = SymbolClz$1.prototype;
  31172. /**
  31173. * @public
  31174. * @static
  31175. * @param {module:echarts/data/List} data
  31176. * @param {number} dataIndex
  31177. * @return {Array.<number>} [width, height]
  31178. */
  31179. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  31180. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  31181. return symbolSize instanceof Array
  31182. ? symbolSize.slice()
  31183. : [+symbolSize, +symbolSize];
  31184. };
  31185. function getScale(symbolSize) {
  31186. return [symbolSize[0] / 2, symbolSize[1] / 2];
  31187. }
  31188. function driftSymbol(dx, dy) {
  31189. this.parent.drift(dx, dy);
  31190. }
  31191. symbolProto._createSymbol = function (
  31192. symbolType,
  31193. data,
  31194. idx,
  31195. symbolSize,
  31196. keepAspect
  31197. ) {
  31198. // Remove paths created before
  31199. this.removeAll();
  31200. var color = data.getItemVisual(idx, 'color');
  31201. // var symbolPath = createSymbol(
  31202. // symbolType, -0.5, -0.5, 1, 1, color
  31203. // );
  31204. // If width/height are set too small (e.g., set to 1) on ios10
  31205. // and macOS Sierra, a circle stroke become a rect, no matter what
  31206. // the scale is set. So we set width/height as 2. See #4150.
  31207. var symbolPath = createSymbol(
  31208. symbolType, -1, -1, 2, 2, color, keepAspect
  31209. );
  31210. symbolPath.attr({
  31211. z2: 100,
  31212. culling: true,
  31213. scale: getScale(symbolSize)
  31214. });
  31215. // Rewrite drift method
  31216. symbolPath.drift = driftSymbol;
  31217. this._symbolType = symbolType;
  31218. this.add(symbolPath);
  31219. };
  31220. /**
  31221. * Stop animation
  31222. * @param {boolean} toLastFrame
  31223. */
  31224. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  31225. this.childAt(0).stopAnimation(toLastFrame);
  31226. };
  31227. /**
  31228. * FIXME:
  31229. * Caution: This method breaks the encapsulation of this module,
  31230. * but it indeed brings convenience. So do not use the method
  31231. * unless you detailedly know all the implements of `Symbol`,
  31232. * especially animation.
  31233. *
  31234. * Get symbol path element.
  31235. */
  31236. symbolProto.getSymbolPath = function () {
  31237. return this.childAt(0);
  31238. };
  31239. /**
  31240. * Get scale(aka, current symbol size).
  31241. * Including the change caused by animation
  31242. */
  31243. symbolProto.getScale = function () {
  31244. return this.childAt(0).scale;
  31245. };
  31246. /**
  31247. * Highlight symbol
  31248. */
  31249. symbolProto.highlight = function () {
  31250. this.childAt(0).trigger('emphasis');
  31251. };
  31252. /**
  31253. * Downplay symbol
  31254. */
  31255. symbolProto.downplay = function () {
  31256. this.childAt(0).trigger('normal');
  31257. };
  31258. /**
  31259. * @param {number} zlevel
  31260. * @param {number} z
  31261. */
  31262. symbolProto.setZ = function (zlevel, z) {
  31263. var symbolPath = this.childAt(0);
  31264. symbolPath.zlevel = zlevel;
  31265. symbolPath.z = z;
  31266. };
  31267. symbolProto.setDraggable = function (draggable) {
  31268. var symbolPath = this.childAt(0);
  31269. symbolPath.draggable = draggable;
  31270. symbolPath.cursor = draggable ? 'move' : 'pointer';
  31271. };
  31272. /**
  31273. * Update symbol properties
  31274. * @param {module:echarts/data/List} data
  31275. * @param {number} idx
  31276. * @param {Object} [seriesScope]
  31277. * @param {Object} [seriesScope.itemStyle]
  31278. * @param {Object} [seriesScope.hoverItemStyle]
  31279. * @param {Object} [seriesScope.symbolRotate]
  31280. * @param {Object} [seriesScope.symbolOffset]
  31281. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  31282. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  31283. * @param {boolean} [seriesScope.hoverAnimation]
  31284. * @param {Object} [seriesScope.cursorStyle]
  31285. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  31286. * @param {string} [seriesScope.symbolInnerColor]
  31287. * @param {Object} [seriesScope.fadeIn=false]
  31288. */
  31289. symbolProto.updateData = function (data, idx, seriesScope) {
  31290. this.silent = false;
  31291. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  31292. var seriesModel = data.hostModel;
  31293. var symbolSize = getSymbolSize(data, idx);
  31294. var isInit = symbolType !== this._symbolType;
  31295. if (isInit) {
  31296. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  31297. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  31298. }
  31299. else {
  31300. var symbolPath = this.childAt(0);
  31301. symbolPath.silent = false;
  31302. updateProps(symbolPath, {
  31303. scale: getScale(symbolSize)
  31304. }, seriesModel, idx);
  31305. }
  31306. this._updateCommon(data, idx, symbolSize, seriesScope);
  31307. if (isInit) {
  31308. var symbolPath = this.childAt(0);
  31309. var fadeIn = seriesScope && seriesScope.fadeIn;
  31310. var target = {scale: symbolPath.scale.slice()};
  31311. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  31312. symbolPath.scale = [0, 0];
  31313. fadeIn && (symbolPath.style.opacity = 0);
  31314. initProps(symbolPath, target, seriesModel, idx);
  31315. }
  31316. this._seriesModel = seriesModel;
  31317. };
  31318. // Update common properties
  31319. var normalStyleAccessPath = ['itemStyle'];
  31320. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  31321. var normalLabelAccessPath = ['label'];
  31322. var emphasisLabelAccessPath = ['emphasis', 'label'];
  31323. /**
  31324. * @param {module:echarts/data/List} data
  31325. * @param {number} idx
  31326. * @param {Array.<number>} symbolSize
  31327. * @param {Object} [seriesScope]
  31328. */
  31329. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  31330. var symbolPath = this.childAt(0);
  31331. var seriesModel = data.hostModel;
  31332. var color = data.getItemVisual(idx, 'color');
  31333. // Reset style
  31334. if (symbolPath.type !== 'image') {
  31335. symbolPath.useStyle({
  31336. strokeNoScale: true
  31337. });
  31338. }
  31339. var itemStyle = seriesScope && seriesScope.itemStyle;
  31340. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  31341. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  31342. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  31343. var labelModel = seriesScope && seriesScope.labelModel;
  31344. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  31345. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  31346. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  31347. if (!seriesScope || data.hasItemOption) {
  31348. var itemModel = (seriesScope && seriesScope.itemModel)
  31349. ? seriesScope.itemModel : data.getItemModel(idx);
  31350. // Color must be excluded.
  31351. // Because symbol provide setColor individually to set fill and stroke
  31352. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  31353. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  31354. symbolRotate = itemModel.getShallow('symbolRotate');
  31355. symbolOffset = itemModel.getShallow('symbolOffset');
  31356. labelModel = itemModel.getModel(normalLabelAccessPath);
  31357. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  31358. hoverAnimation = itemModel.getShallow('hoverAnimation');
  31359. cursorStyle = itemModel.getShallow('cursor');
  31360. }
  31361. else {
  31362. hoverItemStyle = extend({}, hoverItemStyle);
  31363. }
  31364. var elStyle = symbolPath.style;
  31365. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  31366. if (symbolOffset) {
  31367. symbolPath.attr('position', [
  31368. parsePercent$1(symbolOffset[0], symbolSize[0]),
  31369. parsePercent$1(symbolOffset[1], symbolSize[1])
  31370. ]);
  31371. }
  31372. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  31373. // PENDING setColor before setStyle!!!
  31374. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  31375. symbolPath.setStyle(itemStyle);
  31376. var opacity = data.getItemVisual(idx, 'opacity');
  31377. if (opacity != null) {
  31378. elStyle.opacity = opacity;
  31379. }
  31380. var liftZ = data.getItemVisual(idx, 'liftZ');
  31381. var z2Origin = symbolPath.__z2Origin;
  31382. if (liftZ != null) {
  31383. if (z2Origin == null) {
  31384. symbolPath.__z2Origin = symbolPath.z2;
  31385. symbolPath.z2 += liftZ;
  31386. }
  31387. }
  31388. else if (z2Origin != null) {
  31389. symbolPath.z2 = z2Origin;
  31390. symbolPath.__z2Origin = null;
  31391. }
  31392. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  31393. setLabelStyle(
  31394. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  31395. {
  31396. labelFetcher: seriesModel,
  31397. labelDataIndex: idx,
  31398. defaultText: getLabelDefaultText,
  31399. isRectText: true,
  31400. autoColor: color
  31401. }
  31402. );
  31403. // Do not execute util needed.
  31404. function getLabelDefaultText(idx, opt) {
  31405. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  31406. }
  31407. symbolPath.off('mouseover')
  31408. .off('mouseout')
  31409. .off('emphasis')
  31410. .off('normal');
  31411. symbolPath.hoverStyle = hoverItemStyle;
  31412. // FIXME
  31413. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  31414. setHoverStyle(symbolPath);
  31415. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  31416. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  31417. // Note: consider `off`, should use static function here.
  31418. symbolPath.on('mouseover', onMouseOver)
  31419. .on('mouseout', onMouseOut)
  31420. .on('emphasis', onEmphasis)
  31421. .on('normal', onNormal);
  31422. }
  31423. };
  31424. function onMouseOver() {
  31425. // see comment in `graphic.isInEmphasis`
  31426. !isInEmphasis(this) && onEmphasis.call(this);
  31427. }
  31428. function onMouseOut() {
  31429. // see comment in `graphic.isInEmphasis`
  31430. !isInEmphasis(this) && onNormal.call(this);
  31431. }
  31432. function onEmphasis() {
  31433. // Do not support this hover animation util some scenario required.
  31434. // Animation can only be supported in hover layer when using `el.incremetal`.
  31435. if (this.incremental || this.useHoverLayer) {
  31436. return;
  31437. }
  31438. var scale = this.__symbolOriginalScale;
  31439. var ratio = scale[1] / scale[0];
  31440. this.animateTo({
  31441. scale: [
  31442. Math.max(scale[0] * 1.1, scale[0] + 3),
  31443. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  31444. ]
  31445. }, 400, 'elasticOut');
  31446. }
  31447. function onNormal() {
  31448. if (this.incremental || this.useHoverLayer) {
  31449. return;
  31450. }
  31451. this.animateTo({
  31452. scale: this.__symbolOriginalScale
  31453. }, 400, 'elasticOut');
  31454. }
  31455. /**
  31456. * @param {Function} cb
  31457. * @param {Object} [opt]
  31458. * @param {Object} [opt.keepLabel=true]
  31459. */
  31460. symbolProto.fadeOut = function (cb, opt) {
  31461. var symbolPath = this.childAt(0);
  31462. // Avoid mistaken hover when fading out
  31463. this.silent = symbolPath.silent = true;
  31464. // Not show text when animating
  31465. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  31466. updateProps(
  31467. symbolPath,
  31468. {
  31469. style: {opacity: 0},
  31470. scale: [0, 0]
  31471. },
  31472. this._seriesModel,
  31473. this.dataIndex,
  31474. cb
  31475. );
  31476. };
  31477. inherits(SymbolClz$1, Group);
  31478. /*
  31479. * Licensed to the Apache Software Foundation (ASF) under one
  31480. * or more contributor license agreements. See the NOTICE file
  31481. * distributed with this work for additional information
  31482. * regarding copyright ownership. The ASF licenses this file
  31483. * to you under the Apache License, Version 2.0 (the
  31484. * "License"); you may not use this file except in compliance
  31485. * with the License. You may obtain a copy of the License at
  31486. *
  31487. * http://www.apache.org/licenses/LICENSE-2.0
  31488. *
  31489. * Unless required by applicable law or agreed to in writing,
  31490. * software distributed under the License is distributed on an
  31491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31492. * KIND, either express or implied. See the License for the
  31493. * specific language governing permissions and limitations
  31494. * under the License.
  31495. */
  31496. /**
  31497. * @module echarts/chart/helper/SymbolDraw
  31498. */
  31499. /**
  31500. * @constructor
  31501. * @alias module:echarts/chart/helper/SymbolDraw
  31502. * @param {module:zrender/graphic/Group} [symbolCtor]
  31503. */
  31504. function SymbolDraw(symbolCtor) {
  31505. this.group = new Group();
  31506. this._symbolCtor = symbolCtor || SymbolClz$1;
  31507. }
  31508. var symbolDrawProto = SymbolDraw.prototype;
  31509. function symbolNeedsDraw(data, point, idx, opt) {
  31510. return point && !isNaN(point[0]) && !isNaN(point[1])
  31511. && !(opt.isIgnore && opt.isIgnore(idx))
  31512. // We do not set clipShape on group, because it will cut part of
  31513. // the symbol element shape. We use the same clip shape here as
  31514. // the line clip.
  31515. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  31516. && data.getItemVisual(idx, 'symbol') !== 'none';
  31517. }
  31518. /**
  31519. * Update symbols draw by new data
  31520. * @param {module:echarts/data/List} data
  31521. * @param {Object} [opt] Or isIgnore
  31522. * @param {Function} [opt.isIgnore]
  31523. * @param {Object} [opt.clipShape]
  31524. */
  31525. symbolDrawProto.updateData = function (data, opt) {
  31526. opt = normalizeUpdateOpt(opt);
  31527. var group = this.group;
  31528. var seriesModel = data.hostModel;
  31529. var oldData = this._data;
  31530. var SymbolCtor = this._symbolCtor;
  31531. var seriesScope = makeSeriesScope(data);
  31532. // There is no oldLineData only when first rendering or switching from
  31533. // stream mode to normal mode, where previous elements should be removed.
  31534. if (!oldData) {
  31535. group.removeAll();
  31536. }
  31537. data.diff(oldData)
  31538. .add(function (newIdx) {
  31539. var point = data.getItemLayout(newIdx);
  31540. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  31541. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  31542. symbolEl.attr('position', point);
  31543. data.setItemGraphicEl(newIdx, symbolEl);
  31544. group.add(symbolEl);
  31545. }
  31546. })
  31547. .update(function (newIdx, oldIdx) {
  31548. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  31549. var point = data.getItemLayout(newIdx);
  31550. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  31551. group.remove(symbolEl);
  31552. return;
  31553. }
  31554. if (!symbolEl) {
  31555. symbolEl = new SymbolCtor(data, newIdx);
  31556. symbolEl.attr('position', point);
  31557. }
  31558. else {
  31559. symbolEl.updateData(data, newIdx, seriesScope);
  31560. updateProps(symbolEl, {
  31561. position: point
  31562. }, seriesModel);
  31563. }
  31564. // Add back
  31565. group.add(symbolEl);
  31566. data.setItemGraphicEl(newIdx, symbolEl);
  31567. })
  31568. .remove(function (oldIdx) {
  31569. var el = oldData.getItemGraphicEl(oldIdx);
  31570. el && el.fadeOut(function () {
  31571. group.remove(el);
  31572. });
  31573. })
  31574. .execute();
  31575. this._data = data;
  31576. };
  31577. symbolDrawProto.isPersistent = function () {
  31578. return true;
  31579. };
  31580. symbolDrawProto.updateLayout = function () {
  31581. var data = this._data;
  31582. if (data) {
  31583. // Not use animation
  31584. data.eachItemGraphicEl(function (el, idx) {
  31585. var point = data.getItemLayout(idx);
  31586. el.attr('position', point);
  31587. });
  31588. }
  31589. };
  31590. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  31591. this._seriesScope = makeSeriesScope(data);
  31592. this._data = null;
  31593. this.group.removeAll();
  31594. };
  31595. /**
  31596. * Update symbols draw by new data
  31597. * @param {module:echarts/data/List} data
  31598. * @param {Object} [opt] Or isIgnore
  31599. * @param {Function} [opt.isIgnore]
  31600. * @param {Object} [opt.clipShape]
  31601. */
  31602. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  31603. opt = normalizeUpdateOpt(opt);
  31604. function updateIncrementalAndHover(el) {
  31605. if (!el.isGroup) {
  31606. el.incremental = el.useHoverLayer = true;
  31607. }
  31608. }
  31609. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  31610. var point = data.getItemLayout(idx);
  31611. if (symbolNeedsDraw(data, point, idx, opt)) {
  31612. var el = new this._symbolCtor(data, idx, this._seriesScope);
  31613. el.traverse(updateIncrementalAndHover);
  31614. el.attr('position', point);
  31615. this.group.add(el);
  31616. data.setItemGraphicEl(idx, el);
  31617. }
  31618. }
  31619. };
  31620. function normalizeUpdateOpt(opt) {
  31621. if (opt != null && !isObject$1(opt)) {
  31622. opt = {isIgnore: opt};
  31623. }
  31624. return opt || {};
  31625. }
  31626. symbolDrawProto.remove = function (enableAnimation) {
  31627. var group = this.group;
  31628. var data = this._data;
  31629. // Incremental model do not have this._data.
  31630. if (data && enableAnimation) {
  31631. data.eachItemGraphicEl(function (el) {
  31632. el.fadeOut(function () {
  31633. group.remove(el);
  31634. });
  31635. });
  31636. }
  31637. else {
  31638. group.removeAll();
  31639. }
  31640. };
  31641. function makeSeriesScope(data) {
  31642. var seriesModel = data.hostModel;
  31643. return {
  31644. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  31645. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  31646. symbolRotate: seriesModel.get('symbolRotate'),
  31647. symbolOffset: seriesModel.get('symbolOffset'),
  31648. hoverAnimation: seriesModel.get('hoverAnimation'),
  31649. labelModel: seriesModel.getModel('label'),
  31650. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  31651. cursorStyle: seriesModel.get('cursor')
  31652. };
  31653. }
  31654. /*
  31655. * Licensed to the Apache Software Foundation (ASF) under one
  31656. * or more contributor license agreements. See the NOTICE file
  31657. * distributed with this work for additional information
  31658. * regarding copyright ownership. The ASF licenses this file
  31659. * to you under the Apache License, Version 2.0 (the
  31660. * "License"); you may not use this file except in compliance
  31661. * with the License. You may obtain a copy of the License at
  31662. *
  31663. * http://www.apache.org/licenses/LICENSE-2.0
  31664. *
  31665. * Unless required by applicable law or agreed to in writing,
  31666. * software distributed under the License is distributed on an
  31667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31668. * KIND, either express or implied. See the License for the
  31669. * specific language governing permissions and limitations
  31670. * under the License.
  31671. */
  31672. /**
  31673. * @param {Object} coordSys
  31674. * @param {module:echarts/data/List} data
  31675. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  31676. */
  31677. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  31678. var baseAxis = coordSys.getBaseAxis();
  31679. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31680. var valueStart = getValueStart(valueAxis, valueOrigin);
  31681. var baseAxisDim = baseAxis.dim;
  31682. var valueAxisDim = valueAxis.dim;
  31683. var valueDim = data.mapDimension(valueAxisDim);
  31684. var baseDim = data.mapDimension(baseAxisDim);
  31685. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  31686. var dims = map(coordSys.dimensions, function (coordDim) {
  31687. return data.mapDimension(coordDim);
  31688. });
  31689. var stacked;
  31690. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31691. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  31692. dims[0] = stackResultDim;
  31693. }
  31694. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  31695. dims[1] = stackResultDim;
  31696. }
  31697. return {
  31698. dataDimsForPoint: dims,
  31699. valueStart: valueStart,
  31700. valueAxisDim: valueAxisDim,
  31701. baseAxisDim: baseAxisDim,
  31702. stacked: !!stacked,
  31703. valueDim: valueDim,
  31704. baseDim: baseDim,
  31705. baseDataOffset: baseDataOffset,
  31706. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  31707. };
  31708. }
  31709. function getValueStart(valueAxis, valueOrigin) {
  31710. var valueStart = 0;
  31711. var extent = valueAxis.scale.getExtent();
  31712. if (valueOrigin === 'start') {
  31713. valueStart = extent[0];
  31714. }
  31715. else if (valueOrigin === 'end') {
  31716. valueStart = extent[1];
  31717. }
  31718. // auto
  31719. else {
  31720. // Both positive
  31721. if (extent[0] > 0) {
  31722. valueStart = extent[0];
  31723. }
  31724. // Both negative
  31725. else if (extent[1] < 0) {
  31726. valueStart = extent[1];
  31727. }
  31728. // If is one positive, and one negative, onZero shall be true
  31729. }
  31730. return valueStart;
  31731. }
  31732. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  31733. var value = NaN;
  31734. if (dataCoordInfo.stacked) {
  31735. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  31736. }
  31737. if (isNaN(value)) {
  31738. value = dataCoordInfo.valueStart;
  31739. }
  31740. var baseDataOffset = dataCoordInfo.baseDataOffset;
  31741. var stackedData = [];
  31742. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  31743. stackedData[1 - baseDataOffset] = value;
  31744. return coordSys.dataToPoint(stackedData);
  31745. }
  31746. /*
  31747. * Licensed to the Apache Software Foundation (ASF) under one
  31748. * or more contributor license agreements. See the NOTICE file
  31749. * distributed with this work for additional information
  31750. * regarding copyright ownership. The ASF licenses this file
  31751. * to you under the Apache License, Version 2.0 (the
  31752. * "License"); you may not use this file except in compliance
  31753. * with the License. You may obtain a copy of the License at
  31754. *
  31755. * http://www.apache.org/licenses/LICENSE-2.0
  31756. *
  31757. * Unless required by applicable law or agreed to in writing,
  31758. * software distributed under the License is distributed on an
  31759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31760. * KIND, either express or implied. See the License for the
  31761. * specific language governing permissions and limitations
  31762. * under the License.
  31763. */
  31764. // var arrayDiff = require('zrender/src/core/arrayDiff');
  31765. // 'zrender/src/core/arrayDiff' has been used before, but it did
  31766. // not do well in performance when roam with fixed dataZoom window.
  31767. // function convertToIntId(newIdList, oldIdList) {
  31768. // // Generate int id instead of string id.
  31769. // // Compare string maybe slow in score function of arrDiff
  31770. // // Assume id in idList are all unique
  31771. // var idIndicesMap = {};
  31772. // var idx = 0;
  31773. // for (var i = 0; i < newIdList.length; i++) {
  31774. // idIndicesMap[newIdList[i]] = idx;
  31775. // newIdList[i] = idx++;
  31776. // }
  31777. // for (var i = 0; i < oldIdList.length; i++) {
  31778. // var oldId = oldIdList[i];
  31779. // // Same with newIdList
  31780. // if (idIndicesMap[oldId]) {
  31781. // oldIdList[i] = idIndicesMap[oldId];
  31782. // }
  31783. // else {
  31784. // oldIdList[i] = idx++;
  31785. // }
  31786. // }
  31787. // }
  31788. function diffData(oldData, newData) {
  31789. var diffResult = [];
  31790. newData.diff(oldData)
  31791. .add(function (idx) {
  31792. diffResult.push({cmd: '+', idx: idx});
  31793. })
  31794. .update(function (newIdx, oldIdx) {
  31795. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  31796. })
  31797. .remove(function (idx) {
  31798. diffResult.push({cmd: '-', idx: idx});
  31799. })
  31800. .execute();
  31801. return diffResult;
  31802. }
  31803. var lineAnimationDiff = function (
  31804. oldData, newData,
  31805. oldStackedOnPoints, newStackedOnPoints,
  31806. oldCoordSys, newCoordSys,
  31807. oldValueOrigin, newValueOrigin
  31808. ) {
  31809. var diff = diffData(oldData, newData);
  31810. // var newIdList = newData.mapArray(newData.getId);
  31811. // var oldIdList = oldData.mapArray(oldData.getId);
  31812. // convertToIntId(newIdList, oldIdList);
  31813. // // FIXME One data ?
  31814. // diff = arrayDiff(oldIdList, newIdList);
  31815. var currPoints = [];
  31816. var nextPoints = [];
  31817. // Points for stacking base line
  31818. var currStackedPoints = [];
  31819. var nextStackedPoints = [];
  31820. var status = [];
  31821. var sortedIndices = [];
  31822. var rawIndices = [];
  31823. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  31824. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  31825. for (var i = 0; i < diff.length; i++) {
  31826. var diffItem = diff[i];
  31827. var pointAdded = true;
  31828. // FIXME, animation is not so perfect when dataZoom window moves fast
  31829. // Which is in case remvoing or add more than one data in the tail or head
  31830. switch (diffItem.cmd) {
  31831. case '=':
  31832. var currentPt = oldData.getItemLayout(diffItem.idx);
  31833. var nextPt = newData.getItemLayout(diffItem.idx1);
  31834. // If previous data is NaN, use next point directly
  31835. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  31836. currentPt = nextPt.slice();
  31837. }
  31838. currPoints.push(currentPt);
  31839. nextPoints.push(nextPt);
  31840. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  31841. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  31842. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  31843. break;
  31844. case '+':
  31845. var idx = diffItem.idx;
  31846. currPoints.push(
  31847. oldCoordSys.dataToPoint([
  31848. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  31849. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  31850. ])
  31851. );
  31852. nextPoints.push(newData.getItemLayout(idx).slice());
  31853. currStackedPoints.push(
  31854. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  31855. );
  31856. nextStackedPoints.push(newStackedOnPoints[idx]);
  31857. rawIndices.push(newData.getRawIndex(idx));
  31858. break;
  31859. case '-':
  31860. var idx = diffItem.idx;
  31861. var rawIndex = oldData.getRawIndex(idx);
  31862. // Data is replaced. In the case of dynamic data queue
  31863. // FIXME FIXME FIXME
  31864. if (rawIndex !== idx) {
  31865. currPoints.push(oldData.getItemLayout(idx));
  31866. nextPoints.push(newCoordSys.dataToPoint([
  31867. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  31868. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  31869. ]));
  31870. currStackedPoints.push(oldStackedOnPoints[idx]);
  31871. nextStackedPoints.push(
  31872. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  31873. );
  31874. rawIndices.push(rawIndex);
  31875. }
  31876. else {
  31877. pointAdded = false;
  31878. }
  31879. }
  31880. // Original indices
  31881. if (pointAdded) {
  31882. status.push(diffItem);
  31883. sortedIndices.push(sortedIndices.length);
  31884. }
  31885. }
  31886. // Diff result may be crossed if all items are changed
  31887. // Sort by data index
  31888. sortedIndices.sort(function (a, b) {
  31889. return rawIndices[a] - rawIndices[b];
  31890. });
  31891. var sortedCurrPoints = [];
  31892. var sortedNextPoints = [];
  31893. var sortedCurrStackedPoints = [];
  31894. var sortedNextStackedPoints = [];
  31895. var sortedStatus = [];
  31896. for (var i = 0; i < sortedIndices.length; i++) {
  31897. var idx = sortedIndices[i];
  31898. sortedCurrPoints[i] = currPoints[idx];
  31899. sortedNextPoints[i] = nextPoints[idx];
  31900. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  31901. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  31902. sortedStatus[i] = status[idx];
  31903. }
  31904. return {
  31905. current: sortedCurrPoints,
  31906. next: sortedNextPoints,
  31907. stackedOnCurrent: sortedCurrStackedPoints,
  31908. stackedOnNext: sortedNextStackedPoints,
  31909. status: sortedStatus
  31910. };
  31911. };
  31912. /*
  31913. * Licensed to the Apache Software Foundation (ASF) under one
  31914. * or more contributor license agreements. See the NOTICE file
  31915. * distributed with this work for additional information
  31916. * regarding copyright ownership. The ASF licenses this file
  31917. * to you under the Apache License, Version 2.0 (the
  31918. * "License"); you may not use this file except in compliance
  31919. * with the License. You may obtain a copy of the License at
  31920. *
  31921. * http://www.apache.org/licenses/LICENSE-2.0
  31922. *
  31923. * Unless required by applicable law or agreed to in writing,
  31924. * software distributed under the License is distributed on an
  31925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31926. * KIND, either express or implied. See the License for the
  31927. * specific language governing permissions and limitations
  31928. * under the License.
  31929. */
  31930. // Poly path support NaN point
  31931. var vec2Min = min;
  31932. var vec2Max = max;
  31933. var scaleAndAdd$1 = scaleAndAdd;
  31934. var v2Copy = copy;
  31935. // Temporary variable
  31936. var v = [];
  31937. var cp0 = [];
  31938. var cp1 = [];
  31939. function isPointNull(p) {
  31940. return isNaN(p[0]) || isNaN(p[1]);
  31941. }
  31942. function drawSegment(
  31943. ctx, points, start, segLen, allLen,
  31944. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31945. ) {
  31946. // if (smoothMonotone == null) {
  31947. // if (isMono(points, 'x')) {
  31948. // return drawMono(ctx, points, start, segLen, allLen,
  31949. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  31950. // }
  31951. // else if (isMono(points, 'y')) {
  31952. // return drawMono(ctx, points, start, segLen, allLen,
  31953. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  31954. // }
  31955. // else {
  31956. // return drawNonMono.apply(this, arguments);
  31957. // }
  31958. // }
  31959. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  31960. // return drawMono.apply(this, arguments);
  31961. // }
  31962. // else {
  31963. // return drawNonMono.apply(this, arguments);
  31964. // }
  31965. if (smoothMonotone === 'none' || !smoothMonotone) {
  31966. return drawNonMono.apply(this, arguments);
  31967. }
  31968. else {
  31969. return drawMono.apply(this, arguments);
  31970. }
  31971. }
  31972. /**
  31973. * Check if points is in monotone.
  31974. *
  31975. * @param {number[][]} points Array of points which is in [x, y] form
  31976. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  31977. * dimension that is checking.
  31978. * If is 'none', `drawNonMono` should be
  31979. * called.
  31980. * If is undefined, either being monotone
  31981. * in 'x' or 'y' will call `drawMono`.
  31982. */
  31983. // function isMono(points, smoothMonotone) {
  31984. // if (points.length <= 1) {
  31985. // return true;
  31986. // }
  31987. // var dim = smoothMonotone === 'x' ? 0 : 1;
  31988. // var last = points[0][dim];
  31989. // var lastDiff = 0;
  31990. // for (var i = 1; i < points.length; ++i) {
  31991. // var diff = points[i][dim] - last;
  31992. // if (!isNaN(diff) && !isNaN(lastDiff)
  31993. // && diff !== 0 && lastDiff !== 0
  31994. // && ((diff >= 0) !== (lastDiff >= 0))
  31995. // ) {
  31996. // return false;
  31997. // }
  31998. // if (!isNaN(diff) && diff !== 0) {
  31999. // lastDiff = diff;
  32000. // last = points[i][dim];
  32001. // }
  32002. // }
  32003. // return true;
  32004. // }
  32005. /**
  32006. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  32007. * control points will be used. This should be used when points are monotone
  32008. * either in x or y dimension.
  32009. */
  32010. function drawMono(
  32011. ctx, points, start, segLen, allLen,
  32012. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  32013. ) {
  32014. var prevIdx = 0;
  32015. var idx = start;
  32016. for (var k = 0; k < segLen; k++) {
  32017. var p = points[idx];
  32018. if (idx >= allLen || idx < 0) {
  32019. break;
  32020. }
  32021. if (isPointNull(p)) {
  32022. if (connectNulls) {
  32023. idx += dir;
  32024. continue;
  32025. }
  32026. break;
  32027. }
  32028. if (idx === start) {
  32029. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  32030. }
  32031. else {
  32032. if (smooth > 0) {
  32033. var prevP = points[prevIdx];
  32034. var dim = smoothMonotone === 'y' ? 1 : 0;
  32035. // Length of control point to p, either in x or y, but not both
  32036. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  32037. v2Copy(cp0, prevP);
  32038. cp0[dim] = prevP[dim] + ctrlLen;
  32039. v2Copy(cp1, p);
  32040. cp1[dim] = p[dim] - ctrlLen;
  32041. ctx.bezierCurveTo(
  32042. cp0[0], cp0[1],
  32043. cp1[0], cp1[1],
  32044. p[0], p[1]
  32045. );
  32046. }
  32047. else {
  32048. ctx.lineTo(p[0], p[1]);
  32049. }
  32050. }
  32051. prevIdx = idx;
  32052. idx += dir;
  32053. }
  32054. return k;
  32055. }
  32056. /**
  32057. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  32058. * situations. This should be used when points are non-monotone neither in x or
  32059. * y dimension.
  32060. */
  32061. function drawNonMono(
  32062. ctx, points, start, segLen, allLen,
  32063. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  32064. ) {
  32065. var prevIdx = 0;
  32066. var idx = start;
  32067. for (var k = 0; k < segLen; k++) {
  32068. var p = points[idx];
  32069. if (idx >= allLen || idx < 0) {
  32070. break;
  32071. }
  32072. if (isPointNull(p)) {
  32073. if (connectNulls) {
  32074. idx += dir;
  32075. continue;
  32076. }
  32077. break;
  32078. }
  32079. if (idx === start) {
  32080. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  32081. v2Copy(cp0, p);
  32082. }
  32083. else {
  32084. if (smooth > 0) {
  32085. var nextIdx = idx + dir;
  32086. var nextP = points[nextIdx];
  32087. if (connectNulls) {
  32088. // Find next point not null
  32089. while (nextP && isPointNull(points[nextIdx])) {
  32090. nextIdx += dir;
  32091. nextP = points[nextIdx];
  32092. }
  32093. }
  32094. var ratioNextSeg = 0.5;
  32095. var prevP = points[prevIdx];
  32096. var nextP = points[nextIdx];
  32097. // Last point
  32098. if (!nextP || isPointNull(nextP)) {
  32099. v2Copy(cp1, p);
  32100. }
  32101. else {
  32102. // If next data is null in not connect case
  32103. if (isPointNull(nextP) && !connectNulls) {
  32104. nextP = p;
  32105. }
  32106. sub(v, nextP, prevP);
  32107. var lenPrevSeg;
  32108. var lenNextSeg;
  32109. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  32110. var dim = smoothMonotone === 'x' ? 0 : 1;
  32111. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  32112. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  32113. }
  32114. else {
  32115. lenPrevSeg = dist(p, prevP);
  32116. lenNextSeg = dist(p, nextP);
  32117. }
  32118. // Use ratio of seg length
  32119. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  32120. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  32121. }
  32122. // Smooth constraint
  32123. vec2Min(cp0, cp0, smoothMax);
  32124. vec2Max(cp0, cp0, smoothMin);
  32125. vec2Min(cp1, cp1, smoothMax);
  32126. vec2Max(cp1, cp1, smoothMin);
  32127. ctx.bezierCurveTo(
  32128. cp0[0], cp0[1],
  32129. cp1[0], cp1[1],
  32130. p[0], p[1]
  32131. );
  32132. // cp0 of next segment
  32133. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  32134. }
  32135. else {
  32136. ctx.lineTo(p[0], p[1]);
  32137. }
  32138. }
  32139. prevIdx = idx;
  32140. idx += dir;
  32141. }
  32142. return k;
  32143. }
  32144. function getBoundingBox(points, smoothConstraint) {
  32145. var ptMin = [Infinity, Infinity];
  32146. var ptMax = [-Infinity, -Infinity];
  32147. if (smoothConstraint) {
  32148. for (var i = 0; i < points.length; i++) {
  32149. var pt = points[i];
  32150. if (pt[0] < ptMin[0]) {
  32151. ptMin[0] = pt[0];
  32152. }
  32153. if (pt[1] < ptMin[1]) {
  32154. ptMin[1] = pt[1];
  32155. }
  32156. if (pt[0] > ptMax[0]) {
  32157. ptMax[0] = pt[0];
  32158. }
  32159. if (pt[1] > ptMax[1]) {
  32160. ptMax[1] = pt[1];
  32161. }
  32162. }
  32163. }
  32164. return {
  32165. min: smoothConstraint ? ptMin : ptMax,
  32166. max: smoothConstraint ? ptMax : ptMin
  32167. };
  32168. }
  32169. var Polyline$1 = Path.extend({
  32170. type: 'ec-polyline',
  32171. shape: {
  32172. points: [],
  32173. smooth: 0,
  32174. smoothConstraint: true,
  32175. smoothMonotone: null,
  32176. connectNulls: false
  32177. },
  32178. style: {
  32179. fill: null,
  32180. stroke: '#000'
  32181. },
  32182. brush: fixClipWithShadow(Path.prototype.brush),
  32183. buildPath: function (ctx, shape) {
  32184. var points = shape.points;
  32185. var i = 0;
  32186. var len$$1 = points.length;
  32187. var result = getBoundingBox(points, shape.smoothConstraint);
  32188. if (shape.connectNulls) {
  32189. // Must remove first and last null values avoid draw error in polygon
  32190. for (; len$$1 > 0; len$$1--) {
  32191. if (!isPointNull(points[len$$1 - 1])) {
  32192. break;
  32193. }
  32194. }
  32195. for (; i < len$$1; i++) {
  32196. if (!isPointNull(points[i])) {
  32197. break;
  32198. }
  32199. }
  32200. }
  32201. while (i < len$$1) {
  32202. i += drawSegment(
  32203. ctx, points, i, len$$1, len$$1,
  32204. 1, result.min, result.max, shape.smooth,
  32205. shape.smoothMonotone, shape.connectNulls
  32206. ) + 1;
  32207. }
  32208. }
  32209. });
  32210. var Polygon$1 = Path.extend({
  32211. type: 'ec-polygon',
  32212. shape: {
  32213. points: [],
  32214. // Offset between stacked base points and points
  32215. stackedOnPoints: [],
  32216. smooth: 0,
  32217. stackedOnSmooth: 0,
  32218. smoothConstraint: true,
  32219. smoothMonotone: null,
  32220. connectNulls: false
  32221. },
  32222. brush: fixClipWithShadow(Path.prototype.brush),
  32223. buildPath: function (ctx, shape) {
  32224. var points = shape.points;
  32225. var stackedOnPoints = shape.stackedOnPoints;
  32226. var i = 0;
  32227. var len$$1 = points.length;
  32228. var smoothMonotone = shape.smoothMonotone;
  32229. var bbox = getBoundingBox(points, shape.smoothConstraint);
  32230. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  32231. if (shape.connectNulls) {
  32232. // Must remove first and last null values avoid draw error in polygon
  32233. for (; len$$1 > 0; len$$1--) {
  32234. if (!isPointNull(points[len$$1 - 1])) {
  32235. break;
  32236. }
  32237. }
  32238. for (; i < len$$1; i++) {
  32239. if (!isPointNull(points[i])) {
  32240. break;
  32241. }
  32242. }
  32243. }
  32244. while (i < len$$1) {
  32245. var k = drawSegment(
  32246. ctx, points, i, len$$1, len$$1,
  32247. 1, bbox.min, bbox.max, shape.smooth,
  32248. smoothMonotone, shape.connectNulls
  32249. );
  32250. drawSegment(
  32251. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  32252. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  32253. smoothMonotone, shape.connectNulls
  32254. );
  32255. i += k + 1;
  32256. ctx.closePath();
  32257. }
  32258. }
  32259. });
  32260. /*
  32261. * Licensed to the Apache Software Foundation (ASF) under one
  32262. * or more contributor license agreements. See the NOTICE file
  32263. * distributed with this work for additional information
  32264. * regarding copyright ownership. The ASF licenses this file
  32265. * to you under the Apache License, Version 2.0 (the
  32266. * "License"); you may not use this file except in compliance
  32267. * with the License. You may obtain a copy of the License at
  32268. *
  32269. * http://www.apache.org/licenses/LICENSE-2.0
  32270. *
  32271. * Unless required by applicable law or agreed to in writing,
  32272. * software distributed under the License is distributed on an
  32273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32274. * KIND, either express or implied. See the License for the
  32275. * specific language governing permissions and limitations
  32276. * under the License.
  32277. */
  32278. // FIXME step not support polar
  32279. function isPointsSame(points1, points2) {
  32280. if (points1.length !== points2.length) {
  32281. return;
  32282. }
  32283. for (var i = 0; i < points1.length; i++) {
  32284. var p1 = points1[i];
  32285. var p2 = points2[i];
  32286. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  32287. return;
  32288. }
  32289. }
  32290. return true;
  32291. }
  32292. function getSmooth(smooth) {
  32293. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  32294. }
  32295. function getAxisExtentWithGap(axis) {
  32296. var extent = axis.getGlobalExtent();
  32297. if (axis.onBand) {
  32298. // Remove extra 1px to avoid line miter in clipped edge
  32299. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  32300. var dir = extent[1] > extent[0] ? 1 : -1;
  32301. extent[0] += dir * halfBandWidth;
  32302. extent[1] -= dir * halfBandWidth;
  32303. }
  32304. return extent;
  32305. }
  32306. /**
  32307. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  32308. * @param {module:echarts/data/List} data
  32309. * @param {Object} dataCoordInfo
  32310. * @param {Array.<Array.<number>>} points
  32311. */
  32312. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  32313. if (!dataCoordInfo.valueDim) {
  32314. return [];
  32315. }
  32316. var points = [];
  32317. for (var idx = 0, len = data.count(); idx < len; idx++) {
  32318. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  32319. }
  32320. return points;
  32321. }
  32322. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  32323. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  32324. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  32325. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  32326. var x = Math.min(xExtent[0], xExtent[1]);
  32327. var y = Math.min(yExtent[0], yExtent[1]);
  32328. var width = Math.max(xExtent[0], xExtent[1]) - x;
  32329. var height = Math.max(yExtent[0], yExtent[1]) - y;
  32330. // Avoid float number rounding error for symbol on the edge of axis extent.
  32331. // See #7913 and `test/dataZoom-clip.html`.
  32332. if (forSymbol) {
  32333. x -= 0.5;
  32334. width += 0.5;
  32335. y -= 0.5;
  32336. height += 0.5;
  32337. }
  32338. else {
  32339. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  32340. // Expand clip shape to avoid clipping when line value exceeds axis
  32341. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  32342. if (isHorizontal) {
  32343. y -= expandSize;
  32344. height += expandSize * 2;
  32345. }
  32346. else {
  32347. x -= expandSize;
  32348. width += expandSize * 2;
  32349. }
  32350. }
  32351. var clipPath = new Rect({
  32352. shape: {
  32353. x: x,
  32354. y: y,
  32355. width: width,
  32356. height: height
  32357. }
  32358. });
  32359. if (hasAnimation) {
  32360. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  32361. initProps(clipPath, {
  32362. shape: {
  32363. width: width,
  32364. height: height
  32365. }
  32366. }, seriesModel);
  32367. }
  32368. return clipPath;
  32369. }
  32370. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  32371. var angleAxis = polar.getAngleAxis();
  32372. var radiusAxis = polar.getRadiusAxis();
  32373. var radiusExtent = radiusAxis.getExtent().slice();
  32374. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  32375. var angleExtent = angleAxis.getExtent();
  32376. var RADIAN = Math.PI / 180;
  32377. // Avoid float number rounding error for symbol on the edge of axis extent.
  32378. if (forSymbol) {
  32379. radiusExtent[0] -= 0.5;
  32380. radiusExtent[1] += 0.5;
  32381. }
  32382. var clipPath = new Sector({
  32383. shape: {
  32384. cx: round$2(polar.cx, 1),
  32385. cy: round$2(polar.cy, 1),
  32386. r0: round$2(radiusExtent[0], 1),
  32387. r: round$2(radiusExtent[1], 1),
  32388. startAngle: -angleExtent[0] * RADIAN,
  32389. endAngle: -angleExtent[1] * RADIAN,
  32390. clockwise: angleAxis.inverse
  32391. }
  32392. });
  32393. if (hasAnimation) {
  32394. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  32395. initProps(clipPath, {
  32396. shape: {
  32397. endAngle: -angleExtent[1] * RADIAN
  32398. }
  32399. }, seriesModel);
  32400. }
  32401. return clipPath;
  32402. }
  32403. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  32404. return coordSys.type === 'polar'
  32405. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  32406. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  32407. }
  32408. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  32409. var baseAxis = coordSys.getBaseAxis();
  32410. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  32411. var stepPoints = [];
  32412. for (var i = 0; i < points.length - 1; i++) {
  32413. var nextPt = points[i + 1];
  32414. var pt = points[i];
  32415. stepPoints.push(pt);
  32416. var stepPt = [];
  32417. switch (stepTurnAt) {
  32418. case 'end':
  32419. stepPt[baseIndex] = nextPt[baseIndex];
  32420. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32421. // default is start
  32422. stepPoints.push(stepPt);
  32423. break;
  32424. case 'middle':
  32425. // default is start
  32426. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  32427. var stepPt2 = [];
  32428. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  32429. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32430. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  32431. stepPoints.push(stepPt);
  32432. stepPoints.push(stepPt2);
  32433. break;
  32434. default:
  32435. stepPt[baseIndex] = pt[baseIndex];
  32436. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  32437. // default is start
  32438. stepPoints.push(stepPt);
  32439. }
  32440. }
  32441. // Last points
  32442. points[i] && stepPoints.push(points[i]);
  32443. return stepPoints;
  32444. }
  32445. function getVisualGradient(data, coordSys) {
  32446. var visualMetaList = data.getVisual('visualMeta');
  32447. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  32448. // When data.count() is 0, gradient range can not be calculated.
  32449. return;
  32450. }
  32451. if (coordSys.type !== 'cartesian2d') {
  32452. if (__DEV__) {
  32453. console.warn('Visual map on line style is only supported on cartesian2d.');
  32454. }
  32455. return;
  32456. }
  32457. var coordDim;
  32458. var visualMeta;
  32459. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  32460. var dimIndex = visualMetaList[i].dimension;
  32461. var dimName = data.dimensions[dimIndex];
  32462. var dimInfo = data.getDimensionInfo(dimName);
  32463. coordDim = dimInfo && dimInfo.coordDim;
  32464. // Can only be x or y
  32465. if (coordDim === 'x' || coordDim === 'y') {
  32466. visualMeta = visualMetaList[i];
  32467. break;
  32468. }
  32469. }
  32470. if (!visualMeta) {
  32471. if (__DEV__) {
  32472. console.warn('Visual map on line style only support x or y dimension.');
  32473. }
  32474. return;
  32475. }
  32476. // If the area to be rendered is bigger than area defined by LinearGradient,
  32477. // the canvas spec prescribes that the color of the first stop and the last
  32478. // stop should be used. But if two stops are added at offset 0, in effect
  32479. // browsers use the color of the second stop to render area outside
  32480. // LinearGradient. So we can only infinitesimally extend area defined in
  32481. // LinearGradient to render `outerColors`.
  32482. var axis = coordSys.getAxis(coordDim);
  32483. // dataToCoor mapping may not be linear, but must be monotonic.
  32484. var colorStops = map(visualMeta.stops, function (stop) {
  32485. return {
  32486. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  32487. color: stop.color
  32488. };
  32489. });
  32490. var stopLen = colorStops.length;
  32491. var outerColors = visualMeta.outerColors.slice();
  32492. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  32493. colorStops.reverse();
  32494. outerColors.reverse();
  32495. }
  32496. var tinyExtent = 10; // Arbitrary value: 10px
  32497. var minCoord = colorStops[0].coord - tinyExtent;
  32498. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  32499. var coordSpan = maxCoord - minCoord;
  32500. if (coordSpan < 1e-3) {
  32501. return 'transparent';
  32502. }
  32503. each$1(colorStops, function (stop) {
  32504. stop.offset = (stop.coord - minCoord) / coordSpan;
  32505. });
  32506. colorStops.push({
  32507. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  32508. color: outerColors[1] || 'transparent'
  32509. });
  32510. colorStops.unshift({ // notice colorStops.length have been changed.
  32511. offset: stopLen ? colorStops[0].offset : 0.5,
  32512. color: outerColors[0] || 'transparent'
  32513. });
  32514. // zrUtil.each(colorStops, function (colorStop) {
  32515. // // Make sure each offset has rounded px to avoid not sharp edge
  32516. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  32517. // });
  32518. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  32519. gradient[coordDim] = minCoord;
  32520. gradient[coordDim + '2'] = maxCoord;
  32521. return gradient;
  32522. }
  32523. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  32524. var showAllSymbol = seriesModel.get('showAllSymbol');
  32525. var isAuto = showAllSymbol === 'auto';
  32526. if (showAllSymbol && !isAuto) {
  32527. return;
  32528. }
  32529. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  32530. if (!categoryAxis) {
  32531. return;
  32532. }
  32533. // Note that category label interval strategy might bring some weird effect
  32534. // in some scenario: users may wonder why some of the symbols are not
  32535. // displayed. So we show all symbols as possible as we can.
  32536. if (isAuto
  32537. // Simplify the logic, do not determine label overlap here.
  32538. && canShowAllSymbolForCategory(categoryAxis, data)
  32539. ) {
  32540. return;
  32541. }
  32542. // Otherwise follow the label interval strategy on category axis.
  32543. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  32544. var labelMap = {};
  32545. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  32546. labelMap[labelItem.tickValue] = 1;
  32547. });
  32548. return function (dataIndex) {
  32549. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  32550. };
  32551. }
  32552. function canShowAllSymbolForCategory(categoryAxis, data) {
  32553. // In mose cases, line is monotonous on category axis, and the label size
  32554. // is close with each other. So we check the symbol size and some of the
  32555. // label size alone with the category axis to estimate whether all symbol
  32556. // can be shown without overlap.
  32557. var axisExtent = categoryAxis.getExtent();
  32558. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  32559. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  32560. // Sampling some points, max 5.
  32561. var dataLen = data.count();
  32562. var step = Math.max(1, Math.round(dataLen / 5));
  32563. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  32564. if (SymbolClz$1.getSymbolSize(
  32565. data, dataIndex
  32566. // Only for cartesian, where `isHorizontal` exists.
  32567. )[categoryAxis.isHorizontal() ? 1 : 0]
  32568. // Empirical number
  32569. * 1.5 > availSize
  32570. ) {
  32571. return false;
  32572. }
  32573. }
  32574. return true;
  32575. }
  32576. Chart.extend({
  32577. type: 'line',
  32578. init: function () {
  32579. var lineGroup = new Group();
  32580. var symbolDraw = new SymbolDraw();
  32581. this.group.add(symbolDraw.group);
  32582. this._symbolDraw = symbolDraw;
  32583. this._lineGroup = lineGroup;
  32584. },
  32585. render: function (seriesModel, ecModel, api) {
  32586. var coordSys = seriesModel.coordinateSystem;
  32587. var group = this.group;
  32588. var data = seriesModel.getData();
  32589. var lineStyleModel = seriesModel.getModel('lineStyle');
  32590. var areaStyleModel = seriesModel.getModel('areaStyle');
  32591. var points = data.mapArray(data.getItemLayout);
  32592. var isCoordSysPolar = coordSys.type === 'polar';
  32593. var prevCoordSys = this._coordSys;
  32594. var symbolDraw = this._symbolDraw;
  32595. var polyline = this._polyline;
  32596. var polygon = this._polygon;
  32597. var lineGroup = this._lineGroup;
  32598. var hasAnimation = seriesModel.get('animation');
  32599. var isAreaChart = !areaStyleModel.isEmpty();
  32600. var valueOrigin = areaStyleModel.get('origin');
  32601. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  32602. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  32603. var showSymbol = seriesModel.get('showSymbol');
  32604. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  32605. && getIsIgnoreFunc(seriesModel, data, coordSys);
  32606. // Remove temporary symbols
  32607. var oldData = this._data;
  32608. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32609. if (el.__temp) {
  32610. group.remove(el);
  32611. oldData.setItemGraphicEl(idx, null);
  32612. }
  32613. });
  32614. // Remove previous created symbols if showSymbol changed to false
  32615. if (!showSymbol) {
  32616. symbolDraw.remove();
  32617. }
  32618. group.add(lineGroup);
  32619. // FIXME step not support polar
  32620. var step = !isCoordSysPolar && seriesModel.get('step');
  32621. // Initialization animation or coordinate system changed
  32622. if (
  32623. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  32624. ) {
  32625. showSymbol && symbolDraw.updateData(data, {
  32626. isIgnore: isIgnoreFunc,
  32627. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32628. });
  32629. if (step) {
  32630. // TODO If stacked series is not step
  32631. points = turnPointsIntoStep(points, coordSys, step);
  32632. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32633. }
  32634. polyline = this._newPolyline(points, coordSys, hasAnimation);
  32635. if (isAreaChart) {
  32636. polygon = this._newPolygon(
  32637. points, stackedOnPoints,
  32638. coordSys, hasAnimation
  32639. );
  32640. }
  32641. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  32642. }
  32643. else {
  32644. if (isAreaChart && !polygon) {
  32645. // If areaStyle is added
  32646. polygon = this._newPolygon(
  32647. points, stackedOnPoints,
  32648. coordSys, hasAnimation
  32649. );
  32650. }
  32651. else if (polygon && !isAreaChart) {
  32652. // If areaStyle is removed
  32653. lineGroup.remove(polygon);
  32654. polygon = this._polygon = null;
  32655. }
  32656. // Update clipPath
  32657. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  32658. // Always update, or it is wrong in the case turning on legend
  32659. // because points are not changed
  32660. showSymbol && symbolDraw.updateData(data, {
  32661. isIgnore: isIgnoreFunc,
  32662. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32663. });
  32664. // Stop symbol animation and sync with line points
  32665. // FIXME performance?
  32666. data.eachItemGraphicEl(function (el) {
  32667. el.stopAnimation(true);
  32668. });
  32669. // In the case data zoom triggerred refreshing frequently
  32670. // Data may not change if line has a category axis. So it should animate nothing
  32671. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  32672. || !isPointsSame(this._points, points)
  32673. ) {
  32674. if (hasAnimation) {
  32675. this._updateAnimation(
  32676. data, stackedOnPoints, coordSys, api, step, valueOrigin
  32677. );
  32678. }
  32679. else {
  32680. // Not do it in update with animation
  32681. if (step) {
  32682. // TODO If stacked series is not step
  32683. points = turnPointsIntoStep(points, coordSys, step);
  32684. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32685. }
  32686. polyline.setShape({
  32687. points: points
  32688. });
  32689. polygon && polygon.setShape({
  32690. points: points,
  32691. stackedOnPoints: stackedOnPoints
  32692. });
  32693. }
  32694. }
  32695. }
  32696. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  32697. polyline.useStyle(defaults(
  32698. // Use color in lineStyle first
  32699. lineStyleModel.getLineStyle(),
  32700. {
  32701. fill: 'none',
  32702. stroke: visualColor,
  32703. lineJoin: 'bevel'
  32704. }
  32705. ));
  32706. var smooth = seriesModel.get('smooth');
  32707. smooth = getSmooth(seriesModel.get('smooth'));
  32708. polyline.setShape({
  32709. smooth: smooth,
  32710. smoothMonotone: seriesModel.get('smoothMonotone'),
  32711. connectNulls: seriesModel.get('connectNulls')
  32712. });
  32713. if (polygon) {
  32714. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  32715. var stackedOnSmooth = 0;
  32716. polygon.useStyle(defaults(
  32717. areaStyleModel.getAreaStyle(),
  32718. {
  32719. fill: visualColor,
  32720. opacity: 0.7,
  32721. lineJoin: 'bevel'
  32722. }
  32723. ));
  32724. if (stackedOnSeries) {
  32725. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  32726. }
  32727. polygon.setShape({
  32728. smooth: smooth,
  32729. stackedOnSmooth: stackedOnSmooth,
  32730. smoothMonotone: seriesModel.get('smoothMonotone'),
  32731. connectNulls: seriesModel.get('connectNulls')
  32732. });
  32733. }
  32734. this._data = data;
  32735. // Save the coordinate system for transition animation when data changed
  32736. this._coordSys = coordSys;
  32737. this._stackedOnPoints = stackedOnPoints;
  32738. this._points = points;
  32739. this._step = step;
  32740. this._valueOrigin = valueOrigin;
  32741. },
  32742. dispose: function () {},
  32743. highlight: function (seriesModel, ecModel, api, payload) {
  32744. var data = seriesModel.getData();
  32745. var dataIndex = queryDataIndex(data, payload);
  32746. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  32747. var symbol = data.getItemGraphicEl(dataIndex);
  32748. if (!symbol) {
  32749. // Create a temporary symbol if it is not exists
  32750. var pt = data.getItemLayout(dataIndex);
  32751. if (!pt) {
  32752. // Null data
  32753. return;
  32754. }
  32755. symbol = new SymbolClz$1(data, dataIndex);
  32756. symbol.position = pt;
  32757. symbol.setZ(
  32758. seriesModel.get('zlevel'),
  32759. seriesModel.get('z')
  32760. );
  32761. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  32762. symbol.__temp = true;
  32763. data.setItemGraphicEl(dataIndex, symbol);
  32764. // Stop scale animation
  32765. symbol.stopSymbolAnimation(true);
  32766. this.group.add(symbol);
  32767. }
  32768. symbol.highlight();
  32769. }
  32770. else {
  32771. // Highlight whole series
  32772. Chart.prototype.highlight.call(
  32773. this, seriesModel, ecModel, api, payload
  32774. );
  32775. }
  32776. },
  32777. downplay: function (seriesModel, ecModel, api, payload) {
  32778. var data = seriesModel.getData();
  32779. var dataIndex = queryDataIndex(data, payload);
  32780. if (dataIndex != null && dataIndex >= 0) {
  32781. var symbol = data.getItemGraphicEl(dataIndex);
  32782. if (symbol) {
  32783. if (symbol.__temp) {
  32784. data.setItemGraphicEl(dataIndex, null);
  32785. this.group.remove(symbol);
  32786. }
  32787. else {
  32788. symbol.downplay();
  32789. }
  32790. }
  32791. }
  32792. else {
  32793. // FIXME
  32794. // can not downplay completely.
  32795. // Downplay whole series
  32796. Chart.prototype.downplay.call(
  32797. this, seriesModel, ecModel, api, payload
  32798. );
  32799. }
  32800. },
  32801. /**
  32802. * @param {module:zrender/container/Group} group
  32803. * @param {Array.<Array.<number>>} points
  32804. * @private
  32805. */
  32806. _newPolyline: function (points) {
  32807. var polyline = this._polyline;
  32808. // Remove previous created polyline
  32809. if (polyline) {
  32810. this._lineGroup.remove(polyline);
  32811. }
  32812. polyline = new Polyline$1({
  32813. shape: {
  32814. points: points
  32815. },
  32816. silent: true,
  32817. z2: 10
  32818. });
  32819. this._lineGroup.add(polyline);
  32820. this._polyline = polyline;
  32821. return polyline;
  32822. },
  32823. /**
  32824. * @param {module:zrender/container/Group} group
  32825. * @param {Array.<Array.<number>>} stackedOnPoints
  32826. * @param {Array.<Array.<number>>} points
  32827. * @private
  32828. */
  32829. _newPolygon: function (points, stackedOnPoints) {
  32830. var polygon = this._polygon;
  32831. // Remove previous created polygon
  32832. if (polygon) {
  32833. this._lineGroup.remove(polygon);
  32834. }
  32835. polygon = new Polygon$1({
  32836. shape: {
  32837. points: points,
  32838. stackedOnPoints: stackedOnPoints
  32839. },
  32840. silent: true
  32841. });
  32842. this._lineGroup.add(polygon);
  32843. this._polygon = polygon;
  32844. return polygon;
  32845. },
  32846. /**
  32847. * @private
  32848. */
  32849. // FIXME Two value axis
  32850. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  32851. var polyline = this._polyline;
  32852. var polygon = this._polygon;
  32853. var seriesModel = data.hostModel;
  32854. var diff = lineAnimationDiff(
  32855. this._data, data,
  32856. this._stackedOnPoints, stackedOnPoints,
  32857. this._coordSys, coordSys,
  32858. this._valueOrigin, valueOrigin
  32859. );
  32860. var current = diff.current;
  32861. var stackedOnCurrent = diff.stackedOnCurrent;
  32862. var next = diff.next;
  32863. var stackedOnNext = diff.stackedOnNext;
  32864. if (step) {
  32865. // TODO If stacked series is not step
  32866. current = turnPointsIntoStep(diff.current, coordSys, step);
  32867. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  32868. next = turnPointsIntoStep(diff.next, coordSys, step);
  32869. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  32870. }
  32871. // `diff.current` is subset of `current` (which should be ensured by
  32872. // turnPointsIntoStep), so points in `__points` can be updated when
  32873. // points in `current` are update during animation.
  32874. polyline.shape.__points = diff.current;
  32875. polyline.shape.points = current;
  32876. updateProps(polyline, {
  32877. shape: {
  32878. points: next
  32879. }
  32880. }, seriesModel);
  32881. if (polygon) {
  32882. polygon.setShape({
  32883. points: current,
  32884. stackedOnPoints: stackedOnCurrent
  32885. });
  32886. updateProps(polygon, {
  32887. shape: {
  32888. points: next,
  32889. stackedOnPoints: stackedOnNext
  32890. }
  32891. }, seriesModel);
  32892. }
  32893. var updatedDataInfo = [];
  32894. var diffStatus = diff.status;
  32895. for (var i = 0; i < diffStatus.length; i++) {
  32896. var cmd = diffStatus[i].cmd;
  32897. if (cmd === '=') {
  32898. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  32899. if (el) {
  32900. updatedDataInfo.push({
  32901. el: el,
  32902. ptIdx: i // Index of points
  32903. });
  32904. }
  32905. }
  32906. }
  32907. if (polyline.animators && polyline.animators.length) {
  32908. polyline.animators[0].during(function () {
  32909. for (var i = 0; i < updatedDataInfo.length; i++) {
  32910. var el = updatedDataInfo[i].el;
  32911. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  32912. }
  32913. });
  32914. }
  32915. },
  32916. remove: function (ecModel) {
  32917. var group = this.group;
  32918. var oldData = this._data;
  32919. this._lineGroup.removeAll();
  32920. this._symbolDraw.remove(true);
  32921. // Remove temporary created elements when highlighting
  32922. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32923. if (el.__temp) {
  32924. group.remove(el);
  32925. oldData.setItemGraphicEl(idx, null);
  32926. }
  32927. });
  32928. this._polyline
  32929. = this._polygon
  32930. = this._coordSys
  32931. = this._points
  32932. = this._stackedOnPoints
  32933. = this._data = null;
  32934. }
  32935. });
  32936. /*
  32937. * Licensed to the Apache Software Foundation (ASF) under one
  32938. * or more contributor license agreements. See the NOTICE file
  32939. * distributed with this work for additional information
  32940. * regarding copyright ownership. The ASF licenses this file
  32941. * to you under the Apache License, Version 2.0 (the
  32942. * "License"); you may not use this file except in compliance
  32943. * with the License. You may obtain a copy of the License at
  32944. *
  32945. * http://www.apache.org/licenses/LICENSE-2.0
  32946. *
  32947. * Unless required by applicable law or agreed to in writing,
  32948. * software distributed under the License is distributed on an
  32949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32950. * KIND, either express or implied. See the License for the
  32951. * specific language governing permissions and limitations
  32952. * under the License.
  32953. */
  32954. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  32955. // Encoding visual for all series include which is filtered for legend drawing
  32956. return {
  32957. seriesType: seriesType,
  32958. // For legend.
  32959. performRawSeries: true,
  32960. reset: function (seriesModel, ecModel, api) {
  32961. var data = seriesModel.getData();
  32962. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  32963. var symbolSize = seriesModel.get('symbolSize');
  32964. var keepAspect = seriesModel.get('symbolKeepAspect');
  32965. data.setVisual({
  32966. legendSymbol: legendSymbol || symbolType,
  32967. symbol: symbolType,
  32968. symbolSize: symbolSize,
  32969. symbolKeepAspect: keepAspect
  32970. });
  32971. // Only visible series has each data be visual encoded
  32972. if (ecModel.isSeriesFiltered(seriesModel)) {
  32973. return;
  32974. }
  32975. var hasCallback = typeof symbolSize === 'function';
  32976. function dataEach(data, idx) {
  32977. if (typeof symbolSize === 'function') {
  32978. var rawValue = seriesModel.getRawValue(idx);
  32979. // FIXME
  32980. var params = seriesModel.getDataParams(idx);
  32981. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  32982. }
  32983. if (data.hasItemOption) {
  32984. var itemModel = data.getItemModel(idx);
  32985. var itemSymbolType = itemModel.getShallow('symbol', true);
  32986. var itemSymbolSize = itemModel.getShallow('symbolSize',
  32987. true);
  32988. var itemSymbolKeepAspect
  32989. = itemModel.getShallow('symbolKeepAspect', true);
  32990. // If has item symbol
  32991. if (itemSymbolType != null) {
  32992. data.setItemVisual(idx, 'symbol', itemSymbolType);
  32993. }
  32994. if (itemSymbolSize != null) {
  32995. // PENDING Transform symbolSize ?
  32996. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  32997. }
  32998. if (itemSymbolKeepAspect != null) {
  32999. data.setItemVisual(idx, 'symbolKeepAspect',
  33000. itemSymbolKeepAspect);
  33001. }
  33002. }
  33003. }
  33004. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  33005. }
  33006. };
  33007. };
  33008. /*
  33009. * Licensed to the Apache Software Foundation (ASF) under one
  33010. * or more contributor license agreements. See the NOTICE file
  33011. * distributed with this work for additional information
  33012. * regarding copyright ownership. The ASF licenses this file
  33013. * to you under the Apache License, Version 2.0 (the
  33014. * "License"); you may not use this file except in compliance
  33015. * with the License. You may obtain a copy of the License at
  33016. *
  33017. * http://www.apache.org/licenses/LICENSE-2.0
  33018. *
  33019. * Unless required by applicable law or agreed to in writing,
  33020. * software distributed under the License is distributed on an
  33021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33022. * KIND, either express or implied. See the License for the
  33023. * specific language governing permissions and limitations
  33024. * under the License.
  33025. */
  33026. /* global Float32Array */
  33027. var pointsLayout = function (seriesType) {
  33028. return {
  33029. seriesType: seriesType,
  33030. plan: createRenderPlanner(),
  33031. reset: function (seriesModel) {
  33032. var data = seriesModel.getData();
  33033. var coordSys = seriesModel.coordinateSystem;
  33034. var pipelineContext = seriesModel.pipelineContext;
  33035. var isLargeRender = pipelineContext.large;
  33036. if (!coordSys) {
  33037. return;
  33038. }
  33039. var dims = map(coordSys.dimensions, function (dim) {
  33040. return data.mapDimension(dim);
  33041. }).slice(0, 2);
  33042. var dimLen = dims.length;
  33043. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33044. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  33045. dims[0] = stackResultDim;
  33046. }
  33047. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  33048. dims[1] = stackResultDim;
  33049. }
  33050. function progress(params, data) {
  33051. var segCount = params.end - params.start;
  33052. var points = isLargeRender && new Float32Array(segCount * dimLen);
  33053. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  33054. var point;
  33055. if (dimLen === 1) {
  33056. var x = data.get(dims[0], i);
  33057. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  33058. }
  33059. else {
  33060. var x = tmpIn[0] = data.get(dims[0], i);
  33061. var y = tmpIn[1] = data.get(dims[1], i);
  33062. // Also {Array.<number>}, not undefined to avoid if...else... statement
  33063. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  33064. }
  33065. if (isLargeRender) {
  33066. points[offset++] = point ? point[0] : NaN;
  33067. points[offset++] = point ? point[1] : NaN;
  33068. }
  33069. else {
  33070. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  33071. }
  33072. }
  33073. isLargeRender && data.setLayout('symbolPoints', points);
  33074. }
  33075. return dimLen && {progress: progress};
  33076. }
  33077. };
  33078. };
  33079. /*
  33080. * Licensed to the Apache Software Foundation (ASF) under one
  33081. * or more contributor license agreements. See the NOTICE file
  33082. * distributed with this work for additional information
  33083. * regarding copyright ownership. The ASF licenses this file
  33084. * to you under the Apache License, Version 2.0 (the
  33085. * "License"); you may not use this file except in compliance
  33086. * with the License. You may obtain a copy of the License at
  33087. *
  33088. * http://www.apache.org/licenses/LICENSE-2.0
  33089. *
  33090. * Unless required by applicable law or agreed to in writing,
  33091. * software distributed under the License is distributed on an
  33092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33093. * KIND, either express or implied. See the License for the
  33094. * specific language governing permissions and limitations
  33095. * under the License.
  33096. */
  33097. var samplers = {
  33098. average: function (frame) {
  33099. var sum = 0;
  33100. var count = 0;
  33101. for (var i = 0; i < frame.length; i++) {
  33102. if (!isNaN(frame[i])) {
  33103. sum += frame[i];
  33104. count++;
  33105. }
  33106. }
  33107. // Return NaN if count is 0
  33108. return count === 0 ? NaN : sum / count;
  33109. },
  33110. sum: function (frame) {
  33111. var sum = 0;
  33112. for (var i = 0; i < frame.length; i++) {
  33113. // Ignore NaN
  33114. sum += frame[i] || 0;
  33115. }
  33116. return sum;
  33117. },
  33118. max: function (frame) {
  33119. var max = -Infinity;
  33120. for (var i = 0; i < frame.length; i++) {
  33121. frame[i] > max && (max = frame[i]);
  33122. }
  33123. // NaN will cause illegal axis extent.
  33124. return isFinite(max) ? max : NaN;
  33125. },
  33126. min: function (frame) {
  33127. var min = Infinity;
  33128. for (var i = 0; i < frame.length; i++) {
  33129. frame[i] < min && (min = frame[i]);
  33130. }
  33131. // NaN will cause illegal axis extent.
  33132. return isFinite(min) ? min : NaN;
  33133. },
  33134. // TODO
  33135. // Median
  33136. nearest: function (frame) {
  33137. return frame[0];
  33138. }
  33139. };
  33140. var indexSampler = function (frame, value) {
  33141. return Math.round(frame.length / 2);
  33142. };
  33143. var dataSample = function (seriesType) {
  33144. return {
  33145. seriesType: seriesType,
  33146. modifyOutputEnd: true,
  33147. reset: function (seriesModel, ecModel, api) {
  33148. var data = seriesModel.getData();
  33149. var sampling = seriesModel.get('sampling');
  33150. var coordSys = seriesModel.coordinateSystem;
  33151. // Only cartesian2d support down sampling
  33152. if (coordSys.type === 'cartesian2d' && sampling) {
  33153. var baseAxis = coordSys.getBaseAxis();
  33154. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33155. var extent = baseAxis.getExtent();
  33156. // Coordinste system has been resized
  33157. var size = extent[1] - extent[0];
  33158. var rate = Math.round(data.count() / size);
  33159. if (rate > 1) {
  33160. var sampler;
  33161. if (typeof sampling === 'string') {
  33162. sampler = samplers[sampling];
  33163. }
  33164. else if (typeof sampling === 'function') {
  33165. sampler = sampling;
  33166. }
  33167. if (sampler) {
  33168. // Only support sample the first dim mapped from value axis.
  33169. seriesModel.setData(data.downSample(
  33170. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  33171. ));
  33172. }
  33173. }
  33174. }
  33175. }
  33176. };
  33177. };
  33178. /*
  33179. * Licensed to the Apache Software Foundation (ASF) under one
  33180. * or more contributor license agreements. See the NOTICE file
  33181. * distributed with this work for additional information
  33182. * regarding copyright ownership. The ASF licenses this file
  33183. * to you under the Apache License, Version 2.0 (the
  33184. * "License"); you may not use this file except in compliance
  33185. * with the License. You may obtain a copy of the License at
  33186. *
  33187. * http://www.apache.org/licenses/LICENSE-2.0
  33188. *
  33189. * Unless required by applicable law or agreed to in writing,
  33190. * software distributed under the License is distributed on an
  33191. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33192. * KIND, either express or implied. See the License for the
  33193. * specific language governing permissions and limitations
  33194. * under the License.
  33195. */
  33196. /**
  33197. * Cartesian coordinate system
  33198. * @module echarts/coord/Cartesian
  33199. *
  33200. */
  33201. function dimAxisMapper(dim) {
  33202. return this._axes[dim];
  33203. }
  33204. /**
  33205. * @alias module:echarts/coord/Cartesian
  33206. * @constructor
  33207. */
  33208. var Cartesian = function (name) {
  33209. this._axes = {};
  33210. this._dimList = [];
  33211. /**
  33212. * @type {string}
  33213. */
  33214. this.name = name || '';
  33215. };
  33216. Cartesian.prototype = {
  33217. constructor: Cartesian,
  33218. type: 'cartesian',
  33219. /**
  33220. * Get axis
  33221. * @param {number|string} dim
  33222. * @return {module:echarts/coord/Cartesian~Axis}
  33223. */
  33224. getAxis: function (dim) {
  33225. return this._axes[dim];
  33226. },
  33227. /**
  33228. * Get axes list
  33229. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  33230. */
  33231. getAxes: function () {
  33232. return map(this._dimList, dimAxisMapper, this);
  33233. },
  33234. /**
  33235. * Get axes list by given scale type
  33236. */
  33237. getAxesByScale: function (scaleType) {
  33238. scaleType = scaleType.toLowerCase();
  33239. return filter(
  33240. this.getAxes(),
  33241. function (axis) {
  33242. return axis.scale.type === scaleType;
  33243. }
  33244. );
  33245. },
  33246. /**
  33247. * Add axis
  33248. * @param {module:echarts/coord/Cartesian.Axis}
  33249. */
  33250. addAxis: function (axis) {
  33251. var dim = axis.dim;
  33252. this._axes[dim] = axis;
  33253. this._dimList.push(dim);
  33254. },
  33255. /**
  33256. * Convert data to coord in nd space
  33257. * @param {Array.<number>|Object.<string, number>} val
  33258. * @return {Array.<number>|Object.<string, number>}
  33259. */
  33260. dataToCoord: function (val) {
  33261. return this._dataCoordConvert(val, 'dataToCoord');
  33262. },
  33263. /**
  33264. * Convert coord in nd space to data
  33265. * @param {Array.<number>|Object.<string, number>} val
  33266. * @return {Array.<number>|Object.<string, number>}
  33267. */
  33268. coordToData: function (val) {
  33269. return this._dataCoordConvert(val, 'coordToData');
  33270. },
  33271. _dataCoordConvert: function (input, method) {
  33272. var dimList = this._dimList;
  33273. var output = input instanceof Array ? [] : {};
  33274. for (var i = 0; i < dimList.length; i++) {
  33275. var dim = dimList[i];
  33276. var axis = this._axes[dim];
  33277. output[dim] = axis[method](input[dim]);
  33278. }
  33279. return output;
  33280. }
  33281. };
  33282. /*
  33283. * Licensed to the Apache Software Foundation (ASF) under one
  33284. * or more contributor license agreements. See the NOTICE file
  33285. * distributed with this work for additional information
  33286. * regarding copyright ownership. The ASF licenses this file
  33287. * to you under the Apache License, Version 2.0 (the
  33288. * "License"); you may not use this file except in compliance
  33289. * with the License. You may obtain a copy of the License at
  33290. *
  33291. * http://www.apache.org/licenses/LICENSE-2.0
  33292. *
  33293. * Unless required by applicable law or agreed to in writing,
  33294. * software distributed under the License is distributed on an
  33295. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33296. * KIND, either express or implied. See the License for the
  33297. * specific language governing permissions and limitations
  33298. * under the License.
  33299. */
  33300. function Cartesian2D(name) {
  33301. Cartesian.call(this, name);
  33302. }
  33303. Cartesian2D.prototype = {
  33304. constructor: Cartesian2D,
  33305. type: 'cartesian2d',
  33306. /**
  33307. * @type {Array.<string>}
  33308. * @readOnly
  33309. */
  33310. dimensions: ['x', 'y'],
  33311. /**
  33312. * Base axis will be used on stacking.
  33313. *
  33314. * @return {module:echarts/coord/cartesian/Axis2D}
  33315. */
  33316. getBaseAxis: function () {
  33317. return this.getAxesByScale('ordinal')[0]
  33318. || this.getAxesByScale('time')[0]
  33319. || this.getAxis('x');
  33320. },
  33321. /**
  33322. * If contain point
  33323. * @param {Array.<number>} point
  33324. * @return {boolean}
  33325. */
  33326. containPoint: function (point) {
  33327. var axisX = this.getAxis('x');
  33328. var axisY = this.getAxis('y');
  33329. return axisX.contain(axisX.toLocalCoord(point[0]))
  33330. && axisY.contain(axisY.toLocalCoord(point[1]));
  33331. },
  33332. /**
  33333. * If contain data
  33334. * @param {Array.<number>} data
  33335. * @return {boolean}
  33336. */
  33337. containData: function (data) {
  33338. return this.getAxis('x').containData(data[0])
  33339. && this.getAxis('y').containData(data[1]);
  33340. },
  33341. /**
  33342. * @param {Array.<number>} data
  33343. * @param {Array.<number>} out
  33344. * @return {Array.<number>}
  33345. */
  33346. dataToPoint: function (data, reserved, out) {
  33347. var xAxis = this.getAxis('x');
  33348. var yAxis = this.getAxis('y');
  33349. out = out || [];
  33350. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  33351. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  33352. return out;
  33353. },
  33354. /**
  33355. * @param {Array.<number>} data
  33356. * @param {Array.<number>} out
  33357. * @return {Array.<number>}
  33358. */
  33359. clampData: function (data, out) {
  33360. var xScale = this.getAxis('x').scale;
  33361. var yScale = this.getAxis('y').scale;
  33362. var xAxisExtent = xScale.getExtent();
  33363. var yAxisExtent = yScale.getExtent();
  33364. var x = xScale.parse(data[0]);
  33365. var y = yScale.parse(data[1]);
  33366. out = out || [];
  33367. out[0] = Math.min(
  33368. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33369. Math.max(xAxisExtent[0], xAxisExtent[1])
  33370. );
  33371. out[1] = Math.min(
  33372. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33373. Math.max(yAxisExtent[0], yAxisExtent[1])
  33374. );
  33375. return out;
  33376. },
  33377. /**
  33378. * @param {Array.<number>} point
  33379. * @param {Array.<number>} out
  33380. * @return {Array.<number>}
  33381. */
  33382. pointToData: function (point, out) {
  33383. var xAxis = this.getAxis('x');
  33384. var yAxis = this.getAxis('y');
  33385. out = out || [];
  33386. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33387. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33388. return out;
  33389. },
  33390. /**
  33391. * Get other axis
  33392. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33393. */
  33394. getOtherAxis: function (axis) {
  33395. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33396. }
  33397. };
  33398. inherits(Cartesian2D, Cartesian);
  33399. /*
  33400. * Licensed to the Apache Software Foundation (ASF) under one
  33401. * or more contributor license agreements. See the NOTICE file
  33402. * distributed with this work for additional information
  33403. * regarding copyright ownership. The ASF licenses this file
  33404. * to you under the Apache License, Version 2.0 (the
  33405. * "License"); you may not use this file except in compliance
  33406. * with the License. You may obtain a copy of the License at
  33407. *
  33408. * http://www.apache.org/licenses/LICENSE-2.0
  33409. *
  33410. * Unless required by applicable law or agreed to in writing,
  33411. * software distributed under the License is distributed on an
  33412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33413. * KIND, either express or implied. See the License for the
  33414. * specific language governing permissions and limitations
  33415. * under the License.
  33416. */
  33417. /**
  33418. * Extend axis 2d
  33419. * @constructor module:echarts/coord/cartesian/Axis2D
  33420. * @extends {module:echarts/coord/cartesian/Axis}
  33421. * @param {string} dim
  33422. * @param {*} scale
  33423. * @param {Array.<number>} coordExtent
  33424. * @param {string} axisType
  33425. * @param {string} position
  33426. */
  33427. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33428. Axis.call(this, dim, scale, coordExtent);
  33429. /**
  33430. * Axis type
  33431. * - 'category'
  33432. * - 'value'
  33433. * - 'time'
  33434. * - 'log'
  33435. * @type {string}
  33436. */
  33437. this.type = axisType || 'value';
  33438. /**
  33439. * Axis position
  33440. * - 'top'
  33441. * - 'bottom'
  33442. * - 'left'
  33443. * - 'right'
  33444. */
  33445. this.position = position || 'bottom';
  33446. };
  33447. Axis2D.prototype = {
  33448. constructor: Axis2D,
  33449. /**
  33450. * Index of axis, can be used as key
  33451. */
  33452. index: 0,
  33453. /**
  33454. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33455. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33456. * If not on zero of other axis, return null/undefined.
  33457. * If no axes, return an empty array.
  33458. */
  33459. getAxesOnZeroOf: null,
  33460. /**
  33461. * Axis model
  33462. * @param {module:echarts/coord/cartesian/AxisModel}
  33463. */
  33464. model: null,
  33465. isHorizontal: function () {
  33466. var position = this.position;
  33467. return position === 'top' || position === 'bottom';
  33468. },
  33469. /**
  33470. * Each item cooresponds to this.getExtent(), which
  33471. * means globalExtent[0] may greater than globalExtent[1],
  33472. * unless `asc` is input.
  33473. *
  33474. * @param {boolean} [asc]
  33475. * @return {Array.<number>}
  33476. */
  33477. getGlobalExtent: function (asc) {
  33478. var ret = this.getExtent();
  33479. ret[0] = this.toGlobalCoord(ret[0]);
  33480. ret[1] = this.toGlobalCoord(ret[1]);
  33481. asc && ret[0] > ret[1] && ret.reverse();
  33482. return ret;
  33483. },
  33484. getOtherAxis: function () {
  33485. this.grid.getOtherAxis();
  33486. },
  33487. /**
  33488. * @override
  33489. */
  33490. pointToData: function (point, clamp) {
  33491. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33492. },
  33493. /**
  33494. * Transform global coord to local coord,
  33495. * i.e. var localCoord = axis.toLocalCoord(80);
  33496. * designate by module:echarts/coord/cartesian/Grid.
  33497. * @type {Function}
  33498. */
  33499. toLocalCoord: null,
  33500. /**
  33501. * Transform global coord to local coord,
  33502. * i.e. var globalCoord = axis.toLocalCoord(40);
  33503. * designate by module:echarts/coord/cartesian/Grid.
  33504. * @type {Function}
  33505. */
  33506. toGlobalCoord: null
  33507. };
  33508. inherits(Axis2D, Axis);
  33509. /*
  33510. * Licensed to the Apache Software Foundation (ASF) under one
  33511. * or more contributor license agreements. See the NOTICE file
  33512. * distributed with this work for additional information
  33513. * regarding copyright ownership. The ASF licenses this file
  33514. * to you under the Apache License, Version 2.0 (the
  33515. * "License"); you may not use this file except in compliance
  33516. * with the License. You may obtain a copy of the License at
  33517. *
  33518. * http://www.apache.org/licenses/LICENSE-2.0
  33519. *
  33520. * Unless required by applicable law or agreed to in writing,
  33521. * software distributed under the License is distributed on an
  33522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33523. * KIND, either express or implied. See the License for the
  33524. * specific language governing permissions and limitations
  33525. * under the License.
  33526. */
  33527. var defaultOption = {
  33528. show: true,
  33529. zlevel: 0,
  33530. z: 0,
  33531. // Inverse the axis.
  33532. inverse: false,
  33533. // Axis name displayed.
  33534. name: '',
  33535. // 'start' | 'middle' | 'end'
  33536. nameLocation: 'end',
  33537. // By degree. By defualt auto rotate by nameLocation.
  33538. nameRotate: null,
  33539. nameTruncate: {
  33540. maxWidth: null,
  33541. ellipsis: '...',
  33542. placeholder: '.'
  33543. },
  33544. // Use global text style by default.
  33545. nameTextStyle: {},
  33546. // The gap between axisName and axisLine.
  33547. nameGap: 15,
  33548. // Default `false` to support tooltip.
  33549. silent: false,
  33550. // Default `false` to avoid legacy user event listener fail.
  33551. triggerEvent: false,
  33552. tooltip: {
  33553. show: false
  33554. },
  33555. axisPointer: {},
  33556. axisLine: {
  33557. show: true,
  33558. onZero: true,
  33559. onZeroAxisIndex: null,
  33560. lineStyle: {
  33561. color: '#333',
  33562. width: 1,
  33563. type: 'solid'
  33564. },
  33565. // The arrow at both ends the the axis.
  33566. symbol: ['none', 'none'],
  33567. symbolSize: [10, 15]
  33568. },
  33569. axisTick: {
  33570. show: true,
  33571. // Whether axisTick is inside the grid or outside the grid.
  33572. inside: false,
  33573. // The length of axisTick.
  33574. length: 5,
  33575. lineStyle: {
  33576. width: 1
  33577. }
  33578. },
  33579. axisLabel: {
  33580. show: true,
  33581. // Whether axisLabel is inside the grid or outside the grid.
  33582. inside: false,
  33583. rotate: 0,
  33584. // true | false | null/undefined (auto)
  33585. showMinLabel: null,
  33586. // true | false | null/undefined (auto)
  33587. showMaxLabel: null,
  33588. margin: 8,
  33589. // formatter: null,
  33590. fontSize: 12
  33591. },
  33592. splitLine: {
  33593. show: true,
  33594. lineStyle: {
  33595. color: ['#ccc'],
  33596. width: 1,
  33597. type: 'solid'
  33598. }
  33599. },
  33600. splitArea: {
  33601. show: false,
  33602. areaStyle: {
  33603. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33604. }
  33605. }
  33606. };
  33607. var axisDefault = {};
  33608. axisDefault.categoryAxis = merge({
  33609. // The gap at both ends of the axis. For categoryAxis, boolean.
  33610. boundaryGap: true,
  33611. // Set false to faster category collection.
  33612. // Only usefull in the case like: category is
  33613. // ['2012-01-01', '2012-01-02', ...], where the input
  33614. // data has been ensured not duplicate and is large data.
  33615. // null means "auto":
  33616. // if axis.data provided, do not deduplication,
  33617. // else do deduplication.
  33618. deduplication: null,
  33619. // splitArea: {
  33620. // show: false
  33621. // },
  33622. splitLine: {
  33623. show: false
  33624. },
  33625. axisTick: {
  33626. // If tick is align with label when boundaryGap is true
  33627. alignWithLabel: false,
  33628. interval: 'auto'
  33629. },
  33630. axisLabel: {
  33631. interval: 'auto'
  33632. }
  33633. }, defaultOption);
  33634. axisDefault.valueAxis = merge({
  33635. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33636. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33637. boundaryGap: [0, 0],
  33638. // TODO
  33639. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33640. // Min value of the axis. can be:
  33641. // + a number
  33642. // + 'dataMin': use the min value in data.
  33643. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33644. // min: null,
  33645. // Max value of the axis. can be:
  33646. // + a number
  33647. // + 'dataMax': use the max value in data.
  33648. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33649. // max: null,
  33650. // Readonly prop, specifies start value of the range when using data zoom.
  33651. // rangeStart: null
  33652. // Readonly prop, specifies end value of the range when using data zoom.
  33653. // rangeEnd: null
  33654. // Optional value can be:
  33655. // + `false`: always include value 0.
  33656. // + `true`: the extent do not consider value 0.
  33657. // scale: false,
  33658. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33659. splitNumber: 5
  33660. // Interval specifies the span of the ticks is mandatorily.
  33661. // interval: null
  33662. // Specify min interval when auto calculate tick interval.
  33663. // minInterval: null
  33664. // Specify max interval when auto calculate tick interval.
  33665. // maxInterval: null
  33666. }, defaultOption);
  33667. axisDefault.timeAxis = defaults({
  33668. scale: true,
  33669. min: 'dataMin',
  33670. max: 'dataMax'
  33671. }, axisDefault.valueAxis);
  33672. axisDefault.logAxis = defaults({
  33673. scale: true,
  33674. logBase: 10
  33675. }, axisDefault.valueAxis);
  33676. /*
  33677. * Licensed to the Apache Software Foundation (ASF) under one
  33678. * or more contributor license agreements. See the NOTICE file
  33679. * distributed with this work for additional information
  33680. * regarding copyright ownership. The ASF licenses this file
  33681. * to you under the Apache License, Version 2.0 (the
  33682. * "License"); you may not use this file except in compliance
  33683. * with the License. You may obtain a copy of the License at
  33684. *
  33685. * http://www.apache.org/licenses/LICENSE-2.0
  33686. *
  33687. * Unless required by applicable law or agreed to in writing,
  33688. * software distributed under the License is distributed on an
  33689. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33690. * KIND, either express or implied. See the License for the
  33691. * specific language governing permissions and limitations
  33692. * under the License.
  33693. */
  33694. // FIXME axisType is fixed ?
  33695. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  33696. /**
  33697. * Generate sub axis model class
  33698. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  33699. * @param {module:echarts/model/Component} BaseAxisModelClass
  33700. * @param {Function} axisTypeDefaulter
  33701. * @param {Object} [extraDefaultOption]
  33702. */
  33703. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  33704. each$1(AXIS_TYPES, function (axisType) {
  33705. BaseAxisModelClass.extend({
  33706. /**
  33707. * @readOnly
  33708. */
  33709. type: axisName + 'Axis.' + axisType,
  33710. mergeDefaultAndTheme: function (option, ecModel) {
  33711. var layoutMode = this.layoutMode;
  33712. var inputPositionParams = layoutMode
  33713. ? getLayoutParams(option) : {};
  33714. var themeModel = ecModel.getTheme();
  33715. merge(option, themeModel.get(axisType + 'Axis'));
  33716. merge(option, this.getDefaultOption());
  33717. option.type = axisTypeDefaulter(axisName, option);
  33718. if (layoutMode) {
  33719. mergeLayoutParam(option, inputPositionParams, layoutMode);
  33720. }
  33721. },
  33722. /**
  33723. * @override
  33724. */
  33725. optionUpdated: function () {
  33726. var thisOption = this.option;
  33727. if (thisOption.type === 'category') {
  33728. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  33729. }
  33730. },
  33731. /**
  33732. * Should not be called before all of 'getInitailData' finished.
  33733. * Because categories are collected during initializing data.
  33734. */
  33735. getCategories: function (rawData) {
  33736. var option = this.option;
  33737. // FIXME
  33738. // warning if called before all of 'getInitailData' finished.
  33739. if (option.type === 'category') {
  33740. if (rawData) {
  33741. return option.data;
  33742. }
  33743. return this.__ordinalMeta.categories;
  33744. }
  33745. },
  33746. getOrdinalMeta: function () {
  33747. return this.__ordinalMeta;
  33748. },
  33749. defaultOption: mergeAll(
  33750. [
  33751. {},
  33752. axisDefault[axisType + 'Axis'],
  33753. extraDefaultOption
  33754. ],
  33755. true
  33756. )
  33757. });
  33758. });
  33759. ComponentModel.registerSubTypeDefaulter(
  33760. axisName + 'Axis',
  33761. curry(axisTypeDefaulter, axisName)
  33762. );
  33763. };
  33764. /*
  33765. * Licensed to the Apache Software Foundation (ASF) under one
  33766. * or more contributor license agreements. See the NOTICE file
  33767. * distributed with this work for additional information
  33768. * regarding copyright ownership. The ASF licenses this file
  33769. * to you under the Apache License, Version 2.0 (the
  33770. * "License"); you may not use this file except in compliance
  33771. * with the License. You may obtain a copy of the License at
  33772. *
  33773. * http://www.apache.org/licenses/LICENSE-2.0
  33774. *
  33775. * Unless required by applicable law or agreed to in writing,
  33776. * software distributed under the License is distributed on an
  33777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33778. * KIND, either express or implied. See the License for the
  33779. * specific language governing permissions and limitations
  33780. * under the License.
  33781. */
  33782. var AxisModel = ComponentModel.extend({
  33783. type: 'cartesian2dAxis',
  33784. /**
  33785. * @type {module:echarts/coord/cartesian/Axis2D}
  33786. */
  33787. axis: null,
  33788. /**
  33789. * @override
  33790. */
  33791. init: function () {
  33792. AxisModel.superApply(this, 'init', arguments);
  33793. this.resetRange();
  33794. },
  33795. /**
  33796. * @override
  33797. */
  33798. mergeOption: function () {
  33799. AxisModel.superApply(this, 'mergeOption', arguments);
  33800. this.resetRange();
  33801. },
  33802. /**
  33803. * @override
  33804. */
  33805. restoreData: function () {
  33806. AxisModel.superApply(this, 'restoreData', arguments);
  33807. this.resetRange();
  33808. },
  33809. /**
  33810. * @override
  33811. * @return {module:echarts/model/Component}
  33812. */
  33813. getCoordSysModel: function () {
  33814. return this.ecModel.queryComponents({
  33815. mainType: 'grid',
  33816. index: this.option.gridIndex,
  33817. id: this.option.gridId
  33818. })[0];
  33819. }
  33820. });
  33821. function getAxisType(axisDim, option) {
  33822. // Default axis with data is category axis
  33823. return option.type || (option.data ? 'category' : 'value');
  33824. }
  33825. merge(AxisModel.prototype, axisModelCommonMixin);
  33826. var extraOption = {
  33827. // gridIndex: 0,
  33828. // gridId: '',
  33829. // Offset is for multiple axis on the same position
  33830. offset: 0
  33831. };
  33832. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  33833. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  33834. /*
  33835. * Licensed to the Apache Software Foundation (ASF) under one
  33836. * or more contributor license agreements. See the NOTICE file
  33837. * distributed with this work for additional information
  33838. * regarding copyright ownership. The ASF licenses this file
  33839. * to you under the Apache License, Version 2.0 (the
  33840. * "License"); you may not use this file except in compliance
  33841. * with the License. You may obtain a copy of the License at
  33842. *
  33843. * http://www.apache.org/licenses/LICENSE-2.0
  33844. *
  33845. * Unless required by applicable law or agreed to in writing,
  33846. * software distributed under the License is distributed on an
  33847. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33848. * KIND, either express or implied. See the License for the
  33849. * specific language governing permissions and limitations
  33850. * under the License.
  33851. */
  33852. // Grid 是在有直角坐标系的时候必须要存在的
  33853. // 所以这里也要被 Cartesian2D 依赖
  33854. ComponentModel.extend({
  33855. type: 'grid',
  33856. dependencies: ['xAxis', 'yAxis'],
  33857. layoutMode: 'box',
  33858. /**
  33859. * @type {module:echarts/coord/cartesian/Grid}
  33860. */
  33861. coordinateSystem: null,
  33862. defaultOption: {
  33863. show: false,
  33864. zlevel: 0,
  33865. z: 0,
  33866. left: '10%',
  33867. top: 60,
  33868. right: '10%',
  33869. bottom: 60,
  33870. // If grid size contain label
  33871. containLabel: false,
  33872. // width: {totalWidth} - left - right,
  33873. // height: {totalHeight} - top - bottom,
  33874. backgroundColor: 'rgba(0,0,0,0)',
  33875. borderWidth: 1,
  33876. borderColor: '#ccc'
  33877. }
  33878. });
  33879. /*
  33880. * Licensed to the Apache Software Foundation (ASF) under one
  33881. * or more contributor license agreements. See the NOTICE file
  33882. * distributed with this work for additional information
  33883. * regarding copyright ownership. The ASF licenses this file
  33884. * to you under the Apache License, Version 2.0 (the
  33885. * "License"); you may not use this file except in compliance
  33886. * with the License. You may obtain a copy of the License at
  33887. *
  33888. * http://www.apache.org/licenses/LICENSE-2.0
  33889. *
  33890. * Unless required by applicable law or agreed to in writing,
  33891. * software distributed under the License is distributed on an
  33892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33893. * KIND, either express or implied. See the License for the
  33894. * specific language governing permissions and limitations
  33895. * under the License.
  33896. */
  33897. /**
  33898. * Grid is a region which contains at most 4 cartesian systems
  33899. *
  33900. * TODO Default cartesian
  33901. */
  33902. // Depends on GridModel, AxisModel, which performs preprocess.
  33903. /**
  33904. * Check if the axis is used in the specified grid
  33905. * @inner
  33906. */
  33907. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  33908. return axisModel.getCoordSysModel() === gridModel;
  33909. }
  33910. function Grid(gridModel, ecModel, api) {
  33911. /**
  33912. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  33913. * @private
  33914. */
  33915. this._coordsMap = {};
  33916. /**
  33917. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  33918. * @private
  33919. */
  33920. this._coordsList = [];
  33921. /**
  33922. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  33923. * @private
  33924. */
  33925. this._axesMap = {};
  33926. /**
  33927. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  33928. * @private
  33929. */
  33930. this._axesList = [];
  33931. this._initCartesian(gridModel, ecModel, api);
  33932. this.model = gridModel;
  33933. }
  33934. var gridProto = Grid.prototype;
  33935. gridProto.type = 'grid';
  33936. gridProto.axisPointerEnabled = true;
  33937. gridProto.getRect = function () {
  33938. return this._rect;
  33939. };
  33940. gridProto.update = function (ecModel, api) {
  33941. var axesMap = this._axesMap;
  33942. this._updateScale(ecModel, this.model);
  33943. each$1(axesMap.x, function (xAxis) {
  33944. niceScaleExtent(xAxis.scale, xAxis.model);
  33945. });
  33946. each$1(axesMap.y, function (yAxis) {
  33947. niceScaleExtent(yAxis.scale, yAxis.model);
  33948. });
  33949. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  33950. var onZeroRecords = {};
  33951. each$1(axesMap.x, function (xAxis) {
  33952. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  33953. });
  33954. each$1(axesMap.y, function (yAxis) {
  33955. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  33956. });
  33957. // Resize again if containLabel is enabled
  33958. // FIXME It may cause getting wrong grid size in data processing stage
  33959. this.resize(this.model, api);
  33960. };
  33961. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  33962. axis.getAxesOnZeroOf = function () {
  33963. // TODO: onZero of multiple axes.
  33964. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  33965. };
  33966. // onZero can not be enabled in these two situations:
  33967. // 1. When any other axis is a category axis.
  33968. // 2. When no axis is cross 0 point.
  33969. var otherAxes = axesMap[otherAxisDim];
  33970. var otherAxisOnZeroOf;
  33971. var axisModel = axis.model;
  33972. var onZero = axisModel.get('axisLine.onZero');
  33973. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  33974. if (!onZero) {
  33975. return;
  33976. }
  33977. // If target axis is specified.
  33978. if (onZeroAxisIndex != null) {
  33979. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  33980. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  33981. }
  33982. }
  33983. else {
  33984. // Find the first available other axis.
  33985. for (var idx in otherAxes) {
  33986. if (otherAxes.hasOwnProperty(idx)
  33987. && canOnZeroToAxis(otherAxes[idx])
  33988. // Consider that two Y axes on one value axis,
  33989. // if both onZero, the two Y axes overlap.
  33990. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  33991. ) {
  33992. otherAxisOnZeroOf = otherAxes[idx];
  33993. break;
  33994. }
  33995. }
  33996. }
  33997. if (otherAxisOnZeroOf) {
  33998. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  33999. }
  34000. function getOnZeroRecordKey(axis) {
  34001. return axis.dim + '_' + axis.index;
  34002. }
  34003. }
  34004. function canOnZeroToAxis(axis) {
  34005. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  34006. }
  34007. /**
  34008. * Resize the grid
  34009. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34010. * @param {module:echarts/ExtensionAPI} api
  34011. */
  34012. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  34013. var gridRect = getLayoutRect(
  34014. gridModel.getBoxLayoutParams(), {
  34015. width: api.getWidth(),
  34016. height: api.getHeight()
  34017. });
  34018. this._rect = gridRect;
  34019. var axesList = this._axesList;
  34020. adjustAxes();
  34021. // Minus label size
  34022. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  34023. each$1(axesList, function (axis) {
  34024. if (!axis.model.get('axisLabel.inside')) {
  34025. var labelUnionRect = estimateLabelUnionRect(axis);
  34026. if (labelUnionRect) {
  34027. var dim = axis.isHorizontal() ? 'height' : 'width';
  34028. var margin = axis.model.get('axisLabel.margin');
  34029. gridRect[dim] -= labelUnionRect[dim] + margin;
  34030. if (axis.position === 'top') {
  34031. gridRect.y += labelUnionRect.height + margin;
  34032. }
  34033. else if (axis.position === 'left') {
  34034. gridRect.x += labelUnionRect.width + margin;
  34035. }
  34036. }
  34037. }
  34038. });
  34039. adjustAxes();
  34040. }
  34041. function adjustAxes() {
  34042. each$1(axesList, function (axis) {
  34043. var isHorizontal = axis.isHorizontal();
  34044. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  34045. var idx = axis.inverse ? 1 : 0;
  34046. axis.setExtent(extent[idx], extent[1 - idx]);
  34047. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34048. });
  34049. }
  34050. };
  34051. /**
  34052. * @param {string} axisType
  34053. * @param {number} [axisIndex]
  34054. */
  34055. gridProto.getAxis = function (axisType, axisIndex) {
  34056. var axesMapOnDim = this._axesMap[axisType];
  34057. if (axesMapOnDim != null) {
  34058. if (axisIndex == null) {
  34059. // Find first axis
  34060. for (var name in axesMapOnDim) {
  34061. if (axesMapOnDim.hasOwnProperty(name)) {
  34062. return axesMapOnDim[name];
  34063. }
  34064. }
  34065. }
  34066. return axesMapOnDim[axisIndex];
  34067. }
  34068. };
  34069. /**
  34070. * @return {Array.<module:echarts/coord/Axis>}
  34071. */
  34072. gridProto.getAxes = function () {
  34073. return this._axesList.slice();
  34074. };
  34075. /**
  34076. * Usage:
  34077. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34078. * grid.getCartesian(xAxisIndex);
  34079. * grid.getCartesian(null, yAxisIndex);
  34080. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34081. *
  34082. * @param {number|Object} [xAxisIndex]
  34083. * @param {number} [yAxisIndex]
  34084. */
  34085. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34086. if (xAxisIndex != null && yAxisIndex != null) {
  34087. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34088. return this._coordsMap[key];
  34089. }
  34090. if (isObject$1(xAxisIndex)) {
  34091. yAxisIndex = xAxisIndex.yAxisIndex;
  34092. xAxisIndex = xAxisIndex.xAxisIndex;
  34093. }
  34094. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34095. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34096. if (coordList[i].getAxis('x').index === xAxisIndex
  34097. || coordList[i].getAxis('y').index === yAxisIndex
  34098. ) {
  34099. return coordList[i];
  34100. }
  34101. }
  34102. };
  34103. gridProto.getCartesians = function () {
  34104. return this._coordsList.slice();
  34105. };
  34106. /**
  34107. * @implements
  34108. * see {module:echarts/CoodinateSystem}
  34109. */
  34110. gridProto.convertToPixel = function (ecModel, finder, value) {
  34111. var target = this._findConvertTarget(ecModel, finder);
  34112. return target.cartesian
  34113. ? target.cartesian.dataToPoint(value)
  34114. : target.axis
  34115. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34116. : null;
  34117. };
  34118. /**
  34119. * @implements
  34120. * see {module:echarts/CoodinateSystem}
  34121. */
  34122. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34123. var target = this._findConvertTarget(ecModel, finder);
  34124. return target.cartesian
  34125. ? target.cartesian.pointToData(value)
  34126. : target.axis
  34127. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34128. : null;
  34129. };
  34130. /**
  34131. * @inner
  34132. */
  34133. gridProto._findConvertTarget = function (ecModel, finder) {
  34134. var seriesModel = finder.seriesModel;
  34135. var xAxisModel = finder.xAxisModel
  34136. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34137. var yAxisModel = finder.yAxisModel
  34138. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34139. var gridModel = finder.gridModel;
  34140. var coordsList = this._coordsList;
  34141. var cartesian;
  34142. var axis;
  34143. if (seriesModel) {
  34144. cartesian = seriesModel.coordinateSystem;
  34145. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34146. }
  34147. else if (xAxisModel && yAxisModel) {
  34148. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34149. }
  34150. else if (xAxisModel) {
  34151. axis = this.getAxis('x', xAxisModel.componentIndex);
  34152. }
  34153. else if (yAxisModel) {
  34154. axis = this.getAxis('y', yAxisModel.componentIndex);
  34155. }
  34156. // Lowest priority.
  34157. else if (gridModel) {
  34158. var grid = gridModel.coordinateSystem;
  34159. if (grid === this) {
  34160. cartesian = this._coordsList[0];
  34161. }
  34162. }
  34163. return {cartesian: cartesian, axis: axis};
  34164. };
  34165. /**
  34166. * @implements
  34167. * see {module:echarts/CoodinateSystem}
  34168. */
  34169. gridProto.containPoint = function (point) {
  34170. var coord = this._coordsList[0];
  34171. if (coord) {
  34172. return coord.containPoint(point);
  34173. }
  34174. };
  34175. /**
  34176. * Initialize cartesian coordinate systems
  34177. * @private
  34178. */
  34179. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34180. var axisPositionUsed = {
  34181. left: false,
  34182. right: false,
  34183. top: false,
  34184. bottom: false
  34185. };
  34186. var axesMap = {
  34187. x: {},
  34188. y: {}
  34189. };
  34190. var axesCount = {
  34191. x: 0,
  34192. y: 0
  34193. };
  34194. /// Create axis
  34195. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34196. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34197. if (!axesCount.x || !axesCount.y) {
  34198. // Roll back when there no either x or y axis
  34199. this._axesMap = {};
  34200. this._axesList = [];
  34201. return;
  34202. }
  34203. this._axesMap = axesMap;
  34204. /// Create cartesian2d
  34205. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34206. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34207. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34208. var cartesian = new Cartesian2D(key);
  34209. cartesian.grid = this;
  34210. cartesian.model = gridModel;
  34211. this._coordsMap[key] = cartesian;
  34212. this._coordsList.push(cartesian);
  34213. cartesian.addAxis(xAxis);
  34214. cartesian.addAxis(yAxis);
  34215. }, this);
  34216. }, this);
  34217. function createAxisCreator(axisType) {
  34218. return function (axisModel, idx) {
  34219. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34220. return;
  34221. }
  34222. var axisPosition = axisModel.get('position');
  34223. if (axisType === 'x') {
  34224. // Fix position
  34225. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34226. // Default bottom of X
  34227. axisPosition = 'bottom';
  34228. if (axisPositionUsed[axisPosition]) {
  34229. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  34230. }
  34231. }
  34232. }
  34233. else {
  34234. // Fix position
  34235. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34236. // Default left of Y
  34237. axisPosition = 'left';
  34238. if (axisPositionUsed[axisPosition]) {
  34239. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  34240. }
  34241. }
  34242. }
  34243. axisPositionUsed[axisPosition] = true;
  34244. var axis = new Axis2D(
  34245. axisType, createScaleByModel(axisModel),
  34246. [0, 0],
  34247. axisModel.get('type'),
  34248. axisPosition
  34249. );
  34250. var isCategory = axis.type === 'category';
  34251. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34252. axis.inverse = axisModel.get('inverse');
  34253. // Inject axis into axisModel
  34254. axisModel.axis = axis;
  34255. // Inject axisModel into axis
  34256. axis.model = axisModel;
  34257. // Inject grid info axis
  34258. axis.grid = this;
  34259. // Index of axis, can be used as key
  34260. axis.index = idx;
  34261. this._axesList.push(axis);
  34262. axesMap[axisType][idx] = axis;
  34263. axesCount[axisType]++;
  34264. };
  34265. }
  34266. };
  34267. /**
  34268. * Update cartesian properties from series
  34269. * @param {module:echarts/model/Option} option
  34270. * @private
  34271. */
  34272. gridProto._updateScale = function (ecModel, gridModel) {
  34273. // Reset scale
  34274. each$1(this._axesList, function (axis) {
  34275. axis.scale.setExtent(Infinity, -Infinity);
  34276. });
  34277. ecModel.eachSeries(function (seriesModel) {
  34278. if (isCartesian2D(seriesModel)) {
  34279. var axesModels = findAxesModels(seriesModel, ecModel);
  34280. var xAxisModel = axesModels[0];
  34281. var yAxisModel = axesModels[1];
  34282. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34283. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34284. ) {
  34285. return;
  34286. }
  34287. var cartesian = this.getCartesian(
  34288. xAxisModel.componentIndex, yAxisModel.componentIndex
  34289. );
  34290. var data = seriesModel.getData();
  34291. var xAxis = cartesian.getAxis('x');
  34292. var yAxis = cartesian.getAxis('y');
  34293. if (data.type === 'list') {
  34294. unionExtent(data, xAxis, seriesModel);
  34295. unionExtent(data, yAxis, seriesModel);
  34296. }
  34297. }
  34298. }, this);
  34299. function unionExtent(data, axis, seriesModel) {
  34300. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34301. axis.scale.unionExtentFromData(
  34302. // For example, the extent of the orginal dimension
  34303. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34304. // is [7, 9], the final extent should not include [0.1, 0.5].
  34305. data, getStackedDimension(data, dim)
  34306. );
  34307. });
  34308. }
  34309. };
  34310. /**
  34311. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34312. * @return {Object} {baseAxes: [], otherAxes: []}
  34313. */
  34314. gridProto.getTooltipAxes = function (dim) {
  34315. var baseAxes = [];
  34316. var otherAxes = [];
  34317. each$1(this.getCartesians(), function (cartesian) {
  34318. var baseAxis = (dim != null && dim !== 'auto')
  34319. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34320. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34321. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34322. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34323. });
  34324. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34325. };
  34326. /**
  34327. * @inner
  34328. */
  34329. function updateAxisTransform(axis, coordBase) {
  34330. var axisExtent = axis.getExtent();
  34331. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34332. // Fast transform
  34333. axis.toGlobalCoord = axis.dim === 'x'
  34334. ? function (coord) {
  34335. return coord + coordBase;
  34336. }
  34337. : function (coord) {
  34338. return axisExtentSum - coord + coordBase;
  34339. };
  34340. axis.toLocalCoord = axis.dim === 'x'
  34341. ? function (coord) {
  34342. return coord - coordBase;
  34343. }
  34344. : function (coord) {
  34345. return axisExtentSum - coord + coordBase;
  34346. };
  34347. }
  34348. var axesTypes = ['xAxis', 'yAxis'];
  34349. /**
  34350. * @inner
  34351. */
  34352. function findAxesModels(seriesModel, ecModel) {
  34353. return map(axesTypes, function (axisType) {
  34354. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34355. if (__DEV__) {
  34356. if (!axisModel) {
  34357. throw new Error(axisType + ' "' + retrieve(
  34358. seriesModel.get(axisType + 'Index'),
  34359. seriesModel.get(axisType + 'Id'),
  34360. 0
  34361. ) + '" not found');
  34362. }
  34363. }
  34364. return axisModel;
  34365. });
  34366. }
  34367. /**
  34368. * @inner
  34369. */
  34370. function isCartesian2D(seriesModel) {
  34371. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34372. }
  34373. Grid.create = function (ecModel, api) {
  34374. var grids = [];
  34375. ecModel.eachComponent('grid', function (gridModel, idx) {
  34376. var grid = new Grid(gridModel, ecModel, api);
  34377. grid.name = 'grid_' + idx;
  34378. // dataSampling requires axis extent, so resize
  34379. // should be performed in create stage.
  34380. grid.resize(gridModel, api, true);
  34381. gridModel.coordinateSystem = grid;
  34382. grids.push(grid);
  34383. });
  34384. // Inject the coordinateSystems into seriesModel
  34385. ecModel.eachSeries(function (seriesModel) {
  34386. if (!isCartesian2D(seriesModel)) {
  34387. return;
  34388. }
  34389. var axesModels = findAxesModels(seriesModel, ecModel);
  34390. var xAxisModel = axesModels[0];
  34391. var yAxisModel = axesModels[1];
  34392. var gridModel = xAxisModel.getCoordSysModel();
  34393. if (__DEV__) {
  34394. if (!gridModel) {
  34395. throw new Error(
  34396. 'Grid "' + retrieve(
  34397. xAxisModel.get('gridIndex'),
  34398. xAxisModel.get('gridId'),
  34399. 0
  34400. ) + '" not found'
  34401. );
  34402. }
  34403. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34404. throw new Error('xAxis and yAxis must use the same grid');
  34405. }
  34406. }
  34407. var grid = gridModel.coordinateSystem;
  34408. seriesModel.coordinateSystem = grid.getCartesian(
  34409. xAxisModel.componentIndex, yAxisModel.componentIndex
  34410. );
  34411. });
  34412. return grids;
  34413. };
  34414. // For deciding which dimensions to use when creating list data
  34415. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34416. CoordinateSystemManager.register('cartesian2d', Grid);
  34417. /*
  34418. * Licensed to the Apache Software Foundation (ASF) under one
  34419. * or more contributor license agreements. See the NOTICE file
  34420. * distributed with this work for additional information
  34421. * regarding copyright ownership. The ASF licenses this file
  34422. * to you under the Apache License, Version 2.0 (the
  34423. * "License"); you may not use this file except in compliance
  34424. * with the License. You may obtain a copy of the License at
  34425. *
  34426. * http://www.apache.org/licenses/LICENSE-2.0
  34427. *
  34428. * Unless required by applicable law or agreed to in writing,
  34429. * software distributed under the License is distributed on an
  34430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34431. * KIND, either express or implied. See the License for the
  34432. * specific language governing permissions and limitations
  34433. * under the License.
  34434. */
  34435. var PI$2 = Math.PI;
  34436. function makeAxisEventDataBase(axisModel) {
  34437. var eventData = {
  34438. componentType: axisModel.mainType,
  34439. componentIndex: axisModel.componentIndex
  34440. };
  34441. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  34442. return eventData;
  34443. }
  34444. /**
  34445. * A final axis is translated and rotated from a "standard axis".
  34446. * So opt.position and opt.rotation is required.
  34447. *
  34448. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34449. * for example: (0, 0) ------------> (0, 50)
  34450. *
  34451. * nameDirection or tickDirection or labelDirection is 1 means tick
  34452. * or label is below the standard axis, whereas is -1 means above
  34453. * the standard axis. labelOffset means offset between label and axis,
  34454. * which is useful when 'onZero', where axisLabel is in the grid and
  34455. * label in outside grid.
  34456. *
  34457. * Tips: like always,
  34458. * positive rotation represents anticlockwise, and negative rotation
  34459. * represents clockwise.
  34460. * The direction of position coordinate is the same as the direction
  34461. * of screen coordinate.
  34462. *
  34463. * Do not need to consider axis 'inverse', which is auto processed by
  34464. * axis extent.
  34465. *
  34466. * @param {module:zrender/container/Group} group
  34467. * @param {Object} axisModel
  34468. * @param {Object} opt Standard axis parameters.
  34469. * @param {Array.<number>} opt.position [x, y]
  34470. * @param {number} opt.rotation by radian
  34471. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34472. * @param {number} [opt.tickDirection=1] 1 or -1
  34473. * @param {number} [opt.labelDirection=1] 1 or -1
  34474. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34475. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34476. * @param {string} [opt.axisName] default get from axisModel.
  34477. * @param {number} [opt.axisNameAvailableWidth]
  34478. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34479. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34480. * @param {number} [opt.nameTruncateMaxWidth]
  34481. */
  34482. var AxisBuilder = function (axisModel, opt) {
  34483. /**
  34484. * @readOnly
  34485. */
  34486. this.opt = opt;
  34487. /**
  34488. * @readOnly
  34489. */
  34490. this.axisModel = axisModel;
  34491. // Default value
  34492. defaults(
  34493. opt,
  34494. {
  34495. labelOffset: 0,
  34496. nameDirection: 1,
  34497. tickDirection: 1,
  34498. labelDirection: 1,
  34499. silent: true
  34500. }
  34501. );
  34502. /**
  34503. * @readOnly
  34504. */
  34505. this.group = new Group();
  34506. // FIXME Not use a seperate text group?
  34507. var dumbGroup = new Group({
  34508. position: opt.position.slice(),
  34509. rotation: opt.rotation
  34510. });
  34511. // this.group.add(dumbGroup);
  34512. // this._dumbGroup = dumbGroup;
  34513. dumbGroup.updateTransform();
  34514. this._transform = dumbGroup.transform;
  34515. this._dumbGroup = dumbGroup;
  34516. };
  34517. AxisBuilder.prototype = {
  34518. constructor: AxisBuilder,
  34519. hasBuilder: function (name) {
  34520. return !!builders[name];
  34521. },
  34522. add: function (name) {
  34523. builders[name].call(this);
  34524. },
  34525. getGroup: function () {
  34526. return this.group;
  34527. }
  34528. };
  34529. var builders = {
  34530. /**
  34531. * @private
  34532. */
  34533. axisLine: function () {
  34534. var opt = this.opt;
  34535. var axisModel = this.axisModel;
  34536. if (!axisModel.get('axisLine.show')) {
  34537. return;
  34538. }
  34539. var extent = this.axisModel.axis.getExtent();
  34540. var matrix = this._transform;
  34541. var pt1 = [extent[0], 0];
  34542. var pt2 = [extent[1], 0];
  34543. if (matrix) {
  34544. applyTransform(pt1, pt1, matrix);
  34545. applyTransform(pt2, pt2, matrix);
  34546. }
  34547. var lineStyle = extend(
  34548. {
  34549. lineCap: 'round'
  34550. },
  34551. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34552. );
  34553. this.group.add(new Line(subPixelOptimizeLine({
  34554. // Id for animation
  34555. anid: 'line',
  34556. shape: {
  34557. x1: pt1[0],
  34558. y1: pt1[1],
  34559. x2: pt2[0],
  34560. y2: pt2[1]
  34561. },
  34562. style: lineStyle,
  34563. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34564. silent: true,
  34565. z2: 1
  34566. })));
  34567. var arrows = axisModel.get('axisLine.symbol');
  34568. var arrowSize = axisModel.get('axisLine.symbolSize');
  34569. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34570. if (typeof arrowOffset === 'number') {
  34571. arrowOffset = [arrowOffset, arrowOffset];
  34572. }
  34573. if (arrows != null) {
  34574. if (typeof arrows === 'string') {
  34575. // Use the same arrow for start and end point
  34576. arrows = [arrows, arrows];
  34577. }
  34578. if (typeof arrowSize === 'string'
  34579. || typeof arrowSize === 'number'
  34580. ) {
  34581. // Use the same size for width and height
  34582. arrowSize = [arrowSize, arrowSize];
  34583. }
  34584. var symbolWidth = arrowSize[0];
  34585. var symbolHeight = arrowSize[1];
  34586. each$1([{
  34587. rotate: opt.rotation + Math.PI / 2,
  34588. offset: arrowOffset[0],
  34589. r: 0
  34590. }, {
  34591. rotate: opt.rotation - Math.PI / 2,
  34592. offset: arrowOffset[1],
  34593. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34594. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34595. }], function (point, index) {
  34596. if (arrows[index] !== 'none' && arrows[index] != null) {
  34597. var symbol = createSymbol(
  34598. arrows[index],
  34599. -symbolWidth / 2,
  34600. -symbolHeight / 2,
  34601. symbolWidth,
  34602. symbolHeight,
  34603. lineStyle.stroke,
  34604. true
  34605. );
  34606. // Calculate arrow position with offset
  34607. var r = point.r + point.offset;
  34608. var pos = [
  34609. pt1[0] + r * Math.cos(opt.rotation),
  34610. pt1[1] - r * Math.sin(opt.rotation)
  34611. ];
  34612. symbol.attr({
  34613. rotation: point.rotate,
  34614. position: pos,
  34615. silent: true,
  34616. z2: 11
  34617. });
  34618. this.group.add(symbol);
  34619. }
  34620. }, this);
  34621. }
  34622. },
  34623. /**
  34624. * @private
  34625. */
  34626. axisTickLabel: function () {
  34627. var axisModel = this.axisModel;
  34628. var opt = this.opt;
  34629. var tickEls = buildAxisTick(this, axisModel, opt);
  34630. var labelEls = buildAxisLabel(this, axisModel, opt);
  34631. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  34632. },
  34633. /**
  34634. * @private
  34635. */
  34636. axisName: function () {
  34637. var opt = this.opt;
  34638. var axisModel = this.axisModel;
  34639. var name = retrieve(opt.axisName, axisModel.get('name'));
  34640. if (!name) {
  34641. return;
  34642. }
  34643. var nameLocation = axisModel.get('nameLocation');
  34644. var nameDirection = opt.nameDirection;
  34645. var textStyleModel = axisModel.getModel('nameTextStyle');
  34646. var gap = axisModel.get('nameGap') || 0;
  34647. var extent = this.axisModel.axis.getExtent();
  34648. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  34649. var pos = [
  34650. nameLocation === 'start'
  34651. ? extent[0] - gapSignal * gap
  34652. : nameLocation === 'end'
  34653. ? extent[1] + gapSignal * gap
  34654. : (extent[0] + extent[1]) / 2, // 'middle'
  34655. // Reuse labelOffset.
  34656. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  34657. ];
  34658. var labelLayout;
  34659. var nameRotation = axisModel.get('nameRotate');
  34660. if (nameRotation != null) {
  34661. nameRotation = nameRotation * PI$2 / 180; // To radian.
  34662. }
  34663. var axisNameAvailableWidth;
  34664. if (isNameLocationCenter(nameLocation)) {
  34665. labelLayout = innerTextLayout(
  34666. opt.rotation,
  34667. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  34668. nameDirection
  34669. );
  34670. }
  34671. else {
  34672. labelLayout = endTextLayout(
  34673. opt, nameLocation, nameRotation || 0, extent
  34674. );
  34675. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  34676. if (axisNameAvailableWidth != null) {
  34677. axisNameAvailableWidth = Math.abs(
  34678. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  34679. );
  34680. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  34681. }
  34682. }
  34683. var textFont = textStyleModel.getFont();
  34684. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  34685. var ellipsis = truncateOpt.ellipsis;
  34686. var maxWidth = retrieve(
  34687. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  34688. );
  34689. // FIXME
  34690. // truncate rich text? (consider performance)
  34691. var truncatedText = (ellipsis != null && maxWidth != null)
  34692. ? truncateText$1(
  34693. name, maxWidth, textFont, ellipsis,
  34694. {minChar: 2, placeholder: truncateOpt.placeholder}
  34695. )
  34696. : name;
  34697. var tooltipOpt = axisModel.get('tooltip', true);
  34698. var mainType = axisModel.mainType;
  34699. var formatterParams = {
  34700. componentType: mainType,
  34701. name: name,
  34702. $vars: ['name']
  34703. };
  34704. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  34705. var textEl = new Text({
  34706. // Id for animation
  34707. anid: 'name',
  34708. __fullText: name,
  34709. __truncatedText: truncatedText,
  34710. position: pos,
  34711. rotation: labelLayout.rotation,
  34712. silent: isSilent(axisModel),
  34713. z2: 1,
  34714. tooltip: (tooltipOpt && tooltipOpt.show)
  34715. ? extend({
  34716. content: name,
  34717. formatter: function () {
  34718. return name;
  34719. },
  34720. formatterParams: formatterParams
  34721. }, tooltipOpt)
  34722. : null
  34723. });
  34724. setTextStyle(textEl.style, textStyleModel, {
  34725. text: truncatedText,
  34726. textFont: textFont,
  34727. textFill: textStyleModel.getTextColor()
  34728. || axisModel.get('axisLine.lineStyle.color'),
  34729. textAlign: labelLayout.textAlign,
  34730. textVerticalAlign: labelLayout.textVerticalAlign
  34731. });
  34732. if (axisModel.get('triggerEvent')) {
  34733. textEl.eventData = makeAxisEventDataBase(axisModel);
  34734. textEl.eventData.targetType = 'axisName';
  34735. textEl.eventData.name = name;
  34736. }
  34737. // FIXME
  34738. this._dumbGroup.add(textEl);
  34739. textEl.updateTransform();
  34740. this.group.add(textEl);
  34741. textEl.decomposeTransform();
  34742. }
  34743. };
  34744. /**
  34745. * @public
  34746. * @static
  34747. * @param {Object} opt
  34748. * @param {number} axisRotation in radian
  34749. * @param {number} textRotation in radian
  34750. * @param {number} direction
  34751. * @return {Object} {
  34752. * rotation, // according to axis
  34753. * textAlign,
  34754. * textVerticalAlign
  34755. * }
  34756. */
  34757. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  34758. var rotationDiff = remRadian(textRotation - axisRotation);
  34759. var textAlign;
  34760. var textVerticalAlign;
  34761. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  34762. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  34763. textAlign = 'center';
  34764. }
  34765. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  34766. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  34767. textAlign = 'center';
  34768. }
  34769. else {
  34770. textVerticalAlign = 'middle';
  34771. if (rotationDiff > 0 && rotationDiff < PI$2) {
  34772. textAlign = direction > 0 ? 'right' : 'left';
  34773. }
  34774. else {
  34775. textAlign = direction > 0 ? 'left' : 'right';
  34776. }
  34777. }
  34778. return {
  34779. rotation: rotationDiff,
  34780. textAlign: textAlign,
  34781. textVerticalAlign: textVerticalAlign
  34782. };
  34783. };
  34784. function endTextLayout(opt, textPosition, textRotate, extent) {
  34785. var rotationDiff = remRadian(textRotate - opt.rotation);
  34786. var textAlign;
  34787. var textVerticalAlign;
  34788. var inverse = extent[0] > extent[1];
  34789. var onLeft = (textPosition === 'start' && !inverse)
  34790. || (textPosition !== 'start' && inverse);
  34791. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  34792. textVerticalAlign = onLeft ? 'bottom' : 'top';
  34793. textAlign = 'center';
  34794. }
  34795. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  34796. textVerticalAlign = onLeft ? 'top' : 'bottom';
  34797. textAlign = 'center';
  34798. }
  34799. else {
  34800. textVerticalAlign = 'middle';
  34801. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  34802. textAlign = onLeft ? 'left' : 'right';
  34803. }
  34804. else {
  34805. textAlign = onLeft ? 'right' : 'left';
  34806. }
  34807. }
  34808. return {
  34809. rotation: rotationDiff,
  34810. textAlign: textAlign,
  34811. textVerticalAlign: textVerticalAlign
  34812. };
  34813. }
  34814. function isSilent(axisModel) {
  34815. var tooltipOpt = axisModel.get('tooltip');
  34816. return axisModel.get('silent')
  34817. // Consider mouse cursor, add these restrictions.
  34818. || !(
  34819. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  34820. );
  34821. }
  34822. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  34823. if (shouldShowAllLabels(axisModel.axis)) {
  34824. return;
  34825. }
  34826. // If min or max are user set, we need to check
  34827. // If the tick on min(max) are overlap on their neighbour tick
  34828. // If they are overlapped, we need to hide the min(max) tick label
  34829. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  34830. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  34831. // FIXME
  34832. // Have not consider onBand yet, where tick els is more than label els.
  34833. labelEls = labelEls || [];
  34834. tickEls = tickEls || [];
  34835. var firstLabel = labelEls[0];
  34836. var nextLabel = labelEls[1];
  34837. var lastLabel = labelEls[labelEls.length - 1];
  34838. var prevLabel = labelEls[labelEls.length - 2];
  34839. var firstTick = tickEls[0];
  34840. var nextTick = tickEls[1];
  34841. var lastTick = tickEls[tickEls.length - 1];
  34842. var prevTick = tickEls[tickEls.length - 2];
  34843. if (showMinLabel === false) {
  34844. ignoreEl(firstLabel);
  34845. ignoreEl(firstTick);
  34846. }
  34847. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  34848. if (showMinLabel) {
  34849. ignoreEl(nextLabel);
  34850. ignoreEl(nextTick);
  34851. }
  34852. else {
  34853. ignoreEl(firstLabel);
  34854. ignoreEl(firstTick);
  34855. }
  34856. }
  34857. if (showMaxLabel === false) {
  34858. ignoreEl(lastLabel);
  34859. ignoreEl(lastTick);
  34860. }
  34861. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  34862. if (showMaxLabel) {
  34863. ignoreEl(prevLabel);
  34864. ignoreEl(prevTick);
  34865. }
  34866. else {
  34867. ignoreEl(lastLabel);
  34868. ignoreEl(lastTick);
  34869. }
  34870. }
  34871. }
  34872. function ignoreEl(el) {
  34873. el && (el.ignore = true);
  34874. }
  34875. function isTwoLabelOverlapped(current, next, labelLayout) {
  34876. // current and next has the same rotation.
  34877. var firstRect = current && current.getBoundingRect().clone();
  34878. var nextRect = next && next.getBoundingRect().clone();
  34879. if (!firstRect || !nextRect) {
  34880. return;
  34881. }
  34882. // When checking intersect of two rotated labels, we use mRotationBack
  34883. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  34884. var mRotationBack = identity([]);
  34885. rotate(mRotationBack, mRotationBack, -current.rotation);
  34886. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  34887. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  34888. return firstRect.intersect(nextRect);
  34889. }
  34890. function isNameLocationCenter(nameLocation) {
  34891. return nameLocation === 'middle' || nameLocation === 'center';
  34892. }
  34893. function buildAxisTick(axisBuilder, axisModel, opt) {
  34894. var axis = axisModel.axis;
  34895. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  34896. return;
  34897. }
  34898. var tickModel = axisModel.getModel('axisTick');
  34899. var lineStyleModel = tickModel.getModel('lineStyle');
  34900. var tickLen = tickModel.get('length');
  34901. var ticksCoords = axis.getTicksCoords();
  34902. var pt1 = [];
  34903. var pt2 = [];
  34904. var matrix = axisBuilder._transform;
  34905. var tickEls = [];
  34906. for (var i = 0; i < ticksCoords.length; i++) {
  34907. var tickCoord = ticksCoords[i].coord;
  34908. pt1[0] = tickCoord;
  34909. pt1[1] = 0;
  34910. pt2[0] = tickCoord;
  34911. pt2[1] = opt.tickDirection * tickLen;
  34912. if (matrix) {
  34913. applyTransform(pt1, pt1, matrix);
  34914. applyTransform(pt2, pt2, matrix);
  34915. }
  34916. // Tick line, Not use group transform to have better line draw
  34917. var tickEl = new Line(subPixelOptimizeLine({
  34918. // Id for animation
  34919. anid: 'tick_' + ticksCoords[i].tickValue,
  34920. shape: {
  34921. x1: pt1[0],
  34922. y1: pt1[1],
  34923. x2: pt2[0],
  34924. y2: pt2[1]
  34925. },
  34926. style: defaults(
  34927. lineStyleModel.getLineStyle(),
  34928. {
  34929. stroke: axisModel.get('axisLine.lineStyle.color')
  34930. }
  34931. ),
  34932. z2: 2,
  34933. silent: true
  34934. }));
  34935. axisBuilder.group.add(tickEl);
  34936. tickEls.push(tickEl);
  34937. }
  34938. return tickEls;
  34939. }
  34940. function buildAxisLabel(axisBuilder, axisModel, opt) {
  34941. var axis = axisModel.axis;
  34942. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  34943. if (!show || axis.scale.isBlank()) {
  34944. return;
  34945. }
  34946. var labelModel = axisModel.getModel('axisLabel');
  34947. var labelMargin = labelModel.get('margin');
  34948. var labels = axis.getViewLabels();
  34949. // Special label rotate.
  34950. var labelRotation = (
  34951. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  34952. ) * PI$2 / 180;
  34953. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  34954. var rawCategoryData = axisModel.getCategories(true);
  34955. var labelEls = [];
  34956. var silent = isSilent(axisModel);
  34957. var triggerEvent = axisModel.get('triggerEvent');
  34958. each$1(labels, function (labelItem, index) {
  34959. var tickValue = labelItem.tickValue;
  34960. var formattedLabel = labelItem.formattedLabel;
  34961. var rawLabel = labelItem.rawLabel;
  34962. var itemLabelModel = labelModel;
  34963. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  34964. itemLabelModel = new Model(
  34965. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  34966. );
  34967. }
  34968. var textColor = itemLabelModel.getTextColor()
  34969. || axisModel.get('axisLine.lineStyle.color');
  34970. var tickCoord = axis.dataToCoord(tickValue);
  34971. var pos = [
  34972. tickCoord,
  34973. opt.labelOffset + opt.labelDirection * labelMargin
  34974. ];
  34975. var textEl = new Text({
  34976. // Id for animation
  34977. anid: 'label_' + tickValue,
  34978. position: pos,
  34979. rotation: labelLayout.rotation,
  34980. silent: silent,
  34981. z2: 10
  34982. });
  34983. setTextStyle(textEl.style, itemLabelModel, {
  34984. text: formattedLabel,
  34985. textAlign: itemLabelModel.getShallow('align', true)
  34986. || labelLayout.textAlign,
  34987. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  34988. || itemLabelModel.getShallow('baseline', true)
  34989. || labelLayout.textVerticalAlign,
  34990. textFill: typeof textColor === 'function'
  34991. ? textColor(
  34992. // (1) In category axis with data zoom, tick is not the original
  34993. // index of axis.data. So tick should not be exposed to user
  34994. // in category axis.
  34995. // (2) Compatible with previous version, which always use formatted label as
  34996. // input. But in interval scale the formatted label is like '223,445', which
  34997. // maked user repalce ','. So we modify it to return original val but remain
  34998. // it as 'string' to avoid error in replacing.
  34999. axis.type === 'category'
  35000. ? rawLabel
  35001. : axis.type === 'value'
  35002. ? tickValue + ''
  35003. : tickValue,
  35004. index
  35005. )
  35006. : textColor
  35007. });
  35008. // Pack data for mouse event
  35009. if (triggerEvent) {
  35010. textEl.eventData = makeAxisEventDataBase(axisModel);
  35011. textEl.eventData.targetType = 'axisLabel';
  35012. textEl.eventData.value = rawLabel;
  35013. }
  35014. // FIXME
  35015. axisBuilder._dumbGroup.add(textEl);
  35016. textEl.updateTransform();
  35017. labelEls.push(textEl);
  35018. axisBuilder.group.add(textEl);
  35019. textEl.decomposeTransform();
  35020. });
  35021. return labelEls;
  35022. }
  35023. /*
  35024. * Licensed to the Apache Software Foundation (ASF) under one
  35025. * or more contributor license agreements. See the NOTICE file
  35026. * distributed with this work for additional information
  35027. * regarding copyright ownership. The ASF licenses this file
  35028. * to you under the Apache License, Version 2.0 (the
  35029. * "License"); you may not use this file except in compliance
  35030. * with the License. You may obtain a copy of the License at
  35031. *
  35032. * http://www.apache.org/licenses/LICENSE-2.0
  35033. *
  35034. * Unless required by applicable law or agreed to in writing,
  35035. * software distributed under the License is distributed on an
  35036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35037. * KIND, either express or implied. See the License for the
  35038. * specific language governing permissions and limitations
  35039. * under the License.
  35040. */
  35041. var each$6 = each$1;
  35042. var curry$1 = curry;
  35043. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  35044. // allAxesInfo should be updated when setOption performed.
  35045. function collect(ecModel, api) {
  35046. var result = {
  35047. /**
  35048. * key: makeKey(axis.model)
  35049. * value: {
  35050. * axis,
  35051. * coordSys,
  35052. * axisPointerModel,
  35053. * triggerTooltip,
  35054. * involveSeries,
  35055. * snap,
  35056. * seriesModels,
  35057. * seriesDataCount
  35058. * }
  35059. */
  35060. axesInfo: {},
  35061. seriesInvolved: false,
  35062. /**
  35063. * key: makeKey(coordSys.model)
  35064. * value: Object: key makeKey(axis.model), value: axisInfo
  35065. */
  35066. coordSysAxesInfo: {},
  35067. coordSysMap: {}
  35068. };
  35069. collectAxesInfo(result, ecModel, api);
  35070. // Check seriesInvolved for performance, in case too many series in some chart.
  35071. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  35072. return result;
  35073. }
  35074. function collectAxesInfo(result, ecModel, api) {
  35075. var globalTooltipModel = ecModel.getComponent('tooltip');
  35076. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  35077. // links can only be set on global.
  35078. var linksOption = globalAxisPointerModel.get('link', true) || [];
  35079. var linkGroups = [];
  35080. // Collect axes info.
  35081. each$6(api.getCoordinateSystems(), function (coordSys) {
  35082. // Some coordinate system do not support axes, like geo.
  35083. if (!coordSys.axisPointerEnabled) {
  35084. return;
  35085. }
  35086. var coordSysKey = makeKey(coordSys.model);
  35087. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  35088. result.coordSysMap[coordSysKey] = coordSys;
  35089. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  35090. // for user. So we enable seting tooltip on coordSys model.
  35091. var coordSysModel = coordSys.model;
  35092. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  35093. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  35094. // If axis tooltip used, choose tooltip axis for each coordSys.
  35095. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  35096. if (coordSys.getTooltipAxes
  35097. && globalTooltipModel
  35098. // If tooltip.showContent is set as false, tooltip will not
  35099. // show but axisPointer will show as normal.
  35100. && baseTooltipModel.get('show')
  35101. ) {
  35102. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  35103. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  35104. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  35105. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  35106. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  35107. if (triggerAxis || cross) {
  35108. each$6(tooltipAxes.baseAxes, curry$1(
  35109. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  35110. ));
  35111. }
  35112. if (cross) {
  35113. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  35114. }
  35115. }
  35116. // fromTooltip: true | false | 'cross'
  35117. // triggerTooltip: true | false | null
  35118. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  35119. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  35120. var axisPointerShow = axisPointerModel.get('show');
  35121. if (!axisPointerShow || (
  35122. axisPointerShow === 'auto'
  35123. && !fromTooltip
  35124. && !isHandleTrigger(axisPointerModel)
  35125. )) {
  35126. return;
  35127. }
  35128. if (triggerTooltip == null) {
  35129. triggerTooltip = axisPointerModel.get('triggerTooltip');
  35130. }
  35131. axisPointerModel = fromTooltip
  35132. ? makeAxisPointerModel(
  35133. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  35134. fromTooltip, triggerTooltip
  35135. )
  35136. : axisPointerModel;
  35137. var snap = axisPointerModel.get('snap');
  35138. var key = makeKey(axis.model);
  35139. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  35140. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  35141. var axisInfo = result.axesInfo[key] = {
  35142. key: key,
  35143. axis: axis,
  35144. coordSys: coordSys,
  35145. axisPointerModel: axisPointerModel,
  35146. triggerTooltip: triggerTooltip,
  35147. involveSeries: involveSeries,
  35148. snap: snap,
  35149. useHandle: isHandleTrigger(axisPointerModel),
  35150. seriesModels: []
  35151. };
  35152. axesInfoInCoordSys[key] = axisInfo;
  35153. result.seriesInvolved |= involveSeries;
  35154. var groupIndex = getLinkGroupIndex(linksOption, axis);
  35155. if (groupIndex != null) {
  35156. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  35157. linkGroup.axesInfo[key] = axisInfo;
  35158. linkGroup.mapper = linksOption[groupIndex].mapper;
  35159. axisInfo.linkGroup = linkGroup;
  35160. }
  35161. }
  35162. });
  35163. }
  35164. function makeAxisPointerModel(
  35165. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  35166. ) {
  35167. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  35168. var volatileOption = {};
  35169. each$6(
  35170. [
  35171. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  35172. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  35173. ],
  35174. function (field) {
  35175. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  35176. }
  35177. );
  35178. // category axis do not auto snap, otherwise some tick that do not
  35179. // has value can not be hovered. value/time/log axis default snap if
  35180. // triggered from tooltip and trigger tooltip.
  35181. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  35182. // Compatibel with previous behavior, tooltip axis do not show label by default.
  35183. // Only these properties can be overrided from tooltip to axisPointer.
  35184. if (tooltipAxisPointerModel.get('type') === 'cross') {
  35185. volatileOption.type = 'line';
  35186. }
  35187. var labelOption = volatileOption.label || (volatileOption.label = {});
  35188. // Follow the convention, do not show label when triggered by tooltip by default.
  35189. labelOption.show == null && (labelOption.show = false);
  35190. if (fromTooltip === 'cross') {
  35191. // When 'cross', both axes show labels.
  35192. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  35193. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  35194. // If triggerTooltip, this is a base axis, which should better not use cross style
  35195. // (cross style is dashed by default)
  35196. if (!triggerTooltip) {
  35197. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  35198. crossStyle && defaults(labelOption, crossStyle.textStyle);
  35199. }
  35200. }
  35201. return axis.model.getModel(
  35202. 'axisPointer',
  35203. new Model(volatileOption, globalAxisPointerModel, ecModel)
  35204. );
  35205. }
  35206. function collectSeriesInfo(result, ecModel) {
  35207. // Prepare data for axis trigger
  35208. ecModel.eachSeries(function (seriesModel) {
  35209. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  35210. var coordSys = seriesModel.coordinateSystem;
  35211. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  35212. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  35213. if (!coordSys
  35214. || seriesTooltipTrigger === 'none'
  35215. || seriesTooltipTrigger === false
  35216. || seriesTooltipTrigger === 'item'
  35217. || seriesTooltipShow === false
  35218. || seriesModel.get('axisPointer.show', true) === false
  35219. ) {
  35220. return;
  35221. }
  35222. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  35223. var axis = axisInfo.axis;
  35224. if (coordSys.getAxis(axis.dim) === axis) {
  35225. axisInfo.seriesModels.push(seriesModel);
  35226. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  35227. axisInfo.seriesDataCount += seriesModel.getData().count();
  35228. }
  35229. });
  35230. }, this);
  35231. }
  35232. /**
  35233. * For example:
  35234. * {
  35235. * axisPointer: {
  35236. * links: [{
  35237. * xAxisIndex: [2, 4],
  35238. * yAxisIndex: 'all'
  35239. * }, {
  35240. * xAxisId: ['a5', 'a7'],
  35241. * xAxisName: 'xxx'
  35242. * }]
  35243. * }
  35244. * }
  35245. */
  35246. function getLinkGroupIndex(linksOption, axis) {
  35247. var axisModel = axis.model;
  35248. var dim = axis.dim;
  35249. for (var i = 0; i < linksOption.length; i++) {
  35250. var linkOption = linksOption[i] || {};
  35251. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  35252. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  35253. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  35254. ) {
  35255. return i;
  35256. }
  35257. }
  35258. }
  35259. function checkPropInLink(linkPropValue, axisPropValue) {
  35260. return linkPropValue === 'all'
  35261. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  35262. || linkPropValue === axisPropValue;
  35263. }
  35264. function fixValue(axisModel) {
  35265. var axisInfo = getAxisInfo(axisModel);
  35266. if (!axisInfo) {
  35267. return;
  35268. }
  35269. var axisPointerModel = axisInfo.axisPointerModel;
  35270. var scale = axisInfo.axis.scale;
  35271. var option = axisPointerModel.option;
  35272. var status = axisPointerModel.get('status');
  35273. var value = axisPointerModel.get('value');
  35274. // Parse init value for category and time axis.
  35275. if (value != null) {
  35276. value = scale.parse(value);
  35277. }
  35278. var useHandle = isHandleTrigger(axisPointerModel);
  35279. // If `handle` used, `axisPointer` will always be displayed, so value
  35280. // and status should be initialized.
  35281. if (status == null) {
  35282. option.status = useHandle ? 'show' : 'hide';
  35283. }
  35284. var extent = scale.getExtent().slice();
  35285. extent[0] > extent[1] && extent.reverse();
  35286. if (// Pick a value on axis when initializing.
  35287. value == null
  35288. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35289. // where we should re-pick a value to keep `handle` displaying normally.
  35290. || value > extent[1]
  35291. ) {
  35292. // Make handle displayed on the end of the axis when init, which looks better.
  35293. value = extent[1];
  35294. }
  35295. if (value < extent[0]) {
  35296. value = extent[0];
  35297. }
  35298. option.value = value;
  35299. if (useHandle) {
  35300. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35301. }
  35302. }
  35303. function getAxisInfo(axisModel) {
  35304. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35305. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35306. }
  35307. function getAxisPointerModel(axisModel) {
  35308. var axisInfo = getAxisInfo(axisModel);
  35309. return axisInfo && axisInfo.axisPointerModel;
  35310. }
  35311. function isHandleTrigger(axisPointerModel) {
  35312. return !!axisPointerModel.get('handle.show');
  35313. }
  35314. /**
  35315. * @param {module:echarts/model/Model} model
  35316. * @return {string} unique key
  35317. */
  35318. function makeKey(model) {
  35319. return model.type + '||' + model.id;
  35320. }
  35321. /*
  35322. * Licensed to the Apache Software Foundation (ASF) under one
  35323. * or more contributor license agreements. See the NOTICE file
  35324. * distributed with this work for additional information
  35325. * regarding copyright ownership. The ASF licenses this file
  35326. * to you under the Apache License, Version 2.0 (the
  35327. * "License"); you may not use this file except in compliance
  35328. * with the License. You may obtain a copy of the License at
  35329. *
  35330. * http://www.apache.org/licenses/LICENSE-2.0
  35331. *
  35332. * Unless required by applicable law or agreed to in writing,
  35333. * software distributed under the License is distributed on an
  35334. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35335. * KIND, either express or implied. See the License for the
  35336. * specific language governing permissions and limitations
  35337. * under the License.
  35338. */
  35339. /**
  35340. * Base class of AxisView.
  35341. */
  35342. var AxisView = extendComponentView({
  35343. type: 'axis',
  35344. /**
  35345. * @private
  35346. */
  35347. _axisPointer: null,
  35348. /**
  35349. * @protected
  35350. * @type {string}
  35351. */
  35352. axisPointerClass: null,
  35353. /**
  35354. * @override
  35355. */
  35356. render: function (axisModel, ecModel, api, payload) {
  35357. // FIXME
  35358. // This process should proformed after coordinate systems updated
  35359. // (axis scale updated), and should be performed each time update.
  35360. // So put it here temporarily, although it is not appropriate to
  35361. // put a model-writing procedure in `view`.
  35362. this.axisPointerClass && fixValue(axisModel);
  35363. AxisView.superApply(this, 'render', arguments);
  35364. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35365. },
  35366. /**
  35367. * Action handler.
  35368. * @public
  35369. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35370. * @param {module:echarts/model/Global} ecModel
  35371. * @param {module:echarts/ExtensionAPI} api
  35372. * @param {Object} payload
  35373. */
  35374. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35375. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35376. },
  35377. /**
  35378. * @override
  35379. */
  35380. remove: function (ecModel, api) {
  35381. var axisPointer = this._axisPointer;
  35382. axisPointer && axisPointer.remove(api);
  35383. AxisView.superApply(this, 'remove', arguments);
  35384. },
  35385. /**
  35386. * @override
  35387. */
  35388. dispose: function (ecModel, api) {
  35389. disposeAxisPointer(this, api);
  35390. AxisView.superApply(this, 'dispose', arguments);
  35391. }
  35392. });
  35393. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35394. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35395. if (!Clazz) {
  35396. return;
  35397. }
  35398. var axisPointerModel = getAxisPointerModel(axisModel);
  35399. axisPointerModel
  35400. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35401. .render(axisModel, axisPointerModel, api, forceRender)
  35402. : disposeAxisPointer(axisView, api);
  35403. }
  35404. function disposeAxisPointer(axisView, ecModel, api) {
  35405. var axisPointer = axisView._axisPointer;
  35406. axisPointer && axisPointer.dispose(ecModel, api);
  35407. axisView._axisPointer = null;
  35408. }
  35409. var axisPointerClazz = [];
  35410. AxisView.registerAxisPointerClass = function (type, clazz) {
  35411. if (__DEV__) {
  35412. if (axisPointerClazz[type]) {
  35413. throw new Error('axisPointer ' + type + ' exists');
  35414. }
  35415. }
  35416. axisPointerClazz[type] = clazz;
  35417. };
  35418. AxisView.getAxisPointerClass = function (type) {
  35419. return type && axisPointerClazz[type];
  35420. };
  35421. /*
  35422. * Licensed to the Apache Software Foundation (ASF) under one
  35423. * or more contributor license agreements. See the NOTICE file
  35424. * distributed with this work for additional information
  35425. * regarding copyright ownership. The ASF licenses this file
  35426. * to you under the Apache License, Version 2.0 (the
  35427. * "License"); you may not use this file except in compliance
  35428. * with the License. You may obtain a copy of the License at
  35429. *
  35430. * http://www.apache.org/licenses/LICENSE-2.0
  35431. *
  35432. * Unless required by applicable law or agreed to in writing,
  35433. * software distributed under the License is distributed on an
  35434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35435. * KIND, either express or implied. See the License for the
  35436. * specific language governing permissions and limitations
  35437. * under the License.
  35438. */
  35439. /**
  35440. * Can only be called after coordinate system creation stage.
  35441. * (Can be called before coordinate system update stage).
  35442. *
  35443. * @param {Object} opt {labelInside}
  35444. * @return {Object} {
  35445. * position, rotation, labelDirection, labelOffset,
  35446. * tickDirection, labelRotate, z2
  35447. * }
  35448. */
  35449. function layout$1(gridModel, axisModel, opt) {
  35450. opt = opt || {};
  35451. var grid = gridModel.coordinateSystem;
  35452. var axis = axisModel.axis;
  35453. var layout = {};
  35454. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35455. var rawAxisPosition = axis.position;
  35456. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35457. var axisDim = axis.dim;
  35458. var rect = grid.getRect();
  35459. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35460. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35461. var axisOffset = axisModel.get('offset') || 0;
  35462. var posBound = axisDim === 'x'
  35463. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35464. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35465. if (otherAxisOnZeroOf) {
  35466. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35467. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35468. }
  35469. // Axis position
  35470. layout.position = [
  35471. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35472. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35473. ];
  35474. // Axis rotation
  35475. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35476. // Tick and label direction, x y is axisDim
  35477. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35478. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35479. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35480. if (axisModel.get('axisTick.inside')) {
  35481. layout.tickDirection = -layout.tickDirection;
  35482. }
  35483. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35484. layout.labelDirection = -layout.labelDirection;
  35485. }
  35486. // Special label rotation
  35487. var labelRotate = axisModel.get('axisLabel.rotate');
  35488. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35489. // Over splitLine and splitArea
  35490. layout.z2 = 1;
  35491. return layout;
  35492. }
  35493. /*
  35494. * Licensed to the Apache Software Foundation (ASF) under one
  35495. * or more contributor license agreements. See the NOTICE file
  35496. * distributed with this work for additional information
  35497. * regarding copyright ownership. The ASF licenses this file
  35498. * to you under the Apache License, Version 2.0 (the
  35499. * "License"); you may not use this file except in compliance
  35500. * with the License. You may obtain a copy of the License at
  35501. *
  35502. * http://www.apache.org/licenses/LICENSE-2.0
  35503. *
  35504. * Unless required by applicable law or agreed to in writing,
  35505. * software distributed under the License is distributed on an
  35506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35507. * KIND, either express or implied. See the License for the
  35508. * specific language governing permissions and limitations
  35509. * under the License.
  35510. */
  35511. var axisBuilderAttrs = [
  35512. 'axisLine', 'axisTickLabel', 'axisName'
  35513. ];
  35514. var selfBuilderAttrs = [
  35515. 'splitArea', 'splitLine'
  35516. ];
  35517. // function getAlignWithLabel(model, axisModel) {
  35518. // var alignWithLabel = model.get('alignWithLabel');
  35519. // if (alignWithLabel === 'auto') {
  35520. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  35521. // }
  35522. // return alignWithLabel;
  35523. // }
  35524. var CartesianAxisView = AxisView.extend({
  35525. type: 'cartesianAxis',
  35526. axisPointerClass: 'CartesianAxisPointer',
  35527. /**
  35528. * @override
  35529. */
  35530. render: function (axisModel, ecModel, api, payload) {
  35531. this.group.removeAll();
  35532. var oldAxisGroup = this._axisGroup;
  35533. this._axisGroup = new Group();
  35534. this.group.add(this._axisGroup);
  35535. if (!axisModel.get('show')) {
  35536. return;
  35537. }
  35538. var gridModel = axisModel.getCoordSysModel();
  35539. var layout = layout$1(gridModel, axisModel);
  35540. var axisBuilder = new AxisBuilder(axisModel, layout);
  35541. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35542. this._axisGroup.add(axisBuilder.getGroup());
  35543. each$1(selfBuilderAttrs, function (name) {
  35544. if (axisModel.get(name + '.show')) {
  35545. this['_' + name](axisModel, gridModel);
  35546. }
  35547. }, this);
  35548. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35549. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35550. },
  35551. remove: function () {
  35552. this._splitAreaColors = null;
  35553. },
  35554. /**
  35555. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35556. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35557. * @private
  35558. */
  35559. _splitLine: function (axisModel, gridModel) {
  35560. var axis = axisModel.axis;
  35561. if (axis.scale.isBlank()) {
  35562. return;
  35563. }
  35564. var splitLineModel = axisModel.getModel('splitLine');
  35565. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35566. var lineColors = lineStyleModel.get('color');
  35567. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35568. var gridRect = gridModel.coordinateSystem.getRect();
  35569. var isHorizontal = axis.isHorizontal();
  35570. var lineCount = 0;
  35571. var ticksCoords = axis.getTicksCoords({
  35572. tickModel: splitLineModel
  35573. });
  35574. var p1 = [];
  35575. var p2 = [];
  35576. // Simple optimization
  35577. // Batching the lines if color are the same
  35578. var lineStyle = lineStyleModel.getLineStyle();
  35579. for (var i = 0; i < ticksCoords.length; i++) {
  35580. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35581. if (isHorizontal) {
  35582. p1[0] = tickCoord;
  35583. p1[1] = gridRect.y;
  35584. p2[0] = tickCoord;
  35585. p2[1] = gridRect.y + gridRect.height;
  35586. }
  35587. else {
  35588. p1[0] = gridRect.x;
  35589. p1[1] = tickCoord;
  35590. p2[0] = gridRect.x + gridRect.width;
  35591. p2[1] = tickCoord;
  35592. }
  35593. var colorIndex = (lineCount++) % lineColors.length;
  35594. var tickValue = ticksCoords[i].tickValue;
  35595. this._axisGroup.add(new Line(subPixelOptimizeLine({
  35596. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35597. shape: {
  35598. x1: p1[0],
  35599. y1: p1[1],
  35600. x2: p2[0],
  35601. y2: p2[1]
  35602. },
  35603. style: defaults({
  35604. stroke: lineColors[colorIndex]
  35605. }, lineStyle),
  35606. silent: true
  35607. })));
  35608. }
  35609. },
  35610. /**
  35611. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35612. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35613. * @private
  35614. */
  35615. _splitArea: function (axisModel, gridModel) {
  35616. var axis = axisModel.axis;
  35617. if (axis.scale.isBlank()) {
  35618. return;
  35619. }
  35620. var splitAreaModel = axisModel.getModel('splitArea');
  35621. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35622. var areaColors = areaStyleModel.get('color');
  35623. var gridRect = gridModel.coordinateSystem.getRect();
  35624. var ticksCoords = axis.getTicksCoords({
  35625. tickModel: splitAreaModel,
  35626. clamp: true
  35627. });
  35628. if (!ticksCoords.length) {
  35629. return;
  35630. }
  35631. // For Making appropriate splitArea animation, the color and anid
  35632. // should be corresponding to previous one if possible.
  35633. var areaColorsLen = areaColors.length;
  35634. var lastSplitAreaColors = this._splitAreaColors;
  35635. var newSplitAreaColors = createHashMap();
  35636. var colorIndex = 0;
  35637. if (lastSplitAreaColors) {
  35638. for (var i = 0; i < ticksCoords.length; i++) {
  35639. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35640. if (cIndex != null) {
  35641. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35642. break;
  35643. }
  35644. }
  35645. }
  35646. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35647. var areaStyle = areaStyleModel.getAreaStyle();
  35648. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35649. for (var i = 1; i < ticksCoords.length; i++) {
  35650. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35651. var x;
  35652. var y;
  35653. var width;
  35654. var height;
  35655. if (axis.isHorizontal()) {
  35656. x = prev;
  35657. y = gridRect.y;
  35658. width = tickCoord - x;
  35659. height = gridRect.height;
  35660. prev = x + width;
  35661. }
  35662. else {
  35663. x = gridRect.x;
  35664. y = prev;
  35665. width = gridRect.width;
  35666. height = tickCoord - y;
  35667. prev = y + height;
  35668. }
  35669. var tickValue = ticksCoords[i - 1].tickValue;
  35670. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35671. this._axisGroup.add(new Rect({
  35672. anid: tickValue != null ? 'area_' + tickValue : null,
  35673. shape: {
  35674. x: x,
  35675. y: y,
  35676. width: width,
  35677. height: height
  35678. },
  35679. style: defaults({
  35680. fill: areaColors[colorIndex]
  35681. }, areaStyle),
  35682. silent: true
  35683. }));
  35684. colorIndex = (colorIndex + 1) % areaColorsLen;
  35685. }
  35686. this._splitAreaColors = newSplitAreaColors;
  35687. }
  35688. });
  35689. CartesianAxisView.extend({
  35690. type: 'xAxis'
  35691. });
  35692. CartesianAxisView.extend({
  35693. type: 'yAxis'
  35694. });
  35695. /*
  35696. * Licensed to the Apache Software Foundation (ASF) under one
  35697. * or more contributor license agreements. See the NOTICE file
  35698. * distributed with this work for additional information
  35699. * regarding copyright ownership. The ASF licenses this file
  35700. * to you under the Apache License, Version 2.0 (the
  35701. * "License"); you may not use this file except in compliance
  35702. * with the License. You may obtain a copy of the License at
  35703. *
  35704. * http://www.apache.org/licenses/LICENSE-2.0
  35705. *
  35706. * Unless required by applicable law or agreed to in writing,
  35707. * software distributed under the License is distributed on an
  35708. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35709. * KIND, either express or implied. See the License for the
  35710. * specific language governing permissions and limitations
  35711. * under the License.
  35712. */
  35713. /*
  35714. * Licensed to the Apache Software Foundation (ASF) under one
  35715. * or more contributor license agreements. See the NOTICE file
  35716. * distributed with this work for additional information
  35717. * regarding copyright ownership. The ASF licenses this file
  35718. * to you under the Apache License, Version 2.0 (the
  35719. * "License"); you may not use this file except in compliance
  35720. * with the License. You may obtain a copy of the License at
  35721. *
  35722. * http://www.apache.org/licenses/LICENSE-2.0
  35723. *
  35724. * Unless required by applicable law or agreed to in writing,
  35725. * software distributed under the License is distributed on an
  35726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35727. * KIND, either express or implied. See the License for the
  35728. * specific language governing permissions and limitations
  35729. * under the License.
  35730. */
  35731. // Grid view
  35732. extendComponentView({
  35733. type: 'grid',
  35734. render: function (gridModel, ecModel) {
  35735. this.group.removeAll();
  35736. if (gridModel.get('show')) {
  35737. this.group.add(new Rect({
  35738. shape: gridModel.coordinateSystem.getRect(),
  35739. style: defaults({
  35740. fill: gridModel.get('backgroundColor')
  35741. }, gridModel.getItemStyle()),
  35742. silent: true,
  35743. z2: -1
  35744. }));
  35745. }
  35746. }
  35747. });
  35748. registerPreprocessor(function (option) {
  35749. // Only create grid when need
  35750. if (option.xAxis && option.yAxis && !option.grid) {
  35751. option.grid = {};
  35752. }
  35753. });
  35754. /*
  35755. * Licensed to the Apache Software Foundation (ASF) under one
  35756. * or more contributor license agreements. See the NOTICE file
  35757. * distributed with this work for additional information
  35758. * regarding copyright ownership. The ASF licenses this file
  35759. * to you under the Apache License, Version 2.0 (the
  35760. * "License"); you may not use this file except in compliance
  35761. * with the License. You may obtain a copy of the License at
  35762. *
  35763. * http://www.apache.org/licenses/LICENSE-2.0
  35764. *
  35765. * Unless required by applicable law or agreed to in writing,
  35766. * software distributed under the License is distributed on an
  35767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35768. * KIND, either express or implied. See the License for the
  35769. * specific language governing permissions and limitations
  35770. * under the License.
  35771. */
  35772. // In case developer forget to include grid component
  35773. registerVisual(visualSymbol('line', 'circle', 'line'));
  35774. registerLayout(pointsLayout('line'));
  35775. // Down sample after filter
  35776. registerProcessor(
  35777. PRIORITY.PROCESSOR.STATISTIC,
  35778. dataSample('line')
  35779. );
  35780. /*
  35781. * Licensed to the Apache Software Foundation (ASF) under one
  35782. * or more contributor license agreements. See the NOTICE file
  35783. * distributed with this work for additional information
  35784. * regarding copyright ownership. The ASF licenses this file
  35785. * to you under the Apache License, Version 2.0 (the
  35786. * "License"); you may not use this file except in compliance
  35787. * with the License. You may obtain a copy of the License at
  35788. *
  35789. * http://www.apache.org/licenses/LICENSE-2.0
  35790. *
  35791. * Unless required by applicable law or agreed to in writing,
  35792. * software distributed under the License is distributed on an
  35793. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35794. * KIND, either express or implied. See the License for the
  35795. * specific language governing permissions and limitations
  35796. * under the License.
  35797. */
  35798. var BaseBarSeries = SeriesModel.extend({
  35799. type: 'series.__base_bar__',
  35800. getInitialData: function (option, ecModel) {
  35801. return createListFromArray(this.getSource(), this);
  35802. },
  35803. getMarkerPosition: function (value) {
  35804. var coordSys = this.coordinateSystem;
  35805. if (coordSys) {
  35806. // PENDING if clamp ?
  35807. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  35808. var data = this.getData();
  35809. var offset = data.getLayout('offset');
  35810. var size = data.getLayout('size');
  35811. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  35812. pt[offsetIndex] += offset + size / 2;
  35813. return pt;
  35814. }
  35815. return [NaN, NaN];
  35816. },
  35817. defaultOption: {
  35818. zlevel: 0, // 一级层叠
  35819. z: 2, // 二级层叠
  35820. coordinateSystem: 'cartesian2d',
  35821. legendHoverLink: true,
  35822. // stack: null
  35823. // Cartesian coordinate system
  35824. // xAxisIndex: 0,
  35825. // yAxisIndex: 0,
  35826. // 最小高度改为0
  35827. barMinHeight: 0,
  35828. // 最小角度为0,仅对极坐标系下的柱状图有效
  35829. barMinAngle: 0,
  35830. // cursor: null,
  35831. large: false,
  35832. largeThreshold: 400,
  35833. progressive: 3e3,
  35834. progressiveChunkMode: 'mod',
  35835. // barMaxWidth: null,
  35836. // 默认自适应
  35837. // barWidth: null,
  35838. // 柱间距离,默认为柱形宽度的30%,可设固定值
  35839. // barGap: '30%',
  35840. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  35841. // barCategoryGap: '20%',
  35842. // label: {
  35843. // show: false
  35844. // },
  35845. itemStyle: {},
  35846. emphasis: {}
  35847. }
  35848. });
  35849. /*
  35850. * Licensed to the Apache Software Foundation (ASF) under one
  35851. * or more contributor license agreements. See the NOTICE file
  35852. * distributed with this work for additional information
  35853. * regarding copyright ownership. The ASF licenses this file
  35854. * to you under the Apache License, Version 2.0 (the
  35855. * "License"); you may not use this file except in compliance
  35856. * with the License. You may obtain a copy of the License at
  35857. *
  35858. * http://www.apache.org/licenses/LICENSE-2.0
  35859. *
  35860. * Unless required by applicable law or agreed to in writing,
  35861. * software distributed under the License is distributed on an
  35862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35863. * KIND, either express or implied. See the License for the
  35864. * specific language governing permissions and limitations
  35865. * under the License.
  35866. */
  35867. BaseBarSeries.extend({
  35868. type: 'series.bar',
  35869. dependencies: ['grid', 'polar'],
  35870. brushSelector: 'rect',
  35871. /**
  35872. * @override
  35873. */
  35874. getProgressive: function () {
  35875. // Do not support progressive in normal mode.
  35876. return this.get('large')
  35877. ? this.get('progressive')
  35878. : false;
  35879. },
  35880. /**
  35881. * @override
  35882. */
  35883. getProgressiveThreshold: function () {
  35884. // Do not support progressive in normal mode.
  35885. var progressiveThreshold = this.get('progressiveThreshold');
  35886. var largeThreshold = this.get('largeThreshold');
  35887. if (largeThreshold > progressiveThreshold) {
  35888. progressiveThreshold = largeThreshold;
  35889. }
  35890. return progressiveThreshold;
  35891. }
  35892. });
  35893. /*
  35894. * Licensed to the Apache Software Foundation (ASF) under one
  35895. * or more contributor license agreements. See the NOTICE file
  35896. * distributed with this work for additional information
  35897. * regarding copyright ownership. The ASF licenses this file
  35898. * to you under the Apache License, Version 2.0 (the
  35899. * "License"); you may not use this file except in compliance
  35900. * with the License. You may obtain a copy of the License at
  35901. *
  35902. * http://www.apache.org/licenses/LICENSE-2.0
  35903. *
  35904. * Unless required by applicable law or agreed to in writing,
  35905. * software distributed under the License is distributed on an
  35906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35907. * KIND, either express or implied. See the License for the
  35908. * specific language governing permissions and limitations
  35909. * under the License.
  35910. */
  35911. function setLabel(
  35912. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  35913. ) {
  35914. var labelModel = itemModel.getModel('label');
  35915. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35916. setLabelStyle(
  35917. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  35918. {
  35919. labelFetcher: seriesModel,
  35920. labelDataIndex: dataIndex,
  35921. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  35922. isRectText: true,
  35923. autoColor: color
  35924. }
  35925. );
  35926. fixPosition(normalStyle);
  35927. fixPosition(hoverStyle);
  35928. }
  35929. function fixPosition(style, labelPositionOutside) {
  35930. if (style.textPosition === 'outside') {
  35931. style.textPosition = labelPositionOutside;
  35932. }
  35933. }
  35934. /*
  35935. * Licensed to the Apache Software Foundation (ASF) under one
  35936. * or more contributor license agreements. See the NOTICE file
  35937. * distributed with this work for additional information
  35938. * regarding copyright ownership. The ASF licenses this file
  35939. * to you under the Apache License, Version 2.0 (the
  35940. * "License"); you may not use this file except in compliance
  35941. * with the License. You may obtain a copy of the License at
  35942. *
  35943. * http://www.apache.org/licenses/LICENSE-2.0
  35944. *
  35945. * Unless required by applicable law or agreed to in writing,
  35946. * software distributed under the License is distributed on an
  35947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35948. * KIND, either express or implied. See the License for the
  35949. * specific language governing permissions and limitations
  35950. * under the License.
  35951. */
  35952. var getBarItemStyle = makeStyleMapper(
  35953. [
  35954. ['fill', 'color'],
  35955. ['stroke', 'borderColor'],
  35956. ['lineWidth', 'borderWidth'],
  35957. // Compatitable with 2
  35958. ['stroke', 'barBorderColor'],
  35959. ['lineWidth', 'barBorderWidth'],
  35960. ['opacity'],
  35961. ['shadowBlur'],
  35962. ['shadowOffsetX'],
  35963. ['shadowOffsetY'],
  35964. ['shadowColor']
  35965. ]
  35966. );
  35967. var barItemStyle = {
  35968. getBarItemStyle: function (excludes) {
  35969. var style = getBarItemStyle(this, excludes);
  35970. if (this.getBorderLineDash) {
  35971. var lineDash = this.getBorderLineDash();
  35972. lineDash && (style.lineDash = lineDash);
  35973. }
  35974. return style;
  35975. }
  35976. };
  35977. /*
  35978. * Licensed to the Apache Software Foundation (ASF) under one
  35979. * or more contributor license agreements. See the NOTICE file
  35980. * distributed with this work for additional information
  35981. * regarding copyright ownership. The ASF licenses this file
  35982. * to you under the Apache License, Version 2.0 (the
  35983. * "License"); you may not use this file except in compliance
  35984. * with the License. You may obtain a copy of the License at
  35985. *
  35986. * http://www.apache.org/licenses/LICENSE-2.0
  35987. *
  35988. * Unless required by applicable law or agreed to in writing,
  35989. * software distributed under the License is distributed on an
  35990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35991. * KIND, either express or implied. See the License for the
  35992. * specific language governing permissions and limitations
  35993. * under the License.
  35994. */
  35995. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  35996. // FIXME
  35997. // Just for compatible with ec2.
  35998. extend(Model.prototype, barItemStyle);
  35999. extendChartView({
  36000. type: 'bar',
  36001. render: function (seriesModel, ecModel, api) {
  36002. this._updateDrawMode(seriesModel);
  36003. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36004. if (coordinateSystemType === 'cartesian2d'
  36005. || coordinateSystemType === 'polar'
  36006. ) {
  36007. this._isLargeDraw
  36008. ? this._renderLarge(seriesModel, ecModel, api)
  36009. : this._renderNormal(seriesModel, ecModel, api);
  36010. }
  36011. else if (__DEV__) {
  36012. console.warn('Only cartesian2d and polar supported for bar.');
  36013. }
  36014. return this.group;
  36015. },
  36016. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36017. this._clear();
  36018. this._updateDrawMode(seriesModel);
  36019. },
  36020. incrementalRender: function (params, seriesModel, ecModel, api) {
  36021. // Do not support progressive in normal mode.
  36022. this._incrementalRenderLarge(params, seriesModel);
  36023. },
  36024. _updateDrawMode: function (seriesModel) {
  36025. var isLargeDraw = seriesModel.pipelineContext.large;
  36026. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  36027. this._isLargeDraw = isLargeDraw;
  36028. this._clear();
  36029. }
  36030. },
  36031. _renderNormal: function (seriesModel, ecModel, api) {
  36032. var group = this.group;
  36033. var data = seriesModel.getData();
  36034. var oldData = this._data;
  36035. var coord = seriesModel.coordinateSystem;
  36036. var baseAxis = coord.getBaseAxis();
  36037. var isHorizontalOrRadial;
  36038. if (coord.type === 'cartesian2d') {
  36039. isHorizontalOrRadial = baseAxis.isHorizontal();
  36040. }
  36041. else if (coord.type === 'polar') {
  36042. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36043. }
  36044. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36045. data.diff(oldData)
  36046. .add(function (dataIndex) {
  36047. if (!data.hasValue(dataIndex)) {
  36048. return;
  36049. }
  36050. var itemModel = data.getItemModel(dataIndex);
  36051. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36052. var el = elementCreator[coord.type](
  36053. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  36054. );
  36055. data.setItemGraphicEl(dataIndex, el);
  36056. group.add(el);
  36057. updateStyle(
  36058. el, data, dataIndex, itemModel, layout,
  36059. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36060. );
  36061. })
  36062. .update(function (newIndex, oldIndex) {
  36063. var el = oldData.getItemGraphicEl(oldIndex);
  36064. if (!data.hasValue(newIndex)) {
  36065. group.remove(el);
  36066. return;
  36067. }
  36068. var itemModel = data.getItemModel(newIndex);
  36069. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36070. if (el) {
  36071. updateProps(el, {shape: layout}, animationModel, newIndex);
  36072. }
  36073. else {
  36074. el = elementCreator[coord.type](
  36075. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  36076. );
  36077. }
  36078. data.setItemGraphicEl(newIndex, el);
  36079. // Add back
  36080. group.add(el);
  36081. updateStyle(
  36082. el, data, newIndex, itemModel, layout,
  36083. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36084. );
  36085. })
  36086. .remove(function (dataIndex) {
  36087. var el = oldData.getItemGraphicEl(dataIndex);
  36088. if (coord.type === 'cartesian2d') {
  36089. el && removeRect(dataIndex, animationModel, el);
  36090. }
  36091. else {
  36092. el && removeSector(dataIndex, animationModel, el);
  36093. }
  36094. })
  36095. .execute();
  36096. this._data = data;
  36097. },
  36098. _renderLarge: function (seriesModel, ecModel, api) {
  36099. this._clear();
  36100. createLarge(seriesModel, this.group);
  36101. },
  36102. _incrementalRenderLarge: function (params, seriesModel) {
  36103. createLarge(seriesModel, this.group, true);
  36104. },
  36105. dispose: noop,
  36106. remove: function (ecModel) {
  36107. this._clear(ecModel);
  36108. },
  36109. _clear: function (ecModel) {
  36110. var group = this.group;
  36111. var data = this._data;
  36112. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36113. data.eachItemGraphicEl(function (el) {
  36114. if (el.type === 'sector') {
  36115. removeSector(el.dataIndex, ecModel, el);
  36116. }
  36117. else {
  36118. removeRect(el.dataIndex, ecModel, el);
  36119. }
  36120. });
  36121. }
  36122. else {
  36123. group.removeAll();
  36124. }
  36125. this._data = null;
  36126. }
  36127. });
  36128. var elementCreator = {
  36129. cartesian2d: function (
  36130. data, dataIndex, itemModel, layout, isHorizontal,
  36131. animationModel, isUpdate
  36132. ) {
  36133. var rect = new Rect({shape: extend({}, layout)});
  36134. // Animation
  36135. if (animationModel) {
  36136. var rectShape = rect.shape;
  36137. var animateProperty = isHorizontal ? 'height' : 'width';
  36138. var animateTarget = {};
  36139. rectShape[animateProperty] = 0;
  36140. animateTarget[animateProperty] = layout[animateProperty];
  36141. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36142. shape: animateTarget
  36143. }, animationModel, dataIndex);
  36144. }
  36145. return rect;
  36146. },
  36147. polar: function (
  36148. data, dataIndex, itemModel, layout, isRadial,
  36149. animationModel, isUpdate
  36150. ) {
  36151. // Keep the same logic with bar in catesion: use end value to control
  36152. // direction. Notice that if clockwise is true (by default), the sector
  36153. // will always draw clockwisely, no matter whether endAngle is greater
  36154. // or less than startAngle.
  36155. var clockwise = layout.startAngle < layout.endAngle;
  36156. var sector = new Sector({
  36157. shape: defaults({clockwise: clockwise}, layout)
  36158. });
  36159. // Animation
  36160. if (animationModel) {
  36161. var sectorShape = sector.shape;
  36162. var animateProperty = isRadial ? 'r' : 'endAngle';
  36163. var animateTarget = {};
  36164. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36165. animateTarget[animateProperty] = layout[animateProperty];
  36166. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36167. shape: animateTarget
  36168. }, animationModel, dataIndex);
  36169. }
  36170. return sector;
  36171. }
  36172. };
  36173. function removeRect(dataIndex, animationModel, el) {
  36174. // Not show text when animating
  36175. el.style.text = null;
  36176. updateProps(el, {
  36177. shape: {
  36178. width: 0
  36179. }
  36180. }, animationModel, dataIndex, function () {
  36181. el.parent && el.parent.remove(el);
  36182. });
  36183. }
  36184. function removeSector(dataIndex, animationModel, el) {
  36185. // Not show text when animating
  36186. el.style.text = null;
  36187. updateProps(el, {
  36188. shape: {
  36189. r: el.shape.r0
  36190. }
  36191. }, animationModel, dataIndex, function () {
  36192. el.parent && el.parent.remove(el);
  36193. });
  36194. }
  36195. var getLayout = {
  36196. cartesian2d: function (data, dataIndex, itemModel) {
  36197. var layout = data.getItemLayout(dataIndex);
  36198. var fixedLineWidth = getLineWidth(itemModel, layout);
  36199. // fix layout with lineWidth
  36200. var signX = layout.width > 0 ? 1 : -1;
  36201. var signY = layout.height > 0 ? 1 : -1;
  36202. return {
  36203. x: layout.x + signX * fixedLineWidth / 2,
  36204. y: layout.y + signY * fixedLineWidth / 2,
  36205. width: layout.width - signX * fixedLineWidth,
  36206. height: layout.height - signY * fixedLineWidth
  36207. };
  36208. },
  36209. polar: function (data, dataIndex, itemModel) {
  36210. var layout = data.getItemLayout(dataIndex);
  36211. return {
  36212. cx: layout.cx,
  36213. cy: layout.cy,
  36214. r0: layout.r0,
  36215. r: layout.r,
  36216. startAngle: layout.startAngle,
  36217. endAngle: layout.endAngle
  36218. };
  36219. }
  36220. };
  36221. function updateStyle(
  36222. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36223. ) {
  36224. var color = data.getItemVisual(dataIndex, 'color');
  36225. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36226. var itemStyleModel = itemModel.getModel('itemStyle');
  36227. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36228. if (!isPolar) {
  36229. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36230. }
  36231. el.useStyle(defaults(
  36232. {
  36233. fill: color,
  36234. opacity: opacity
  36235. },
  36236. itemStyleModel.getBarItemStyle()
  36237. ));
  36238. var cursorStyle = itemModel.getShallow('cursor');
  36239. cursorStyle && el.attr('cursor', cursorStyle);
  36240. var labelPositionOutside = isHorizontal
  36241. ? (layout.height > 0 ? 'bottom' : 'top')
  36242. : (layout.width > 0 ? 'left' : 'right');
  36243. if (!isPolar) {
  36244. setLabel(
  36245. el.style, hoverStyle, itemModel, color,
  36246. seriesModel, dataIndex, labelPositionOutside
  36247. );
  36248. }
  36249. setHoverStyle(el, hoverStyle);
  36250. }
  36251. // In case width or height are too small.
  36252. function getLineWidth(itemModel, rawLayout) {
  36253. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36254. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  36255. }
  36256. var LargePath = Path.extend({
  36257. type: 'largeBar',
  36258. shape: {points: []},
  36259. buildPath: function (ctx, shape) {
  36260. // Drawing lines is more efficient than drawing
  36261. // a whole line or drawing rects.
  36262. var points = shape.points;
  36263. var startPoint = this.__startPoint;
  36264. var valueIdx = this.__valueIdx;
  36265. for (var i = 0; i < points.length; i += 2) {
  36266. startPoint[this.__valueIdx] = points[i + valueIdx];
  36267. ctx.moveTo(startPoint[0], startPoint[1]);
  36268. ctx.lineTo(points[i], points[i + 1]);
  36269. }
  36270. }
  36271. });
  36272. function createLarge(seriesModel, group, incremental) {
  36273. // TODO support polar
  36274. var data = seriesModel.getData();
  36275. var startPoint = [];
  36276. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36277. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  36278. var el = new LargePath({
  36279. shape: {points: data.getLayout('largePoints')},
  36280. incremental: !!incremental,
  36281. __startPoint: startPoint,
  36282. __valueIdx: valueIdx
  36283. });
  36284. group.add(el);
  36285. setLargeStyle(el, seriesModel, data);
  36286. }
  36287. function setLargeStyle(el, seriesModel, data) {
  36288. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36289. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36290. el.useStyle(itemStyle);
  36291. el.style.fill = null;
  36292. el.style.stroke = borderColor;
  36293. el.style.lineWidth = data.getLayout('barWidth');
  36294. }
  36295. /*
  36296. * Licensed to the Apache Software Foundation (ASF) under one
  36297. * or more contributor license agreements. See the NOTICE file
  36298. * distributed with this work for additional information
  36299. * regarding copyright ownership. The ASF licenses this file
  36300. * to you under the Apache License, Version 2.0 (the
  36301. * "License"); you may not use this file except in compliance
  36302. * with the License. You may obtain a copy of the License at
  36303. *
  36304. * http://www.apache.org/licenses/LICENSE-2.0
  36305. *
  36306. * Unless required by applicable law or agreed to in writing,
  36307. * software distributed under the License is distributed on an
  36308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36309. * KIND, either express or implied. See the License for the
  36310. * specific language governing permissions and limitations
  36311. * under the License.
  36312. */
  36313. // In case developer forget to include grid component
  36314. registerLayout(curry(layout, 'bar'));
  36315. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  36316. registerLayout(largeLayout);
  36317. registerVisual({
  36318. seriesType: 'bar',
  36319. reset: function (seriesModel) {
  36320. // Visual coding for legend
  36321. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  36322. }
  36323. });
  36324. /*
  36325. * Licensed to the Apache Software Foundation (ASF) under one
  36326. * or more contributor license agreements. See the NOTICE file
  36327. * distributed with this work for additional information
  36328. * regarding copyright ownership. The ASF licenses this file
  36329. * to you under the Apache License, Version 2.0 (the
  36330. * "License"); you may not use this file except in compliance
  36331. * with the License. You may obtain a copy of the License at
  36332. *
  36333. * http://www.apache.org/licenses/LICENSE-2.0
  36334. *
  36335. * Unless required by applicable law or agreed to in writing,
  36336. * software distributed under the License is distributed on an
  36337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36338. * KIND, either express or implied. See the License for the
  36339. * specific language governing permissions and limitations
  36340. * under the License.
  36341. */
  36342. /**
  36343. * [Usage]:
  36344. * (1)
  36345. * createListSimply(seriesModel, ['value']);
  36346. * (2)
  36347. * createListSimply(seriesModel, {
  36348. * coordDimensions: ['value'],
  36349. * dimensionsCount: 5
  36350. * });
  36351. *
  36352. * @param {module:echarts/model/Series} seriesModel
  36353. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  36354. * The options in opt, see `echarts/data/helper/createDimensions`
  36355. * @param {Array.<string>} [nameList]
  36356. * @return {module:echarts/data/List}
  36357. */
  36358. var createListSimply = function (seriesModel, opt, nameList) {
  36359. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  36360. var source = seriesModel.getSource();
  36361. var dimensionsInfo = createDimensions(source, opt);
  36362. var list = new List(dimensionsInfo, seriesModel);
  36363. list.initData(source, nameList);
  36364. return list;
  36365. };
  36366. /*
  36367. * Licensed to the Apache Software Foundation (ASF) under one
  36368. * or more contributor license agreements. See the NOTICE file
  36369. * distributed with this work for additional information
  36370. * regarding copyright ownership. The ASF licenses this file
  36371. * to you under the Apache License, Version 2.0 (the
  36372. * "License"); you may not use this file except in compliance
  36373. * with the License. You may obtain a copy of the License at
  36374. *
  36375. * http://www.apache.org/licenses/LICENSE-2.0
  36376. *
  36377. * Unless required by applicable law or agreed to in writing,
  36378. * software distributed under the License is distributed on an
  36379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36380. * KIND, either express or implied. See the License for the
  36381. * specific language governing permissions and limitations
  36382. * under the License.
  36383. */
  36384. /**
  36385. * Data selectable mixin for chart series.
  36386. * To eanble data select, option of series must have `selectedMode`.
  36387. * And each data item will use `selected` to toggle itself selected status
  36388. */
  36389. var selectableMixin = {
  36390. /**
  36391. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36392. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36393. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36394. */
  36395. updateSelectedMap: function (targetList) {
  36396. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36397. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36398. targetMap.set(target.name, target);
  36399. return targetMap;
  36400. }, createHashMap());
  36401. },
  36402. /**
  36403. * Either name or id should be passed as input here.
  36404. * If both of them are defined, id is used.
  36405. *
  36406. * @param {string|undefined} name name of data
  36407. * @param {number|undefined} id dataIndex of data
  36408. */
  36409. // PENGING If selectedMode is null ?
  36410. select: function (name, id) {
  36411. var target = id != null
  36412. ? this._targetList[id]
  36413. : this._selectTargetMap.get(name);
  36414. var selectedMode = this.get('selectedMode');
  36415. if (selectedMode === 'single') {
  36416. this._selectTargetMap.each(function (target) {
  36417. target.selected = false;
  36418. });
  36419. }
  36420. target && (target.selected = true);
  36421. },
  36422. /**
  36423. * Either name or id should be passed as input here.
  36424. * If both of them are defined, id is used.
  36425. *
  36426. * @param {string|undefined} name name of data
  36427. * @param {number|undefined} id dataIndex of data
  36428. */
  36429. unSelect: function (name, id) {
  36430. var target = id != null
  36431. ? this._targetList[id]
  36432. : this._selectTargetMap.get(name);
  36433. // var selectedMode = this.get('selectedMode');
  36434. // selectedMode !== 'single' && target && (target.selected = false);
  36435. target && (target.selected = false);
  36436. },
  36437. /**
  36438. * Either name or id should be passed as input here.
  36439. * If both of them are defined, id is used.
  36440. *
  36441. * @param {string|undefined} name name of data
  36442. * @param {number|undefined} id dataIndex of data
  36443. */
  36444. toggleSelected: function (name, id) {
  36445. var target = id != null
  36446. ? this._targetList[id]
  36447. : this._selectTargetMap.get(name);
  36448. if (target != null) {
  36449. this[target.selected ? 'unSelect' : 'select'](name, id);
  36450. return target.selected;
  36451. }
  36452. },
  36453. /**
  36454. * Either name or id should be passed as input here.
  36455. * If both of them are defined, id is used.
  36456. *
  36457. * @param {string|undefined} name name of data
  36458. * @param {number|undefined} id dataIndex of data
  36459. */
  36460. isSelected: function (name, id) {
  36461. var target = id != null
  36462. ? this._targetList[id]
  36463. : this._selectTargetMap.get(name);
  36464. return target && target.selected;
  36465. }
  36466. };
  36467. /*
  36468. * Licensed to the Apache Software Foundation (ASF) under one
  36469. * or more contributor license agreements. See the NOTICE file
  36470. * distributed with this work for additional information
  36471. * regarding copyright ownership. The ASF licenses this file
  36472. * to you under the Apache License, Version 2.0 (the
  36473. * "License"); you may not use this file except in compliance
  36474. * with the License. You may obtain a copy of the License at
  36475. *
  36476. * http://www.apache.org/licenses/LICENSE-2.0
  36477. *
  36478. * Unless required by applicable law or agreed to in writing,
  36479. * software distributed under the License is distributed on an
  36480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36481. * KIND, either express or implied. See the License for the
  36482. * specific language governing permissions and limitations
  36483. * under the License.
  36484. */
  36485. var PieSeries = extendSeriesModel({
  36486. type: 'series.pie',
  36487. // Overwrite
  36488. init: function (option) {
  36489. PieSeries.superApply(this, 'init', arguments);
  36490. // Enable legend selection for each data item
  36491. // Use a function instead of direct access because data reference may changed
  36492. this.legendDataProvider = function () {
  36493. return this.getRawData();
  36494. };
  36495. this.updateSelectedMap(this._createSelectableList());
  36496. this._defaultLabelLine(option);
  36497. },
  36498. // Overwrite
  36499. mergeOption: function (newOption) {
  36500. PieSeries.superCall(this, 'mergeOption', newOption);
  36501. this.updateSelectedMap(this._createSelectableList());
  36502. },
  36503. getInitialData: function (option, ecModel) {
  36504. return createListSimply(this, ['value']);
  36505. },
  36506. _createSelectableList: function () {
  36507. var data = this.getRawData();
  36508. var valueDim = data.mapDimension('value');
  36509. var targetList = [];
  36510. for (var i = 0, len = data.count(); i < len; i++) {
  36511. targetList.push({
  36512. name: data.getName(i),
  36513. value: data.get(valueDim, i),
  36514. selected: retrieveRawAttr(data, i, 'selected')
  36515. });
  36516. }
  36517. return targetList;
  36518. },
  36519. // Overwrite
  36520. getDataParams: function (dataIndex) {
  36521. var data = this.getData();
  36522. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  36523. // FIXME toFixed?
  36524. var valueList = [];
  36525. data.each(data.mapDimension('value'), function (value) {
  36526. valueList.push(value);
  36527. });
  36528. params.percent = getPercentWithPrecision(
  36529. valueList,
  36530. dataIndex,
  36531. data.hostModel.get('percentPrecision')
  36532. );
  36533. params.$vars.push('percent');
  36534. return params;
  36535. },
  36536. _defaultLabelLine: function (option) {
  36537. // Extend labelLine emphasis
  36538. defaultEmphasis(option, 'labelLine', ['show']);
  36539. var labelLineNormalOpt = option.labelLine;
  36540. var labelLineEmphasisOpt = option.emphasis.labelLine;
  36541. // Not show label line if `label.normal.show = false`
  36542. labelLineNormalOpt.show = labelLineNormalOpt.show
  36543. && option.label.show;
  36544. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  36545. && option.emphasis.label.show;
  36546. },
  36547. defaultOption: {
  36548. zlevel: 0,
  36549. z: 2,
  36550. legendHoverLink: true,
  36551. hoverAnimation: true,
  36552. // 默认全局居中
  36553. center: ['50%', '50%'],
  36554. radius: [0, '75%'],
  36555. // 默认顺时针
  36556. clockwise: true,
  36557. startAngle: 90,
  36558. // 最小角度改为0
  36559. minAngle: 0,
  36560. // 选中时扇区偏移量
  36561. selectedOffset: 10,
  36562. // 高亮扇区偏移量
  36563. hoverOffset: 10,
  36564. // If use strategy to avoid label overlapping
  36565. avoidLabelOverlap: true,
  36566. // 选择模式,默认关闭,可选single,multiple
  36567. // selectedMode: false,
  36568. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  36569. // roseType: null,
  36570. percentPrecision: 2,
  36571. // If still show when all data zero.
  36572. stillShowZeroSum: true,
  36573. // cursor: null,
  36574. label: {
  36575. // If rotate around circle
  36576. rotate: false,
  36577. show: true,
  36578. // 'outer', 'inside', 'center'
  36579. position: 'outer'
  36580. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36581. // 默认使用全局文本样式,详见TEXTSTYLE
  36582. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  36583. },
  36584. // Enabled when label.normal.position is 'outer'
  36585. labelLine: {
  36586. show: true,
  36587. // 引导线两段中的第一段长度
  36588. length: 15,
  36589. // 引导线两段中的第二段长度
  36590. length2: 15,
  36591. smooth: false,
  36592. lineStyle: {
  36593. // color: 各异,
  36594. width: 1,
  36595. type: 'solid'
  36596. }
  36597. },
  36598. itemStyle: {
  36599. borderWidth: 1
  36600. },
  36601. // Animation type canbe expansion, scale
  36602. animationType: 'expansion',
  36603. animationEasing: 'cubicOut'
  36604. }
  36605. });
  36606. mixin(PieSeries, selectableMixin);
  36607. /*
  36608. * Licensed to the Apache Software Foundation (ASF) under one
  36609. * or more contributor license agreements. See the NOTICE file
  36610. * distributed with this work for additional information
  36611. * regarding copyright ownership. The ASF licenses this file
  36612. * to you under the Apache License, Version 2.0 (the
  36613. * "License"); you may not use this file except in compliance
  36614. * with the License. You may obtain a copy of the License at
  36615. *
  36616. * http://www.apache.org/licenses/LICENSE-2.0
  36617. *
  36618. * Unless required by applicable law or agreed to in writing,
  36619. * software distributed under the License is distributed on an
  36620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36621. * KIND, either express or implied. See the License for the
  36622. * specific language governing permissions and limitations
  36623. * under the License.
  36624. */
  36625. /**
  36626. * @param {module:echarts/model/Series} seriesModel
  36627. * @param {boolean} hasAnimation
  36628. * @inner
  36629. */
  36630. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  36631. var data = seriesModel.getData();
  36632. var dataIndex = this.dataIndex;
  36633. var name = data.getName(dataIndex);
  36634. var selectedOffset = seriesModel.get('selectedOffset');
  36635. api.dispatchAction({
  36636. type: 'pieToggleSelect',
  36637. from: uid,
  36638. name: name,
  36639. seriesId: seriesModel.id
  36640. });
  36641. data.each(function (idx) {
  36642. toggleItemSelected(
  36643. data.getItemGraphicEl(idx),
  36644. data.getItemLayout(idx),
  36645. seriesModel.isSelected(data.getName(idx)),
  36646. selectedOffset,
  36647. hasAnimation
  36648. );
  36649. });
  36650. }
  36651. /**
  36652. * @param {module:zrender/graphic/Sector} el
  36653. * @param {Object} layout
  36654. * @param {boolean} isSelected
  36655. * @param {number} selectedOffset
  36656. * @param {boolean} hasAnimation
  36657. * @inner
  36658. */
  36659. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  36660. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36661. var dx = Math.cos(midAngle);
  36662. var dy = Math.sin(midAngle);
  36663. var offset = isSelected ? selectedOffset : 0;
  36664. var position = [dx * offset, dy * offset];
  36665. hasAnimation
  36666. // animateTo will stop revious animation like update transition
  36667. ? el.animate()
  36668. .when(200, {
  36669. position: position
  36670. })
  36671. .start('bounceOut')
  36672. : el.attr('position', position);
  36673. }
  36674. /**
  36675. * Piece of pie including Sector, Label, LabelLine
  36676. * @constructor
  36677. * @extends {module:zrender/graphic/Group}
  36678. */
  36679. function PiePiece(data, idx) {
  36680. Group.call(this);
  36681. var sector = new Sector({
  36682. z2: 2
  36683. });
  36684. var polyline = new Polyline();
  36685. var text = new Text();
  36686. this.add(sector);
  36687. this.add(polyline);
  36688. this.add(text);
  36689. this.updateData(data, idx, true);
  36690. // Hover to change label and labelLine
  36691. function onEmphasis() {
  36692. polyline.ignore = polyline.hoverIgnore;
  36693. text.ignore = text.hoverIgnore;
  36694. }
  36695. function onNormal() {
  36696. polyline.ignore = polyline.normalIgnore;
  36697. text.ignore = text.normalIgnore;
  36698. }
  36699. this.on('emphasis', onEmphasis)
  36700. .on('normal', onNormal)
  36701. .on('mouseover', onEmphasis)
  36702. .on('mouseout', onNormal);
  36703. }
  36704. var piePieceProto = PiePiece.prototype;
  36705. piePieceProto.updateData = function (data, idx, firstCreate) {
  36706. var sector = this.childAt(0);
  36707. var seriesModel = data.hostModel;
  36708. var itemModel = data.getItemModel(idx);
  36709. var layout = data.getItemLayout(idx);
  36710. var sectorShape = extend({}, layout);
  36711. sectorShape.label = null;
  36712. if (firstCreate) {
  36713. sector.setShape(sectorShape);
  36714. var animationType = seriesModel.getShallow('animationType');
  36715. if (animationType === 'scale') {
  36716. sector.shape.r = layout.r0;
  36717. initProps(sector, {
  36718. shape: {
  36719. r: layout.r
  36720. }
  36721. }, seriesModel, idx);
  36722. }
  36723. // Expansion
  36724. else {
  36725. sector.shape.endAngle = layout.startAngle;
  36726. updateProps(sector, {
  36727. shape: {
  36728. endAngle: layout.endAngle
  36729. }
  36730. }, seriesModel, idx);
  36731. }
  36732. }
  36733. else {
  36734. updateProps(sector, {
  36735. shape: sectorShape
  36736. }, seriesModel, idx);
  36737. }
  36738. // Update common style
  36739. var visualColor = data.getItemVisual(idx, 'color');
  36740. sector.useStyle(
  36741. defaults(
  36742. {
  36743. lineJoin: 'bevel',
  36744. fill: visualColor
  36745. },
  36746. itemModel.getModel('itemStyle').getItemStyle()
  36747. )
  36748. );
  36749. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36750. var cursorStyle = itemModel.getShallow('cursor');
  36751. cursorStyle && sector.attr('cursor', cursorStyle);
  36752. // Toggle selected
  36753. toggleItemSelected(
  36754. this,
  36755. data.getItemLayout(idx),
  36756. seriesModel.isSelected(null, idx),
  36757. seriesModel.get('selectedOffset'),
  36758. seriesModel.get('animation')
  36759. );
  36760. function onEmphasis() {
  36761. // Sector may has animation of updating data. Force to move to the last frame
  36762. // Or it may stopped on the wrong shape
  36763. sector.stopAnimation(true);
  36764. sector.animateTo({
  36765. shape: {
  36766. r: layout.r + seriesModel.get('hoverOffset')
  36767. }
  36768. }, 300, 'elasticOut');
  36769. }
  36770. function onNormal() {
  36771. sector.stopAnimation(true);
  36772. sector.animateTo({
  36773. shape: {
  36774. r: layout.r
  36775. }
  36776. }, 300, 'elasticOut');
  36777. }
  36778. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  36779. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  36780. sector
  36781. .on('mouseover', onEmphasis)
  36782. .on('mouseout', onNormal)
  36783. .on('emphasis', onEmphasis)
  36784. .on('normal', onNormal);
  36785. }
  36786. this._updateLabel(data, idx);
  36787. setHoverStyle(this);
  36788. };
  36789. piePieceProto._updateLabel = function (data, idx) {
  36790. var labelLine = this.childAt(1);
  36791. var labelText = this.childAt(2);
  36792. var seriesModel = data.hostModel;
  36793. var itemModel = data.getItemModel(idx);
  36794. var layout = data.getItemLayout(idx);
  36795. var labelLayout = layout.label;
  36796. var visualColor = data.getItemVisual(idx, 'color');
  36797. updateProps(labelLine, {
  36798. shape: {
  36799. points: labelLayout.linePoints || [
  36800. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  36801. ]
  36802. }
  36803. }, seriesModel, idx);
  36804. updateProps(labelText, {
  36805. style: {
  36806. x: labelLayout.x,
  36807. y: labelLayout.y
  36808. }
  36809. }, seriesModel, idx);
  36810. labelText.attr({
  36811. rotation: labelLayout.rotation,
  36812. origin: [labelLayout.x, labelLayout.y],
  36813. z2: 10
  36814. });
  36815. var labelModel = itemModel.getModel('label');
  36816. var labelHoverModel = itemModel.getModel('emphasis.label');
  36817. var labelLineModel = itemModel.getModel('labelLine');
  36818. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  36819. var visualColor = data.getItemVisual(idx, 'color');
  36820. setLabelStyle(
  36821. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  36822. {
  36823. labelFetcher: data.hostModel,
  36824. labelDataIndex: idx,
  36825. defaultText: data.getName(idx),
  36826. autoColor: visualColor,
  36827. useInsideStyle: !!labelLayout.inside
  36828. },
  36829. {
  36830. textAlign: labelLayout.textAlign,
  36831. textVerticalAlign: labelLayout.verticalAlign,
  36832. opacity: data.getItemVisual(idx, 'opacity')
  36833. }
  36834. );
  36835. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  36836. labelText.hoverIgnore = !labelHoverModel.get('show');
  36837. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  36838. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  36839. // Default use item visual color
  36840. labelLine.setStyle({
  36841. stroke: visualColor,
  36842. opacity: data.getItemVisual(idx, 'opacity')
  36843. });
  36844. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  36845. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  36846. var smooth = labelLineModel.get('smooth');
  36847. if (smooth && smooth === true) {
  36848. smooth = 0.4;
  36849. }
  36850. labelLine.setShape({
  36851. smooth: smooth
  36852. });
  36853. };
  36854. inherits(PiePiece, Group);
  36855. // Pie view
  36856. var PieView = Chart.extend({
  36857. type: 'pie',
  36858. init: function () {
  36859. var sectorGroup = new Group();
  36860. this._sectorGroup = sectorGroup;
  36861. },
  36862. render: function (seriesModel, ecModel, api, payload) {
  36863. if (payload && (payload.from === this.uid)) {
  36864. return;
  36865. }
  36866. var data = seriesModel.getData();
  36867. var oldData = this._data;
  36868. var group = this.group;
  36869. var hasAnimation = ecModel.get('animation');
  36870. var isFirstRender = !oldData;
  36871. var animationType = seriesModel.get('animationType');
  36872. var onSectorClick = curry(
  36873. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  36874. );
  36875. var selectedMode = seriesModel.get('selectedMode');
  36876. data.diff(oldData)
  36877. .add(function (idx) {
  36878. var piePiece = new PiePiece(data, idx);
  36879. // Default expansion animation
  36880. if (isFirstRender && animationType !== 'scale') {
  36881. piePiece.eachChild(function (child) {
  36882. child.stopAnimation(true);
  36883. });
  36884. }
  36885. selectedMode && piePiece.on('click', onSectorClick);
  36886. data.setItemGraphicEl(idx, piePiece);
  36887. group.add(piePiece);
  36888. })
  36889. .update(function (newIdx, oldIdx) {
  36890. var piePiece = oldData.getItemGraphicEl(oldIdx);
  36891. piePiece.updateData(data, newIdx);
  36892. piePiece.off('click');
  36893. selectedMode && piePiece.on('click', onSectorClick);
  36894. group.add(piePiece);
  36895. data.setItemGraphicEl(newIdx, piePiece);
  36896. })
  36897. .remove(function (idx) {
  36898. var piePiece = oldData.getItemGraphicEl(idx);
  36899. group.remove(piePiece);
  36900. })
  36901. .execute();
  36902. if (
  36903. hasAnimation && isFirstRender && data.count() > 0
  36904. // Default expansion animation
  36905. && animationType !== 'scale'
  36906. ) {
  36907. var shape = data.getItemLayout(0);
  36908. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  36909. var removeClipPath = bind(group.removeClipPath, group);
  36910. group.setClipPath(this._createClipPath(
  36911. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  36912. ));
  36913. }
  36914. else {
  36915. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  36916. group.removeClipPath();
  36917. }
  36918. this._data = data;
  36919. },
  36920. dispose: function () {},
  36921. _createClipPath: function (
  36922. cx, cy, r, startAngle, clockwise, cb, seriesModel
  36923. ) {
  36924. var clipPath = new Sector({
  36925. shape: {
  36926. cx: cx,
  36927. cy: cy,
  36928. r0: 0,
  36929. r: r,
  36930. startAngle: startAngle,
  36931. endAngle: startAngle,
  36932. clockwise: clockwise
  36933. }
  36934. });
  36935. initProps(clipPath, {
  36936. shape: {
  36937. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  36938. }
  36939. }, seriesModel, cb);
  36940. return clipPath;
  36941. },
  36942. /**
  36943. * @implement
  36944. */
  36945. containPoint: function (point, seriesModel) {
  36946. var data = seriesModel.getData();
  36947. var itemLayout = data.getItemLayout(0);
  36948. if (itemLayout) {
  36949. var dx = point[0] - itemLayout.cx;
  36950. var dy = point[1] - itemLayout.cy;
  36951. var radius = Math.sqrt(dx * dx + dy * dy);
  36952. return radius <= itemLayout.r && radius >= itemLayout.r0;
  36953. }
  36954. }
  36955. });
  36956. /*
  36957. * Licensed to the Apache Software Foundation (ASF) under one
  36958. * or more contributor license agreements. See the NOTICE file
  36959. * distributed with this work for additional information
  36960. * regarding copyright ownership. The ASF licenses this file
  36961. * to you under the Apache License, Version 2.0 (the
  36962. * "License"); you may not use this file except in compliance
  36963. * with the License. You may obtain a copy of the License at
  36964. *
  36965. * http://www.apache.org/licenses/LICENSE-2.0
  36966. *
  36967. * Unless required by applicable law or agreed to in writing,
  36968. * software distributed under the License is distributed on an
  36969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36970. * KIND, either express or implied. See the License for the
  36971. * specific language governing permissions and limitations
  36972. * under the License.
  36973. */
  36974. var createDataSelectAction = function (seriesType, actionInfos) {
  36975. each$1(actionInfos, function (actionInfo) {
  36976. actionInfo.update = 'updateView';
  36977. /**
  36978. * @payload
  36979. * @property {string} seriesName
  36980. * @property {string} name
  36981. */
  36982. registerAction(actionInfo, function (payload, ecModel) {
  36983. var selected = {};
  36984. ecModel.eachComponent(
  36985. {mainType: 'series', subType: seriesType, query: payload},
  36986. function (seriesModel) {
  36987. if (seriesModel[actionInfo.method]) {
  36988. seriesModel[actionInfo.method](
  36989. payload.name,
  36990. payload.dataIndex
  36991. );
  36992. }
  36993. var data = seriesModel.getData();
  36994. // Create selected map
  36995. data.each(function (idx) {
  36996. var name = data.getName(idx);
  36997. selected[name] = seriesModel.isSelected(name)
  36998. || false;
  36999. });
  37000. }
  37001. );
  37002. return {
  37003. name: payload.name,
  37004. selected: selected
  37005. };
  37006. });
  37007. });
  37008. };
  37009. /*
  37010. * Licensed to the Apache Software Foundation (ASF) under one
  37011. * or more contributor license agreements. See the NOTICE file
  37012. * distributed with this work for additional information
  37013. * regarding copyright ownership. The ASF licenses this file
  37014. * to you under the Apache License, Version 2.0 (the
  37015. * "License"); you may not use this file except in compliance
  37016. * with the License. You may obtain a copy of the License at
  37017. *
  37018. * http://www.apache.org/licenses/LICENSE-2.0
  37019. *
  37020. * Unless required by applicable law or agreed to in writing,
  37021. * software distributed under the License is distributed on an
  37022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37023. * KIND, either express or implied. See the License for the
  37024. * specific language governing permissions and limitations
  37025. * under the License.
  37026. */
  37027. // Pick color from palette for each data item.
  37028. // Applicable for charts that require applying color palette
  37029. // in data level (like pie, funnel, chord).
  37030. var dataColor = function (seriesType) {
  37031. return {
  37032. getTargetSeries: function (ecModel) {
  37033. // Pie and funnel may use diferrent scope
  37034. var paletteScope = {};
  37035. var seiresModelMap = createHashMap();
  37036. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37037. seriesModel.__paletteScope = paletteScope;
  37038. seiresModelMap.set(seriesModel.uid, seriesModel);
  37039. });
  37040. return seiresModelMap;
  37041. },
  37042. reset: function (seriesModel, ecModel) {
  37043. var dataAll = seriesModel.getRawData();
  37044. var idxMap = {};
  37045. var data = seriesModel.getData();
  37046. data.each(function (idx) {
  37047. var rawIdx = data.getRawIndex(idx);
  37048. idxMap[rawIdx] = idx;
  37049. });
  37050. dataAll.each(function (rawIdx) {
  37051. var filteredIdx = idxMap[rawIdx];
  37052. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37053. var singleDataColor = filteredIdx != null
  37054. && data.getItemVisual(filteredIdx, 'color', true);
  37055. if (!singleDataColor) {
  37056. // FIXME Performance
  37057. var itemModel = dataAll.getItemModel(rawIdx);
  37058. var color = itemModel.get('itemStyle.color')
  37059. || seriesModel.getColorFromPalette(
  37060. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37061. dataAll.count()
  37062. );
  37063. // Legend may use the visual info in data before processed
  37064. dataAll.setItemVisual(rawIdx, 'color', color);
  37065. // Data is not filtered
  37066. if (filteredIdx != null) {
  37067. data.setItemVisual(filteredIdx, 'color', color);
  37068. }
  37069. }
  37070. else {
  37071. // Set data all color for legend
  37072. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  37073. }
  37074. });
  37075. }
  37076. };
  37077. };
  37078. /*
  37079. * Licensed to the Apache Software Foundation (ASF) under one
  37080. * or more contributor license agreements. See the NOTICE file
  37081. * distributed with this work for additional information
  37082. * regarding copyright ownership. The ASF licenses this file
  37083. * to you under the Apache License, Version 2.0 (the
  37084. * "License"); you may not use this file except in compliance
  37085. * with the License. You may obtain a copy of the License at
  37086. *
  37087. * http://www.apache.org/licenses/LICENSE-2.0
  37088. *
  37089. * Unless required by applicable law or agreed to in writing,
  37090. * software distributed under the License is distributed on an
  37091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37092. * KIND, either express or implied. See the License for the
  37093. * specific language governing permissions and limitations
  37094. * under the License.
  37095. */
  37096. // FIXME emphasis label position is not same with normal label position
  37097. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  37098. list.sort(function (a, b) {
  37099. return a.y - b.y;
  37100. });
  37101. function shiftDown(start, end, delta, dir) {
  37102. for (var j = start; j < end; j++) {
  37103. list[j].y += delta;
  37104. if (j > start
  37105. && j + 1 < end
  37106. && list[j + 1].y > list[j].y + list[j].height
  37107. ) {
  37108. shiftUp(j, delta / 2);
  37109. return;
  37110. }
  37111. }
  37112. shiftUp(end - 1, delta / 2);
  37113. }
  37114. function shiftUp(end, delta) {
  37115. for (var j = end; j >= 0; j--) {
  37116. list[j].y -= delta;
  37117. if (j > 0
  37118. && list[j].y > list[j - 1].y + list[j - 1].height
  37119. ) {
  37120. break;
  37121. }
  37122. }
  37123. }
  37124. function changeX(list, isDownList, cx, cy, r, dir) {
  37125. var lastDeltaX = dir > 0
  37126. ? isDownList // right-side
  37127. ? Number.MAX_VALUE // down
  37128. : 0 // up
  37129. : isDownList // left-side
  37130. ? Number.MAX_VALUE // down
  37131. : 0; // up
  37132. for (var i = 0, l = list.length; i < l; i++) {
  37133. var deltaY = Math.abs(list[i].y - cy);
  37134. var length = list[i].len;
  37135. var length2 = list[i].len2;
  37136. var deltaX = (deltaY < r + length)
  37137. ? Math.sqrt(
  37138. (r + length + length2) * (r + length + length2)
  37139. - deltaY * deltaY
  37140. )
  37141. : Math.abs(list[i].x - cx);
  37142. if (isDownList && deltaX >= lastDeltaX) {
  37143. // right-down, left-down
  37144. deltaX = lastDeltaX - 10;
  37145. }
  37146. if (!isDownList && deltaX <= lastDeltaX) {
  37147. // right-up, left-up
  37148. deltaX = lastDeltaX + 10;
  37149. }
  37150. list[i].x = cx + deltaX * dir;
  37151. lastDeltaX = deltaX;
  37152. }
  37153. }
  37154. var lastY = 0;
  37155. var delta;
  37156. var len = list.length;
  37157. var upList = [];
  37158. var downList = [];
  37159. for (var i = 0; i < len; i++) {
  37160. delta = list[i].y - lastY;
  37161. if (delta < 0) {
  37162. shiftDown(i, len, -delta, dir);
  37163. }
  37164. lastY = list[i].y + list[i].height;
  37165. }
  37166. if (viewHeight - lastY < 0) {
  37167. shiftUp(len - 1, lastY - viewHeight);
  37168. }
  37169. for (var i = 0; i < len; i++) {
  37170. if (list[i].y >= cy) {
  37171. downList.push(list[i]);
  37172. }
  37173. else {
  37174. upList.push(list[i]);
  37175. }
  37176. }
  37177. changeX(upList, false, cx, cy, r, dir);
  37178. changeX(downList, true, cx, cy, r, dir);
  37179. }
  37180. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  37181. var leftList = [];
  37182. var rightList = [];
  37183. for (var i = 0; i < labelLayoutList.length; i++) {
  37184. if (isPositionCenter(labelLayoutList[i])) {
  37185. continue;
  37186. }
  37187. if (labelLayoutList[i].x < cx) {
  37188. leftList.push(labelLayoutList[i]);
  37189. }
  37190. else {
  37191. rightList.push(labelLayoutList[i]);
  37192. }
  37193. }
  37194. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  37195. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  37196. for (var i = 0; i < labelLayoutList.length; i++) {
  37197. if (isPositionCenter(labelLayoutList[i])) {
  37198. continue;
  37199. }
  37200. var linePoints = labelLayoutList[i].linePoints;
  37201. if (linePoints) {
  37202. var dist = linePoints[1][0] - linePoints[2][0];
  37203. if (labelLayoutList[i].x < cx) {
  37204. linePoints[2][0] = labelLayoutList[i].x + 3;
  37205. }
  37206. else {
  37207. linePoints[2][0] = labelLayoutList[i].x - 3;
  37208. }
  37209. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  37210. linePoints[1][0] = linePoints[2][0] + dist;
  37211. }
  37212. }
  37213. }
  37214. function isPositionCenter(layout) {
  37215. // Not change x for center label
  37216. return layout.position === 'center';
  37217. }
  37218. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  37219. var data = seriesModel.getData();
  37220. var labelLayoutList = [];
  37221. var cx;
  37222. var cy;
  37223. var hasLabelRotate = false;
  37224. data.each(function (idx) {
  37225. var layout = data.getItemLayout(idx);
  37226. var itemModel = data.getItemModel(idx);
  37227. var labelModel = itemModel.getModel('label');
  37228. // Use position in normal or emphasis
  37229. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  37230. var labelLineModel = itemModel.getModel('labelLine');
  37231. var labelLineLen = labelLineModel.get('length');
  37232. var labelLineLen2 = labelLineModel.get('length2');
  37233. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37234. var dx = Math.cos(midAngle);
  37235. var dy = Math.sin(midAngle);
  37236. var textX;
  37237. var textY;
  37238. var linePoints;
  37239. var textAlign;
  37240. cx = layout.cx;
  37241. cy = layout.cy;
  37242. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  37243. if (labelPosition === 'center') {
  37244. textX = layout.cx;
  37245. textY = layout.cy;
  37246. textAlign = 'center';
  37247. }
  37248. else {
  37249. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  37250. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  37251. textX = x1 + dx * 3;
  37252. textY = y1 + dy * 3;
  37253. if (!isLabelInside) {
  37254. // For roseType
  37255. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  37256. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  37257. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  37258. var y3 = y2;
  37259. textX = x3 + (dx < 0 ? -5 : 5);
  37260. textY = y3;
  37261. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  37262. }
  37263. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  37264. }
  37265. var font = labelModel.getFont();
  37266. var labelRotate = labelModel.get('rotate')
  37267. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  37268. var text = seriesModel.getFormattedLabel(idx, 'normal')
  37269. || data.getName(idx);
  37270. var textRect = getBoundingRect(
  37271. text, font, textAlign, 'top'
  37272. );
  37273. hasLabelRotate = !!labelRotate;
  37274. layout.label = {
  37275. x: textX,
  37276. y: textY,
  37277. position: labelPosition,
  37278. height: textRect.height,
  37279. len: labelLineLen,
  37280. len2: labelLineLen2,
  37281. linePoints: linePoints,
  37282. textAlign: textAlign,
  37283. verticalAlign: 'middle',
  37284. rotation: labelRotate,
  37285. inside: isLabelInside
  37286. };
  37287. // Not layout the inside label
  37288. if (!isLabelInside) {
  37289. labelLayoutList.push(layout.label);
  37290. }
  37291. });
  37292. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  37293. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  37294. }
  37295. };
  37296. /*
  37297. * Licensed to the Apache Software Foundation (ASF) under one
  37298. * or more contributor license agreements. See the NOTICE file
  37299. * distributed with this work for additional information
  37300. * regarding copyright ownership. The ASF licenses this file
  37301. * to you under the Apache License, Version 2.0 (the
  37302. * "License"); you may not use this file except in compliance
  37303. * with the License. You may obtain a copy of the License at
  37304. *
  37305. * http://www.apache.org/licenses/LICENSE-2.0
  37306. *
  37307. * Unless required by applicable law or agreed to in writing,
  37308. * software distributed under the License is distributed on an
  37309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37310. * KIND, either express or implied. See the License for the
  37311. * specific language governing permissions and limitations
  37312. * under the License.
  37313. */
  37314. var PI2$4 = Math.PI * 2;
  37315. var RADIAN = Math.PI / 180;
  37316. var pieLayout = function (seriesType, ecModel, api, payload) {
  37317. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37318. var data = seriesModel.getData();
  37319. var valueDim = data.mapDimension('value');
  37320. var center = seriesModel.get('center');
  37321. var radius = seriesModel.get('radius');
  37322. if (!isArray(radius)) {
  37323. radius = [0, radius];
  37324. }
  37325. if (!isArray(center)) {
  37326. center = [center, center];
  37327. }
  37328. var width = api.getWidth();
  37329. var height = api.getHeight();
  37330. var size = Math.min(width, height);
  37331. var cx = parsePercent$1(center[0], width);
  37332. var cy = parsePercent$1(center[1], height);
  37333. var r0 = parsePercent$1(radius[0], size / 2);
  37334. var r = parsePercent$1(radius[1], size / 2);
  37335. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37336. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37337. var validDataCount = 0;
  37338. data.each(valueDim, function (value) {
  37339. !isNaN(value) && validDataCount++;
  37340. });
  37341. var sum = data.getSum(valueDim);
  37342. // Sum may be 0
  37343. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37344. var clockwise = seriesModel.get('clockwise');
  37345. var roseType = seriesModel.get('roseType');
  37346. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  37347. // [0...max]
  37348. var extent = data.getDataExtent(valueDim);
  37349. extent[0] = 0;
  37350. // In the case some sector angle is smaller than minAngle
  37351. var restAngle = PI2$4;
  37352. var valueSumLargerThanMinAngle = 0;
  37353. var currentAngle = startAngle;
  37354. var dir = clockwise ? 1 : -1;
  37355. data.each(valueDim, function (value, idx) {
  37356. var angle;
  37357. if (isNaN(value)) {
  37358. data.setItemLayout(idx, {
  37359. angle: NaN,
  37360. startAngle: NaN,
  37361. endAngle: NaN,
  37362. clockwise: clockwise,
  37363. cx: cx,
  37364. cy: cy,
  37365. r0: r0,
  37366. r: roseType
  37367. ? NaN
  37368. : r
  37369. });
  37370. return;
  37371. }
  37372. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37373. if (roseType !== 'area') {
  37374. angle = (sum === 0 && stillShowZeroSum)
  37375. ? unitRadian : (value * unitRadian);
  37376. }
  37377. else {
  37378. angle = PI2$4 / validDataCount;
  37379. }
  37380. if (angle < minAngle) {
  37381. angle = minAngle;
  37382. restAngle -= minAngle;
  37383. }
  37384. else {
  37385. valueSumLargerThanMinAngle += value;
  37386. }
  37387. var endAngle = currentAngle + dir * angle;
  37388. data.setItemLayout(idx, {
  37389. angle: angle,
  37390. startAngle: currentAngle,
  37391. endAngle: endAngle,
  37392. clockwise: clockwise,
  37393. cx: cx,
  37394. cy: cy,
  37395. r0: r0,
  37396. r: roseType
  37397. ? linearMap(value, extent, [r0, r])
  37398. : r
  37399. });
  37400. currentAngle = endAngle;
  37401. });
  37402. // Some sector is constrained by minAngle
  37403. // Rest sectors needs recalculate angle
  37404. if (restAngle < PI2$4 && validDataCount) {
  37405. // Average the angle if rest angle is not enough after all angles is
  37406. // Constrained by minAngle
  37407. if (restAngle <= 1e-3) {
  37408. var angle = PI2$4 / validDataCount;
  37409. data.each(valueDim, function (value, idx) {
  37410. if (!isNaN(value)) {
  37411. var layout = data.getItemLayout(idx);
  37412. layout.angle = angle;
  37413. layout.startAngle = startAngle + dir * idx * angle;
  37414. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  37415. }
  37416. });
  37417. }
  37418. else {
  37419. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37420. currentAngle = startAngle;
  37421. data.each(valueDim, function (value, idx) {
  37422. if (!isNaN(value)) {
  37423. var layout = data.getItemLayout(idx);
  37424. var angle = layout.angle === minAngle
  37425. ? minAngle : value * unitRadian;
  37426. layout.startAngle = currentAngle;
  37427. layout.endAngle = currentAngle + dir * angle;
  37428. currentAngle += dir * angle;
  37429. }
  37430. });
  37431. }
  37432. }
  37433. labelLayout(seriesModel, r, width, height);
  37434. });
  37435. };
  37436. /*
  37437. * Licensed to the Apache Software Foundation (ASF) under one
  37438. * or more contributor license agreements. See the NOTICE file
  37439. * distributed with this work for additional information
  37440. * regarding copyright ownership. The ASF licenses this file
  37441. * to you under the Apache License, Version 2.0 (the
  37442. * "License"); you may not use this file except in compliance
  37443. * with the License. You may obtain a copy of the License at
  37444. *
  37445. * http://www.apache.org/licenses/LICENSE-2.0
  37446. *
  37447. * Unless required by applicable law or agreed to in writing,
  37448. * software distributed under the License is distributed on an
  37449. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37450. * KIND, either express or implied. See the License for the
  37451. * specific language governing permissions and limitations
  37452. * under the License.
  37453. */
  37454. var dataFilter = function (seriesType) {
  37455. return {
  37456. seriesType: seriesType,
  37457. reset: function (seriesModel, ecModel) {
  37458. var legendModels = ecModel.findComponents({
  37459. mainType: 'legend'
  37460. });
  37461. if (!legendModels || !legendModels.length) {
  37462. return;
  37463. }
  37464. var data = seriesModel.getData();
  37465. data.filterSelf(function (idx) {
  37466. var name = data.getName(idx);
  37467. // If in any legend component the status is not selected.
  37468. for (var i = 0; i < legendModels.length; i++) {
  37469. if (!legendModels[i].isSelected(name)) {
  37470. return false;
  37471. }
  37472. }
  37473. return true;
  37474. });
  37475. }
  37476. };
  37477. };
  37478. /*
  37479. * Licensed to the Apache Software Foundation (ASF) under one
  37480. * or more contributor license agreements. See the NOTICE file
  37481. * distributed with this work for additional information
  37482. * regarding copyright ownership. The ASF licenses this file
  37483. * to you under the Apache License, Version 2.0 (the
  37484. * "License"); you may not use this file except in compliance
  37485. * with the License. You may obtain a copy of the License at
  37486. *
  37487. * http://www.apache.org/licenses/LICENSE-2.0
  37488. *
  37489. * Unless required by applicable law or agreed to in writing,
  37490. * software distributed under the License is distributed on an
  37491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37492. * KIND, either express or implied. See the License for the
  37493. * specific language governing permissions and limitations
  37494. * under the License.
  37495. */
  37496. createDataSelectAction('pie', [{
  37497. type: 'pieToggleSelect',
  37498. event: 'pieselectchanged',
  37499. method: 'toggleSelected'
  37500. }, {
  37501. type: 'pieSelect',
  37502. event: 'pieselected',
  37503. method: 'select'
  37504. }, {
  37505. type: 'pieUnSelect',
  37506. event: 'pieunselected',
  37507. method: 'unSelect'
  37508. }]);
  37509. registerVisual(dataColor('pie'));
  37510. registerLayout(curry(pieLayout, 'pie'));
  37511. registerProcessor(dataFilter('pie'));
  37512. /*
  37513. * Licensed to the Apache Software Foundation (ASF) under one
  37514. * or more contributor license agreements. See the NOTICE file
  37515. * distributed with this work for additional information
  37516. * regarding copyright ownership. The ASF licenses this file
  37517. * to you under the Apache License, Version 2.0 (the
  37518. * "License"); you may not use this file except in compliance
  37519. * with the License. You may obtain a copy of the License at
  37520. *
  37521. * http://www.apache.org/licenses/LICENSE-2.0
  37522. *
  37523. * Unless required by applicable law or agreed to in writing,
  37524. * software distributed under the License is distributed on an
  37525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37526. * KIND, either express or implied. See the License for the
  37527. * specific language governing permissions and limitations
  37528. * under the License.
  37529. */
  37530. SeriesModel.extend({
  37531. type: 'series.scatter',
  37532. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  37533. getInitialData: function (option, ecModel) {
  37534. return createListFromArray(this.getSource(), this);
  37535. },
  37536. brushSelector: 'point',
  37537. getProgressive: function () {
  37538. var progressive = this.option.progressive;
  37539. if (progressive == null) {
  37540. // PENDING
  37541. return this.option.large ? 5e3 : this.get('progressive');
  37542. }
  37543. return progressive;
  37544. },
  37545. getProgressiveThreshold: function () {
  37546. var progressiveThreshold = this.option.progressiveThreshold;
  37547. if (progressiveThreshold == null) {
  37548. // PENDING
  37549. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  37550. }
  37551. return progressiveThreshold;
  37552. },
  37553. defaultOption: {
  37554. coordinateSystem: 'cartesian2d',
  37555. zlevel: 0,
  37556. z: 2,
  37557. legendHoverLink: true,
  37558. hoverAnimation: true,
  37559. // Cartesian coordinate system
  37560. // xAxisIndex: 0,
  37561. // yAxisIndex: 0,
  37562. // Polar coordinate system
  37563. // polarIndex: 0,
  37564. // Geo coordinate system
  37565. // geoIndex: 0,
  37566. // symbol: null, // 图形类型
  37567. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  37568. // symbolRotate: null, // 图形旋转控制
  37569. large: false,
  37570. // Available when large is true
  37571. largeThreshold: 2000,
  37572. // cursor: null,
  37573. // label: {
  37574. // show: false
  37575. // distance: 5,
  37576. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37577. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  37578. // 'inside'|'left'|'right'|'top'|'bottom'
  37579. // 默认使用全局文本样式,详见TEXTSTYLE
  37580. // },
  37581. itemStyle: {
  37582. opacity: 0.8
  37583. // color: 各异
  37584. }
  37585. // progressive: null
  37586. }
  37587. });
  37588. /*
  37589. * Licensed to the Apache Software Foundation (ASF) under one
  37590. * or more contributor license agreements. See the NOTICE file
  37591. * distributed with this work for additional information
  37592. * regarding copyright ownership. The ASF licenses this file
  37593. * to you under the Apache License, Version 2.0 (the
  37594. * "License"); you may not use this file except in compliance
  37595. * with the License. You may obtain a copy of the License at
  37596. *
  37597. * http://www.apache.org/licenses/LICENSE-2.0
  37598. *
  37599. * Unless required by applicable law or agreed to in writing,
  37600. * software distributed under the License is distributed on an
  37601. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37602. * KIND, either express or implied. See the License for the
  37603. * specific language governing permissions and limitations
  37604. * under the License.
  37605. */
  37606. /* global Float32Array */
  37607. // TODO Batch by color
  37608. var BOOST_SIZE_THRESHOLD = 4;
  37609. var LargeSymbolPath = extendShape({
  37610. shape: {
  37611. points: null
  37612. },
  37613. symbolProxy: null,
  37614. buildPath: function (path, shape) {
  37615. var points = shape.points;
  37616. var size = shape.size;
  37617. var symbolProxy = this.symbolProxy;
  37618. var symbolProxyShape = symbolProxy.shape;
  37619. var ctx = path.getContext ? path.getContext() : path;
  37620. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  37621. // Do draw in afterBrush.
  37622. if (canBoost) {
  37623. return;
  37624. }
  37625. for (var i = 0; i < points.length;) {
  37626. var x = points[i++];
  37627. var y = points[i++];
  37628. if (isNaN(x) || isNaN(y)) {
  37629. continue;
  37630. }
  37631. symbolProxyShape.x = x - size[0] / 2;
  37632. symbolProxyShape.y = y - size[1] / 2;
  37633. symbolProxyShape.width = size[0];
  37634. symbolProxyShape.height = size[1];
  37635. symbolProxy.buildPath(path, symbolProxyShape, true);
  37636. }
  37637. },
  37638. afterBrush: function (ctx) {
  37639. var shape = this.shape;
  37640. var points = shape.points;
  37641. var size = shape.size;
  37642. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  37643. if (!canBoost) {
  37644. return;
  37645. }
  37646. this.setTransform(ctx);
  37647. // PENDING If style or other canvas status changed?
  37648. for (var i = 0; i < points.length;) {
  37649. var x = points[i++];
  37650. var y = points[i++];
  37651. if (isNaN(x) || isNaN(y)) {
  37652. continue;
  37653. }
  37654. // fillRect is faster than building a rect path and draw.
  37655. // And it support light globalCompositeOperation.
  37656. ctx.fillRect(
  37657. x - size[0] / 2, y - size[1] / 2,
  37658. size[0], size[1]
  37659. );
  37660. }
  37661. this.restoreTransform(ctx);
  37662. },
  37663. findDataIndex: function (x, y) {
  37664. // TODO ???
  37665. // Consider transform
  37666. var shape = this.shape;
  37667. var points = shape.points;
  37668. var size = shape.size;
  37669. var w = Math.max(size[0], 4);
  37670. var h = Math.max(size[1], 4);
  37671. // Not consider transform
  37672. // Treat each element as a rect
  37673. // top down traverse
  37674. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  37675. var i = idx * 2;
  37676. var x0 = points[i] - w / 2;
  37677. var y0 = points[i + 1] - h / 2;
  37678. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  37679. return idx;
  37680. }
  37681. }
  37682. return -1;
  37683. }
  37684. });
  37685. function LargeSymbolDraw() {
  37686. this.group = new Group();
  37687. }
  37688. var largeSymbolProto = LargeSymbolDraw.prototype;
  37689. largeSymbolProto.isPersistent = function () {
  37690. return !this._incremental;
  37691. };
  37692. /**
  37693. * Update symbols draw by new data
  37694. * @param {module:echarts/data/List} data
  37695. */
  37696. largeSymbolProto.updateData = function (data) {
  37697. this.group.removeAll();
  37698. var symbolEl = new LargeSymbolPath({
  37699. rectHover: true,
  37700. cursor: 'default'
  37701. });
  37702. symbolEl.setShape({
  37703. points: data.getLayout('symbolPoints')
  37704. });
  37705. this._setCommon(symbolEl, data);
  37706. this.group.add(symbolEl);
  37707. this._incremental = null;
  37708. };
  37709. largeSymbolProto.updateLayout = function (data) {
  37710. if (this._incremental) {
  37711. return;
  37712. }
  37713. var points = data.getLayout('symbolPoints');
  37714. this.group.eachChild(function (child) {
  37715. if (child.startIndex != null) {
  37716. var len = (child.endIndex - child.startIndex) * 2;
  37717. var byteOffset = child.startIndex * 4 * 2;
  37718. points = new Float32Array(points.buffer, byteOffset, len);
  37719. }
  37720. child.setShape('points', points);
  37721. });
  37722. };
  37723. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  37724. this.group.removeAll();
  37725. this._clearIncremental();
  37726. // Only use incremental displayables when data amount is larger than 2 million.
  37727. // PENDING Incremental data?
  37728. if (data.count() > 2e6) {
  37729. if (!this._incremental) {
  37730. this._incremental = new IncrementalDisplayble({
  37731. silent: true
  37732. });
  37733. }
  37734. this.group.add(this._incremental);
  37735. }
  37736. else {
  37737. this._incremental = null;
  37738. }
  37739. };
  37740. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  37741. var symbolEl;
  37742. if (this._incremental) {
  37743. symbolEl = new LargeSymbolPath();
  37744. this._incremental.addDisplayable(symbolEl, true);
  37745. }
  37746. else {
  37747. symbolEl = new LargeSymbolPath({
  37748. rectHover: true,
  37749. cursor: 'default',
  37750. startIndex: taskParams.start,
  37751. endIndex: taskParams.end
  37752. });
  37753. symbolEl.incremental = true;
  37754. this.group.add(symbolEl);
  37755. }
  37756. symbolEl.setShape({
  37757. points: data.getLayout('symbolPoints')
  37758. });
  37759. this._setCommon(symbolEl, data, !!this._incremental);
  37760. };
  37761. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  37762. var hostModel = data.hostModel;
  37763. // TODO
  37764. // if (data.hasItemVisual.symbolSize) {
  37765. // // TODO typed array?
  37766. // symbolEl.setShape('sizes', data.mapArray(
  37767. // function (idx) {
  37768. // var size = data.getItemVisual(idx, 'symbolSize');
  37769. // return (size instanceof Array) ? size : [size, size];
  37770. // }
  37771. // ));
  37772. // }
  37773. // else {
  37774. var size = data.getVisual('symbolSize');
  37775. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  37776. // }
  37777. // Create symbolProxy to build path for each data
  37778. symbolEl.symbolProxy = createSymbol(
  37779. data.getVisual('symbol'), 0, 0, 0, 0
  37780. );
  37781. // Use symbolProxy setColor method
  37782. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  37783. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  37784. symbolEl.useStyle(
  37785. // Draw shadow when doing fillRect is extremely slow.
  37786. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  37787. );
  37788. var visualColor = data.getVisual('color');
  37789. if (visualColor) {
  37790. symbolEl.setColor(visualColor);
  37791. }
  37792. if (!isIncremental) {
  37793. // Enable tooltip
  37794. // PENDING May have performance issue when path is extremely large
  37795. symbolEl.seriesIndex = hostModel.seriesIndex;
  37796. symbolEl.on('mousemove', function (e) {
  37797. symbolEl.dataIndex = null;
  37798. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  37799. if (dataIndex >= 0) {
  37800. // Provide dataIndex for tooltip
  37801. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  37802. }
  37803. });
  37804. }
  37805. };
  37806. largeSymbolProto.remove = function () {
  37807. this._clearIncremental();
  37808. this._incremental = null;
  37809. this.group.removeAll();
  37810. };
  37811. largeSymbolProto._clearIncremental = function () {
  37812. var incremental = this._incremental;
  37813. if (incremental) {
  37814. incremental.clearDisplaybles();
  37815. }
  37816. };
  37817. /*
  37818. * Licensed to the Apache Software Foundation (ASF) under one
  37819. * or more contributor license agreements. See the NOTICE file
  37820. * distributed with this work for additional information
  37821. * regarding copyright ownership. The ASF licenses this file
  37822. * to you under the Apache License, Version 2.0 (the
  37823. * "License"); you may not use this file except in compliance
  37824. * with the License. You may obtain a copy of the License at
  37825. *
  37826. * http://www.apache.org/licenses/LICENSE-2.0
  37827. *
  37828. * Unless required by applicable law or agreed to in writing,
  37829. * software distributed under the License is distributed on an
  37830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37831. * KIND, either express or implied. See the License for the
  37832. * specific language governing permissions and limitations
  37833. * under the License.
  37834. */
  37835. extendChartView({
  37836. type: 'scatter',
  37837. render: function (seriesModel, ecModel, api) {
  37838. var data = seriesModel.getData();
  37839. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37840. symbolDraw.updateData(data);
  37841. this._finished = true;
  37842. },
  37843. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37844. var data = seriesModel.getData();
  37845. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37846. symbolDraw.incrementalPrepareUpdate(data);
  37847. this._finished = false;
  37848. },
  37849. incrementalRender: function (taskParams, seriesModel, ecModel) {
  37850. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  37851. this._finished = taskParams.end === seriesModel.getData().count();
  37852. },
  37853. updateTransform: function (seriesModel, ecModel, api) {
  37854. var data = seriesModel.getData();
  37855. // Must mark group dirty and make sure the incremental layer will be cleared
  37856. // PENDING
  37857. this.group.dirty();
  37858. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  37859. return {
  37860. update: true
  37861. };
  37862. }
  37863. else {
  37864. var res = pointsLayout().reset(seriesModel);
  37865. if (res.progress) {
  37866. res.progress({ start: 0, end: data.count() }, data);
  37867. }
  37868. this._symbolDraw.updateLayout(data);
  37869. }
  37870. },
  37871. _updateSymbolDraw: function (data, seriesModel) {
  37872. var symbolDraw = this._symbolDraw;
  37873. var pipelineContext = seriesModel.pipelineContext;
  37874. var isLargeDraw = pipelineContext.large;
  37875. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  37876. symbolDraw && symbolDraw.remove();
  37877. symbolDraw = this._symbolDraw = isLargeDraw
  37878. ? new LargeSymbolDraw()
  37879. : new SymbolDraw();
  37880. this._isLargeDraw = isLargeDraw;
  37881. this.group.removeAll();
  37882. }
  37883. this.group.add(symbolDraw.group);
  37884. return symbolDraw;
  37885. },
  37886. remove: function (ecModel, api) {
  37887. this._symbolDraw && this._symbolDraw.remove(true);
  37888. this._symbolDraw = null;
  37889. },
  37890. dispose: function () {}
  37891. });
  37892. /*
  37893. * Licensed to the Apache Software Foundation (ASF) under one
  37894. * or more contributor license agreements. See the NOTICE file
  37895. * distributed with this work for additional information
  37896. * regarding copyright ownership. The ASF licenses this file
  37897. * to you under the Apache License, Version 2.0 (the
  37898. * "License"); you may not use this file except in compliance
  37899. * with the License. You may obtain a copy of the License at
  37900. *
  37901. * http://www.apache.org/licenses/LICENSE-2.0
  37902. *
  37903. * Unless required by applicable law or agreed to in writing,
  37904. * software distributed under the License is distributed on an
  37905. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37906. * KIND, either express or implied. See the License for the
  37907. * specific language governing permissions and limitations
  37908. * under the License.
  37909. */
  37910. // import * as zrUtil from 'zrender/src/core/util';
  37911. // In case developer forget to include grid component
  37912. registerVisual(visualSymbol('scatter', 'circle'));
  37913. registerLayout(pointsLayout('scatter'));
  37914. // echarts.registerProcessor(function (ecModel, api) {
  37915. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  37916. // var data = seriesModel.getData();
  37917. // var coordSys = seriesModel.coordinateSystem;
  37918. // if (coordSys.type !== 'geo') {
  37919. // return;
  37920. // }
  37921. // var startPt = coordSys.pointToData([0, 0]);
  37922. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  37923. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  37924. // return data.mapDimension(dim);
  37925. // });
  37926. // var range = {};
  37927. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  37928. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  37929. // data.selectRange(range);
  37930. // });
  37931. // });
  37932. /*
  37933. * Licensed to the Apache Software Foundation (ASF) under one
  37934. * or more contributor license agreements. See the NOTICE file
  37935. * distributed with this work for additional information
  37936. * regarding copyright ownership. The ASF licenses this file
  37937. * to you under the Apache License, Version 2.0 (the
  37938. * "License"); you may not use this file except in compliance
  37939. * with the License. You may obtain a copy of the License at
  37940. *
  37941. * http://www.apache.org/licenses/LICENSE-2.0
  37942. *
  37943. * Unless required by applicable law or agreed to in writing,
  37944. * software distributed under the License is distributed on an
  37945. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37946. * KIND, either express or implied. See the License for the
  37947. * specific language governing permissions and limitations
  37948. * under the License.
  37949. */
  37950. function IndicatorAxis(dim, scale, radiusExtent) {
  37951. Axis.call(this, dim, scale, radiusExtent);
  37952. /**
  37953. * Axis type
  37954. * - 'category'
  37955. * - 'value'
  37956. * - 'time'
  37957. * - 'log'
  37958. * @type {string}
  37959. */
  37960. this.type = 'value';
  37961. this.angle = 0;
  37962. /**
  37963. * Indicator name
  37964. * @type {string}
  37965. */
  37966. this.name = '';
  37967. /**
  37968. * @type {module:echarts/model/Model}
  37969. */
  37970. this.model;
  37971. }
  37972. inherits(IndicatorAxis, Axis);
  37973. /*
  37974. * Licensed to the Apache Software Foundation (ASF) under one
  37975. * or more contributor license agreements. See the NOTICE file
  37976. * distributed with this work for additional information
  37977. * regarding copyright ownership. The ASF licenses this file
  37978. * to you under the Apache License, Version 2.0 (the
  37979. * "License"); you may not use this file except in compliance
  37980. * with the License. You may obtain a copy of the License at
  37981. *
  37982. * http://www.apache.org/licenses/LICENSE-2.0
  37983. *
  37984. * Unless required by applicable law or agreed to in writing,
  37985. * software distributed under the License is distributed on an
  37986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37987. * KIND, either express or implied. See the License for the
  37988. * specific language governing permissions and limitations
  37989. * under the License.
  37990. */
  37991. // TODO clockwise
  37992. function Radar(radarModel, ecModel, api) {
  37993. this._model = radarModel;
  37994. /**
  37995. * Radar dimensions
  37996. * @type {Array.<string>}
  37997. */
  37998. this.dimensions = [];
  37999. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  38000. var dim = 'indicator_' + idx;
  38001. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  38002. indicatorAxis.name = indicatorModel.get('name');
  38003. // Inject model and axis
  38004. indicatorAxis.model = indicatorModel;
  38005. indicatorModel.axis = indicatorAxis;
  38006. this.dimensions.push(dim);
  38007. return indicatorAxis;
  38008. }, this);
  38009. this.resize(radarModel, api);
  38010. /**
  38011. * @type {number}
  38012. * @readOnly
  38013. */
  38014. this.cx;
  38015. /**
  38016. * @type {number}
  38017. * @readOnly
  38018. */
  38019. this.cy;
  38020. /**
  38021. * @type {number}
  38022. * @readOnly
  38023. */
  38024. this.r;
  38025. /**
  38026. * @type {number}
  38027. * @readOnly
  38028. */
  38029. this.r0;
  38030. /**
  38031. * @type {number}
  38032. * @readOnly
  38033. */
  38034. this.startAngle;
  38035. }
  38036. Radar.prototype.getIndicatorAxes = function () {
  38037. return this._indicatorAxes;
  38038. };
  38039. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  38040. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38041. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  38042. };
  38043. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  38044. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38045. var angle = indicatorAxis.angle;
  38046. var x = this.cx + coord * Math.cos(angle);
  38047. var y = this.cy - coord * Math.sin(angle);
  38048. return [x, y];
  38049. };
  38050. Radar.prototype.pointToData = function (pt) {
  38051. var dx = pt[0] - this.cx;
  38052. var dy = pt[1] - this.cy;
  38053. var radius = Math.sqrt(dx * dx + dy * dy);
  38054. dx /= radius;
  38055. dy /= radius;
  38056. var radian = Math.atan2(-dy, dx);
  38057. // Find the closest angle
  38058. // FIXME index can calculated directly
  38059. var minRadianDiff = Infinity;
  38060. var closestAxis;
  38061. var closestAxisIdx = -1;
  38062. for (var i = 0; i < this._indicatorAxes.length; i++) {
  38063. var indicatorAxis = this._indicatorAxes[i];
  38064. var diff = Math.abs(radian - indicatorAxis.angle);
  38065. if (diff < minRadianDiff) {
  38066. closestAxis = indicatorAxis;
  38067. closestAxisIdx = i;
  38068. minRadianDiff = diff;
  38069. }
  38070. }
  38071. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  38072. };
  38073. Radar.prototype.resize = function (radarModel, api) {
  38074. var center = radarModel.get('center');
  38075. var viewWidth = api.getWidth();
  38076. var viewHeight = api.getHeight();
  38077. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  38078. this.cx = parsePercent$1(center[0], viewWidth);
  38079. this.cy = parsePercent$1(center[1], viewHeight);
  38080. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  38081. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  38082. var radius = radarModel.get('radius');
  38083. if (typeof radius === 'string' || typeof radius === 'number') {
  38084. radius = [0, radius];
  38085. }
  38086. this.r0 = parsePercent$1(radius[0], viewSize);
  38087. this.r = parsePercent$1(radius[1], viewSize);
  38088. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  38089. indicatorAxis.setExtent(this.r0, this.r);
  38090. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  38091. // Normalize to [-PI, PI]
  38092. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  38093. indicatorAxis.angle = angle;
  38094. }, this);
  38095. };
  38096. Radar.prototype.update = function (ecModel, api) {
  38097. var indicatorAxes = this._indicatorAxes;
  38098. var radarModel = this._model;
  38099. each$1(indicatorAxes, function (indicatorAxis) {
  38100. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  38101. });
  38102. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  38103. if (radarSeries.get('coordinateSystem') !== 'radar'
  38104. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  38105. ) {
  38106. return;
  38107. }
  38108. var data = radarSeries.getData();
  38109. each$1(indicatorAxes, function (indicatorAxis) {
  38110. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  38111. });
  38112. }, this);
  38113. var splitNumber = radarModel.get('splitNumber');
  38114. function increaseInterval(interval) {
  38115. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  38116. // Increase interval
  38117. var f = interval / exp10;
  38118. if (f === 2) {
  38119. f = 5;
  38120. }
  38121. else { // f is 2 or 5
  38122. f *= 2;
  38123. }
  38124. return f * exp10;
  38125. }
  38126. // Force all the axis fixing the maxSplitNumber.
  38127. each$1(indicatorAxes, function (indicatorAxis, idx) {
  38128. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  38129. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  38130. var axisModel = indicatorAxis.model;
  38131. var scale = indicatorAxis.scale;
  38132. var fixedMin = axisModel.getMin();
  38133. var fixedMax = axisModel.getMax();
  38134. var interval = scale.getInterval();
  38135. if (fixedMin != null && fixedMax != null) {
  38136. // User set min, max, divide to get new interval
  38137. scale.setExtent(+fixedMin, +fixedMax);
  38138. scale.setInterval(
  38139. (fixedMax - fixedMin) / splitNumber
  38140. );
  38141. }
  38142. else if (fixedMin != null) {
  38143. var max;
  38144. // User set min, expand extent on the other side
  38145. do {
  38146. max = fixedMin + interval * splitNumber;
  38147. scale.setExtent(+fixedMin, max);
  38148. // Interval must been set after extent
  38149. // FIXME
  38150. scale.setInterval(interval);
  38151. interval = increaseInterval(interval);
  38152. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  38153. }
  38154. else if (fixedMax != null) {
  38155. var min;
  38156. // User set min, expand extent on the other side
  38157. do {
  38158. min = fixedMax - interval * splitNumber;
  38159. scale.setExtent(min, +fixedMax);
  38160. scale.setInterval(interval);
  38161. interval = increaseInterval(interval);
  38162. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  38163. }
  38164. else {
  38165. var nicedSplitNumber = scale.getTicks().length - 1;
  38166. if (nicedSplitNumber > splitNumber) {
  38167. interval = increaseInterval(interval);
  38168. }
  38169. // PENDING
  38170. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  38171. var halfSplitNumber = Math.round(splitNumber / 2);
  38172. scale.setExtent(
  38173. round$2(center - halfSplitNumber * interval),
  38174. round$2(center + (splitNumber - halfSplitNumber) * interval)
  38175. );
  38176. scale.setInterval(interval);
  38177. }
  38178. });
  38179. };
  38180. /**
  38181. * Radar dimensions is based on the data
  38182. * @type {Array}
  38183. */
  38184. Radar.dimensions = [];
  38185. Radar.create = function (ecModel, api) {
  38186. var radarList = [];
  38187. ecModel.eachComponent('radar', function (radarModel) {
  38188. var radar = new Radar(radarModel, ecModel, api);
  38189. radarList.push(radar);
  38190. radarModel.coordinateSystem = radar;
  38191. });
  38192. ecModel.eachSeriesByType('radar', function (radarSeries) {
  38193. if (radarSeries.get('coordinateSystem') === 'radar') {
  38194. // Inject coordinate system
  38195. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  38196. }
  38197. });
  38198. return radarList;
  38199. };
  38200. CoordinateSystemManager.register('radar', Radar);
  38201. /*
  38202. * Licensed to the Apache Software Foundation (ASF) under one
  38203. * or more contributor license agreements. See the NOTICE file
  38204. * distributed with this work for additional information
  38205. * regarding copyright ownership. The ASF licenses this file
  38206. * to you under the Apache License, Version 2.0 (the
  38207. * "License"); you may not use this file except in compliance
  38208. * with the License. You may obtain a copy of the License at
  38209. *
  38210. * http://www.apache.org/licenses/LICENSE-2.0
  38211. *
  38212. * Unless required by applicable law or agreed to in writing,
  38213. * software distributed under the License is distributed on an
  38214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38215. * KIND, either express or implied. See the License for the
  38216. * specific language governing permissions and limitations
  38217. * under the License.
  38218. */
  38219. var valueAxisDefault = axisDefault.valueAxis;
  38220. function defaultsShow(opt, show) {
  38221. return defaults({
  38222. show: show
  38223. }, opt);
  38224. }
  38225. var RadarModel = extendComponentModel({
  38226. type: 'radar',
  38227. optionUpdated: function () {
  38228. var boundaryGap = this.get('boundaryGap');
  38229. var splitNumber = this.get('splitNumber');
  38230. var scale = this.get('scale');
  38231. var axisLine = this.get('axisLine');
  38232. var axisTick = this.get('axisTick');
  38233. var axisLabel = this.get('axisLabel');
  38234. var nameTextStyle = this.get('name');
  38235. var showName = this.get('name.show');
  38236. var nameFormatter = this.get('name.formatter');
  38237. var nameGap = this.get('nameGap');
  38238. var triggerEvent = this.get('triggerEvent');
  38239. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  38240. // PENDING
  38241. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  38242. indicatorOpt.min = 0;
  38243. }
  38244. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  38245. indicatorOpt.max = 0;
  38246. }
  38247. var iNameTextStyle = nameTextStyle;
  38248. if (indicatorOpt.color != null) {
  38249. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  38250. }
  38251. // Use same configuration
  38252. indicatorOpt = merge(clone(indicatorOpt), {
  38253. boundaryGap: boundaryGap,
  38254. splitNumber: splitNumber,
  38255. scale: scale,
  38256. axisLine: axisLine,
  38257. axisTick: axisTick,
  38258. axisLabel: axisLabel,
  38259. // Competitable with 2 and use text
  38260. name: indicatorOpt.text,
  38261. nameLocation: 'end',
  38262. nameGap: nameGap,
  38263. // min: 0,
  38264. nameTextStyle: iNameTextStyle,
  38265. triggerEvent: triggerEvent
  38266. }, false);
  38267. if (!showName) {
  38268. indicatorOpt.name = '';
  38269. }
  38270. if (typeof nameFormatter === 'string') {
  38271. var indName = indicatorOpt.name;
  38272. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  38273. }
  38274. else if (typeof nameFormatter === 'function') {
  38275. indicatorOpt.name = nameFormatter(
  38276. indicatorOpt.name, indicatorOpt
  38277. );
  38278. }
  38279. var model = extend(
  38280. new Model(indicatorOpt, null, this.ecModel),
  38281. axisModelCommonMixin
  38282. );
  38283. // For triggerEvent.
  38284. model.mainType = 'radar';
  38285. model.componentIndex = this.componentIndex;
  38286. return model;
  38287. }, this);
  38288. this.getIndicatorModels = function () {
  38289. return indicatorModels;
  38290. };
  38291. },
  38292. defaultOption: {
  38293. zlevel: 0,
  38294. z: 0,
  38295. center: ['50%', '50%'],
  38296. radius: '75%',
  38297. startAngle: 90,
  38298. name: {
  38299. show: true
  38300. // formatter: null
  38301. // textStyle: {}
  38302. },
  38303. boundaryGap: [0, 0],
  38304. splitNumber: 5,
  38305. nameGap: 15,
  38306. scale: false,
  38307. // Polygon or circle
  38308. shape: 'polygon',
  38309. axisLine: merge(
  38310. {
  38311. lineStyle: {
  38312. color: '#bbb'
  38313. }
  38314. },
  38315. valueAxisDefault.axisLine
  38316. ),
  38317. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  38318. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  38319. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  38320. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  38321. // {text, min, max}
  38322. indicator: []
  38323. }
  38324. });
  38325. /*
  38326. * Licensed to the Apache Software Foundation (ASF) under one
  38327. * or more contributor license agreements. See the NOTICE file
  38328. * distributed with this work for additional information
  38329. * regarding copyright ownership. The ASF licenses this file
  38330. * to you under the Apache License, Version 2.0 (the
  38331. * "License"); you may not use this file except in compliance
  38332. * with the License. You may obtain a copy of the License at
  38333. *
  38334. * http://www.apache.org/licenses/LICENSE-2.0
  38335. *
  38336. * Unless required by applicable law or agreed to in writing,
  38337. * software distributed under the License is distributed on an
  38338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38339. * KIND, either express or implied. See the License for the
  38340. * specific language governing permissions and limitations
  38341. * under the License.
  38342. */
  38343. var axisBuilderAttrs$1 = [
  38344. 'axisLine', 'axisTickLabel', 'axisName'
  38345. ];
  38346. extendComponentView({
  38347. type: 'radar',
  38348. render: function (radarModel, ecModel, api) {
  38349. var group = this.group;
  38350. group.removeAll();
  38351. this._buildAxes(radarModel);
  38352. this._buildSplitLineAndArea(radarModel);
  38353. },
  38354. _buildAxes: function (radarModel) {
  38355. var radar = radarModel.coordinateSystem;
  38356. var indicatorAxes = radar.getIndicatorAxes();
  38357. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  38358. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  38359. position: [radar.cx, radar.cy],
  38360. rotation: indicatorAxis.angle,
  38361. labelDirection: -1,
  38362. tickDirection: -1,
  38363. nameDirection: 1
  38364. });
  38365. return axisBuilder;
  38366. });
  38367. each$1(axisBuilders, function (axisBuilder) {
  38368. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  38369. this.group.add(axisBuilder.getGroup());
  38370. }, this);
  38371. },
  38372. _buildSplitLineAndArea: function (radarModel) {
  38373. var radar = radarModel.coordinateSystem;
  38374. var indicatorAxes = radar.getIndicatorAxes();
  38375. if (!indicatorAxes.length) {
  38376. return;
  38377. }
  38378. var shape = radarModel.get('shape');
  38379. var splitLineModel = radarModel.getModel('splitLine');
  38380. var splitAreaModel = radarModel.getModel('splitArea');
  38381. var lineStyleModel = splitLineModel.getModel('lineStyle');
  38382. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  38383. var showSplitLine = splitLineModel.get('show');
  38384. var showSplitArea = splitAreaModel.get('show');
  38385. var splitLineColors = lineStyleModel.get('color');
  38386. var splitAreaColors = areaStyleModel.get('color');
  38387. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  38388. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  38389. var splitLines = [];
  38390. var splitAreas = [];
  38391. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  38392. var colorIndex = idx % areaOrLineColorList.length;
  38393. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  38394. return colorIndex;
  38395. }
  38396. if (shape === 'circle') {
  38397. var ticksRadius = indicatorAxes[0].getTicksCoords();
  38398. var cx = radar.cx;
  38399. var cy = radar.cy;
  38400. for (var i = 0; i < ticksRadius.length; i++) {
  38401. if (showSplitLine) {
  38402. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38403. splitLines[colorIndex].push(new Circle({
  38404. shape: {
  38405. cx: cx,
  38406. cy: cy,
  38407. r: ticksRadius[i].coord
  38408. }
  38409. }));
  38410. }
  38411. if (showSplitArea && i < ticksRadius.length - 1) {
  38412. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  38413. splitAreas[colorIndex].push(new Ring({
  38414. shape: {
  38415. cx: cx,
  38416. cy: cy,
  38417. r0: ticksRadius[i].coord,
  38418. r: ticksRadius[i + 1].coord
  38419. }
  38420. }));
  38421. }
  38422. }
  38423. }
  38424. // Polyyon
  38425. else {
  38426. var realSplitNumber;
  38427. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  38428. var ticksCoords = indicatorAxis.getTicksCoords();
  38429. realSplitNumber = realSplitNumber == null
  38430. ? ticksCoords.length - 1
  38431. : Math.min(ticksCoords.length - 1, realSplitNumber);
  38432. return map(ticksCoords, function (tickCoord) {
  38433. return radar.coordToPoint(tickCoord.coord, idx);
  38434. });
  38435. });
  38436. var prevPoints = [];
  38437. for (var i = 0; i <= realSplitNumber; i++) {
  38438. var points = [];
  38439. for (var j = 0; j < indicatorAxes.length; j++) {
  38440. points.push(axesTicksPoints[j][i]);
  38441. }
  38442. // Close
  38443. if (points[0]) {
  38444. points.push(points[0].slice());
  38445. }
  38446. else {
  38447. if (__DEV__) {
  38448. console.error('Can\'t draw value axis ' + i);
  38449. }
  38450. }
  38451. if (showSplitLine) {
  38452. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38453. splitLines[colorIndex].push(new Polyline({
  38454. shape: {
  38455. points: points
  38456. }
  38457. }));
  38458. }
  38459. if (showSplitArea && prevPoints) {
  38460. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  38461. splitAreas[colorIndex].push(new Polygon({
  38462. shape: {
  38463. points: points.concat(prevPoints)
  38464. }
  38465. }));
  38466. }
  38467. prevPoints = points.slice().reverse();
  38468. }
  38469. }
  38470. var lineStyle = lineStyleModel.getLineStyle();
  38471. var areaStyle = areaStyleModel.getAreaStyle();
  38472. // Add splitArea before splitLine
  38473. each$1(splitAreas, function (splitAreas, idx) {
  38474. this.group.add(mergePath(
  38475. splitAreas, {
  38476. style: defaults({
  38477. stroke: 'none',
  38478. fill: splitAreaColors[idx % splitAreaColors.length]
  38479. }, areaStyle),
  38480. silent: true
  38481. }
  38482. ));
  38483. }, this);
  38484. each$1(splitLines, function (splitLines, idx) {
  38485. this.group.add(mergePath(
  38486. splitLines, {
  38487. style: defaults({
  38488. fill: 'none',
  38489. stroke: splitLineColors[idx % splitLineColors.length]
  38490. }, lineStyle),
  38491. silent: true
  38492. }
  38493. ));
  38494. }, this);
  38495. }
  38496. });
  38497. /*
  38498. * Licensed to the Apache Software Foundation (ASF) under one
  38499. * or more contributor license agreements. See the NOTICE file
  38500. * distributed with this work for additional information
  38501. * regarding copyright ownership. The ASF licenses this file
  38502. * to you under the Apache License, Version 2.0 (the
  38503. * "License"); you may not use this file except in compliance
  38504. * with the License. You may obtain a copy of the License at
  38505. *
  38506. * http://www.apache.org/licenses/LICENSE-2.0
  38507. *
  38508. * Unless required by applicable law or agreed to in writing,
  38509. * software distributed under the License is distributed on an
  38510. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38511. * KIND, either express or implied. See the License for the
  38512. * specific language governing permissions and limitations
  38513. * under the License.
  38514. */
  38515. /*
  38516. * Licensed to the Apache Software Foundation (ASF) under one
  38517. * or more contributor license agreements. See the NOTICE file
  38518. * distributed with this work for additional information
  38519. * regarding copyright ownership. The ASF licenses this file
  38520. * to you under the Apache License, Version 2.0 (the
  38521. * "License"); you may not use this file except in compliance
  38522. * with the License. You may obtain a copy of the License at
  38523. *
  38524. * http://www.apache.org/licenses/LICENSE-2.0
  38525. *
  38526. * Unless required by applicable law or agreed to in writing,
  38527. * software distributed under the License is distributed on an
  38528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38529. * KIND, either express or implied. See the License for the
  38530. * specific language governing permissions and limitations
  38531. * under the License.
  38532. */
  38533. var RadarSeries = SeriesModel.extend({
  38534. type: 'series.radar',
  38535. dependencies: ['radar'],
  38536. // Overwrite
  38537. init: function (option) {
  38538. RadarSeries.superApply(this, 'init', arguments);
  38539. // Enable legend selection for each data item
  38540. // Use a function instead of direct access because data reference may changed
  38541. this.legendDataProvider = function () {
  38542. return this.getRawData();
  38543. };
  38544. },
  38545. getInitialData: function (option, ecModel) {
  38546. return createListSimply(this, {
  38547. generateCoord: 'indicator_',
  38548. generateCoordCount: Infinity
  38549. });
  38550. },
  38551. formatTooltip: function (dataIndex) {
  38552. var data = this.getData();
  38553. var coordSys = this.coordinateSystem;
  38554. var indicatorAxes = coordSys.getIndicatorAxes();
  38555. var name = this.getData().getName(dataIndex);
  38556. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  38557. + map(indicatorAxes, function (axis, idx) {
  38558. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  38559. return encodeHTML(axis.name + ' : ' + val);
  38560. }).join('<br />');
  38561. },
  38562. defaultOption: {
  38563. zlevel: 0,
  38564. z: 2,
  38565. coordinateSystem: 'radar',
  38566. legendHoverLink: true,
  38567. radarIndex: 0,
  38568. lineStyle: {
  38569. width: 2,
  38570. type: 'solid'
  38571. },
  38572. label: {
  38573. position: 'top'
  38574. },
  38575. // areaStyle: {
  38576. // },
  38577. // itemStyle: {}
  38578. symbol: 'emptyCircle',
  38579. symbolSize: 4
  38580. // symbolRotate: null
  38581. }
  38582. });
  38583. /*
  38584. * Licensed to the Apache Software Foundation (ASF) under one
  38585. * or more contributor license agreements. See the NOTICE file
  38586. * distributed with this work for additional information
  38587. * regarding copyright ownership. The ASF licenses this file
  38588. * to you under the Apache License, Version 2.0 (the
  38589. * "License"); you may not use this file except in compliance
  38590. * with the License. You may obtain a copy of the License at
  38591. *
  38592. * http://www.apache.org/licenses/LICENSE-2.0
  38593. *
  38594. * Unless required by applicable law or agreed to in writing,
  38595. * software distributed under the License is distributed on an
  38596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38597. * KIND, either express or implied. See the License for the
  38598. * specific language governing permissions and limitations
  38599. * under the License.
  38600. */
  38601. function normalizeSymbolSize(symbolSize) {
  38602. if (!isArray(symbolSize)) {
  38603. symbolSize = [+symbolSize, +symbolSize];
  38604. }
  38605. return symbolSize;
  38606. }
  38607. extendChartView({
  38608. type: 'radar',
  38609. render: function (seriesModel, ecModel, api) {
  38610. var polar = seriesModel.coordinateSystem;
  38611. var group = this.group;
  38612. var data = seriesModel.getData();
  38613. var oldData = this._data;
  38614. function createSymbol$$1(data, idx) {
  38615. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  38616. var color = data.getItemVisual(idx, 'color');
  38617. if (symbolType === 'none') {
  38618. return;
  38619. }
  38620. var symbolSize = normalizeSymbolSize(
  38621. data.getItemVisual(idx, 'symbolSize')
  38622. );
  38623. var symbolPath = createSymbol(
  38624. symbolType, -1, -1, 2, 2, color
  38625. );
  38626. symbolPath.attr({
  38627. style: {
  38628. strokeNoScale: true
  38629. },
  38630. z2: 100,
  38631. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  38632. });
  38633. return symbolPath;
  38634. }
  38635. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  38636. // Simply rerender all
  38637. symbolGroup.removeAll();
  38638. for (var i = 0; i < newPoints.length - 1; i++) {
  38639. var symbolPath = createSymbol$$1(data, idx);
  38640. if (symbolPath) {
  38641. symbolPath.__dimIdx = i;
  38642. if (oldPoints[i]) {
  38643. symbolPath.attr('position', oldPoints[i]);
  38644. graphic[isInit ? 'initProps' : 'updateProps'](
  38645. symbolPath, {
  38646. position: newPoints[i]
  38647. }, seriesModel, idx
  38648. );
  38649. }
  38650. else {
  38651. symbolPath.attr('position', newPoints[i]);
  38652. }
  38653. symbolGroup.add(symbolPath);
  38654. }
  38655. }
  38656. }
  38657. function getInitialPoints(points) {
  38658. return map(points, function (pt) {
  38659. return [polar.cx, polar.cy];
  38660. });
  38661. }
  38662. data.diff(oldData)
  38663. .add(function (idx) {
  38664. var points = data.getItemLayout(idx);
  38665. if (!points) {
  38666. return;
  38667. }
  38668. var polygon = new Polygon();
  38669. var polyline = new Polyline();
  38670. var target = {
  38671. shape: {
  38672. points: points
  38673. }
  38674. };
  38675. polygon.shape.points = getInitialPoints(points);
  38676. polyline.shape.points = getInitialPoints(points);
  38677. initProps(polygon, target, seriesModel, idx);
  38678. initProps(polyline, target, seriesModel, idx);
  38679. var itemGroup = new Group();
  38680. var symbolGroup = new Group();
  38681. itemGroup.add(polyline);
  38682. itemGroup.add(polygon);
  38683. itemGroup.add(symbolGroup);
  38684. updateSymbols(
  38685. polyline.shape.points, points, symbolGroup, data, idx, true
  38686. );
  38687. data.setItemGraphicEl(idx, itemGroup);
  38688. })
  38689. .update(function (newIdx, oldIdx) {
  38690. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  38691. var polyline = itemGroup.childAt(0);
  38692. var polygon = itemGroup.childAt(1);
  38693. var symbolGroup = itemGroup.childAt(2);
  38694. var target = {
  38695. shape: {
  38696. points: data.getItemLayout(newIdx)
  38697. }
  38698. };
  38699. if (!target.shape.points) {
  38700. return;
  38701. }
  38702. updateSymbols(
  38703. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  38704. );
  38705. updateProps(polyline, target, seriesModel);
  38706. updateProps(polygon, target, seriesModel);
  38707. data.setItemGraphicEl(newIdx, itemGroup);
  38708. })
  38709. .remove(function (idx) {
  38710. group.remove(oldData.getItemGraphicEl(idx));
  38711. })
  38712. .execute();
  38713. data.eachItemGraphicEl(function (itemGroup, idx) {
  38714. var itemModel = data.getItemModel(idx);
  38715. var polyline = itemGroup.childAt(0);
  38716. var polygon = itemGroup.childAt(1);
  38717. var symbolGroup = itemGroup.childAt(2);
  38718. var color = data.getItemVisual(idx, 'color');
  38719. group.add(itemGroup);
  38720. polyline.useStyle(
  38721. defaults(
  38722. itemModel.getModel('lineStyle').getLineStyle(),
  38723. {
  38724. fill: 'none',
  38725. stroke: color
  38726. }
  38727. )
  38728. );
  38729. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  38730. var areaStyleModel = itemModel.getModel('areaStyle');
  38731. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  38732. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  38733. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  38734. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  38735. polygon.ignore = polygonIgnore;
  38736. polygon.useStyle(
  38737. defaults(
  38738. areaStyleModel.getAreaStyle(),
  38739. {
  38740. fill: color,
  38741. opacity: 0.7
  38742. }
  38743. )
  38744. );
  38745. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  38746. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  38747. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38748. var labelModel = itemModel.getModel('label');
  38749. var labelHoverModel = itemModel.getModel('emphasis.label');
  38750. symbolGroup.eachChild(function (symbolPath) {
  38751. symbolPath.setStyle(itemStyle);
  38752. symbolPath.hoverStyle = clone(itemHoverStyle);
  38753. setLabelStyle(
  38754. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  38755. {
  38756. labelFetcher: data.hostModel,
  38757. labelDataIndex: idx,
  38758. labelDimIndex: symbolPath.__dimIdx,
  38759. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  38760. autoColor: color,
  38761. isRectText: true
  38762. }
  38763. );
  38764. });
  38765. function onEmphasis() {
  38766. polygon.attr('ignore', hoverPolygonIgnore);
  38767. }
  38768. function onNormal() {
  38769. polygon.attr('ignore', polygonIgnore);
  38770. }
  38771. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  38772. itemGroup.on('emphasis', onEmphasis)
  38773. .on('mouseover', onEmphasis)
  38774. .on('normal', onNormal)
  38775. .on('mouseout', onNormal);
  38776. setHoverStyle(itemGroup);
  38777. });
  38778. this._data = data;
  38779. },
  38780. remove: function () {
  38781. this.group.removeAll();
  38782. this._data = null;
  38783. },
  38784. dispose: function () {}
  38785. });
  38786. /*
  38787. * Licensed to the Apache Software Foundation (ASF) under one
  38788. * or more contributor license agreements. See the NOTICE file
  38789. * distributed with this work for additional information
  38790. * regarding copyright ownership. The ASF licenses this file
  38791. * to you under the Apache License, Version 2.0 (the
  38792. * "License"); you may not use this file except in compliance
  38793. * with the License. You may obtain a copy of the License at
  38794. *
  38795. * http://www.apache.org/licenses/LICENSE-2.0
  38796. *
  38797. * Unless required by applicable law or agreed to in writing,
  38798. * software distributed under the License is distributed on an
  38799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38800. * KIND, either express or implied. See the License for the
  38801. * specific language governing permissions and limitations
  38802. * under the License.
  38803. */
  38804. var radarLayout = function (ecModel) {
  38805. ecModel.eachSeriesByType('radar', function (seriesModel) {
  38806. var data = seriesModel.getData();
  38807. var points = [];
  38808. var coordSys = seriesModel.coordinateSystem;
  38809. if (!coordSys) {
  38810. return;
  38811. }
  38812. function pointsConverter(val, idx) {
  38813. points[idx] = points[idx] || [];
  38814. points[idx][i] = coordSys.dataToPoint(val, i);
  38815. }
  38816. var axes = coordSys.getIndicatorAxes();
  38817. for (var i = 0; i < axes.length; i++) {
  38818. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  38819. }
  38820. data.each(function (idx) {
  38821. // Close polygon
  38822. points[idx][0] && points[idx].push(points[idx][0].slice());
  38823. data.setItemLayout(idx, points[idx]);
  38824. });
  38825. });
  38826. };
  38827. /*
  38828. * Licensed to the Apache Software Foundation (ASF) under one
  38829. * or more contributor license agreements. See the NOTICE file
  38830. * distributed with this work for additional information
  38831. * regarding copyright ownership. The ASF licenses this file
  38832. * to you under the Apache License, Version 2.0 (the
  38833. * "License"); you may not use this file except in compliance
  38834. * with the License. You may obtain a copy of the License at
  38835. *
  38836. * http://www.apache.org/licenses/LICENSE-2.0
  38837. *
  38838. * Unless required by applicable law or agreed to in writing,
  38839. * software distributed under the License is distributed on an
  38840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38841. * KIND, either express or implied. See the License for the
  38842. * specific language governing permissions and limitations
  38843. * under the License.
  38844. */
  38845. // Backward compat for radar chart in 2
  38846. var backwardCompat$1 = function (option) {
  38847. var polarOptArr = option.polar;
  38848. if (polarOptArr) {
  38849. if (!isArray(polarOptArr)) {
  38850. polarOptArr = [polarOptArr];
  38851. }
  38852. var polarNotRadar = [];
  38853. each$1(polarOptArr, function (polarOpt, idx) {
  38854. if (polarOpt.indicator) {
  38855. if (polarOpt.type && !polarOpt.shape) {
  38856. polarOpt.shape = polarOpt.type;
  38857. }
  38858. option.radar = option.radar || [];
  38859. if (!isArray(option.radar)) {
  38860. option.radar = [option.radar];
  38861. }
  38862. option.radar.push(polarOpt);
  38863. }
  38864. else {
  38865. polarNotRadar.push(polarOpt);
  38866. }
  38867. });
  38868. option.polar = polarNotRadar;
  38869. }
  38870. each$1(option.series, function (seriesOpt) {
  38871. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  38872. seriesOpt.radarIndex = seriesOpt.polarIndex;
  38873. }
  38874. });
  38875. };
  38876. /*
  38877. * Licensed to the Apache Software Foundation (ASF) under one
  38878. * or more contributor license agreements. See the NOTICE file
  38879. * distributed with this work for additional information
  38880. * regarding copyright ownership. The ASF licenses this file
  38881. * to you under the Apache License, Version 2.0 (the
  38882. * "License"); you may not use this file except in compliance
  38883. * with the License. You may obtain a copy of the License at
  38884. *
  38885. * http://www.apache.org/licenses/LICENSE-2.0
  38886. *
  38887. * Unless required by applicable law or agreed to in writing,
  38888. * software distributed under the License is distributed on an
  38889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38890. * KIND, either express or implied. See the License for the
  38891. * specific language governing permissions and limitations
  38892. * under the License.
  38893. */
  38894. // Must use radar component
  38895. registerVisual(dataColor('radar'));
  38896. registerVisual(visualSymbol('radar', 'circle'));
  38897. registerLayout(radarLayout);
  38898. registerProcessor(dataFilter('radar'));
  38899. registerPreprocessor(backwardCompat$1);
  38900. /*
  38901. * Licensed to the Apache Software Foundation (ASF) under one
  38902. * or more contributor license agreements. See the NOTICE file
  38903. * distributed with this work for additional information
  38904. * regarding copyright ownership. The ASF licenses this file
  38905. * to you under the Apache License, Version 2.0 (the
  38906. * "License"); you may not use this file except in compliance
  38907. * with the License. You may obtain a copy of the License at
  38908. *
  38909. * http://www.apache.org/licenses/LICENSE-2.0
  38910. *
  38911. * Unless required by applicable law or agreed to in writing,
  38912. * software distributed under the License is distributed on an
  38913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38914. * KIND, either express or implied. See the License for the
  38915. * specific language governing permissions and limitations
  38916. * under the License.
  38917. */
  38918. // Fix for 南海诸岛
  38919. var geoCoord = [126, 25];
  38920. var points$1 = [
  38921. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  38922. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  38923. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  38924. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  38925. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  38926. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  38927. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  38928. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  38929. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  38930. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  38931. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  38932. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  38933. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  38934. [1, 92.4], [1, 3.5], [0, 3.5]]
  38935. ];
  38936. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  38937. for (var k = 0; k < points$1[i$1].length; k++) {
  38938. points$1[i$1][k][0] /= 10.5;
  38939. points$1[i$1][k][1] /= -10.5 / 0.75;
  38940. points$1[i$1][k][0] += geoCoord[0];
  38941. points$1[i$1][k][1] += geoCoord[1];
  38942. }
  38943. }
  38944. var fixNanhai = function (mapType, regions) {
  38945. if (mapType === 'china') {
  38946. regions.push(new Region(
  38947. '南海诸岛',
  38948. map(points$1, function (exterior) {
  38949. return {
  38950. type: 'polygon',
  38951. exterior: exterior
  38952. };
  38953. }), geoCoord
  38954. ));
  38955. }
  38956. };
  38957. /*
  38958. * Licensed to the Apache Software Foundation (ASF) under one
  38959. * or more contributor license agreements. See the NOTICE file
  38960. * distributed with this work for additional information
  38961. * regarding copyright ownership. The ASF licenses this file
  38962. * to you under the Apache License, Version 2.0 (the
  38963. * "License"); you may not use this file except in compliance
  38964. * with the License. You may obtain a copy of the License at
  38965. *
  38966. * http://www.apache.org/licenses/LICENSE-2.0
  38967. *
  38968. * Unless required by applicable law or agreed to in writing,
  38969. * software distributed under the License is distributed on an
  38970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38971. * KIND, either express or implied. See the License for the
  38972. * specific language governing permissions and limitations
  38973. * under the License.
  38974. */
  38975. var coordsOffsetMap = {
  38976. '南海诸岛': [32, 80],
  38977. // 全国
  38978. '广东': [0, -10],
  38979. '香港': [10, 5],
  38980. '澳门': [-10, 10],
  38981. //'北京': [-10, 0],
  38982. '天津': [5, 5]
  38983. };
  38984. var fixTextCoord = function (mapType, region) {
  38985. if (mapType === 'china') {
  38986. var coordFix = coordsOffsetMap[region.name];
  38987. if (coordFix) {
  38988. var cp = region.center;
  38989. cp[0] += coordFix[0] / 10.5;
  38990. cp[1] += -coordFix[1] / (10.5 / 0.75);
  38991. }
  38992. }
  38993. };
  38994. /*
  38995. * Licensed to the Apache Software Foundation (ASF) under one
  38996. * or more contributor license agreements. See the NOTICE file
  38997. * distributed with this work for additional information
  38998. * regarding copyright ownership. The ASF licenses this file
  38999. * to you under the Apache License, Version 2.0 (the
  39000. * "License"); you may not use this file except in compliance
  39001. * with the License. You may obtain a copy of the License at
  39002. *
  39003. * http://www.apache.org/licenses/LICENSE-2.0
  39004. *
  39005. * Unless required by applicable law or agreed to in writing,
  39006. * software distributed under the License is distributed on an
  39007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39008. * KIND, either express or implied. See the License for the
  39009. * specific language governing permissions and limitations
  39010. * under the License.
  39011. */
  39012. var geoCoordMap = {
  39013. 'Russia': [100, 60],
  39014. 'United States': [-99, 38],
  39015. 'United States of America': [-99, 38]
  39016. };
  39017. var fixGeoCoord = function (mapType, region) {
  39018. if (mapType === 'world') {
  39019. var geoCoord = geoCoordMap[region.name];
  39020. if (geoCoord) {
  39021. var cp = region.center;
  39022. cp[0] = geoCoord[0];
  39023. cp[1] = geoCoord[1];
  39024. }
  39025. }
  39026. };
  39027. /*
  39028. * Licensed to the Apache Software Foundation (ASF) under one
  39029. * or more contributor license agreements. See the NOTICE file
  39030. * distributed with this work for additional information
  39031. * regarding copyright ownership. The ASF licenses this file
  39032. * to you under the Apache License, Version 2.0 (the
  39033. * "License"); you may not use this file except in compliance
  39034. * with the License. You may obtain a copy of the License at
  39035. *
  39036. * http://www.apache.org/licenses/LICENSE-2.0
  39037. *
  39038. * Unless required by applicable law or agreed to in writing,
  39039. * software distributed under the License is distributed on an
  39040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39041. * KIND, either express or implied. See the License for the
  39042. * specific language governing permissions and limitations
  39043. * under the License.
  39044. */
  39045. // Fix for 钓鱼岛
  39046. // var Region = require('../Region');
  39047. // var zrUtil = require('zrender/src/core/util');
  39048. // var geoCoord = [126, 25];
  39049. var points$2 = [
  39050. [
  39051. [123.45165252685547, 25.73527164402261],
  39052. [123.49731445312499, 25.73527164402261],
  39053. [123.49731445312499, 25.750734064600884],
  39054. [123.45165252685547, 25.750734064600884],
  39055. [123.45165252685547, 25.73527164402261]
  39056. ]
  39057. ];
  39058. var fixDiaoyuIsland = function (mapType, region) {
  39059. if (mapType === 'china' && region.name === '台湾') {
  39060. region.geometries.push({
  39061. type: 'polygon',
  39062. exterior: points$2[0]
  39063. });
  39064. }
  39065. };
  39066. /*
  39067. * Licensed to the Apache Software Foundation (ASF) under one
  39068. * or more contributor license agreements. See the NOTICE file
  39069. * distributed with this work for additional information
  39070. * regarding copyright ownership. The ASF licenses this file
  39071. * to you under the Apache License, Version 2.0 (the
  39072. * "License"); you may not use this file except in compliance
  39073. * with the License. You may obtain a copy of the License at
  39074. *
  39075. * http://www.apache.org/licenses/LICENSE-2.0
  39076. *
  39077. * Unless required by applicable law or agreed to in writing,
  39078. * software distributed under the License is distributed on an
  39079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39080. * KIND, either express or implied. See the License for the
  39081. * specific language governing permissions and limitations
  39082. * under the License.
  39083. */
  39084. // Built-in GEO fixer.
  39085. var inner$7 = makeInner();
  39086. var geoJSONLoader = {
  39087. /**
  39088. * @param {string} mapName
  39089. * @param {Object} mapRecord {specialAreas, geoJSON}
  39090. * @return {Object} {regions, boundingRect}
  39091. */
  39092. load: function (mapName, mapRecord) {
  39093. var parsed = inner$7(mapRecord).parsed;
  39094. if (parsed) {
  39095. return parsed;
  39096. }
  39097. var specialAreas = mapRecord.specialAreas || {};
  39098. var geoJSON = mapRecord.geoJSON;
  39099. var regions;
  39100. // https://jsperf.com/try-catch-performance-overhead
  39101. try {
  39102. regions = geoJSON ? parseGeoJson$1(geoJSON) : [];
  39103. }
  39104. catch (e) {
  39105. throw new Error('Invalid geoJson format\n' + e.message);
  39106. }
  39107. each$1(regions, function (region) {
  39108. var regionName = region.name;
  39109. fixTextCoord(mapName, region);
  39110. fixGeoCoord(mapName, region);
  39111. fixDiaoyuIsland(mapName, region);
  39112. // Some area like Alaska in USA map needs to be tansformed
  39113. // to look better
  39114. var specialArea = specialAreas[regionName];
  39115. if (specialArea) {
  39116. region.transformTo(
  39117. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  39118. );
  39119. }
  39120. });
  39121. fixNanhai(mapName, regions);
  39122. return (inner$7(mapRecord).parsed = {
  39123. regions: regions,
  39124. boundingRect: getBoundingRect$1(regions)
  39125. });
  39126. }
  39127. };
  39128. function getBoundingRect$1(regions) {
  39129. var rect;
  39130. for (var i = 0; i < regions.length; i++) {
  39131. var regionRect = regions[i].getBoundingRect();
  39132. rect = rect || regionRect.clone();
  39133. rect.union(regionRect);
  39134. }
  39135. return rect;
  39136. }
  39137. /*
  39138. * Licensed to the Apache Software Foundation (ASF) under one
  39139. * or more contributor license agreements. See the NOTICE file
  39140. * distributed with this work for additional information
  39141. * regarding copyright ownership. The ASF licenses this file
  39142. * to you under the Apache License, Version 2.0 (the
  39143. * "License"); you may not use this file except in compliance
  39144. * with the License. You may obtain a copy of the License at
  39145. *
  39146. * http://www.apache.org/licenses/LICENSE-2.0
  39147. *
  39148. * Unless required by applicable law or agreed to in writing,
  39149. * software distributed under the License is distributed on an
  39150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39151. * KIND, either express or implied. See the License for the
  39152. * specific language governing permissions and limitations
  39153. * under the License.
  39154. */
  39155. var inner$8 = makeInner();
  39156. var geoSVGLoader = {
  39157. /**
  39158. * @param {string} mapName
  39159. * @param {Object} mapRecord {specialAreas, geoJSON}
  39160. * @return {Object} {root, boundingRect}
  39161. */
  39162. load: function (mapName, mapRecord) {
  39163. var originRoot = inner$8(mapRecord).originRoot;
  39164. if (originRoot) {
  39165. return {
  39166. root: originRoot,
  39167. boundingRect: inner$8(mapRecord).boundingRect
  39168. };
  39169. }
  39170. var graphic = buildGraphic(mapRecord);
  39171. inner$8(mapRecord).originRoot = graphic.root;
  39172. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  39173. return graphic;
  39174. },
  39175. makeGraphic: function (mapName, mapRecord, hostKey) {
  39176. // For performance consideration (in large SVG), graphic only maked
  39177. // when necessary and reuse them according to hostKey.
  39178. var field = inner$8(mapRecord);
  39179. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  39180. var root = rootMap.get(hostKey);
  39181. if (root) {
  39182. return root;
  39183. }
  39184. var originRoot = field.originRoot;
  39185. var boundingRect = field.boundingRect;
  39186. // For performance, if originRoot is not used by a view,
  39187. // assign it to a view, but not reproduce graphic elements.
  39188. if (!field.originRootHostKey) {
  39189. field.originRootHostKey = hostKey;
  39190. root = originRoot;
  39191. }
  39192. else {
  39193. root = buildGraphic(mapRecord, boundingRect).root;
  39194. }
  39195. return rootMap.set(hostKey, root);
  39196. },
  39197. removeGraphic: function (mapName, mapRecord, hostKey) {
  39198. var field = inner$8(mapRecord);
  39199. var rootMap = field.rootMap;
  39200. rootMap && rootMap.removeKey(hostKey);
  39201. if (hostKey === field.originRootHostKey) {
  39202. field.originRootHostKey = null;
  39203. }
  39204. }
  39205. };
  39206. function buildGraphic(mapRecord, boundingRect) {
  39207. var svgXML = mapRecord.svgXML;
  39208. var result;
  39209. var root;
  39210. try {
  39211. result = svgXML && parseSVG(svgXML, {
  39212. ignoreViewBox: true,
  39213. ignoreRootClip: true
  39214. }) || {};
  39215. root = result.root;
  39216. assert$1(root != null);
  39217. }
  39218. catch (e) {
  39219. throw new Error('Invalid svg format\n' + e.message);
  39220. }
  39221. var svgWidth = result.width;
  39222. var svgHeight = result.height;
  39223. var viewBoxRect = result.viewBoxRect;
  39224. if (!boundingRect) {
  39225. boundingRect = (svgWidth == null || svgHeight == null)
  39226. // If svg width / height not specified, calculate
  39227. // bounding rect as the width / height
  39228. ? root.getBoundingRect()
  39229. : new BoundingRect(0, 0, 0, 0);
  39230. if (svgWidth != null) {
  39231. boundingRect.width = svgWidth;
  39232. }
  39233. if (svgHeight != null) {
  39234. boundingRect.height = svgHeight;
  39235. }
  39236. }
  39237. if (viewBoxRect) {
  39238. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  39239. var elRoot = root;
  39240. root = new Group();
  39241. root.add(elRoot);
  39242. elRoot.scale = viewBoxTransform.scale;
  39243. elRoot.position = viewBoxTransform.position;
  39244. }
  39245. root.setClipPath(new Rect({
  39246. shape: boundingRect.plain()
  39247. }));
  39248. return {
  39249. root: root,
  39250. boundingRect: boundingRect
  39251. };
  39252. }
  39253. /*
  39254. * Licensed to the Apache Software Foundation (ASF) under one
  39255. * or more contributor license agreements. See the NOTICE file
  39256. * distributed with this work for additional information
  39257. * regarding copyright ownership. The ASF licenses this file
  39258. * to you under the Apache License, Version 2.0 (the
  39259. * "License"); you may not use this file except in compliance
  39260. * with the License. You may obtain a copy of the License at
  39261. *
  39262. * http://www.apache.org/licenses/LICENSE-2.0
  39263. *
  39264. * Unless required by applicable law or agreed to in writing,
  39265. * software distributed under the License is distributed on an
  39266. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39267. * KIND, either express or implied. See the License for the
  39268. * specific language governing permissions and limitations
  39269. * under the License.
  39270. */
  39271. var loaders = {
  39272. geoJSON: geoJSONLoader,
  39273. svg: geoSVGLoader
  39274. };
  39275. var geoSourceManager = {
  39276. /**
  39277. * @param {string} mapName
  39278. * @param {Object} nameMap
  39279. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  39280. */
  39281. load: function (mapName, nameMap) {
  39282. var regions = [];
  39283. var regionsMap = createHashMap();
  39284. var nameCoordMap = createHashMap();
  39285. var boundingRect;
  39286. var mapRecords = retrieveMap(mapName);
  39287. each$1(mapRecords, function (record) {
  39288. var singleSource = loaders[record.type].load(mapName, record);
  39289. each$1(singleSource.regions, function (region) {
  39290. var regionName = region.name;
  39291. // Try use the alias in geoNameMap
  39292. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  39293. region = region.cloneShallow(regionName = nameMap[regionName]);
  39294. }
  39295. regions.push(region);
  39296. regionsMap.set(regionName, region);
  39297. nameCoordMap.set(regionName, region.center);
  39298. });
  39299. var rect = singleSource.boundingRect;
  39300. if (rect) {
  39301. boundingRect
  39302. ? boundingRect.union(rect)
  39303. : (boundingRect = rect.clone());
  39304. }
  39305. });
  39306. return {
  39307. regions: regions,
  39308. regionsMap: regionsMap,
  39309. nameCoordMap: nameCoordMap,
  39310. // FIXME Always return new ?
  39311. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  39312. };
  39313. },
  39314. /**
  39315. * @param {string} mapName
  39316. * @param {string} hostKey For cache.
  39317. * @return {Array.<module:zrender/Element>} Roots.
  39318. */
  39319. makeGraphic: makeInvoker('makeGraphic'),
  39320. /**
  39321. * @param {string} mapName
  39322. * @param {string} hostKey For cache.
  39323. */
  39324. removeGraphic: makeInvoker('removeGraphic')
  39325. };
  39326. function makeInvoker(methodName) {
  39327. return function (mapName, hostKey) {
  39328. var mapRecords = retrieveMap(mapName);
  39329. var results = [];
  39330. each$1(mapRecords, function (record) {
  39331. var method = loaders[record.type][methodName];
  39332. method && results.push(method(mapName, record, hostKey));
  39333. });
  39334. return results;
  39335. };
  39336. }
  39337. function mapNotExistsError(mapName) {
  39338. if (__DEV__) {
  39339. console.error(
  39340. 'Map ' + mapName + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html'
  39341. );
  39342. }
  39343. }
  39344. function retrieveMap(mapName) {
  39345. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  39346. if (__DEV__) {
  39347. if (!mapRecords.length) {
  39348. mapNotExistsError(mapName);
  39349. }
  39350. }
  39351. return mapRecords;
  39352. }
  39353. /*
  39354. * Licensed to the Apache Software Foundation (ASF) under one
  39355. * or more contributor license agreements. See the NOTICE file
  39356. * distributed with this work for additional information
  39357. * regarding copyright ownership. The ASF licenses this file
  39358. * to you under the Apache License, Version 2.0 (the
  39359. * "License"); you may not use this file except in compliance
  39360. * with the License. You may obtain a copy of the License at
  39361. *
  39362. * http://www.apache.org/licenses/LICENSE-2.0
  39363. *
  39364. * Unless required by applicable law or agreed to in writing,
  39365. * software distributed under the License is distributed on an
  39366. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39367. * KIND, either express or implied. See the License for the
  39368. * specific language governing permissions and limitations
  39369. * under the License.
  39370. */
  39371. var MapSeries = SeriesModel.extend({
  39372. type: 'series.map',
  39373. dependencies: ['geo'],
  39374. layoutMode: 'box',
  39375. /**
  39376. * Only first map series of same mapType will drawMap
  39377. * @type {boolean}
  39378. */
  39379. needsDrawMap: false,
  39380. /**
  39381. * Group of all map series with same mapType
  39382. * @type {boolean}
  39383. */
  39384. seriesGroup: [],
  39385. getInitialData: function (option) {
  39386. var data = createListSimply(this, ['value']);
  39387. var valueDim = data.mapDimension('value');
  39388. var dataNameMap = createHashMap();
  39389. var selectTargetList = [];
  39390. var toAppendNames = [];
  39391. for (var i = 0, len = data.count(); i < len; i++) {
  39392. var name = data.getName(i);
  39393. dataNameMap.set(name, true);
  39394. selectTargetList.push({
  39395. name: name,
  39396. value: data.get(valueDim, i),
  39397. selected: retrieveRawAttr(data, i, 'selected')
  39398. });
  39399. }
  39400. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap);
  39401. each$1(geoSource.regions, function (region) {
  39402. var name = region.name;
  39403. if (!dataNameMap.get(name)) {
  39404. selectTargetList.push({name: name});
  39405. toAppendNames.push(name);
  39406. }
  39407. });
  39408. this.updateSelectedMap(selectTargetList);
  39409. // Complete data with missing regions. The consequent processes (like visual
  39410. // map and render) can not be performed without a "full data". For example,
  39411. // find `dataIndex` by name.
  39412. data.appendValues([], toAppendNames);
  39413. return data;
  39414. },
  39415. /**
  39416. * If no host geo model, return null, which means using a
  39417. * inner exclusive geo model.
  39418. */
  39419. getHostGeoModel: function () {
  39420. var geoIndex = this.option.geoIndex;
  39421. return geoIndex != null
  39422. ? this.dependentModels.geo[geoIndex]
  39423. : null;
  39424. },
  39425. getMapType: function () {
  39426. return (this.getHostGeoModel() || this).option.map;
  39427. },
  39428. // _fillOption: function (option, mapName) {
  39429. // Shallow clone
  39430. // option = zrUtil.extend({}, option);
  39431. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  39432. // return option;
  39433. // },
  39434. getRawValue: function (dataIndex) {
  39435. // Use value stored in data instead because it is calculated from multiple series
  39436. // FIXME Provide all value of multiple series ?
  39437. var data = this.getData();
  39438. return data.get(data.mapDimension('value'), dataIndex);
  39439. },
  39440. /**
  39441. * Get model of region
  39442. * @param {string} name
  39443. * @return {module:echarts/model/Model}
  39444. */
  39445. getRegionModel: function (regionName) {
  39446. var data = this.getData();
  39447. return data.getItemModel(data.indexOfName(regionName));
  39448. },
  39449. /**
  39450. * Map tooltip formatter
  39451. *
  39452. * @param {number} dataIndex
  39453. */
  39454. formatTooltip: function (dataIndex) {
  39455. // FIXME orignalData and data is a bit confusing
  39456. var data = this.getData();
  39457. var formattedValue = addCommas(this.getRawValue(dataIndex));
  39458. var name = data.getName(dataIndex);
  39459. var seriesGroup = this.seriesGroup;
  39460. var seriesNames = [];
  39461. for (var i = 0; i < seriesGroup.length; i++) {
  39462. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  39463. var valueDim = data.mapDimension('value');
  39464. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  39465. seriesNames.push(
  39466. encodeHTML(seriesGroup[i].name)
  39467. );
  39468. }
  39469. }
  39470. return seriesNames.join(', ') + '<br />'
  39471. + encodeHTML(name + ' : ' + formattedValue);
  39472. },
  39473. /**
  39474. * @implement
  39475. */
  39476. getTooltipPosition: function (dataIndex) {
  39477. if (dataIndex != null) {
  39478. var name = this.getData().getName(dataIndex);
  39479. var geo = this.coordinateSystem;
  39480. var region = geo.getRegion(name);
  39481. return region && geo.dataToPoint(region.center);
  39482. }
  39483. },
  39484. setZoom: function (zoom) {
  39485. this.option.zoom = zoom;
  39486. },
  39487. setCenter: function (center) {
  39488. this.option.center = center;
  39489. },
  39490. defaultOption: {
  39491. // 一级层叠
  39492. zlevel: 0,
  39493. // 二级层叠
  39494. z: 2,
  39495. coordinateSystem: 'geo',
  39496. // map should be explicitly specified since ec3.
  39497. map: '',
  39498. // If `geoIndex` is not specified, a exclusive geo will be
  39499. // created. Otherwise use the specified geo component, and
  39500. // `map` and `mapType` are ignored.
  39501. // geoIndex: 0,
  39502. // 'center' | 'left' | 'right' | 'x%' | {number}
  39503. left: 'center',
  39504. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  39505. top: 'center',
  39506. // right
  39507. // bottom
  39508. // width:
  39509. // height
  39510. // Aspect is width / height. Inited to be geoJson bbox aspect
  39511. // This parameter is used for scale this aspect
  39512. aspectScale: 0.75,
  39513. ///// Layout with center and size
  39514. // If you wan't to put map in a fixed size box with right aspect ratio
  39515. // This two properties may more conveninet
  39516. // layoutCenter: [50%, 50%]
  39517. // layoutSize: 100
  39518. // 数值合并方式,默认加和,可选为:
  39519. // 'sum' | 'average' | 'max' | 'min'
  39520. // mapValueCalculation: 'sum',
  39521. // 地图数值计算结果小数精度
  39522. // mapValuePrecision: 0,
  39523. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  39524. showLegendSymbol: true,
  39525. // 选择模式,默认关闭,可选single,multiple
  39526. // selectedMode: false,
  39527. dataRangeHoverLink: true,
  39528. // 是否开启缩放及漫游模式
  39529. // roam: false,
  39530. // Define left-top, right-bottom coords to control view
  39531. // For example, [ [180, 90], [-180, -90] ],
  39532. // higher priority than center and zoom
  39533. boundingCoords: null,
  39534. // Default on center of map
  39535. center: null,
  39536. zoom: 1,
  39537. scaleLimit: null,
  39538. label: {
  39539. show: false,
  39540. color: '#000'
  39541. },
  39542. // scaleLimit: null,
  39543. itemStyle: {
  39544. borderWidth: 0.5,
  39545. borderColor: '#444',
  39546. areaColor: '#eee'
  39547. },
  39548. emphasis: {
  39549. label: {
  39550. show: true,
  39551. color: 'rgb(100,0,0)'
  39552. },
  39553. itemStyle: {
  39554. areaColor: 'rgba(255,215,0,0.8)'
  39555. }
  39556. }
  39557. }
  39558. });
  39559. mixin(MapSeries, selectableMixin);
  39560. /*
  39561. * Licensed to the Apache Software Foundation (ASF) under one
  39562. * or more contributor license agreements. See the NOTICE file
  39563. * distributed with this work for additional information
  39564. * regarding copyright ownership. The ASF licenses this file
  39565. * to you under the Apache License, Version 2.0 (the
  39566. * "License"); you may not use this file except in compliance
  39567. * with the License. You may obtain a copy of the License at
  39568. *
  39569. * http://www.apache.org/licenses/LICENSE-2.0
  39570. *
  39571. * Unless required by applicable law or agreed to in writing,
  39572. * software distributed under the License is distributed on an
  39573. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39574. * KIND, either express or implied. See the License for the
  39575. * specific language governing permissions and limitations
  39576. * under the License.
  39577. */
  39578. var ATTR = '\0_ec_interaction_mutex';
  39579. function take(zr, resourceKey, userKey) {
  39580. var store = getStore(zr);
  39581. store[resourceKey] = userKey;
  39582. }
  39583. function release(zr, resourceKey, userKey) {
  39584. var store = getStore(zr);
  39585. var uKey = store[resourceKey];
  39586. if (uKey === userKey) {
  39587. store[resourceKey] = null;
  39588. }
  39589. }
  39590. function isTaken(zr, resourceKey) {
  39591. return !!getStore(zr)[resourceKey];
  39592. }
  39593. function getStore(zr) {
  39594. return zr[ATTR] || (zr[ATTR] = {});
  39595. }
  39596. /**
  39597. * payload: {
  39598. * type: 'takeGlobalCursor',
  39599. * key: 'dataZoomSelect', or 'brush', or ...,
  39600. * If no userKey, release global cursor.
  39601. * }
  39602. */
  39603. registerAction(
  39604. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  39605. function () {}
  39606. );
  39607. /*
  39608. * Licensed to the Apache Software Foundation (ASF) under one
  39609. * or more contributor license agreements. See the NOTICE file
  39610. * distributed with this work for additional information
  39611. * regarding copyright ownership. The ASF licenses this file
  39612. * to you under the Apache License, Version 2.0 (the
  39613. * "License"); you may not use this file except in compliance
  39614. * with the License. You may obtain a copy of the License at
  39615. *
  39616. * http://www.apache.org/licenses/LICENSE-2.0
  39617. *
  39618. * Unless required by applicable law or agreed to in writing,
  39619. * software distributed under the License is distributed on an
  39620. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39621. * KIND, either express or implied. See the License for the
  39622. * specific language governing permissions and limitations
  39623. * under the License.
  39624. */
  39625. /**
  39626. * @alias module:echarts/component/helper/RoamController
  39627. * @constructor
  39628. * @mixin {module:zrender/mixin/Eventful}
  39629. *
  39630. * @param {module:zrender/zrender~ZRender} zr
  39631. */
  39632. function RoamController(zr) {
  39633. /**
  39634. * @type {Function}
  39635. */
  39636. this.pointerChecker;
  39637. /**
  39638. * @type {module:zrender}
  39639. */
  39640. this._zr = zr;
  39641. /**
  39642. * @type {Object}
  39643. */
  39644. this._opt = {};
  39645. // Avoid two roamController bind the same handler
  39646. var bind$$1 = bind;
  39647. var mousedownHandler = bind$$1(mousedown, this);
  39648. var mousemoveHandler = bind$$1(mousemove, this);
  39649. var mouseupHandler = bind$$1(mouseup, this);
  39650. var mousewheelHandler = bind$$1(mousewheel, this);
  39651. var pinchHandler = bind$$1(pinch, this);
  39652. Eventful.call(this);
  39653. /**
  39654. * @param {Function} pointerChecker
  39655. * input: x, y
  39656. * output: boolean
  39657. */
  39658. this.setPointerChecker = function (pointerChecker) {
  39659. this.pointerChecker = pointerChecker;
  39660. };
  39661. /**
  39662. * Notice: only enable needed types. For example, if 'zoom'
  39663. * is not needed, 'zoom' should not be enabled, otherwise
  39664. * default mousewheel behaviour (scroll page) will be disabled.
  39665. *
  39666. * @param {boolean|string} [controlType=true] Specify the control type,
  39667. * which can be null/undefined or true/false
  39668. * or 'pan/move' or 'zoom'/'scale'
  39669. * @param {Object} [opt]
  39670. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39671. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39672. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39673. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  39674. */
  39675. this.enable = function (controlType, opt) {
  39676. // Disable previous first
  39677. this.disable();
  39678. this._opt = defaults(clone(opt) || {}, {
  39679. zoomOnMouseWheel: true,
  39680. moveOnMouseMove: true,
  39681. // By default, wheel do not trigger move.
  39682. moveOnMouseWheel: false,
  39683. preventDefaultMouseMove: true
  39684. });
  39685. if (controlType == null) {
  39686. controlType = true;
  39687. }
  39688. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  39689. zr.on('mousedown', mousedownHandler);
  39690. zr.on('mousemove', mousemoveHandler);
  39691. zr.on('mouseup', mouseupHandler);
  39692. }
  39693. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  39694. zr.on('mousewheel', mousewheelHandler);
  39695. zr.on('pinch', pinchHandler);
  39696. }
  39697. };
  39698. this.disable = function () {
  39699. zr.off('mousedown', mousedownHandler);
  39700. zr.off('mousemove', mousemoveHandler);
  39701. zr.off('mouseup', mouseupHandler);
  39702. zr.off('mousewheel', mousewheelHandler);
  39703. zr.off('pinch', pinchHandler);
  39704. };
  39705. this.dispose = this.disable;
  39706. this.isDragging = function () {
  39707. return this._dragging;
  39708. };
  39709. this.isPinching = function () {
  39710. return this._pinching;
  39711. };
  39712. }
  39713. mixin(RoamController, Eventful);
  39714. function mousedown(e) {
  39715. if (isMiddleOrRightButtonOnMouseUpDown(e)
  39716. || (e.target && e.target.draggable)
  39717. ) {
  39718. return;
  39719. }
  39720. var x = e.offsetX;
  39721. var y = e.offsetY;
  39722. // Only check on mosedown, but not mousemove.
  39723. // Mouse can be out of target when mouse moving.
  39724. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  39725. this._x = x;
  39726. this._y = y;
  39727. this._dragging = true;
  39728. }
  39729. }
  39730. function mousemove(e) {
  39731. if (!this._dragging
  39732. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  39733. || e.gestureEvent === 'pinch'
  39734. || isTaken(this._zr, 'globalPan')
  39735. ) {
  39736. return;
  39737. }
  39738. var x = e.offsetX;
  39739. var y = e.offsetY;
  39740. var oldX = this._x;
  39741. var oldY = this._y;
  39742. var dx = x - oldX;
  39743. var dy = y - oldY;
  39744. this._x = x;
  39745. this._y = y;
  39746. this._opt.preventDefaultMouseMove && stop(e.event);
  39747. trigger(this, 'pan', 'moveOnMouseMove', e, {
  39748. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  39749. });
  39750. }
  39751. function mouseup(e) {
  39752. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  39753. this._dragging = false;
  39754. }
  39755. }
  39756. function mousewheel(e) {
  39757. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  39758. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  39759. var wheelDelta = e.wheelDelta;
  39760. var absWheelDeltaDelta = Math.abs(wheelDelta);
  39761. var originX = e.offsetX;
  39762. var originY = e.offsetY;
  39763. // wheelDelta maybe -0 in chrome mac.
  39764. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  39765. return;
  39766. }
  39767. // If both `shouldZoom` and `shouldMove` is true, trigger
  39768. // their event both, and the final behavior is determined
  39769. // by event listener themselves.
  39770. if (shouldZoom) {
  39771. // Convenience:
  39772. // Mac and VM Windows on Mac: scroll up: zoom out.
  39773. // Windows: scroll up: zoom in.
  39774. // FIXME: Should do more test in different environment.
  39775. // wheelDelta is too complicated in difference nvironment
  39776. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  39777. // although it has been normallized by zrender.
  39778. // wheelDelta of mouse wheel is bigger than touch pad.
  39779. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  39780. var scale = wheelDelta > 0 ? factor : 1 / factor;
  39781. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  39782. scale: scale, originX: originX, originY: originY
  39783. });
  39784. }
  39785. if (shouldMove) {
  39786. // FIXME: Should do more test in different environment.
  39787. var absDelta = Math.abs(wheelDelta);
  39788. // wheelDelta of mouse wheel is bigger than touch pad.
  39789. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  39790. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  39791. scrollDelta: scrollDelta, originX: originX, originY: originY
  39792. });
  39793. }
  39794. }
  39795. function pinch(e) {
  39796. if (isTaken(this._zr, 'globalPan')) {
  39797. return;
  39798. }
  39799. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  39800. checkPointerAndTrigger(this, 'zoom', null, e, {
  39801. scale: scale, originX: e.pinchX, originY: e.pinchY
  39802. });
  39803. }
  39804. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  39805. if (controller.pointerChecker
  39806. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  39807. ) {
  39808. // When mouse is out of roamController rect,
  39809. // default befavoius should not be be disabled, otherwise
  39810. // page sliding is disabled, contrary to expectation.
  39811. stop(e.event);
  39812. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  39813. }
  39814. }
  39815. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  39816. // Also provide behavior checker for event listener, for some case that
  39817. // multiple components share one listener.
  39818. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  39819. controller.trigger(eventName, contollerEvent);
  39820. }
  39821. // settings: {
  39822. // zoomOnMouseWheel
  39823. // moveOnMouseMove
  39824. // moveOnMouseWheel
  39825. // }
  39826. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39827. function isAvailableBehavior(behaviorToCheck, e, settings) {
  39828. var setting = settings[behaviorToCheck];
  39829. return !behaviorToCheck || (
  39830. setting && (!isString(setting) || e.event[setting + 'Key'])
  39831. );
  39832. }
  39833. /*
  39834. * Licensed to the Apache Software Foundation (ASF) under one
  39835. * or more contributor license agreements. See the NOTICE file
  39836. * distributed with this work for additional information
  39837. * regarding copyright ownership. The ASF licenses this file
  39838. * to you under the Apache License, Version 2.0 (the
  39839. * "License"); you may not use this file except in compliance
  39840. * with the License. You may obtain a copy of the License at
  39841. *
  39842. * http://www.apache.org/licenses/LICENSE-2.0
  39843. *
  39844. * Unless required by applicable law or agreed to in writing,
  39845. * software distributed under the License is distributed on an
  39846. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39847. * KIND, either express or implied. See the License for the
  39848. * specific language governing permissions and limitations
  39849. * under the License.
  39850. */
  39851. /**
  39852. * For geo and graph.
  39853. *
  39854. * @param {Object} controllerHost
  39855. * @param {module:zrender/Element} controllerHost.target
  39856. */
  39857. function updateViewOnPan(controllerHost, dx, dy) {
  39858. var target = controllerHost.target;
  39859. var pos = target.position;
  39860. pos[0] += dx;
  39861. pos[1] += dy;
  39862. target.dirty();
  39863. }
  39864. /**
  39865. * For geo and graph.
  39866. *
  39867. * @param {Object} controllerHost
  39868. * @param {module:zrender/Element} controllerHost.target
  39869. * @param {number} controllerHost.zoom
  39870. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  39871. */
  39872. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  39873. var target = controllerHost.target;
  39874. var zoomLimit = controllerHost.zoomLimit;
  39875. var pos = target.position;
  39876. var scale = target.scale;
  39877. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  39878. newZoom *= zoomDelta;
  39879. if (zoomLimit) {
  39880. var zoomMin = zoomLimit.min || 0;
  39881. var zoomMax = zoomLimit.max || Infinity;
  39882. newZoom = Math.max(
  39883. Math.min(zoomMax, newZoom),
  39884. zoomMin
  39885. );
  39886. }
  39887. var zoomScale = newZoom / controllerHost.zoom;
  39888. controllerHost.zoom = newZoom;
  39889. // Keep the mouse center when scaling
  39890. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  39891. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  39892. scale[0] *= zoomScale;
  39893. scale[1] *= zoomScale;
  39894. target.dirty();
  39895. }
  39896. /*
  39897. * Licensed to the Apache Software Foundation (ASF) under one
  39898. * or more contributor license agreements. See the NOTICE file
  39899. * distributed with this work for additional information
  39900. * regarding copyright ownership. The ASF licenses this file
  39901. * to you under the Apache License, Version 2.0 (the
  39902. * "License"); you may not use this file except in compliance
  39903. * with the License. You may obtain a copy of the License at
  39904. *
  39905. * http://www.apache.org/licenses/LICENSE-2.0
  39906. *
  39907. * Unless required by applicable law or agreed to in writing,
  39908. * software distributed under the License is distributed on an
  39909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39910. * KIND, either express or implied. See the License for the
  39911. * specific language governing permissions and limitations
  39912. * under the License.
  39913. */
  39914. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  39915. /**
  39916. * Avoid that: mouse click on a elements that is over geo or graph,
  39917. * but roam is triggered.
  39918. */
  39919. function onIrrelevantElement(e, api, targetCoordSysModel) {
  39920. var model = api.getComponentByElement(e.topTarget);
  39921. // If model is axisModel, it works only if it is injected with coordinateSystem.
  39922. var coordSys = model && model.coordinateSystem;
  39923. return model
  39924. && model !== targetCoordSysModel
  39925. && !IRRELEVANT_EXCLUDES[model.mainType]
  39926. && (coordSys && coordSys.model !== targetCoordSysModel);
  39927. }
  39928. /*
  39929. * Licensed to the Apache Software Foundation (ASF) under one
  39930. * or more contributor license agreements. See the NOTICE file
  39931. * distributed with this work for additional information
  39932. * regarding copyright ownership. The ASF licenses this file
  39933. * to you under the Apache License, Version 2.0 (the
  39934. * "License"); you may not use this file except in compliance
  39935. * with the License. You may obtain a copy of the License at
  39936. *
  39937. * http://www.apache.org/licenses/LICENSE-2.0
  39938. *
  39939. * Unless required by applicable law or agreed to in writing,
  39940. * software distributed under the License is distributed on an
  39941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39942. * KIND, either express or implied. See the License for the
  39943. * specific language governing permissions and limitations
  39944. * under the License.
  39945. */
  39946. function getFixedItemStyle(model, scale) {
  39947. var itemStyle = model.getItemStyle();
  39948. var areaColor = model.get('areaColor');
  39949. // If user want the color not to be changed when hover,
  39950. // they should both set areaColor and color to be null.
  39951. if (areaColor != null) {
  39952. itemStyle.fill = areaColor;
  39953. }
  39954. return itemStyle;
  39955. }
  39956. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  39957. regionsGroup.off('click');
  39958. regionsGroup.off('mousedown');
  39959. if (mapOrGeoModel.get('selectedMode')) {
  39960. regionsGroup.on('mousedown', function () {
  39961. mapDraw._mouseDownFlag = true;
  39962. });
  39963. regionsGroup.on('click', function (e) {
  39964. if (!mapDraw._mouseDownFlag) {
  39965. return;
  39966. }
  39967. mapDraw._mouseDownFlag = false;
  39968. var el = e.target;
  39969. while (!el.__regions) {
  39970. el = el.parent;
  39971. }
  39972. if (!el) {
  39973. return;
  39974. }
  39975. var action = {
  39976. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  39977. batch: map(el.__regions, function (region) {
  39978. return {
  39979. name: region.name,
  39980. from: fromView.uid
  39981. };
  39982. })
  39983. };
  39984. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  39985. api.dispatchAction(action);
  39986. updateMapSelected(mapOrGeoModel, regionsGroup);
  39987. });
  39988. }
  39989. }
  39990. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  39991. // FIXME
  39992. regionsGroup.eachChild(function (otherRegionEl) {
  39993. each$1(otherRegionEl.__regions, function (region) {
  39994. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  39995. });
  39996. });
  39997. }
  39998. /**
  39999. * @alias module:echarts/component/helper/MapDraw
  40000. * @param {module:echarts/ExtensionAPI} api
  40001. * @param {boolean} updateGroup
  40002. */
  40003. function MapDraw(api, updateGroup) {
  40004. var group = new Group();
  40005. /**
  40006. * @type {string}
  40007. * @private
  40008. */
  40009. this.uid = getUID('ec_map_draw');
  40010. /**
  40011. * @type {module:echarts/component/helper/RoamController}
  40012. * @private
  40013. */
  40014. this._controller = new RoamController(api.getZr());
  40015. /**
  40016. * @type {Object} {target, zoom, zoomLimit}
  40017. * @private
  40018. */
  40019. this._controllerHost = {target: updateGroup ? group : null};
  40020. /**
  40021. * @type {module:zrender/container/Group}
  40022. * @readOnly
  40023. */
  40024. this.group = group;
  40025. /**
  40026. * @type {boolean}
  40027. * @private
  40028. */
  40029. this._updateGroup = updateGroup;
  40030. /**
  40031. * This flag is used to make sure that only one among
  40032. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  40033. * action may be triggered when `pan`, which is unexpected.
  40034. * @type {booelan}
  40035. */
  40036. this._mouseDownFlag;
  40037. /**
  40038. * @type {string}
  40039. */
  40040. this._mapName;
  40041. /**
  40042. * @type {boolean}
  40043. */
  40044. this._initialized;
  40045. /**
  40046. * @type {module:zrender/container/Group}
  40047. */
  40048. group.add(this._regionsGroup = new Group());
  40049. /**
  40050. * @type {module:zrender/container/Group}
  40051. */
  40052. group.add(this._backgroundGroup = new Group());
  40053. }
  40054. MapDraw.prototype = {
  40055. constructor: MapDraw,
  40056. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  40057. var isGeo = mapOrGeoModel.mainType === 'geo';
  40058. // Map series has data. GEO model that controlled by map series
  40059. // will be assigned with map data. Other GEO model has no data.
  40060. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  40061. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  40062. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  40063. data = mapSeries.getData();
  40064. }
  40065. });
  40066. var geo = mapOrGeoModel.coordinateSystem;
  40067. this._updateBackground(geo);
  40068. var regionsGroup = this._regionsGroup;
  40069. var group = this.group;
  40070. var scale = geo.scale;
  40071. var transform = {
  40072. position: geo.position,
  40073. scale: scale
  40074. };
  40075. // No animation when first draw or in action
  40076. if (!regionsGroup.childAt(0) || payload) {
  40077. group.attr(transform);
  40078. }
  40079. else {
  40080. updateProps(group, transform, mapOrGeoModel);
  40081. }
  40082. regionsGroup.removeAll();
  40083. var itemStyleAccessPath = ['itemStyle'];
  40084. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  40085. var labelAccessPath = ['label'];
  40086. var hoverLabelAccessPath = ['emphasis', 'label'];
  40087. var nameMap = createHashMap();
  40088. each$1(geo.regions, function (region) {
  40089. // Consider in GeoJson properties.name may be duplicated, for example,
  40090. // there is multiple region named "United Kindom" or "France" (so many
  40091. // colonies). And it is not appropriate to merge them in geo, which
  40092. // will make them share the same label and bring trouble in label
  40093. // location calculation.
  40094. var regionGroup = nameMap.get(region.name)
  40095. || nameMap.set(region.name, new Group());
  40096. var compoundPath = new CompoundPath({
  40097. shape: {
  40098. paths: []
  40099. }
  40100. });
  40101. regionGroup.add(compoundPath);
  40102. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  40103. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  40104. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  40105. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  40106. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  40107. var labelModel = regionModel.getModel(labelAccessPath);
  40108. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  40109. var dataIdx;
  40110. // Use the itemStyle in data if has data
  40111. if (data) {
  40112. dataIdx = data.indexOfName(region.name);
  40113. // Only visual color of each item will be used. It can be encoded by dataRange
  40114. // But visual color of series is used in symbol drawing
  40115. //
  40116. // Visual color for each series is for the symbol draw
  40117. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  40118. if (visualColor) {
  40119. itemStyle.fill = visualColor;
  40120. }
  40121. }
  40122. each$1(region.geometries, function (geometry) {
  40123. if (geometry.type !== 'polygon') {
  40124. return;
  40125. }
  40126. compoundPath.shape.paths.push(new Polygon({
  40127. shape: {
  40128. points: geometry.exterior
  40129. }
  40130. }));
  40131. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  40132. compoundPath.shape.paths.push(new Polygon({
  40133. shape: {
  40134. points: geometry.interiors[i]
  40135. }
  40136. }));
  40137. }
  40138. });
  40139. compoundPath.setStyle(itemStyle);
  40140. compoundPath.style.strokeNoScale = true;
  40141. compoundPath.culling = true;
  40142. // Label
  40143. var showLabel = labelModel.get('show');
  40144. var hoverShowLabel = hoverLabelModel.get('show');
  40145. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  40146. var itemLayout = data && data.getItemLayout(dataIdx);
  40147. // In the following cases label will be drawn
  40148. // 1. In map series and data value is NaN
  40149. // 2. In geo component
  40150. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  40151. if (
  40152. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  40153. || (itemLayout && itemLayout.showLabel)
  40154. ) {
  40155. var query = !isGeo ? dataIdx : region.name;
  40156. var labelFetcher;
  40157. // Consider dataIdx not found.
  40158. if (!data || dataIdx >= 0) {
  40159. labelFetcher = mapOrGeoModel;
  40160. }
  40161. var textEl = new Text({
  40162. position: region.center.slice(),
  40163. // FIXME
  40164. // label rotation is not support yet in geo or regions of series-map
  40165. // that has no data. The rotation will be effected by this `scale`.
  40166. // So needed to change to RectText?
  40167. scale: [1 / scale[0], 1 / scale[1]],
  40168. z2: 10,
  40169. silent: true
  40170. });
  40171. setLabelStyle(
  40172. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  40173. {
  40174. labelFetcher: labelFetcher,
  40175. labelDataIndex: query,
  40176. defaultText: region.name,
  40177. useInsideStyle: false
  40178. },
  40179. {
  40180. textAlign: 'center',
  40181. textVerticalAlign: 'middle'
  40182. }
  40183. );
  40184. regionGroup.add(textEl);
  40185. }
  40186. // setItemGraphicEl, setHoverStyle after all polygons and labels
  40187. // are added to the rigionGroup
  40188. if (data) {
  40189. data.setItemGraphicEl(dataIdx, regionGroup);
  40190. }
  40191. else {
  40192. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  40193. // Package custom mouse event for geo component
  40194. compoundPath.eventData = {
  40195. componentType: 'geo',
  40196. componentIndex: mapOrGeoModel.componentIndex,
  40197. geoIndex: mapOrGeoModel.componentIndex,
  40198. name: region.name,
  40199. region: (regionModel && regionModel.option) || {}
  40200. };
  40201. }
  40202. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  40203. groupRegions.push(region);
  40204. setHoverStyle(
  40205. regionGroup,
  40206. hoverItemStyle,
  40207. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  40208. );
  40209. regionsGroup.add(regionGroup);
  40210. });
  40211. this._updateController(mapOrGeoModel, ecModel, api);
  40212. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  40213. updateMapSelected(mapOrGeoModel, regionsGroup);
  40214. },
  40215. remove: function () {
  40216. this._regionsGroup.removeAll();
  40217. this._backgroundGroup.removeAll();
  40218. this._controller.dispose();
  40219. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  40220. this._mapName = null;
  40221. this._controllerHost = {};
  40222. },
  40223. _updateBackground: function (geo) {
  40224. var mapName = geo.map;
  40225. if (this._mapName !== mapName) {
  40226. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  40227. this._backgroundGroup.add(root);
  40228. }, this);
  40229. }
  40230. this._mapName = mapName;
  40231. },
  40232. _updateController: function (mapOrGeoModel, ecModel, api) {
  40233. var geo = mapOrGeoModel.coordinateSystem;
  40234. var controller = this._controller;
  40235. var controllerHost = this._controllerHost;
  40236. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  40237. controllerHost.zoom = geo.getZoom();
  40238. // roamType is will be set default true if it is null
  40239. controller.enable(mapOrGeoModel.get('roam') || false);
  40240. var mainType = mapOrGeoModel.mainType;
  40241. function makeActionBase() {
  40242. var action = {
  40243. type: 'geoRoam',
  40244. componentType: mainType
  40245. };
  40246. action[mainType + 'Id'] = mapOrGeoModel.id;
  40247. return action;
  40248. }
  40249. controller.off('pan').on('pan', function (e) {
  40250. this._mouseDownFlag = false;
  40251. updateViewOnPan(controllerHost, e.dx, e.dy);
  40252. api.dispatchAction(extend(makeActionBase(), {
  40253. dx: e.dx,
  40254. dy: e.dy
  40255. }));
  40256. }, this);
  40257. controller.off('zoom').on('zoom', function (e) {
  40258. this._mouseDownFlag = false;
  40259. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  40260. api.dispatchAction(extend(makeActionBase(), {
  40261. zoom: e.scale,
  40262. originX: e.originX,
  40263. originY: e.originY
  40264. }));
  40265. if (this._updateGroup) {
  40266. var scale = this.group.scale;
  40267. this._regionsGroup.traverse(function (el) {
  40268. if (el.type === 'text') {
  40269. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  40270. }
  40271. });
  40272. }
  40273. }, this);
  40274. controller.setPointerChecker(function (e, x, y) {
  40275. return geo.getViewRectAfterRoam().contain(x, y)
  40276. && !onIrrelevantElement(e, api, mapOrGeoModel);
  40277. });
  40278. }
  40279. };
  40280. /*
  40281. * Licensed to the Apache Software Foundation (ASF) under one
  40282. * or more contributor license agreements. See the NOTICE file
  40283. * distributed with this work for additional information
  40284. * regarding copyright ownership. The ASF licenses this file
  40285. * to you under the Apache License, Version 2.0 (the
  40286. * "License"); you may not use this file except in compliance
  40287. * with the License. You may obtain a copy of the License at
  40288. *
  40289. * http://www.apache.org/licenses/LICENSE-2.0
  40290. *
  40291. * Unless required by applicable law or agreed to in writing,
  40292. * software distributed under the License is distributed on an
  40293. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40294. * KIND, either express or implied. See the License for the
  40295. * specific language governing permissions and limitations
  40296. * under the License.
  40297. */
  40298. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  40299. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  40300. extendChartView({
  40301. type: 'map',
  40302. render: function (mapModel, ecModel, api, payload) {
  40303. // Not render if it is an toggleSelect action from self
  40304. if (payload && payload.type === 'mapToggleSelect'
  40305. && payload.from === this.uid
  40306. ) {
  40307. return;
  40308. }
  40309. var group = this.group;
  40310. group.removeAll();
  40311. if (mapModel.getHostGeoModel()) {
  40312. return;
  40313. }
  40314. // Not update map if it is an roam action from self
  40315. if (!(payload && payload.type === 'geoRoam'
  40316. && payload.componentType === 'series'
  40317. && payload.seriesId === mapModel.id
  40318. )
  40319. ) {
  40320. if (mapModel.needsDrawMap) {
  40321. var mapDraw = this._mapDraw || new MapDraw(api, true);
  40322. group.add(mapDraw.group);
  40323. mapDraw.draw(mapModel, ecModel, api, this, payload);
  40324. this._mapDraw = mapDraw;
  40325. }
  40326. else {
  40327. // Remove drawed map
  40328. this._mapDraw && this._mapDraw.remove();
  40329. this._mapDraw = null;
  40330. }
  40331. }
  40332. else {
  40333. var mapDraw = this._mapDraw;
  40334. mapDraw && group.add(mapDraw.group);
  40335. }
  40336. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  40337. && this._renderSymbols(mapModel, ecModel, api);
  40338. },
  40339. remove: function () {
  40340. this._mapDraw && this._mapDraw.remove();
  40341. this._mapDraw = null;
  40342. this.group.removeAll();
  40343. },
  40344. dispose: function () {
  40345. this._mapDraw && this._mapDraw.remove();
  40346. this._mapDraw = null;
  40347. },
  40348. _renderSymbols: function (mapModel, ecModel, api) {
  40349. var originalData = mapModel.originalData;
  40350. var group = this.group;
  40351. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  40352. if (isNaN(value)) {
  40353. return;
  40354. }
  40355. var layout = originalData.getItemLayout(originalDataIndex);
  40356. if (!layout || !layout.point) {
  40357. // Not exists in map
  40358. return;
  40359. }
  40360. var point = layout.point;
  40361. var offset = layout.offset;
  40362. var circle = new Circle({
  40363. style: {
  40364. // Because the special of map draw.
  40365. // Which needs statistic of multiple series and draw on one map.
  40366. // And each series also need a symbol with legend color
  40367. //
  40368. // Layout and visual are put one the different data
  40369. fill: mapModel.getData().getVisual('color')
  40370. },
  40371. shape: {
  40372. cx: point[0] + offset * 9,
  40373. cy: point[1],
  40374. r: 3
  40375. },
  40376. silent: true,
  40377. // Do not overlap the first series, on which labels are displayed.
  40378. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  40379. });
  40380. // Only the series that has the first value on the same region is in charge of rendering the label.
  40381. // But consider the case:
  40382. // series: [
  40383. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  40384. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  40385. // ]
  40386. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  40387. // For backward compatibility, we follow the rule that render label `A` by the
  40388. // settings on series `X` but render label `C` by the settings on series `Y`.
  40389. if (!offset) {
  40390. var fullData = mapModel.mainSeries.getData();
  40391. var name = originalData.getName(originalDataIndex);
  40392. var fullIndex = fullData.indexOfName(name);
  40393. var itemModel = originalData.getItemModel(originalDataIndex);
  40394. var labelModel = itemModel.getModel('label');
  40395. var hoverLabelModel = itemModel.getModel('emphasis.label');
  40396. var regionGroup = fullData.getItemGraphicEl(fullIndex);
  40397. // `getFormattedLabel` needs to use `getData` inside. Here
  40398. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  40399. // FIXME
  40400. // If this is not the `mainSeries`, the item model (like label formatter)
  40401. // set on original data item will never get. But it has been working
  40402. // like that from the begining, and this scenario is rarely encountered.
  40403. // So it won't be fixed until have to.
  40404. var normalText = retrieve2(
  40405. mapModel.getFormattedLabel(fullIndex, 'normal'),
  40406. name
  40407. );
  40408. var emphasisText = retrieve2(
  40409. mapModel.getFormattedLabel(fullIndex, 'emphasis'),
  40410. normalText
  40411. );
  40412. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  40413. var recordVersion = Math.random();
  40414. // Prevent from register listeners duplicatedly when roaming.
  40415. if (!highDownRecord) {
  40416. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  40417. var onEmphasis = curry(onRegionHighDown, true);
  40418. var onNormal = curry(onRegionHighDown, false);
  40419. regionGroup.on('mouseover', onEmphasis)
  40420. .on('mouseout', onNormal)
  40421. .on('emphasis', onEmphasis)
  40422. .on('normal', onNormal);
  40423. }
  40424. // Prevent removed regions effect current grapics.
  40425. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  40426. extend(highDownRecord, {
  40427. recordVersion: recordVersion,
  40428. circle: circle,
  40429. labelModel: labelModel,
  40430. hoverLabelModel: hoverLabelModel,
  40431. emphasisText: emphasisText,
  40432. normalText: normalText
  40433. });
  40434. // FIXME
  40435. // Consider set option when emphasis.
  40436. enterRegionHighDown(highDownRecord, false);
  40437. }
  40438. group.add(circle);
  40439. });
  40440. }
  40441. });
  40442. function onRegionHighDown(toHighOrDown) {
  40443. var highDownRecord = this[HIGH_DOWN_PROP];
  40444. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  40445. enterRegionHighDown(highDownRecord, toHighOrDown);
  40446. }
  40447. }
  40448. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  40449. var circle = highDownRecord.circle;
  40450. var labelModel = highDownRecord.labelModel;
  40451. var hoverLabelModel = highDownRecord.hoverLabelModel;
  40452. var emphasisText = highDownRecord.emphasisText;
  40453. var normalText = highDownRecord.normalText;
  40454. if (toHighOrDown) {
  40455. circle.style.extendFrom(
  40456. setTextStyle({}, hoverLabelModel, {
  40457. text: hoverLabelModel.get('show') ? emphasisText : null
  40458. }, {isRectText: true, useInsideStyle: false}, true)
  40459. );
  40460. // Make label upper than others if overlaps.
  40461. circle.__mapOriginalZ2 = circle.z2;
  40462. circle.z2 += Z2_EMPHASIS_LIFT;
  40463. }
  40464. else {
  40465. setTextStyle(circle.style, labelModel, {
  40466. text: labelModel.get('show') ? normalText : null,
  40467. textPosition: labelModel.getShallow('position') || 'bottom'
  40468. }, {isRectText: true, useInsideStyle: false});
  40469. // Trigger normalize style like padding.
  40470. circle.dirty(false);
  40471. if (circle.__mapOriginalZ2 != null) {
  40472. circle.z2 = circle.__mapOriginalZ2;
  40473. circle.__mapOriginalZ2 = null;
  40474. }
  40475. }
  40476. }
  40477. /*
  40478. * Licensed to the Apache Software Foundation (ASF) under one
  40479. * or more contributor license agreements. See the NOTICE file
  40480. * distributed with this work for additional information
  40481. * regarding copyright ownership. The ASF licenses this file
  40482. * to you under the Apache License, Version 2.0 (the
  40483. * "License"); you may not use this file except in compliance
  40484. * with the License. You may obtain a copy of the License at
  40485. *
  40486. * http://www.apache.org/licenses/LICENSE-2.0
  40487. *
  40488. * Unless required by applicable law or agreed to in writing,
  40489. * software distributed under the License is distributed on an
  40490. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40491. * KIND, either express or implied. See the License for the
  40492. * specific language governing permissions and limitations
  40493. * under the License.
  40494. */
  40495. /**
  40496. * @param {module:echarts/coord/View} view
  40497. * @param {Object} payload
  40498. * @param {Object} [zoomLimit]
  40499. */
  40500. function updateCenterAndZoom(
  40501. view, payload, zoomLimit
  40502. ) {
  40503. var previousZoom = view.getZoom();
  40504. var center = view.getCenter();
  40505. var zoom = payload.zoom;
  40506. var point = view.dataToPoint(center);
  40507. if (payload.dx != null && payload.dy != null) {
  40508. point[0] -= payload.dx;
  40509. point[1] -= payload.dy;
  40510. var center = view.pointToData(point);
  40511. view.setCenter(center);
  40512. }
  40513. if (zoom != null) {
  40514. if (zoomLimit) {
  40515. var zoomMin = zoomLimit.min || 0;
  40516. var zoomMax = zoomLimit.max || Infinity;
  40517. zoom = Math.max(
  40518. Math.min(previousZoom * zoom, zoomMax),
  40519. zoomMin
  40520. ) / previousZoom;
  40521. }
  40522. // Zoom on given point(originX, originY)
  40523. view.scale[0] *= zoom;
  40524. view.scale[1] *= zoom;
  40525. var position = view.position;
  40526. var fixX = (payload.originX - position[0]) * (zoom - 1);
  40527. var fixY = (payload.originY - position[1]) * (zoom - 1);
  40528. position[0] -= fixX;
  40529. position[1] -= fixY;
  40530. view.updateTransform();
  40531. // Get the new center
  40532. var center = view.pointToData(point);
  40533. view.setCenter(center);
  40534. view.setZoom(zoom * previousZoom);
  40535. }
  40536. return {
  40537. center: view.getCenter(),
  40538. zoom: view.getZoom()
  40539. };
  40540. }
  40541. /*
  40542. * Licensed to the Apache Software Foundation (ASF) under one
  40543. * or more contributor license agreements. See the NOTICE file
  40544. * distributed with this work for additional information
  40545. * regarding copyright ownership. The ASF licenses this file
  40546. * to you under the Apache License, Version 2.0 (the
  40547. * "License"); you may not use this file except in compliance
  40548. * with the License. You may obtain a copy of the License at
  40549. *
  40550. * http://www.apache.org/licenses/LICENSE-2.0
  40551. *
  40552. * Unless required by applicable law or agreed to in writing,
  40553. * software distributed under the License is distributed on an
  40554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40555. * KIND, either express or implied. See the License for the
  40556. * specific language governing permissions and limitations
  40557. * under the License.
  40558. */
  40559. /**
  40560. * @payload
  40561. * @property {string} [componentType=series]
  40562. * @property {number} [dx]
  40563. * @property {number} [dy]
  40564. * @property {number} [zoom]
  40565. * @property {number} [originX]
  40566. * @property {number} [originY]
  40567. */
  40568. registerAction({
  40569. type: 'geoRoam',
  40570. event: 'geoRoam',
  40571. update: 'updateTransform'
  40572. }, function (payload, ecModel) {
  40573. var componentType = payload.componentType || 'series';
  40574. ecModel.eachComponent(
  40575. { mainType: componentType, query: payload },
  40576. function (componentModel) {
  40577. var geo = componentModel.coordinateSystem;
  40578. if (geo.type !== 'geo') {
  40579. return;
  40580. }
  40581. var res = updateCenterAndZoom(
  40582. geo, payload, componentModel.get('scaleLimit')
  40583. );
  40584. componentModel.setCenter
  40585. && componentModel.setCenter(res.center);
  40586. componentModel.setZoom
  40587. && componentModel.setZoom(res.zoom);
  40588. // All map series with same `map` use the same geo coordinate system
  40589. // So the center and zoom must be in sync. Include the series not selected by legend
  40590. if (componentType === 'series') {
  40591. each$1(componentModel.seriesGroup, function (seriesModel) {
  40592. seriesModel.setCenter(res.center);
  40593. seriesModel.setZoom(res.zoom);
  40594. });
  40595. }
  40596. }
  40597. );
  40598. });
  40599. /*
  40600. * Licensed to the Apache Software Foundation (ASF) under one
  40601. * or more contributor license agreements. See the NOTICE file
  40602. * distributed with this work for additional information
  40603. * regarding copyright ownership. The ASF licenses this file
  40604. * to you under the Apache License, Version 2.0 (the
  40605. * "License"); you may not use this file except in compliance
  40606. * with the License. You may obtain a copy of the License at
  40607. *
  40608. * http://www.apache.org/licenses/LICENSE-2.0
  40609. *
  40610. * Unless required by applicable law or agreed to in writing,
  40611. * software distributed under the License is distributed on an
  40612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40613. * KIND, either express or implied. See the License for the
  40614. * specific language governing permissions and limitations
  40615. * under the License.
  40616. */
  40617. /**
  40618. * Simple view coordinate system
  40619. * Mapping given x, y to transformd view x, y
  40620. */
  40621. var v2ApplyTransform$1 = applyTransform;
  40622. // Dummy transform node
  40623. function TransformDummy() {
  40624. Transformable.call(this);
  40625. }
  40626. mixin(TransformDummy, Transformable);
  40627. function View(name) {
  40628. /**
  40629. * @type {string}
  40630. */
  40631. this.name = name;
  40632. /**
  40633. * @type {Object}
  40634. */
  40635. this.zoomLimit;
  40636. Transformable.call(this);
  40637. this._roamTransformable = new TransformDummy();
  40638. this._rawTransformable = new TransformDummy();
  40639. this._center;
  40640. this._zoom;
  40641. }
  40642. View.prototype = {
  40643. constructor: View,
  40644. type: 'view',
  40645. /**
  40646. * @param {Array.<string>}
  40647. * @readOnly
  40648. */
  40649. dimensions: ['x', 'y'],
  40650. /**
  40651. * Set bounding rect
  40652. * @param {number} x
  40653. * @param {number} y
  40654. * @param {number} width
  40655. * @param {number} height
  40656. */
  40657. // PENDING to getRect
  40658. setBoundingRect: function (x, y, width, height) {
  40659. this._rect = new BoundingRect(x, y, width, height);
  40660. return this._rect;
  40661. },
  40662. /**
  40663. * @return {module:zrender/core/BoundingRect}
  40664. */
  40665. // PENDING to getRect
  40666. getBoundingRect: function () {
  40667. return this._rect;
  40668. },
  40669. /**
  40670. * @param {number} x
  40671. * @param {number} y
  40672. * @param {number} width
  40673. * @param {number} height
  40674. */
  40675. setViewRect: function (x, y, width, height) {
  40676. this.transformTo(x, y, width, height);
  40677. this._viewRect = new BoundingRect(x, y, width, height);
  40678. },
  40679. /**
  40680. * Transformed to particular position and size
  40681. * @param {number} x
  40682. * @param {number} y
  40683. * @param {number} width
  40684. * @param {number} height
  40685. */
  40686. transformTo: function (x, y, width, height) {
  40687. var rect = this.getBoundingRect();
  40688. var rawTransform = this._rawTransformable;
  40689. rawTransform.transform = rect.calculateTransform(
  40690. new BoundingRect(x, y, width, height)
  40691. );
  40692. rawTransform.decomposeTransform();
  40693. this._updateTransform();
  40694. },
  40695. /**
  40696. * Set center of view
  40697. * @param {Array.<number>} [centerCoord]
  40698. */
  40699. setCenter: function (centerCoord) {
  40700. if (!centerCoord) {
  40701. return;
  40702. }
  40703. this._center = centerCoord;
  40704. this._updateCenterAndZoom();
  40705. },
  40706. /**
  40707. * @param {number} zoom
  40708. */
  40709. setZoom: function (zoom) {
  40710. zoom = zoom || 1;
  40711. var zoomLimit = this.zoomLimit;
  40712. if (zoomLimit) {
  40713. if (zoomLimit.max != null) {
  40714. zoom = Math.min(zoomLimit.max, zoom);
  40715. }
  40716. if (zoomLimit.min != null) {
  40717. zoom = Math.max(zoomLimit.min, zoom);
  40718. }
  40719. }
  40720. this._zoom = zoom;
  40721. this._updateCenterAndZoom();
  40722. },
  40723. /**
  40724. * Get default center without roam
  40725. */
  40726. getDefaultCenter: function () {
  40727. // Rect before any transform
  40728. var rawRect = this.getBoundingRect();
  40729. var cx = rawRect.x + rawRect.width / 2;
  40730. var cy = rawRect.y + rawRect.height / 2;
  40731. return [cx, cy];
  40732. },
  40733. getCenter: function () {
  40734. return this._center || this.getDefaultCenter();
  40735. },
  40736. getZoom: function () {
  40737. return this._zoom || 1;
  40738. },
  40739. /**
  40740. * @return {Array.<number}
  40741. */
  40742. getRoamTransform: function () {
  40743. return this._roamTransformable.getLocalTransform();
  40744. },
  40745. /**
  40746. * Remove roam
  40747. */
  40748. _updateCenterAndZoom: function () {
  40749. // Must update after view transform updated
  40750. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  40751. var roamTransform = this._roamTransformable;
  40752. var defaultCenter = this.getDefaultCenter();
  40753. var center = this.getCenter();
  40754. var zoom = this.getZoom();
  40755. center = applyTransform([], center, rawTransformMatrix);
  40756. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  40757. roamTransform.origin = center;
  40758. roamTransform.position = [
  40759. defaultCenter[0] - center[0],
  40760. defaultCenter[1] - center[1]
  40761. ];
  40762. roamTransform.scale = [zoom, zoom];
  40763. this._updateTransform();
  40764. },
  40765. /**
  40766. * Update transform from roam and mapLocation
  40767. * @private
  40768. */
  40769. _updateTransform: function () {
  40770. var roamTransformable = this._roamTransformable;
  40771. var rawTransformable = this._rawTransformable;
  40772. rawTransformable.parent = roamTransformable;
  40773. roamTransformable.updateTransform();
  40774. rawTransformable.updateTransform();
  40775. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  40776. this._rawTransform = rawTransformable.getLocalTransform();
  40777. this.invTransform = this.invTransform || [];
  40778. invert(this.invTransform, this.transform);
  40779. this.decomposeTransform();
  40780. },
  40781. /**
  40782. * @return {module:zrender/core/BoundingRect}
  40783. */
  40784. getViewRect: function () {
  40785. return this._viewRect;
  40786. },
  40787. /**
  40788. * Get view rect after roam transform
  40789. * @return {module:zrender/core/BoundingRect}
  40790. */
  40791. getViewRectAfterRoam: function () {
  40792. var rect = this.getBoundingRect().clone();
  40793. rect.applyTransform(this.transform);
  40794. return rect;
  40795. },
  40796. /**
  40797. * Convert a single (lon, lat) data item to (x, y) point.
  40798. * @param {Array.<number>} data
  40799. * @param {boolean} noRoam
  40800. * @param {Array.<number>} [out]
  40801. * @return {Array.<number>}
  40802. */
  40803. dataToPoint: function (data, noRoam, out) {
  40804. var transform = noRoam ? this._rawTransform : this.transform;
  40805. out = out || [];
  40806. return transform
  40807. ? v2ApplyTransform$1(out, data, transform)
  40808. : copy(out, data);
  40809. },
  40810. /**
  40811. * Convert a (x, y) point to (lon, lat) data
  40812. * @param {Array.<number>} point
  40813. * @return {Array.<number>}
  40814. */
  40815. pointToData: function (point) {
  40816. var invTransform = this.invTransform;
  40817. return invTransform
  40818. ? v2ApplyTransform$1([], point, invTransform)
  40819. : [point[0], point[1]];
  40820. },
  40821. /**
  40822. * @implements
  40823. * see {module:echarts/CoodinateSystem}
  40824. */
  40825. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  40826. /**
  40827. * @implements
  40828. * see {module:echarts/CoodinateSystem}
  40829. */
  40830. convertFromPixel: curry(doConvert$1, 'pointToData'),
  40831. /**
  40832. * @implements
  40833. * see {module:echarts/CoodinateSystem}
  40834. */
  40835. containPoint: function (point) {
  40836. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  40837. }
  40838. /**
  40839. * @return {number}
  40840. */
  40841. // getScalarScale: function () {
  40842. // // Use determinant square root of transform to mutiply scalar
  40843. // var m = this.transform;
  40844. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  40845. // return det;
  40846. // }
  40847. };
  40848. mixin(View, Transformable);
  40849. function doConvert$1(methodName, ecModel, finder, value) {
  40850. var seriesModel = finder.seriesModel;
  40851. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  40852. return coordSys === this ? coordSys[methodName](value) : null;
  40853. }
  40854. /*
  40855. * Licensed to the Apache Software Foundation (ASF) under one
  40856. * or more contributor license agreements. See the NOTICE file
  40857. * distributed with this work for additional information
  40858. * regarding copyright ownership. The ASF licenses this file
  40859. * to you under the Apache License, Version 2.0 (the
  40860. * "License"); you may not use this file except in compliance
  40861. * with the License. You may obtain a copy of the License at
  40862. *
  40863. * http://www.apache.org/licenses/LICENSE-2.0
  40864. *
  40865. * Unless required by applicable law or agreed to in writing,
  40866. * software distributed under the License is distributed on an
  40867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40868. * KIND, either express or implied. See the License for the
  40869. * specific language governing permissions and limitations
  40870. * under the License.
  40871. */
  40872. /**
  40873. * [Geo description]
  40874. * For backward compatibility, the orginal interface:
  40875. * `name, map, geoJson, specialAreas, nameMap` is kept.
  40876. *
  40877. * @param {string|Object} name
  40878. * @param {string} map Map type
  40879. * Specify the positioned areas by left, top, width, height
  40880. * @param {Object.<string, string>} [nameMap]
  40881. * Specify name alias
  40882. * @param {boolean} [invertLongitute=true]
  40883. */
  40884. function Geo(name, map$$1, nameMap, invertLongitute) {
  40885. View.call(this, name);
  40886. /**
  40887. * Map type
  40888. * @type {string}
  40889. */
  40890. this.map = map$$1;
  40891. var source = geoSourceManager.load(map$$1, nameMap);
  40892. this._nameCoordMap = source.nameCoordMap;
  40893. this._regionsMap = source.regionsMap;
  40894. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  40895. /**
  40896. * @readOnly
  40897. */
  40898. this.regions = source.regions;
  40899. /**
  40900. * @type {module:zrender/src/core/BoundingRect}
  40901. */
  40902. this._rect = source.boundingRect;
  40903. }
  40904. Geo.prototype = {
  40905. constructor: Geo,
  40906. type: 'geo',
  40907. /**
  40908. * @param {Array.<string>}
  40909. * @readOnly
  40910. */
  40911. dimensions: ['lng', 'lat'],
  40912. /**
  40913. * If contain given lng,lat coord
  40914. * @param {Array.<number>}
  40915. * @readOnly
  40916. */
  40917. containCoord: function (coord) {
  40918. var regions = this.regions;
  40919. for (var i = 0; i < regions.length; i++) {
  40920. if (regions[i].contain(coord)) {
  40921. return true;
  40922. }
  40923. }
  40924. return false;
  40925. },
  40926. /**
  40927. * @override
  40928. */
  40929. transformTo: function (x, y, width, height) {
  40930. var rect = this.getBoundingRect();
  40931. var invertLongitute = this._invertLongitute;
  40932. rect = rect.clone();
  40933. if (invertLongitute) {
  40934. // Longitute is inverted
  40935. rect.y = -rect.y - rect.height;
  40936. }
  40937. var rawTransformable = this._rawTransformable;
  40938. rawTransformable.transform = rect.calculateTransform(
  40939. new BoundingRect(x, y, width, height)
  40940. );
  40941. rawTransformable.decomposeTransform();
  40942. if (invertLongitute) {
  40943. var scale = rawTransformable.scale;
  40944. scale[1] = -scale[1];
  40945. }
  40946. rawTransformable.updateTransform();
  40947. this._updateTransform();
  40948. },
  40949. /**
  40950. * @param {string} name
  40951. * @return {module:echarts/coord/geo/Region}
  40952. */
  40953. getRegion: function (name) {
  40954. return this._regionsMap.get(name);
  40955. },
  40956. getRegionByCoord: function (coord) {
  40957. var regions = this.regions;
  40958. for (var i = 0; i < regions.length; i++) {
  40959. if (regions[i].contain(coord)) {
  40960. return regions[i];
  40961. }
  40962. }
  40963. },
  40964. /**
  40965. * Add geoCoord for indexing by name
  40966. * @param {string} name
  40967. * @param {Array.<number>} geoCoord
  40968. */
  40969. addGeoCoord: function (name, geoCoord) {
  40970. this._nameCoordMap.set(name, geoCoord);
  40971. },
  40972. /**
  40973. * Get geoCoord by name
  40974. * @param {string} name
  40975. * @return {Array.<number>}
  40976. */
  40977. getGeoCoord: function (name) {
  40978. return this._nameCoordMap.get(name);
  40979. },
  40980. /**
  40981. * @override
  40982. */
  40983. getBoundingRect: function () {
  40984. return this._rect;
  40985. },
  40986. /**
  40987. * @param {string|Array.<number>} data
  40988. * @param {boolean} noRoam
  40989. * @param {Array.<number>} [out]
  40990. * @return {Array.<number>}
  40991. */
  40992. dataToPoint: function (data, noRoam, out) {
  40993. if (typeof data === 'string') {
  40994. // Map area name to geoCoord
  40995. data = this.getGeoCoord(data);
  40996. }
  40997. if (data) {
  40998. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  40999. }
  41000. },
  41001. /**
  41002. * @override
  41003. */
  41004. convertToPixel: curry(doConvert, 'dataToPoint'),
  41005. /**
  41006. * @override
  41007. */
  41008. convertFromPixel: curry(doConvert, 'pointToData')
  41009. };
  41010. mixin(Geo, View);
  41011. function doConvert(methodName, ecModel, finder, value) {
  41012. var geoModel = finder.geoModel;
  41013. var seriesModel = finder.seriesModel;
  41014. var coordSys = geoModel
  41015. ? geoModel.coordinateSystem
  41016. : seriesModel
  41017. ? (
  41018. seriesModel.coordinateSystem // For map.
  41019. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  41020. )
  41021. : null;
  41022. return coordSys === this ? coordSys[methodName](value) : null;
  41023. }
  41024. /*
  41025. * Licensed to the Apache Software Foundation (ASF) under one
  41026. * or more contributor license agreements. See the NOTICE file
  41027. * distributed with this work for additional information
  41028. * regarding copyright ownership. The ASF licenses this file
  41029. * to you under the Apache License, Version 2.0 (the
  41030. * "License"); you may not use this file except in compliance
  41031. * with the License. You may obtain a copy of the License at
  41032. *
  41033. * http://www.apache.org/licenses/LICENSE-2.0
  41034. *
  41035. * Unless required by applicable law or agreed to in writing,
  41036. * software distributed under the License is distributed on an
  41037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41038. * KIND, either express or implied. See the License for the
  41039. * specific language governing permissions and limitations
  41040. * under the License.
  41041. */
  41042. /**
  41043. * Resize method bound to the geo
  41044. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  41045. * @param {module:echarts/ExtensionAPI} api
  41046. */
  41047. function resizeGeo(geoModel, api) {
  41048. var boundingCoords = geoModel.get('boundingCoords');
  41049. if (boundingCoords != null) {
  41050. var leftTop = boundingCoords[0];
  41051. var rightBottom = boundingCoords[1];
  41052. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  41053. if (__DEV__) {
  41054. console.error('Invalid boundingCoords');
  41055. }
  41056. }
  41057. else {
  41058. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  41059. }
  41060. }
  41061. var rect = this.getBoundingRect();
  41062. var boxLayoutOption;
  41063. var center = geoModel.get('layoutCenter');
  41064. var size = geoModel.get('layoutSize');
  41065. var viewWidth = api.getWidth();
  41066. var viewHeight = api.getHeight();
  41067. var aspect = rect.width / rect.height * this.aspectScale;
  41068. var useCenterAndSize = false;
  41069. if (center && size) {
  41070. center = [
  41071. parsePercent$1(center[0], viewWidth),
  41072. parsePercent$1(center[1], viewHeight)
  41073. ];
  41074. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  41075. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  41076. useCenterAndSize = true;
  41077. }
  41078. else {
  41079. if (__DEV__) {
  41080. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  41081. }
  41082. }
  41083. }
  41084. var viewRect;
  41085. if (useCenterAndSize) {
  41086. var viewRect = {};
  41087. if (aspect > 1) {
  41088. // Width is same with size
  41089. viewRect.width = size;
  41090. viewRect.height = size / aspect;
  41091. }
  41092. else {
  41093. viewRect.height = size;
  41094. viewRect.width = size * aspect;
  41095. }
  41096. viewRect.y = center[1] - viewRect.height / 2;
  41097. viewRect.x = center[0] - viewRect.width / 2;
  41098. }
  41099. else {
  41100. // Use left/top/width/height
  41101. boxLayoutOption = geoModel.getBoxLayoutParams();
  41102. // 0.75 rate
  41103. boxLayoutOption.aspect = aspect;
  41104. viewRect = getLayoutRect(boxLayoutOption, {
  41105. width: viewWidth,
  41106. height: viewHeight
  41107. });
  41108. }
  41109. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  41110. this.setCenter(geoModel.get('center'));
  41111. this.setZoom(geoModel.get('zoom'));
  41112. }
  41113. /**
  41114. * @param {module:echarts/coord/Geo} geo
  41115. * @param {module:echarts/model/Model} model
  41116. * @inner
  41117. */
  41118. function setGeoCoords(geo, model) {
  41119. each$1(model.get('geoCoord'), function (geoCoord, name) {
  41120. geo.addGeoCoord(name, geoCoord);
  41121. });
  41122. }
  41123. var geoCreator = {
  41124. // For deciding which dimensions to use when creating list data
  41125. dimensions: Geo.prototype.dimensions,
  41126. create: function (ecModel, api) {
  41127. var geoList = [];
  41128. // FIXME Create each time may be slow
  41129. ecModel.eachComponent('geo', function (geoModel, idx) {
  41130. var name = geoModel.get('map');
  41131. var aspectScale = geoModel.get('aspectScale');
  41132. var invertLongitute = true;
  41133. var mapRecords = mapDataStorage.retrieveMap(name);
  41134. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  41135. aspectScale == null && (aspectScale = 1);
  41136. invertLongitute = false;
  41137. }
  41138. else {
  41139. aspectScale == null && (aspectScale = 0.75);
  41140. }
  41141. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  41142. geo.aspectScale = aspectScale;
  41143. geo.zoomLimit = geoModel.get('scaleLimit');
  41144. geoList.push(geo);
  41145. setGeoCoords(geo, geoModel);
  41146. geoModel.coordinateSystem = geo;
  41147. geo.model = geoModel;
  41148. // Inject resize method
  41149. geo.resize = resizeGeo;
  41150. geo.resize(geoModel, api);
  41151. });
  41152. ecModel.eachSeries(function (seriesModel) {
  41153. var coordSys = seriesModel.get('coordinateSystem');
  41154. if (coordSys === 'geo') {
  41155. var geoIndex = seriesModel.get('geoIndex') || 0;
  41156. seriesModel.coordinateSystem = geoList[geoIndex];
  41157. }
  41158. });
  41159. // If has map series
  41160. var mapModelGroupBySeries = {};
  41161. ecModel.eachSeriesByType('map', function (seriesModel) {
  41162. if (!seriesModel.getHostGeoModel()) {
  41163. var mapType = seriesModel.getMapType();
  41164. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  41165. mapModelGroupBySeries[mapType].push(seriesModel);
  41166. }
  41167. });
  41168. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  41169. var nameMapList = map(mapSeries, function (singleMapSeries) {
  41170. return singleMapSeries.get('nameMap');
  41171. });
  41172. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  41173. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  41174. return singleMapSeries.get('scaleLimit');
  41175. }));
  41176. geoList.push(geo);
  41177. // Inject resize method
  41178. geo.resize = resizeGeo;
  41179. geo.aspectScale = mapSeries[0].get('aspectScale');
  41180. geo.resize(mapSeries[0], api);
  41181. each$1(mapSeries, function (singleMapSeries) {
  41182. singleMapSeries.coordinateSystem = geo;
  41183. setGeoCoords(geo, singleMapSeries);
  41184. });
  41185. });
  41186. return geoList;
  41187. },
  41188. /**
  41189. * Fill given regions array
  41190. * @param {Array.<Object>} originRegionArr
  41191. * @param {string} mapName
  41192. * @param {Object} [nameMap]
  41193. * @return {Array}
  41194. */
  41195. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  41196. // Not use the original
  41197. var regionsArr = (originRegionArr || []).slice();
  41198. var dataNameMap = createHashMap();
  41199. for (var i = 0; i < regionsArr.length; i++) {
  41200. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  41201. }
  41202. var source = geoSourceManager.load(mapName, nameMap);
  41203. each$1(source.regions, function (region) {
  41204. var name = region.name;
  41205. !dataNameMap.get(name) && regionsArr.push({name: name});
  41206. });
  41207. return regionsArr;
  41208. }
  41209. };
  41210. registerCoordinateSystem('geo', geoCreator);
  41211. /*
  41212. * Licensed to the Apache Software Foundation (ASF) under one
  41213. * or more contributor license agreements. See the NOTICE file
  41214. * distributed with this work for additional information
  41215. * regarding copyright ownership. The ASF licenses this file
  41216. * to you under the Apache License, Version 2.0 (the
  41217. * "License"); you may not use this file except in compliance
  41218. * with the License. You may obtain a copy of the License at
  41219. *
  41220. * http://www.apache.org/licenses/LICENSE-2.0
  41221. *
  41222. * Unless required by applicable law or agreed to in writing,
  41223. * software distributed under the License is distributed on an
  41224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41225. * KIND, either express or implied. See the License for the
  41226. * specific language governing permissions and limitations
  41227. * under the License.
  41228. */
  41229. var mapSymbolLayout = function (ecModel) {
  41230. var processedMapType = {};
  41231. ecModel.eachSeriesByType('map', function (mapSeries) {
  41232. var mapType = mapSeries.getMapType();
  41233. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  41234. return;
  41235. }
  41236. var mapSymbolOffsets = {};
  41237. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  41238. var geo = subMapSeries.coordinateSystem;
  41239. var data = subMapSeries.originalData;
  41240. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  41241. data.each(data.mapDimension('value'), function (value, idx) {
  41242. var name = data.getName(idx);
  41243. var region = geo.getRegion(name);
  41244. // If input series.data is [11, 22, '-'/null/undefined, 44],
  41245. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  41246. // not be drawn. So here must validate if value is NaN.
  41247. if (!region || isNaN(value)) {
  41248. return;
  41249. }
  41250. var offset = mapSymbolOffsets[name] || 0;
  41251. var point = geo.dataToPoint(region.center);
  41252. mapSymbolOffsets[name] = offset + 1;
  41253. data.setItemLayout(idx, {
  41254. point: point,
  41255. offset: offset
  41256. });
  41257. });
  41258. }
  41259. });
  41260. // Show label of those region not has legendSymbol(which is offset 0)
  41261. var data = mapSeries.getData();
  41262. data.each(function (idx) {
  41263. var name = data.getName(idx);
  41264. var layout = data.getItemLayout(idx) || {};
  41265. layout.showLabel = !mapSymbolOffsets[name];
  41266. data.setItemLayout(idx, layout);
  41267. });
  41268. processedMapType[mapType] = true;
  41269. });
  41270. };
  41271. /*
  41272. * Licensed to the Apache Software Foundation (ASF) under one
  41273. * or more contributor license agreements. See the NOTICE file
  41274. * distributed with this work for additional information
  41275. * regarding copyright ownership. The ASF licenses this file
  41276. * to you under the Apache License, Version 2.0 (the
  41277. * "License"); you may not use this file except in compliance
  41278. * with the License. You may obtain a copy of the License at
  41279. *
  41280. * http://www.apache.org/licenses/LICENSE-2.0
  41281. *
  41282. * Unless required by applicable law or agreed to in writing,
  41283. * software distributed under the License is distributed on an
  41284. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41285. * KIND, either express or implied. See the License for the
  41286. * specific language governing permissions and limitations
  41287. * under the License.
  41288. */
  41289. var mapVisual = function (ecModel) {
  41290. ecModel.eachSeriesByType('map', function (seriesModel) {
  41291. var colorList = seriesModel.get('color');
  41292. var itemStyleModel = seriesModel.getModel('itemStyle');
  41293. var areaColor = itemStyleModel.get('areaColor');
  41294. var color = itemStyleModel.get('color')
  41295. || colorList[seriesModel.seriesIndex % colorList.length];
  41296. seriesModel.getData().setVisual({
  41297. 'areaColor': areaColor,
  41298. 'color': color
  41299. });
  41300. });
  41301. };
  41302. /*
  41303. * Licensed to the Apache Software Foundation (ASF) under one
  41304. * or more contributor license agreements. See the NOTICE file
  41305. * distributed with this work for additional information
  41306. * regarding copyright ownership. The ASF licenses this file
  41307. * to you under the Apache License, Version 2.0 (the
  41308. * "License"); you may not use this file except in compliance
  41309. * with the License. You may obtain a copy of the License at
  41310. *
  41311. * http://www.apache.org/licenses/LICENSE-2.0
  41312. *
  41313. * Unless required by applicable law or agreed to in writing,
  41314. * software distributed under the License is distributed on an
  41315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41316. * KIND, either express or implied. See the License for the
  41317. * specific language governing permissions and limitations
  41318. * under the License.
  41319. */
  41320. // FIXME 公用?
  41321. /**
  41322. * @param {Array.<module:echarts/data/List>} datas
  41323. * @param {string} statisticType 'average' 'sum'
  41324. * @inner
  41325. */
  41326. function dataStatistics(datas, statisticType) {
  41327. var dataNameMap = {};
  41328. each$1(datas, function (data) {
  41329. data.each(data.mapDimension('value'), function (value, idx) {
  41330. // Add prefix to avoid conflict with Object.prototype.
  41331. var mapKey = 'ec-' + data.getName(idx);
  41332. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  41333. if (!isNaN(value)) {
  41334. dataNameMap[mapKey].push(value);
  41335. }
  41336. });
  41337. });
  41338. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  41339. var mapKey = 'ec-' + datas[0].getName(idx);
  41340. var sum = 0;
  41341. var min = Infinity;
  41342. var max = -Infinity;
  41343. var len = dataNameMap[mapKey].length;
  41344. for (var i = 0; i < len; i++) {
  41345. min = Math.min(min, dataNameMap[mapKey][i]);
  41346. max = Math.max(max, dataNameMap[mapKey][i]);
  41347. sum += dataNameMap[mapKey][i];
  41348. }
  41349. var result;
  41350. if (statisticType === 'min') {
  41351. result = min;
  41352. }
  41353. else if (statisticType === 'max') {
  41354. result = max;
  41355. }
  41356. else if (statisticType === 'average') {
  41357. result = sum / len;
  41358. }
  41359. else {
  41360. result = sum;
  41361. }
  41362. return len === 0 ? NaN : result;
  41363. });
  41364. }
  41365. var mapDataStatistic = function (ecModel) {
  41366. var seriesGroups = {};
  41367. ecModel.eachSeriesByType('map', function (seriesModel) {
  41368. var hostGeoModel = seriesModel.getHostGeoModel();
  41369. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  41370. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  41371. });
  41372. each$1(seriesGroups, function (seriesList, key) {
  41373. var data = dataStatistics(
  41374. map(seriesList, function (seriesModel) {
  41375. return seriesModel.getData();
  41376. }),
  41377. seriesList[0].get('mapValueCalculation')
  41378. );
  41379. for (var i = 0; i < seriesList.length; i++) {
  41380. seriesList[i].originalData = seriesList[i].getData();
  41381. }
  41382. // FIXME Put where?
  41383. for (var i = 0; i < seriesList.length; i++) {
  41384. seriesList[i].seriesGroup = seriesList;
  41385. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  41386. seriesList[i].setData(data.cloneShallow());
  41387. seriesList[i].mainSeries = seriesList[0];
  41388. }
  41389. });
  41390. };
  41391. /*
  41392. * Licensed to the Apache Software Foundation (ASF) under one
  41393. * or more contributor license agreements. See the NOTICE file
  41394. * distributed with this work for additional information
  41395. * regarding copyright ownership. The ASF licenses this file
  41396. * to you under the Apache License, Version 2.0 (the
  41397. * "License"); you may not use this file except in compliance
  41398. * with the License. You may obtain a copy of the License at
  41399. *
  41400. * http://www.apache.org/licenses/LICENSE-2.0
  41401. *
  41402. * Unless required by applicable law or agreed to in writing,
  41403. * software distributed under the License is distributed on an
  41404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41405. * KIND, either express or implied. See the License for the
  41406. * specific language governing permissions and limitations
  41407. * under the License.
  41408. */
  41409. var backwardCompat$2 = function (option) {
  41410. // Save geoCoord
  41411. var mapSeries = [];
  41412. each$1(option.series, function (seriesOpt) {
  41413. if (seriesOpt && seriesOpt.type === 'map') {
  41414. mapSeries.push(seriesOpt);
  41415. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  41416. // Put x, y, width, height, x2, y2 in the top level
  41417. defaults(seriesOpt, seriesOpt.mapLocation);
  41418. }
  41419. });
  41420. };
  41421. /*
  41422. * Licensed to the Apache Software Foundation (ASF) under one
  41423. * or more contributor license agreements. See the NOTICE file
  41424. * distributed with this work for additional information
  41425. * regarding copyright ownership. The ASF licenses this file
  41426. * to you under the Apache License, Version 2.0 (the
  41427. * "License"); you may not use this file except in compliance
  41428. * with the License. You may obtain a copy of the License at
  41429. *
  41430. * http://www.apache.org/licenses/LICENSE-2.0
  41431. *
  41432. * Unless required by applicable law or agreed to in writing,
  41433. * software distributed under the License is distributed on an
  41434. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41435. * KIND, either express or implied. See the License for the
  41436. * specific language governing permissions and limitations
  41437. * under the License.
  41438. */
  41439. registerLayout(mapSymbolLayout);
  41440. registerVisual(mapVisual);
  41441. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  41442. registerPreprocessor(backwardCompat$2);
  41443. createDataSelectAction('map', [{
  41444. type: 'mapToggleSelect',
  41445. event: 'mapselectchanged',
  41446. method: 'toggleSelected'
  41447. }, {
  41448. type: 'mapSelect',
  41449. event: 'mapselected',
  41450. method: 'select'
  41451. }, {
  41452. type: 'mapUnSelect',
  41453. event: 'mapunselected',
  41454. method: 'unSelect'
  41455. }]);
  41456. /*
  41457. * Licensed to the Apache Software Foundation (ASF) under one
  41458. * or more contributor license agreements. See the NOTICE file
  41459. * distributed with this work for additional information
  41460. * regarding copyright ownership. The ASF licenses this file
  41461. * to you under the Apache License, Version 2.0 (the
  41462. * "License"); you may not use this file except in compliance
  41463. * with the License. You may obtain a copy of the License at
  41464. *
  41465. * http://www.apache.org/licenses/LICENSE-2.0
  41466. *
  41467. * Unless required by applicable law or agreed to in writing,
  41468. * software distributed under the License is distributed on an
  41469. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41470. * KIND, either express or implied. See the License for the
  41471. * specific language governing permissions and limitations
  41472. * under the License.
  41473. */
  41474. /**
  41475. * Link lists and struct (graph or tree)
  41476. */
  41477. var each$7 = each$1;
  41478. var DATAS = '\0__link_datas';
  41479. var MAIN_DATA = '\0__link_mainData';
  41480. // Caution:
  41481. // In most case, either list or its shallow clones (see list.cloneShallow)
  41482. // is active in echarts process. So considering heap memory consumption,
  41483. // we do not clone tree or graph, but share them among list and its shallow clones.
  41484. // But in some rare case, we have to keep old list (like do animation in chart). So
  41485. // please take care that both the old list and the new list share the same tree/graph.
  41486. /**
  41487. * @param {Object} opt
  41488. * @param {module:echarts/data/List} opt.mainData
  41489. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  41490. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  41491. * @param {Object} [opt.datas] {dataType: data},
  41492. * like: {node: nodeList, edge: edgeList}.
  41493. * Should contain mainData.
  41494. * @param {Object} [opt.datasAttr] {dataType: attr},
  41495. * designation: struct[datasAttr[dataType]] = list;
  41496. */
  41497. function linkList(opt) {
  41498. var mainData = opt.mainData;
  41499. var datas = opt.datas;
  41500. if (!datas) {
  41501. datas = {main: mainData};
  41502. opt.datasAttr = {main: 'data'};
  41503. }
  41504. opt.datas = opt.mainData = null;
  41505. linkAll(mainData, datas, opt);
  41506. // Porxy data original methods.
  41507. each$7(datas, function (data) {
  41508. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  41509. data.wrapMethod(methodName, curry(transferInjection, opt));
  41510. });
  41511. });
  41512. // Beyond transfer, additional features should be added to `cloneShallow`.
  41513. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  41514. // Only mainData trigger change, because struct.update may trigger
  41515. // another changable methods, which may bring about dead lock.
  41516. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  41517. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  41518. });
  41519. // Make sure datas contains mainData.
  41520. assert$1(datas[mainData.dataType] === mainData);
  41521. }
  41522. function transferInjection(opt, res) {
  41523. if (isMainData(this)) {
  41524. // Transfer datas to new main data.
  41525. var datas = extend({}, this[DATAS]);
  41526. datas[this.dataType] = res;
  41527. linkAll(res, datas, opt);
  41528. }
  41529. else {
  41530. // Modify the reference in main data to point newData.
  41531. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  41532. }
  41533. return res;
  41534. }
  41535. function changeInjection(opt, res) {
  41536. opt.struct && opt.struct.update(this);
  41537. return res;
  41538. }
  41539. function cloneShallowInjection(opt, res) {
  41540. // cloneShallow, which brings about some fragilities, may be inappropriate
  41541. // to be exposed as an API. So for implementation simplicity we can make
  41542. // the restriction that cloneShallow of not-mainData should not be invoked
  41543. // outside, but only be invoked here.
  41544. each$7(res[DATAS], function (data, dataType) {
  41545. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  41546. });
  41547. return res;
  41548. }
  41549. /**
  41550. * Supplement method to List.
  41551. *
  41552. * @public
  41553. * @param {string} [dataType] If not specified, return mainData.
  41554. * @return {module:echarts/data/List}
  41555. */
  41556. function getLinkedData(dataType) {
  41557. var mainData = this[MAIN_DATA];
  41558. return (dataType == null || mainData == null)
  41559. ? mainData
  41560. : mainData[DATAS][dataType];
  41561. }
  41562. function isMainData(data) {
  41563. return data[MAIN_DATA] === data;
  41564. }
  41565. function linkAll(mainData, datas, opt) {
  41566. mainData[DATAS] = {};
  41567. each$7(datas, function (data, dataType) {
  41568. linkSingle(data, dataType, mainData, opt);
  41569. });
  41570. }
  41571. function linkSingle(data, dataType, mainData, opt) {
  41572. mainData[DATAS][dataType] = data;
  41573. data[MAIN_DATA] = mainData;
  41574. data.dataType = dataType;
  41575. if (opt.struct) {
  41576. data[opt.structAttr] = opt.struct;
  41577. opt.struct[opt.datasAttr[dataType]] = data;
  41578. }
  41579. // Supplement method.
  41580. data.getLinkedData = getLinkedData;
  41581. }
  41582. /*
  41583. * Licensed to the Apache Software Foundation (ASF) under one
  41584. * or more contributor license agreements. See the NOTICE file
  41585. * distributed with this work for additional information
  41586. * regarding copyright ownership. The ASF licenses this file
  41587. * to you under the Apache License, Version 2.0 (the
  41588. * "License"); you may not use this file except in compliance
  41589. * with the License. You may obtain a copy of the License at
  41590. *
  41591. * http://www.apache.org/licenses/LICENSE-2.0
  41592. *
  41593. * Unless required by applicable law or agreed to in writing,
  41594. * software distributed under the License is distributed on an
  41595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41596. * KIND, either express or implied. See the License for the
  41597. * specific language governing permissions and limitations
  41598. * under the License.
  41599. */
  41600. /**
  41601. * Tree data structure
  41602. *
  41603. * @module echarts/data/Tree
  41604. */
  41605. /**
  41606. * @constructor module:echarts/data/Tree~TreeNode
  41607. * @param {string} name
  41608. * @param {module:echarts/data/Tree} hostTree
  41609. */
  41610. var TreeNode = function (name, hostTree) {
  41611. /**
  41612. * @type {string}
  41613. */
  41614. this.name = name || '';
  41615. /**
  41616. * Depth of node
  41617. *
  41618. * @type {number}
  41619. * @readOnly
  41620. */
  41621. this.depth = 0;
  41622. /**
  41623. * Height of the subtree rooted at this node.
  41624. * @type {number}
  41625. * @readOnly
  41626. */
  41627. this.height = 0;
  41628. /**
  41629. * @type {module:echarts/data/Tree~TreeNode}
  41630. * @readOnly
  41631. */
  41632. this.parentNode = null;
  41633. /**
  41634. * Reference to list item.
  41635. * Do not persistent dataIndex outside,
  41636. * besause it may be changed by list.
  41637. * If dataIndex -1,
  41638. * this node is logical deleted (filtered) in list.
  41639. *
  41640. * @type {Object}
  41641. * @readOnly
  41642. */
  41643. this.dataIndex = -1;
  41644. /**
  41645. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41646. * @readOnly
  41647. */
  41648. this.children = [];
  41649. /**
  41650. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41651. * @pubilc
  41652. */
  41653. this.viewChildren = [];
  41654. /**
  41655. * @type {moduel:echarts/data/Tree}
  41656. * @readOnly
  41657. */
  41658. this.hostTree = hostTree;
  41659. };
  41660. TreeNode.prototype = {
  41661. constructor: TreeNode,
  41662. /**
  41663. * The node is removed.
  41664. * @return {boolean} is removed.
  41665. */
  41666. isRemoved: function () {
  41667. return this.dataIndex < 0;
  41668. },
  41669. /**
  41670. * Travel this subtree (include this node).
  41671. * Usage:
  41672. * node.eachNode(function () { ... }); // preorder
  41673. * node.eachNode('preorder', function () { ... }); // preorder
  41674. * node.eachNode('postorder', function () { ... }); // postorder
  41675. * node.eachNode(
  41676. * {order: 'postorder', attr: 'viewChildren'},
  41677. * function () { ... }
  41678. * ); // postorder
  41679. *
  41680. * @param {(Object|string)} options If string, means order.
  41681. * @param {string=} options.order 'preorder' or 'postorder'
  41682. * @param {string=} options.attr 'children' or 'viewChildren'
  41683. * @param {Function} cb If in preorder and return false,
  41684. * its subtree will not be visited.
  41685. * @param {Object} [context]
  41686. */
  41687. eachNode: function (options, cb, context) {
  41688. if (typeof options === 'function') {
  41689. context = cb;
  41690. cb = options;
  41691. options = null;
  41692. }
  41693. options = options || {};
  41694. if (isString(options)) {
  41695. options = {order: options};
  41696. }
  41697. var order = options.order || 'preorder';
  41698. var children = this[options.attr || 'children'];
  41699. var suppressVisitSub;
  41700. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  41701. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  41702. children[i].eachNode(options, cb, context);
  41703. }
  41704. order === 'postorder' && cb.call(context, this);
  41705. },
  41706. /**
  41707. * Update depth and height of this subtree.
  41708. *
  41709. * @param {number} depth
  41710. */
  41711. updateDepthAndHeight: function (depth) {
  41712. var height = 0;
  41713. this.depth = depth;
  41714. for (var i = 0; i < this.children.length; i++) {
  41715. var child = this.children[i];
  41716. child.updateDepthAndHeight(depth + 1);
  41717. if (child.height > height) {
  41718. height = child.height;
  41719. }
  41720. }
  41721. this.height = height + 1;
  41722. },
  41723. /**
  41724. * @param {string} id
  41725. * @return {module:echarts/data/Tree~TreeNode}
  41726. */
  41727. getNodeById: function (id) {
  41728. if (this.getId() === id) {
  41729. return this;
  41730. }
  41731. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41732. var res = children[i].getNodeById(id);
  41733. if (res) {
  41734. return res;
  41735. }
  41736. }
  41737. },
  41738. /**
  41739. * @param {module:echarts/data/Tree~TreeNode} node
  41740. * @return {boolean}
  41741. */
  41742. contains: function (node) {
  41743. if (node === this) {
  41744. return true;
  41745. }
  41746. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41747. var res = children[i].contains(node);
  41748. if (res) {
  41749. return res;
  41750. }
  41751. }
  41752. },
  41753. /**
  41754. * @param {boolean} includeSelf Default false.
  41755. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  41756. */
  41757. getAncestors: function (includeSelf) {
  41758. var ancestors = [];
  41759. var node = includeSelf ? this : this.parentNode;
  41760. while (node) {
  41761. ancestors.push(node);
  41762. node = node.parentNode;
  41763. }
  41764. ancestors.reverse();
  41765. return ancestors;
  41766. },
  41767. /**
  41768. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  41769. * @return {number} Value.
  41770. */
  41771. getValue: function (dimension) {
  41772. var data = this.hostTree.data;
  41773. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  41774. },
  41775. /**
  41776. * @param {Object} layout
  41777. * @param {boolean=} [merge=false]
  41778. */
  41779. setLayout: function (layout, merge$$1) {
  41780. this.dataIndex >= 0
  41781. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  41782. },
  41783. /**
  41784. * @return {Object} layout
  41785. */
  41786. getLayout: function () {
  41787. return this.hostTree.data.getItemLayout(this.dataIndex);
  41788. },
  41789. /**
  41790. * @param {string} [path]
  41791. * @return {module:echarts/model/Model}
  41792. */
  41793. getModel: function (path) {
  41794. if (this.dataIndex < 0) {
  41795. return;
  41796. }
  41797. var hostTree = this.hostTree;
  41798. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  41799. var levelModel = this.getLevelModel();
  41800. var leavesModel;
  41801. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  41802. leavesModel = this.getLeavesModel();
  41803. }
  41804. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  41805. },
  41806. /**
  41807. * @return {module:echarts/model/Model}
  41808. */
  41809. getLevelModel: function () {
  41810. return (this.hostTree.levelModels || [])[this.depth];
  41811. },
  41812. /**
  41813. * @return {module:echarts/model/Model}
  41814. */
  41815. getLeavesModel: function () {
  41816. return this.hostTree.leavesModel;
  41817. },
  41818. /**
  41819. * @example
  41820. * setItemVisual('color', color);
  41821. * setItemVisual({
  41822. * 'color': color
  41823. * });
  41824. */
  41825. setVisual: function (key, value) {
  41826. this.dataIndex >= 0
  41827. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  41828. },
  41829. /**
  41830. * Get item visual
  41831. */
  41832. getVisual: function (key, ignoreParent) {
  41833. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  41834. },
  41835. /**
  41836. * @public
  41837. * @return {number}
  41838. */
  41839. getRawIndex: function () {
  41840. return this.hostTree.data.getRawIndex(this.dataIndex);
  41841. },
  41842. /**
  41843. * @public
  41844. * @return {string}
  41845. */
  41846. getId: function () {
  41847. return this.hostTree.data.getId(this.dataIndex);
  41848. },
  41849. /**
  41850. * if this is an ancestor of another node
  41851. *
  41852. * @public
  41853. * @param {TreeNode} node another node
  41854. * @return {boolean} if is ancestor
  41855. */
  41856. isAncestorOf: function (node) {
  41857. var parent = node.parentNode;
  41858. while (parent) {
  41859. if (parent === this) {
  41860. return true;
  41861. }
  41862. parent = parent.parentNode;
  41863. }
  41864. return false;
  41865. },
  41866. /**
  41867. * if this is an descendant of another node
  41868. *
  41869. * @public
  41870. * @param {TreeNode} node another node
  41871. * @return {boolean} if is descendant
  41872. */
  41873. isDescendantOf: function (node) {
  41874. return node !== this && node.isAncestorOf(this);
  41875. }
  41876. };
  41877. /**
  41878. * @constructor
  41879. * @alias module:echarts/data/Tree
  41880. * @param {module:echarts/model/Model} hostModel
  41881. * @param {Array.<Object>} levelOptions
  41882. * @param {Object} leavesOption
  41883. */
  41884. function Tree(hostModel, levelOptions, leavesOption) {
  41885. /**
  41886. * @type {module:echarts/data/Tree~TreeNode}
  41887. * @readOnly
  41888. */
  41889. this.root;
  41890. /**
  41891. * @type {module:echarts/data/List}
  41892. * @readOnly
  41893. */
  41894. this.data;
  41895. /**
  41896. * Index of each item is the same as the raw index of coresponding list item.
  41897. * @private
  41898. * @type {Array.<module:echarts/data/Tree~TreeNode}
  41899. */
  41900. this._nodes = [];
  41901. /**
  41902. * @private
  41903. * @readOnly
  41904. * @type {module:echarts/model/Model}
  41905. */
  41906. this.hostModel = hostModel;
  41907. /**
  41908. * @private
  41909. * @readOnly
  41910. * @type {Array.<module:echarts/model/Model}
  41911. */
  41912. this.levelModels = map(levelOptions || [], function (levelDefine) {
  41913. return new Model(levelDefine, hostModel, hostModel.ecModel);
  41914. });
  41915. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  41916. }
  41917. Tree.prototype = {
  41918. constructor: Tree,
  41919. type: 'tree',
  41920. /**
  41921. * Travel this subtree (include this node).
  41922. * Usage:
  41923. * node.eachNode(function () { ... }); // preorder
  41924. * node.eachNode('preorder', function () { ... }); // preorder
  41925. * node.eachNode('postorder', function () { ... }); // postorder
  41926. * node.eachNode(
  41927. * {order: 'postorder', attr: 'viewChildren'},
  41928. * function () { ... }
  41929. * ); // postorder
  41930. *
  41931. * @param {(Object|string)} options If string, means order.
  41932. * @param {string=} options.order 'preorder' or 'postorder'
  41933. * @param {string=} options.attr 'children' or 'viewChildren'
  41934. * @param {Function} cb
  41935. * @param {Object} [context]
  41936. */
  41937. eachNode: function (options, cb, context) {
  41938. this.root.eachNode(options, cb, context);
  41939. },
  41940. /**
  41941. * @param {number} dataIndex
  41942. * @return {module:echarts/data/Tree~TreeNode}
  41943. */
  41944. getNodeByDataIndex: function (dataIndex) {
  41945. var rawIndex = this.data.getRawIndex(dataIndex);
  41946. return this._nodes[rawIndex];
  41947. },
  41948. /**
  41949. * @param {string} name
  41950. * @return {module:echarts/data/Tree~TreeNode}
  41951. */
  41952. getNodeByName: function (name) {
  41953. return this.root.getNodeByName(name);
  41954. },
  41955. /**
  41956. * Update item available by list,
  41957. * when list has been performed options like 'filterSelf' or 'map'.
  41958. */
  41959. update: function () {
  41960. var data = this.data;
  41961. var nodes = this._nodes;
  41962. for (var i = 0, len = nodes.length; i < len; i++) {
  41963. nodes[i].dataIndex = -1;
  41964. }
  41965. for (var i = 0, len = data.count(); i < len; i++) {
  41966. nodes[data.getRawIndex(i)].dataIndex = i;
  41967. }
  41968. },
  41969. /**
  41970. * Clear all layouts
  41971. */
  41972. clearLayouts: function () {
  41973. this.data.clearItemLayouts();
  41974. }
  41975. };
  41976. /**
  41977. * data node format:
  41978. * {
  41979. * name: ...
  41980. * value: ...
  41981. * children: [
  41982. * {
  41983. * name: ...
  41984. * value: ...
  41985. * children: ...
  41986. * },
  41987. * ...
  41988. * ]
  41989. * }
  41990. *
  41991. * @static
  41992. * @param {Object} dataRoot Root node.
  41993. * @param {module:echarts/model/Model} hostModel
  41994. * @param {Object} treeOptions
  41995. * @param {Array.<Object>} treeOptions.levels
  41996. * @param {Array.<Object>} treeOptions.leaves
  41997. * @return module:echarts/data/Tree
  41998. */
  41999. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  42000. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  42001. var listData = [];
  42002. var dimMax = 1;
  42003. buildHierarchy(dataRoot);
  42004. function buildHierarchy(dataNode, parentNode) {
  42005. var value = dataNode.value;
  42006. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  42007. listData.push(dataNode);
  42008. var node = new TreeNode(dataNode.name, tree);
  42009. parentNode
  42010. ? addChild(node, parentNode)
  42011. : (tree.root = node);
  42012. tree._nodes.push(node);
  42013. var children = dataNode.children;
  42014. if (children) {
  42015. for (var i = 0; i < children.length; i++) {
  42016. buildHierarchy(children[i], node);
  42017. }
  42018. }
  42019. }
  42020. tree.root.updateDepthAndHeight(0);
  42021. var dimensionsInfo = createDimensions(listData, {
  42022. coordDimensions: ['value'],
  42023. dimensionsCount: dimMax
  42024. });
  42025. var list = new List(dimensionsInfo, hostModel);
  42026. list.initData(listData);
  42027. linkList({
  42028. mainData: list,
  42029. struct: tree,
  42030. structAttr: 'tree'
  42031. });
  42032. tree.update();
  42033. return tree;
  42034. };
  42035. /**
  42036. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  42037. * so this function is not ready and not necessary to be public.
  42038. *
  42039. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  42040. */
  42041. function addChild(child, node) {
  42042. var children = node.children;
  42043. if (child.parentNode === node) {
  42044. return;
  42045. }
  42046. children.push(child);
  42047. child.parentNode = node;
  42048. }
  42049. /*
  42050. * Licensed to the Apache Software Foundation (ASF) under one
  42051. * or more contributor license agreements. See the NOTICE file
  42052. * distributed with this work for additional information
  42053. * regarding copyright ownership. The ASF licenses this file
  42054. * to you under the Apache License, Version 2.0 (the
  42055. * "License"); you may not use this file except in compliance
  42056. * with the License. You may obtain a copy of the License at
  42057. *
  42058. * http://www.apache.org/licenses/LICENSE-2.0
  42059. *
  42060. * Unless required by applicable law or agreed to in writing,
  42061. * software distributed under the License is distributed on an
  42062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42063. * KIND, either express or implied. See the License for the
  42064. * specific language governing permissions and limitations
  42065. * under the License.
  42066. */
  42067. /**
  42068. * @file Create data struct and define tree view's series model
  42069. * @author Deqing Li(annong035@gmail.com)
  42070. */
  42071. SeriesModel.extend({
  42072. type: 'series.tree',
  42073. layoutInfo: null,
  42074. // can support the position parameters 'left', 'top','right','bottom', 'width',
  42075. // 'height' in the setOption() with 'merge' mode normal.
  42076. layoutMode: 'box',
  42077. /**
  42078. * Init a tree data structure from data in option series
  42079. * @param {Object} option the object used to config echarts view
  42080. * @return {module:echarts/data/List} storage initial data
  42081. */
  42082. getInitialData: function (option) {
  42083. //create an virtual root
  42084. var root = {name: option.name, children: option.data};
  42085. var leaves = option.leaves || {};
  42086. var treeOption = {};
  42087. treeOption.leaves = leaves;
  42088. var tree = Tree.createTree(root, this, treeOption);
  42089. var treeDepth = 0;
  42090. tree.eachNode('preorder', function (node) {
  42091. if (node.depth > treeDepth) {
  42092. treeDepth = node.depth;
  42093. }
  42094. });
  42095. var expandAndCollapse = option.expandAndCollapse;
  42096. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  42097. ? option.initialTreeDepth : treeDepth;
  42098. tree.root.eachNode('preorder', function (node) {
  42099. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  42100. // Add item.collapsed != null, because users can collapse node original in the series.data.
  42101. node.isExpand = (item && item.collapsed != null)
  42102. ? !item.collapsed
  42103. : node.depth <= expandTreeDepth;
  42104. });
  42105. return tree.data;
  42106. },
  42107. /**
  42108. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  42109. * @returns {string} orient
  42110. */
  42111. getOrient: function () {
  42112. var orient = this.get('orient');
  42113. if (orient === 'horizontal') {
  42114. orient = 'LR';
  42115. }
  42116. else if (orient === 'vertical') {
  42117. orient = 'TB';
  42118. }
  42119. return orient;
  42120. },
  42121. setZoom: function (zoom) {
  42122. this.option.zoom = zoom;
  42123. },
  42124. setCenter: function (center) {
  42125. this.option.center = center;
  42126. },
  42127. /**
  42128. * @override
  42129. * @param {number} dataIndex
  42130. */
  42131. formatTooltip: function (dataIndex) {
  42132. var tree = this.getData().tree;
  42133. var realRoot = tree.root.children[0];
  42134. var node = tree.getNodeByDataIndex(dataIndex);
  42135. var value = node.getValue();
  42136. var name = node.name;
  42137. while (node && (node !== realRoot)) {
  42138. name = node.parentNode.name + '.' + name;
  42139. node = node.parentNode;
  42140. }
  42141. return encodeHTML(name + (
  42142. (isNaN(value) || value == null) ? '' : ' : ' + value
  42143. ));
  42144. },
  42145. defaultOption: {
  42146. zlevel: 0,
  42147. z: 2,
  42148. coordinateSystem: 'view',
  42149. // the position of the whole view
  42150. left: '12%',
  42151. top: '12%',
  42152. right: '12%',
  42153. bottom: '12%',
  42154. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  42155. layout: 'orthogonal',
  42156. roam: false, // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  42157. // Symbol size scale ratio in roam
  42158. nodeScaleRatio: 0.4,
  42159. // Default on center of graph
  42160. center: null,
  42161. zoom: 1,
  42162. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  42163. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  42164. orient: 'LR',
  42165. symbol: 'emptyCircle',
  42166. symbolSize: 7,
  42167. expandAndCollapse: true,
  42168. initialTreeDepth: 2,
  42169. lineStyle: {
  42170. color: '#ccc',
  42171. width: 1.5,
  42172. curveness: 0.5
  42173. },
  42174. itemStyle: {
  42175. color: 'lightsteelblue',
  42176. borderColor: '#c23531',
  42177. borderWidth: 1.5
  42178. },
  42179. label: {
  42180. show: true,
  42181. color: '#555'
  42182. },
  42183. leaves: {
  42184. label: {
  42185. show: true
  42186. }
  42187. },
  42188. animationEasing: 'linear',
  42189. animationDuration: 700,
  42190. animationDurationUpdate: 1000
  42191. }
  42192. });
  42193. /*
  42194. * Licensed to the Apache Software Foundation (ASF) under one
  42195. * or more contributor license agreements. See the NOTICE file
  42196. * distributed with this work for additional information
  42197. * regarding copyright ownership. The ASF licenses this file
  42198. * to you under the Apache License, Version 2.0 (the
  42199. * "License"); you may not use this file except in compliance
  42200. * with the License. You may obtain a copy of the License at
  42201. *
  42202. * http://www.apache.org/licenses/LICENSE-2.0
  42203. *
  42204. * Unless required by applicable law or agreed to in writing,
  42205. * software distributed under the License is distributed on an
  42206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42207. * KIND, either express or implied. See the License for the
  42208. * specific language governing permissions and limitations
  42209. * under the License.
  42210. */
  42211. /*
  42212. * The tree layout implementation references to d3.js
  42213. * (https://github.com/d3/d3-hierarchy). The use of the source
  42214. * code of this file is also subject to the terms and consitions
  42215. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  42216. */
  42217. /**
  42218. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  42219. * the tree.
  42220. * @see https://github.com/d3/d3-hierarchy
  42221. */
  42222. /**
  42223. * Initialize all computational message for following algorithm
  42224. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  42225. */
  42226. function init$2(root) {
  42227. root.hierNode = {
  42228. defaultAncestor: null,
  42229. ancestor: root,
  42230. prelim: 0,
  42231. modifier: 0,
  42232. change: 0,
  42233. shift: 0,
  42234. i: 0,
  42235. thread: null
  42236. };
  42237. var nodes = [root];
  42238. var node;
  42239. var children;
  42240. while (node = nodes.pop()) { // jshint ignore:line
  42241. children = node.children;
  42242. if (node.isExpand && children.length) {
  42243. var n = children.length;
  42244. for (var i = n - 1; i >= 0; i--) {
  42245. var child = children[i];
  42246. child.hierNode = {
  42247. defaultAncestor: null,
  42248. ancestor: child,
  42249. prelim: 0,
  42250. modifier: 0,
  42251. change: 0,
  42252. shift: 0,
  42253. i: i,
  42254. thread: null
  42255. };
  42256. nodes.push(child);
  42257. }
  42258. }
  42259. }
  42260. }
  42261. /**
  42262. * Computes a preliminary x coordinate for node. Before that, this function is
  42263. * applied recursively to the children of node, as well as the function
  42264. * apportion(). After spacing out the children by calling executeShifts(), the
  42265. * node is placed to the midpoint of its outermost children.
  42266. * @param {module:echarts/data/Tree~TreeNode} node
  42267. * @param {Function} separation
  42268. */
  42269. function firstWalk(node, separation) {
  42270. var children = node.isExpand ? node.children : [];
  42271. var siblings = node.parentNode.children;
  42272. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  42273. if (children.length) {
  42274. executeShifts(node);
  42275. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  42276. if (subtreeW) {
  42277. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  42278. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  42279. }
  42280. else {
  42281. node.hierNode.prelim = midPoint;
  42282. }
  42283. }
  42284. else if (subtreeW) {
  42285. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  42286. }
  42287. node.parentNode.hierNode.defaultAncestor = apportion(
  42288. node,
  42289. subtreeW,
  42290. node.parentNode.hierNode.defaultAncestor || siblings[0],
  42291. separation
  42292. );
  42293. }
  42294. /**
  42295. * Computes all real x-coordinates by summing up the modifiers recursively.
  42296. * @param {module:echarts/data/Tree~TreeNode} node
  42297. */
  42298. function secondWalk(node) {
  42299. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  42300. node.setLayout({x: nodeX}, true);
  42301. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  42302. }
  42303. function separation(cb) {
  42304. return arguments.length ? cb : defaultSeparation;
  42305. }
  42306. /**
  42307. * Transform the common coordinate to radial coordinate
  42308. * @param {number} x
  42309. * @param {number} y
  42310. * @return {Object}
  42311. */
  42312. function radialCoordinate(x, y) {
  42313. var radialCoor = {};
  42314. x -= Math.PI / 2;
  42315. radialCoor.x = y * Math.cos(x);
  42316. radialCoor.y = y * Math.sin(x);
  42317. return radialCoor;
  42318. }
  42319. /**
  42320. * Get the layout position of the whole view
  42321. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  42322. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  42323. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  42324. */
  42325. function getViewRect(seriesModel, api) {
  42326. return getLayoutRect(
  42327. seriesModel.getBoxLayoutParams(), {
  42328. width: api.getWidth(),
  42329. height: api.getHeight()
  42330. }
  42331. );
  42332. }
  42333. /**
  42334. * All other shifts, applied to the smaller subtrees between w- and w+, are
  42335. * performed by this function.
  42336. * @param {module:echarts/data/Tree~TreeNode} node
  42337. */
  42338. function executeShifts(node) {
  42339. var children = node.children;
  42340. var n = children.length;
  42341. var shift = 0;
  42342. var change = 0;
  42343. while (--n >= 0) {
  42344. var child = children[n];
  42345. child.hierNode.prelim += shift;
  42346. child.hierNode.modifier += shift;
  42347. change += child.hierNode.change;
  42348. shift += child.hierNode.shift + change;
  42349. }
  42350. }
  42351. /**
  42352. * The core of the algorithm. Here, a new subtree is combined with the
  42353. * previous subtrees. Threads are used to traverse the inside and outside
  42354. * contours of the left and right subtree up to the highest common level.
  42355. * Whenever two nodes of the inside contours conflict, we compute the left
  42356. * one of the greatest uncommon ancestors using the function nextAncestor()
  42357. * and call moveSubtree() to shift the subtree and prepare the shifts of
  42358. * smaller subtrees. Finally, we add a new thread (if necessary).
  42359. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  42360. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  42361. * @param {module:echarts/data/Tree~TreeNode} ancestor
  42362. * @param {Function} separation
  42363. * @return {module:echarts/data/Tree~TreeNode}
  42364. */
  42365. function apportion(subtreeV, subtreeW, ancestor, separation) {
  42366. if (subtreeW) {
  42367. var nodeOutRight = subtreeV;
  42368. var nodeInRight = subtreeV;
  42369. var nodeOutLeft = nodeInRight.parentNode.children[0];
  42370. var nodeInLeft = subtreeW;
  42371. var sumOutRight = nodeOutRight.hierNode.modifier;
  42372. var sumInRight = nodeInRight.hierNode.modifier;
  42373. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  42374. var sumInLeft = nodeInLeft.hierNode.modifier;
  42375. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  42376. nodeOutRight = nextRight(nodeOutRight);
  42377. nodeOutLeft = nextLeft(nodeOutLeft);
  42378. nodeOutRight.hierNode.ancestor = subtreeV;
  42379. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  42380. - sumInRight + separation(nodeInLeft, nodeInRight);
  42381. if (shift > 0) {
  42382. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  42383. sumInRight += shift;
  42384. sumOutRight += shift;
  42385. }
  42386. sumInLeft += nodeInLeft.hierNode.modifier;
  42387. sumInRight += nodeInRight.hierNode.modifier;
  42388. sumOutRight += nodeOutRight.hierNode.modifier;
  42389. sumOutLeft += nodeOutLeft.hierNode.modifier;
  42390. }
  42391. if (nodeInLeft && !nextRight(nodeOutRight)) {
  42392. nodeOutRight.hierNode.thread = nodeInLeft;
  42393. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  42394. }
  42395. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  42396. nodeOutLeft.hierNode.thread = nodeInRight;
  42397. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  42398. ancestor = subtreeV;
  42399. }
  42400. }
  42401. return ancestor;
  42402. }
  42403. /**
  42404. * This function is used to traverse the right contour of a subtree.
  42405. * It returns the rightmost child of node or the thread of node. The function
  42406. * returns null if and only if node is on the highest depth of its subtree.
  42407. * @param {module:echarts/data/Tree~TreeNode} node
  42408. * @return {module:echarts/data/Tree~TreeNode}
  42409. */
  42410. function nextRight(node) {
  42411. var children = node.children;
  42412. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  42413. }
  42414. /**
  42415. * This function is used to traverse the left contour of a subtree (or a subforest).
  42416. * It returns the leftmost child of node or the thread of node. The function
  42417. * returns null if and only if node is on the highest depth of its subtree.
  42418. * @param {module:echarts/data/Tree~TreeNode} node
  42419. * @return {module:echarts/data/Tree~TreeNode}
  42420. */
  42421. function nextLeft(node) {
  42422. var children = node.children;
  42423. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  42424. }
  42425. /**
  42426. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  42427. * Otherwise, returns the specified ancestor.
  42428. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  42429. * @param {module:echarts/data/Tree~TreeNode} node
  42430. * @param {module:echarts/data/Tree~TreeNode} ancestor
  42431. * @return {module:echarts/data/Tree~TreeNode}
  42432. */
  42433. function nextAncestor(nodeInLeft, node, ancestor) {
  42434. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  42435. ? nodeInLeft.hierNode.ancestor : ancestor;
  42436. }
  42437. /**
  42438. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  42439. * @param {module:echarts/data/Tree~TreeNode} wl
  42440. * @param {module:echarts/data/Tree~TreeNode} wr
  42441. * @param {number} shift [description]
  42442. */
  42443. function moveSubtree(wl, wr, shift) {
  42444. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  42445. wr.hierNode.change -= change;
  42446. wr.hierNode.shift += shift;
  42447. wr.hierNode.modifier += shift;
  42448. wr.hierNode.prelim += shift;
  42449. wl.hierNode.change += change;
  42450. }
  42451. function defaultSeparation(node1, node2) {
  42452. return node1.parentNode === node2.parentNode ? 1 : 2;
  42453. }
  42454. /*
  42455. * Licensed to the Apache Software Foundation (ASF) under one
  42456. * or more contributor license agreements. See the NOTICE file
  42457. * distributed with this work for additional information
  42458. * regarding copyright ownership. The ASF licenses this file
  42459. * to you under the Apache License, Version 2.0 (the
  42460. * "License"); you may not use this file except in compliance
  42461. * with the License. You may obtain a copy of the License at
  42462. *
  42463. * http://www.apache.org/licenses/LICENSE-2.0
  42464. *
  42465. * Unless required by applicable law or agreed to in writing,
  42466. * software distributed under the License is distributed on an
  42467. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42468. * KIND, either express or implied. See the License for the
  42469. * specific language governing permissions and limitations
  42470. * under the License.
  42471. */
  42472. /**
  42473. * @file This file used to draw tree view.
  42474. * @author Deqing Li(annong035@gmail.com)
  42475. */
  42476. extendChartView({
  42477. type: 'tree',
  42478. /**
  42479. * Init the chart
  42480. * @override
  42481. * @param {module:echarts/model/Global} ecModel
  42482. * @param {module:echarts/ExtensionAPI} api
  42483. */
  42484. init: function (ecModel, api) {
  42485. /**
  42486. * @private
  42487. * @type {module:echarts/data/Tree}
  42488. */
  42489. this._oldTree;
  42490. /**
  42491. * @private
  42492. * @type {module:zrender/container/Group}
  42493. */
  42494. this._mainGroup = new Group();
  42495. /**
  42496. * @private
  42497. * @type {module:echarts/componet/helper/RoamController}
  42498. */
  42499. this._controller = new RoamController(api.getZr());
  42500. this._controllerHost = {target: this.group};
  42501. this.group.add(this._mainGroup);
  42502. },
  42503. render: function (seriesModel, ecModel, api, payload) {
  42504. var data = seriesModel.getData();
  42505. var layoutInfo = seriesModel.layoutInfo;
  42506. var group = this._mainGroup;
  42507. var layout = seriesModel.get('layout');
  42508. if (layout === 'radial') {
  42509. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  42510. }
  42511. else {
  42512. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  42513. }
  42514. this._updateViewCoordSys(seriesModel);
  42515. this._updateController(seriesModel, ecModel, api);
  42516. var oldData = this._data;
  42517. var seriesScope = {
  42518. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  42519. layout: layout,
  42520. orient: seriesModel.getOrient(),
  42521. curvature: seriesModel.get('lineStyle.curveness'),
  42522. symbolRotate: seriesModel.get('symbolRotate'),
  42523. symbolOffset: seriesModel.get('symbolOffset'),
  42524. hoverAnimation: seriesModel.get('hoverAnimation'),
  42525. useNameLabel: true,
  42526. fadeIn: true
  42527. };
  42528. data.diff(oldData)
  42529. .add(function (newIdx) {
  42530. if (symbolNeedsDraw$1(data, newIdx)) {
  42531. // Create node and edge
  42532. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  42533. }
  42534. })
  42535. .update(function (newIdx, oldIdx) {
  42536. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42537. if (!symbolNeedsDraw$1(data, newIdx)) {
  42538. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42539. return;
  42540. }
  42541. // Update node and edge
  42542. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  42543. })
  42544. .remove(function (oldIdx) {
  42545. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42546. // When remove a collapsed node of subtree, since the collapsed
  42547. // node haven't been initialized with a symbol element,
  42548. // you can't found it's symbol element through index.
  42549. // so if we want to remove the symbol element we should insure
  42550. // that the symbol element is not null.
  42551. if (symbolEl) {
  42552. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42553. }
  42554. })
  42555. .execute();
  42556. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  42557. this._updateNodeAndLinkScale(seriesModel);
  42558. if (seriesScope.expandAndCollapse === true) {
  42559. data.eachItemGraphicEl(function (el, dataIndex) {
  42560. el.off('click').on('click', function () {
  42561. api.dispatchAction({
  42562. type: 'treeExpandAndCollapse',
  42563. seriesId: seriesModel.id,
  42564. dataIndex: dataIndex
  42565. });
  42566. });
  42567. });
  42568. }
  42569. this._data = data;
  42570. },
  42571. _updateViewCoordSys: function (seriesModel) {
  42572. var data = seriesModel.getData();
  42573. var points = [];
  42574. data.each(function (idx) {
  42575. var layout = data.getItemLayout(idx);
  42576. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  42577. points.push([+layout.x, +layout.y]);
  42578. }
  42579. });
  42580. var min = [];
  42581. var max = [];
  42582. fromPoints(points, min, max);
  42583. // If width or height is 0
  42584. if (max[0] - min[0] === 0) {
  42585. max[0] += 1;
  42586. min[0] -= 1;
  42587. }
  42588. if (max[1] - min[1] === 0) {
  42589. max[1] += 1;
  42590. min[1] -= 1;
  42591. }
  42592. var viewCoordSys = seriesModel.coordinateSystem = new View();
  42593. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  42594. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  42595. viewCoordSys.setCenter(seriesModel.get('center'));
  42596. viewCoordSys.setZoom(seriesModel.get('zoom'));
  42597. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  42598. this.group.attr({
  42599. position: viewCoordSys.position,
  42600. scale: viewCoordSys.scale
  42601. });
  42602. this._viewCoordSys = viewCoordSys;
  42603. },
  42604. _updateController: function (seriesModel, ecModel, api) {
  42605. var controller = this._controller;
  42606. var controllerHost = this._controllerHost;
  42607. var group = this.group;
  42608. controller.setPointerChecker(function (e, x, y) {
  42609. var rect = group.getBoundingRect();
  42610. rect.applyTransform(group.transform);
  42611. return rect.contain(x, y)
  42612. && !onIrrelevantElement(e, api, seriesModel);
  42613. });
  42614. controller.enable(seriesModel.get('roam'));
  42615. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  42616. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  42617. controller
  42618. .off('pan')
  42619. .off('zoom')
  42620. .on('pan', function (e) {
  42621. updateViewOnPan(controllerHost, e.dx, e.dy);
  42622. api.dispatchAction({
  42623. seriesId: seriesModel.id,
  42624. type: 'treeRoam',
  42625. dx: e.dx,
  42626. dy: e.dy
  42627. });
  42628. }, this)
  42629. .on('zoom', function (e) {
  42630. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42631. api.dispatchAction({
  42632. seriesId: seriesModel.id,
  42633. type: 'treeRoam',
  42634. zoom: e.scale,
  42635. originX: e.originX,
  42636. originY: e.originY
  42637. });
  42638. this._updateNodeAndLinkScale(seriesModel);
  42639. }, this);
  42640. },
  42641. _updateNodeAndLinkScale: function (seriesModel) {
  42642. var data = seriesModel.getData();
  42643. var nodeScale = this._getNodeGlobalScale(seriesModel);
  42644. var invScale = [nodeScale, nodeScale];
  42645. data.eachItemGraphicEl(function (el, idx) {
  42646. el.attr('scale', invScale);
  42647. });
  42648. },
  42649. _getNodeGlobalScale: function (seriesModel) {
  42650. var coordSys = seriesModel.coordinateSystem;
  42651. if (coordSys.type !== 'view') {
  42652. return 1;
  42653. }
  42654. var nodeScaleRatio = this._nodeScaleRatio;
  42655. var groupScale = coordSys.scale;
  42656. var groupZoom = (groupScale && groupScale[0]) || 1;
  42657. // Scale node when zoom changes
  42658. var roamZoom = coordSys.getZoom();
  42659. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  42660. return nodeScale / groupZoom;
  42661. },
  42662. dispose: function () {
  42663. this._controller && this._controller.dispose();
  42664. this._controllerHost = {};
  42665. },
  42666. remove: function () {
  42667. this._mainGroup.removeAll();
  42668. this._data = null;
  42669. }
  42670. });
  42671. function symbolNeedsDraw$1(data, dataIndex) {
  42672. var layout = data.getItemLayout(dataIndex);
  42673. return layout
  42674. && !isNaN(layout.x) && !isNaN(layout.y)
  42675. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  42676. }
  42677. function getTreeNodeStyle(node, itemModel, seriesScope) {
  42678. seriesScope.itemModel = itemModel;
  42679. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  42680. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  42681. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  42682. seriesScope.labelModel = itemModel.getModel('label');
  42683. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  42684. if (node.isExpand === false && node.children.length !== 0) {
  42685. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  42686. }
  42687. else {
  42688. seriesScope.symbolInnerColor = '#fff';
  42689. }
  42690. return seriesScope;
  42691. }
  42692. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42693. var isInit = !symbolEl;
  42694. var node = data.tree.getNodeByDataIndex(dataIndex);
  42695. var itemModel = node.getModel();
  42696. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42697. var virtualRoot = data.tree.root;
  42698. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42699. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  42700. var sourceLayout = source.getLayout();
  42701. var sourceOldLayout = sourceSymbolEl
  42702. ? {
  42703. x: sourceSymbolEl.position[0],
  42704. y: sourceSymbolEl.position[1],
  42705. rawX: sourceSymbolEl.__radialOldRawX,
  42706. rawY: sourceSymbolEl.__radialOldRawY
  42707. }
  42708. : sourceLayout;
  42709. var targetLayout = node.getLayout();
  42710. if (isInit) {
  42711. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  42712. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  42713. }
  42714. else {
  42715. symbolEl.updateData(data, dataIndex, seriesScope);
  42716. }
  42717. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  42718. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  42719. symbolEl.__radialRawX = targetLayout.rawX;
  42720. symbolEl.__radialRawY = targetLayout.rawY;
  42721. group.add(symbolEl);
  42722. data.setItemGraphicEl(dataIndex, symbolEl);
  42723. updateProps(symbolEl, {
  42724. position: [targetLayout.x, targetLayout.y]
  42725. }, seriesModel);
  42726. var symbolPath = symbolEl.getSymbolPath();
  42727. if (seriesScope.layout === 'radial') {
  42728. var realRoot = virtualRoot.children[0];
  42729. var rootLayout = realRoot.getLayout();
  42730. var length = realRoot.children.length;
  42731. var rad;
  42732. var isLeft;
  42733. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  42734. var center = {};
  42735. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  42736. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  42737. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  42738. if (rad < 0) {
  42739. rad = Math.PI * 2 + rad;
  42740. }
  42741. isLeft = center.x < rootLayout.x;
  42742. if (isLeft) {
  42743. rad = rad - Math.PI;
  42744. }
  42745. }
  42746. else {
  42747. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  42748. if (rad < 0) {
  42749. rad = Math.PI * 2 + rad;
  42750. }
  42751. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  42752. isLeft = targetLayout.x < rootLayout.x;
  42753. if (isLeft) {
  42754. rad = rad - Math.PI;
  42755. }
  42756. }
  42757. else {
  42758. isLeft = targetLayout.x > rootLayout.x;
  42759. if (!isLeft) {
  42760. rad = rad - Math.PI;
  42761. }
  42762. }
  42763. }
  42764. var textPosition = isLeft ? 'left' : 'right';
  42765. symbolPath.setStyle({
  42766. textPosition: textPosition,
  42767. textRotation: -rad,
  42768. textOrigin: 'center',
  42769. verticalAlign: 'middle'
  42770. });
  42771. }
  42772. if (node.parentNode && node.parentNode !== virtualRoot) {
  42773. var edge = symbolEl.__edge;
  42774. if (!edge) {
  42775. edge = symbolEl.__edge = new BezierCurve({
  42776. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  42777. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  42778. });
  42779. }
  42780. updateProps(edge, {
  42781. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  42782. style: {opacity: 1}
  42783. }, seriesModel);
  42784. group.add(edge);
  42785. }
  42786. }
  42787. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42788. var node = data.tree.getNodeByDataIndex(dataIndex);
  42789. var virtualRoot = data.tree.root;
  42790. var itemModel = node.getModel();
  42791. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42792. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42793. var sourceLayout;
  42794. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  42795. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  42796. }
  42797. updateProps(symbolEl, {
  42798. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  42799. }, seriesModel, function () {
  42800. group.remove(symbolEl);
  42801. data.setItemGraphicEl(dataIndex, null);
  42802. });
  42803. symbolEl.fadeOut(null, {keepLabel: true});
  42804. var edge = symbolEl.__edge;
  42805. if (edge) {
  42806. updateProps(edge, {
  42807. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  42808. style: {
  42809. opacity: 0
  42810. }
  42811. }, seriesModel, function () {
  42812. group.remove(edge);
  42813. });
  42814. }
  42815. }
  42816. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  42817. var cpx1;
  42818. var cpy1;
  42819. var cpx2;
  42820. var cpy2;
  42821. var orient = seriesScope.orient;
  42822. var x1;
  42823. var x2;
  42824. var y1;
  42825. var y2;
  42826. if (seriesScope.layout === 'radial') {
  42827. x1 = sourceLayout.rawX;
  42828. y1 = sourceLayout.rawY;
  42829. x2 = targetLayout.rawX;
  42830. y2 = targetLayout.rawY;
  42831. var radialCoor1 = radialCoordinate(x1, y1);
  42832. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  42833. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  42834. var radialCoor4 = radialCoordinate(x2, y2);
  42835. return {
  42836. x1: radialCoor1.x,
  42837. y1: radialCoor1.y,
  42838. x2: radialCoor4.x,
  42839. y2: radialCoor4.y,
  42840. cpx1: radialCoor2.x,
  42841. cpy1: radialCoor2.y,
  42842. cpx2: radialCoor3.x,
  42843. cpy2: radialCoor3.y
  42844. };
  42845. }
  42846. else {
  42847. x1 = sourceLayout.x;
  42848. y1 = sourceLayout.y;
  42849. x2 = targetLayout.x;
  42850. y2 = targetLayout.y;
  42851. if (orient === 'LR' || orient === 'RL') {
  42852. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  42853. cpy1 = y1;
  42854. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  42855. cpy2 = y2;
  42856. }
  42857. if (orient === 'TB' || orient === 'BT') {
  42858. cpx1 = x1;
  42859. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  42860. cpx2 = x2;
  42861. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  42862. }
  42863. }
  42864. return {
  42865. x1: x1,
  42866. y1: y1,
  42867. x2: x2,
  42868. y2: y2,
  42869. cpx1: cpx1,
  42870. cpy1: cpy1,
  42871. cpx2: cpx2,
  42872. cpy2: cpy2
  42873. };
  42874. }
  42875. /*
  42876. * Licensed to the Apache Software Foundation (ASF) under one
  42877. * or more contributor license agreements. See the NOTICE file
  42878. * distributed with this work for additional information
  42879. * regarding copyright ownership. The ASF licenses this file
  42880. * to you under the Apache License, Version 2.0 (the
  42881. * "License"); you may not use this file except in compliance
  42882. * with the License. You may obtain a copy of the License at
  42883. *
  42884. * http://www.apache.org/licenses/LICENSE-2.0
  42885. *
  42886. * Unless required by applicable law or agreed to in writing,
  42887. * software distributed under the License is distributed on an
  42888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42889. * KIND, either express or implied. See the License for the
  42890. * specific language governing permissions and limitations
  42891. * under the License.
  42892. */
  42893. /**
  42894. * @file Register the actions of the tree
  42895. * @author Deqing Li(annong035@gmail.com)
  42896. */
  42897. registerAction({
  42898. type: 'treeExpandAndCollapse',
  42899. event: 'treeExpandAndCollapse',
  42900. update: 'update'
  42901. }, function (payload, ecModel) {
  42902. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42903. var dataIndex = payload.dataIndex;
  42904. var tree = seriesModel.getData().tree;
  42905. var node = tree.getNodeByDataIndex(dataIndex);
  42906. node.isExpand = !node.isExpand;
  42907. });
  42908. });
  42909. registerAction({
  42910. type: 'treeRoam',
  42911. event: 'treeRoam',
  42912. // Here we set 'none' instead of 'update', because roam action
  42913. // just need to update the transform matrix without having to recalculate
  42914. // the layout. So don't need to go through the whole update process, such
  42915. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  42916. update: 'none'
  42917. }, function (payload, ecModel) {
  42918. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42919. var coordSys = seriesModel.coordinateSystem;
  42920. var res = updateCenterAndZoom(coordSys, payload);
  42921. seriesModel.setCenter
  42922. && seriesModel.setCenter(res.center);
  42923. seriesModel.setZoom
  42924. && seriesModel.setZoom(res.zoom);
  42925. });
  42926. });
  42927. /*
  42928. * Licensed to the Apache Software Foundation (ASF) under one
  42929. * or more contributor license agreements. See the NOTICE file
  42930. * distributed with this work for additional information
  42931. * regarding copyright ownership. The ASF licenses this file
  42932. * to you under the Apache License, Version 2.0 (the
  42933. * "License"); you may not use this file except in compliance
  42934. * with the License. You may obtain a copy of the License at
  42935. *
  42936. * http://www.apache.org/licenses/LICENSE-2.0
  42937. *
  42938. * Unless required by applicable law or agreed to in writing,
  42939. * software distributed under the License is distributed on an
  42940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42941. * KIND, either express or implied. See the License for the
  42942. * specific language governing permissions and limitations
  42943. * under the License.
  42944. */
  42945. /**
  42946. * Traverse the tree from bottom to top and do something
  42947. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  42948. * @param {Function} callback
  42949. */
  42950. function eachAfter(root, callback, separation) {
  42951. var nodes = [root];
  42952. var next = [];
  42953. var node;
  42954. while (node = nodes.pop()) { // jshint ignore:line
  42955. next.push(node);
  42956. if (node.isExpand) {
  42957. var children = node.children;
  42958. if (children.length) {
  42959. for (var i = 0; i < children.length; i++) {
  42960. nodes.push(children[i]);
  42961. }
  42962. }
  42963. }
  42964. }
  42965. while (node = next.pop()) { // jshint ignore:line
  42966. callback(node, separation);
  42967. }
  42968. }
  42969. /**
  42970. * Traverse the tree from top to bottom and do something
  42971. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  42972. * @param {Function} callback
  42973. */
  42974. function eachBefore(root, callback) {
  42975. var nodes = [root];
  42976. var node;
  42977. while (node = nodes.pop()) { // jshint ignore:line
  42978. callback(node);
  42979. if (node.isExpand) {
  42980. var children = node.children;
  42981. if (children.length) {
  42982. for (var i = children.length - 1; i >= 0; i--) {
  42983. nodes.push(children[i]);
  42984. }
  42985. }
  42986. }
  42987. }
  42988. }
  42989. /*
  42990. * Licensed to the Apache Software Foundation (ASF) under one
  42991. * or more contributor license agreements. See the NOTICE file
  42992. * distributed with this work for additional information
  42993. * regarding copyright ownership. The ASF licenses this file
  42994. * to you under the Apache License, Version 2.0 (the
  42995. * "License"); you may not use this file except in compliance
  42996. * with the License. You may obtain a copy of the License at
  42997. *
  42998. * http://www.apache.org/licenses/LICENSE-2.0
  42999. *
  43000. * Unless required by applicable law or agreed to in writing,
  43001. * software distributed under the License is distributed on an
  43002. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43003. * KIND, either express or implied. See the License for the
  43004. * specific language governing permissions and limitations
  43005. * under the License.
  43006. */
  43007. var treeLayout = function (ecModel, api) {
  43008. ecModel.eachSeriesByType('tree', function (seriesModel) {
  43009. commonLayout(seriesModel, api);
  43010. });
  43011. };
  43012. function commonLayout(seriesModel, api) {
  43013. var layoutInfo = getViewRect(seriesModel, api);
  43014. seriesModel.layoutInfo = layoutInfo;
  43015. var layout = seriesModel.get('layout');
  43016. var width = 0;
  43017. var height = 0;
  43018. var separation$$1 = null;
  43019. if (layout === 'radial') {
  43020. width = 2 * Math.PI;
  43021. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  43022. separation$$1 = separation(function (node1, node2) {
  43023. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  43024. });
  43025. }
  43026. else {
  43027. width = layoutInfo.width;
  43028. height = layoutInfo.height;
  43029. separation$$1 = separation();
  43030. }
  43031. var virtualRoot = seriesModel.getData().tree.root;
  43032. var realRoot = virtualRoot.children[0];
  43033. if (realRoot) {
  43034. init$2(virtualRoot);
  43035. eachAfter(realRoot, firstWalk, separation$$1);
  43036. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  43037. eachBefore(realRoot, secondWalk);
  43038. var left = realRoot;
  43039. var right = realRoot;
  43040. var bottom = realRoot;
  43041. eachBefore(realRoot, function (node) {
  43042. var x = node.getLayout().x;
  43043. if (x < left.getLayout().x) {
  43044. left = node;
  43045. }
  43046. if (x > right.getLayout().x) {
  43047. right = node;
  43048. }
  43049. if (node.depth > bottom.depth) {
  43050. bottom = node;
  43051. }
  43052. });
  43053. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  43054. var tx = delta - left.getLayout().x;
  43055. var kx = 0;
  43056. var ky = 0;
  43057. var coorX = 0;
  43058. var coorY = 0;
  43059. if (layout === 'radial') {
  43060. kx = width / (right.getLayout().x + delta + tx);
  43061. // here we use (node.depth - 1), bucause the real root's depth is 1
  43062. ky = height / ((bottom.depth - 1) || 1);
  43063. eachBefore(realRoot, function (node) {
  43064. coorX = (node.getLayout().x + tx) * kx;
  43065. coorY = (node.depth - 1) * ky;
  43066. var finalCoor = radialCoordinate(coorX, coorY);
  43067. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  43068. });
  43069. }
  43070. else {
  43071. var orient = seriesModel.getOrient();
  43072. if (orient === 'RL' || orient === 'LR') {
  43073. ky = height / (right.getLayout().x + delta + tx);
  43074. kx = width / ((bottom.depth - 1) || 1);
  43075. eachBefore(realRoot, function (node) {
  43076. coorY = (node.getLayout().x + tx) * ky;
  43077. coorX = orient === 'LR'
  43078. ? (node.depth - 1) * kx
  43079. : width - (node.depth - 1) * kx;
  43080. node.setLayout({x: coorX, y: coorY}, true);
  43081. });
  43082. }
  43083. else if (orient === 'TB' || orient === 'BT') {
  43084. kx = width / (right.getLayout().x + delta + tx);
  43085. ky = height / ((bottom.depth - 1) || 1);
  43086. eachBefore(realRoot, function (node) {
  43087. coorX = (node.getLayout().x + tx) * kx;
  43088. coorY = orient === 'TB'
  43089. ? (node.depth - 1) * ky
  43090. : height - (node.depth - 1) * ky;
  43091. node.setLayout({x: coorX, y: coorY}, true);
  43092. });
  43093. }
  43094. }
  43095. }
  43096. }
  43097. /*
  43098. * Licensed to the Apache Software Foundation (ASF) under one
  43099. * or more contributor license agreements. See the NOTICE file
  43100. * distributed with this work for additional information
  43101. * regarding copyright ownership. The ASF licenses this file
  43102. * to you under the Apache License, Version 2.0 (the
  43103. * "License"); you may not use this file except in compliance
  43104. * with the License. You may obtain a copy of the License at
  43105. *
  43106. * http://www.apache.org/licenses/LICENSE-2.0
  43107. *
  43108. * Unless required by applicable law or agreed to in writing,
  43109. * software distributed under the License is distributed on an
  43110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43111. * KIND, either express or implied. See the License for the
  43112. * specific language governing permissions and limitations
  43113. * under the License.
  43114. */
  43115. registerVisual(visualSymbol('tree', 'circle'));
  43116. registerLayout(treeLayout);
  43117. /*
  43118. * Licensed to the Apache Software Foundation (ASF) under one
  43119. * or more contributor license agreements. See the NOTICE file
  43120. * distributed with this work for additional information
  43121. * regarding copyright ownership. The ASF licenses this file
  43122. * to you under the Apache License, Version 2.0 (the
  43123. * "License"); you may not use this file except in compliance
  43124. * with the License. You may obtain a copy of the License at
  43125. *
  43126. * http://www.apache.org/licenses/LICENSE-2.0
  43127. *
  43128. * Unless required by applicable law or agreed to in writing,
  43129. * software distributed under the License is distributed on an
  43130. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43131. * KIND, either express or implied. See the License for the
  43132. * specific language governing permissions and limitations
  43133. * under the License.
  43134. */
  43135. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  43136. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  43137. var root = seriesModel.getData().tree.root;
  43138. var targetNode = payload.targetNode;
  43139. if (typeof targetNode === 'string') {
  43140. targetNode = root.getNodeById(targetNode);
  43141. }
  43142. if (targetNode && root.contains(targetNode)) {
  43143. return {node: targetNode};
  43144. }
  43145. var targetNodeId = payload.targetNodeId;
  43146. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  43147. return {node: targetNode};
  43148. }
  43149. }
  43150. }
  43151. // Not includes the given node at the last item.
  43152. function getPathToRoot(node) {
  43153. var path = [];
  43154. while (node) {
  43155. node = node.parentNode;
  43156. node && path.push(node);
  43157. }
  43158. return path.reverse();
  43159. }
  43160. function aboveViewRoot(viewRoot, node) {
  43161. var viewPath = getPathToRoot(viewRoot);
  43162. return indexOf(viewPath, node) >= 0;
  43163. }
  43164. // From root to the input node (the input node will be included).
  43165. function wrapTreePathInfo(node, seriesModel) {
  43166. var treePathInfo = [];
  43167. while (node) {
  43168. var nodeDataIndex = node.dataIndex;
  43169. treePathInfo.push({
  43170. name: node.name,
  43171. dataIndex: nodeDataIndex,
  43172. value: seriesModel.getRawValue(nodeDataIndex)
  43173. });
  43174. node = node.parentNode;
  43175. }
  43176. treePathInfo.reverse();
  43177. return treePathInfo;
  43178. }
  43179. /*
  43180. * Licensed to the Apache Software Foundation (ASF) under one
  43181. * or more contributor license agreements. See the NOTICE file
  43182. * distributed with this work for additional information
  43183. * regarding copyright ownership. The ASF licenses this file
  43184. * to you under the Apache License, Version 2.0 (the
  43185. * "License"); you may not use this file except in compliance
  43186. * with the License. You may obtain a copy of the License at
  43187. *
  43188. * http://www.apache.org/licenses/LICENSE-2.0
  43189. *
  43190. * Unless required by applicable law or agreed to in writing,
  43191. * software distributed under the License is distributed on an
  43192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43193. * KIND, either express or implied. See the License for the
  43194. * specific language governing permissions and limitations
  43195. * under the License.
  43196. */
  43197. SeriesModel.extend({
  43198. type: 'series.treemap',
  43199. layoutMode: 'box',
  43200. dependencies: ['grid', 'polar'],
  43201. /**
  43202. * @type {module:echarts/data/Tree~Node}
  43203. */
  43204. _viewRoot: null,
  43205. defaultOption: {
  43206. // Disable progressive rendering
  43207. progressive: 0,
  43208. hoverLayerThreshold: Infinity,
  43209. // center: ['50%', '50%'], // not supported in ec3.
  43210. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  43211. left: 'center',
  43212. top: 'middle',
  43213. right: null,
  43214. bottom: null,
  43215. width: '80%',
  43216. height: '80%',
  43217. sort: true, // Can be null or false or true
  43218. // (order by desc default, asc not supported yet (strange effect))
  43219. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  43220. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  43221. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  43222. // Count from zero (zero represents only view root).
  43223. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  43224. // to align specialized icon. ▷▶❒❐▼✚
  43225. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  43226. // target node area in the view area.
  43227. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  43228. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  43229. // If leafDepth is set and clicking a node which has children but
  43230. // be on left depth, the behaviour would be changing root. Otherwise
  43231. // use behavious defined above.
  43232. animation: true,
  43233. animationDurationUpdate: 900,
  43234. animationEasing: 'quinticInOut',
  43235. breadcrumb: {
  43236. show: true,
  43237. height: 22,
  43238. left: 'center',
  43239. top: 'bottom',
  43240. // right
  43241. // bottom
  43242. emptyItemWidth: 25, // Width of empty node.
  43243. itemStyle: {
  43244. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  43245. borderColor: 'rgba(255,255,255,0.7)',
  43246. borderWidth: 1,
  43247. shadowColor: 'rgba(150,150,150,1)',
  43248. shadowBlur: 3,
  43249. shadowOffsetX: 0,
  43250. shadowOffsetY: 0,
  43251. textStyle: {
  43252. color: '#fff'
  43253. }
  43254. },
  43255. emphasis: {
  43256. textStyle: {}
  43257. }
  43258. },
  43259. label: {
  43260. show: true,
  43261. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  43262. distance: 0,
  43263. padding: 5,
  43264. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  43265. // formatter: null,
  43266. color: '#fff',
  43267. ellipsis: true
  43268. // align
  43269. // verticalAlign
  43270. },
  43271. upperLabel: { // Label when node is parent.
  43272. show: false,
  43273. position: [0, '50%'],
  43274. height: 20,
  43275. // formatter: null,
  43276. color: '#fff',
  43277. ellipsis: true,
  43278. // align: null,
  43279. verticalAlign: 'middle'
  43280. },
  43281. itemStyle: {
  43282. color: null, // Can be 'none' if not necessary.
  43283. colorAlpha: null, // Can be 'none' if not necessary.
  43284. colorSaturation: null, // Can be 'none' if not necessary.
  43285. borderWidth: 0,
  43286. gapWidth: 0,
  43287. borderColor: '#fff',
  43288. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  43289. // border color is evaluated by color of current node and
  43290. // borderColorSaturation.
  43291. },
  43292. emphasis: {
  43293. upperLabel: {
  43294. show: true,
  43295. position: [0, '50%'],
  43296. color: '#fff',
  43297. ellipsis: true,
  43298. verticalAlign: 'middle'
  43299. }
  43300. },
  43301. visualDimension: 0, // Can be 0, 1, 2, 3.
  43302. visualMin: null,
  43303. visualMax: null,
  43304. color: [], // + treemapSeries.color should not be modified. Please only modified
  43305. // level[n].color (if necessary).
  43306. // + Specify color list of each level. level[0].color would be global
  43307. // color list if not specified. (see method `setDefault`).
  43308. // + But set as a empty array to forbid fetch color from global palette
  43309. // when using nodeModel.get('color'), otherwise nodes on deep level
  43310. // will always has color palette set and are not able to inherit color
  43311. // from parent node.
  43312. // + TreemapSeries.color can not be set as 'none', otherwise effect
  43313. // legend color fetching (see seriesColor.js).
  43314. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  43315. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  43316. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  43317. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  43318. // be rendered. Only works when sort is 'asc' or 'desc'.
  43319. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  43320. // grandchildren will not show.
  43321. // Why grandchildren? If not grandchildren but children,
  43322. // some siblings show children and some not,
  43323. // the appearance may be mess and not consistent,
  43324. levels: [] // Each item: {
  43325. // visibleMin, itemStyle, visualDimension, label
  43326. // }
  43327. // data: {
  43328. // value: [],
  43329. // children: [],
  43330. // link: 'http://xxx.xxx.xxx',
  43331. // target: 'blank' or 'self'
  43332. // }
  43333. },
  43334. /**
  43335. * @override
  43336. */
  43337. getInitialData: function (option, ecModel) {
  43338. // Create a virtual root.
  43339. var root = {name: option.name, children: option.data};
  43340. completeTreeValue(root);
  43341. var levels = option.levels || [];
  43342. levels = option.levels = setDefault(levels, ecModel);
  43343. var treeOption = {};
  43344. treeOption.levels = levels;
  43345. // Make sure always a new tree is created when setOption,
  43346. // in TreemapView, we check whether oldTree === newTree
  43347. // to choose mappings approach among old shapes and new shapes.
  43348. return Tree.createTree(root, this, treeOption).data;
  43349. },
  43350. optionUpdated: function () {
  43351. this.resetViewRoot();
  43352. },
  43353. /**
  43354. * @override
  43355. * @param {number} dataIndex
  43356. * @param {boolean} [mutipleSeries=false]
  43357. */
  43358. formatTooltip: function (dataIndex) {
  43359. var data = this.getData();
  43360. var value = this.getRawValue(dataIndex);
  43361. var formattedValue = isArray(value)
  43362. ? addCommas(value[0]) : addCommas(value);
  43363. var name = data.getName(dataIndex);
  43364. return encodeHTML(name + ': ' + formattedValue);
  43365. },
  43366. /**
  43367. * Add tree path to tooltip param
  43368. *
  43369. * @override
  43370. * @param {number} dataIndex
  43371. * @return {Object}
  43372. */
  43373. getDataParams: function (dataIndex) {
  43374. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  43375. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  43376. params.treePathInfo = wrapTreePathInfo(node, this);
  43377. return params;
  43378. },
  43379. /**
  43380. * @public
  43381. * @param {Object} layoutInfo {
  43382. * x: containerGroup x
  43383. * y: containerGroup y
  43384. * width: containerGroup width
  43385. * height: containerGroup height
  43386. * }
  43387. */
  43388. setLayoutInfo: function (layoutInfo) {
  43389. /**
  43390. * @readOnly
  43391. * @type {Object}
  43392. */
  43393. this.layoutInfo = this.layoutInfo || {};
  43394. extend(this.layoutInfo, layoutInfo);
  43395. },
  43396. /**
  43397. * @param {string} id
  43398. * @return {number} index
  43399. */
  43400. mapIdToIndex: function (id) {
  43401. // A feature is implemented:
  43402. // index is monotone increasing with the sequence of
  43403. // input id at the first time.
  43404. // This feature can make sure that each data item and its
  43405. // mapped color have the same index between data list and
  43406. // color list at the beginning, which is useful for user
  43407. // to adjust data-color mapping.
  43408. /**
  43409. * @private
  43410. * @type {Object}
  43411. */
  43412. var idIndexMap = this._idIndexMap;
  43413. if (!idIndexMap) {
  43414. idIndexMap = this._idIndexMap = createHashMap();
  43415. /**
  43416. * @private
  43417. * @type {number}
  43418. */
  43419. this._idIndexMapCount = 0;
  43420. }
  43421. var index = idIndexMap.get(id);
  43422. if (index == null) {
  43423. idIndexMap.set(id, index = this._idIndexMapCount++);
  43424. }
  43425. return index;
  43426. },
  43427. getViewRoot: function () {
  43428. return this._viewRoot;
  43429. },
  43430. /**
  43431. * @param {module:echarts/data/Tree~Node} [viewRoot]
  43432. */
  43433. resetViewRoot: function (viewRoot) {
  43434. viewRoot
  43435. ? (this._viewRoot = viewRoot)
  43436. : (viewRoot = this._viewRoot);
  43437. var root = this.getRawData().tree.root;
  43438. if (!viewRoot
  43439. || (viewRoot !== root && !root.contains(viewRoot))
  43440. ) {
  43441. this._viewRoot = root;
  43442. }
  43443. }
  43444. });
  43445. /**
  43446. * @param {Object} dataNode
  43447. */
  43448. function completeTreeValue(dataNode) {
  43449. // Postorder travel tree.
  43450. // If value of none-leaf node is not set,
  43451. // calculate it by suming up the value of all children.
  43452. var sum = 0;
  43453. each$1(dataNode.children, function (child) {
  43454. completeTreeValue(child);
  43455. var childValue = child.value;
  43456. isArray(childValue) && (childValue = childValue[0]);
  43457. sum += childValue;
  43458. });
  43459. var thisValue = dataNode.value;
  43460. if (isArray(thisValue)) {
  43461. thisValue = thisValue[0];
  43462. }
  43463. if (thisValue == null || isNaN(thisValue)) {
  43464. thisValue = sum;
  43465. }
  43466. // Value should not less than 0.
  43467. if (thisValue < 0) {
  43468. thisValue = 0;
  43469. }
  43470. isArray(dataNode.value)
  43471. ? (dataNode.value[0] = thisValue)
  43472. : (dataNode.value = thisValue);
  43473. }
  43474. /**
  43475. * set default to level configuration
  43476. */
  43477. function setDefault(levels, ecModel) {
  43478. var globalColorList = ecModel.get('color');
  43479. if (!globalColorList) {
  43480. return;
  43481. }
  43482. levels = levels || [];
  43483. var hasColorDefine;
  43484. each$1(levels, function (levelDefine) {
  43485. var model = new Model(levelDefine);
  43486. var modelColor = model.get('color');
  43487. if (model.get('itemStyle.color')
  43488. || (modelColor && modelColor !== 'none')
  43489. ) {
  43490. hasColorDefine = true;
  43491. }
  43492. });
  43493. if (!hasColorDefine) {
  43494. var level0 = levels[0] || (levels[0] = {});
  43495. level0.color = globalColorList.slice();
  43496. }
  43497. return levels;
  43498. }
  43499. /*
  43500. * Licensed to the Apache Software Foundation (ASF) under one
  43501. * or more contributor license agreements. See the NOTICE file
  43502. * distributed with this work for additional information
  43503. * regarding copyright ownership. The ASF licenses this file
  43504. * to you under the Apache License, Version 2.0 (the
  43505. * "License"); you may not use this file except in compliance
  43506. * with the License. You may obtain a copy of the License at
  43507. *
  43508. * http://www.apache.org/licenses/LICENSE-2.0
  43509. *
  43510. * Unless required by applicable law or agreed to in writing,
  43511. * software distributed under the License is distributed on an
  43512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43513. * KIND, either express or implied. See the License for the
  43514. * specific language governing permissions and limitations
  43515. * under the License.
  43516. */
  43517. var TEXT_PADDING = 8;
  43518. var ITEM_GAP = 8;
  43519. var ARRAY_LENGTH = 5;
  43520. function Breadcrumb(containerGroup) {
  43521. /**
  43522. * @private
  43523. * @type {module:zrender/container/Group}
  43524. */
  43525. this.group = new Group();
  43526. containerGroup.add(this.group);
  43527. }
  43528. Breadcrumb.prototype = {
  43529. constructor: Breadcrumb,
  43530. render: function (seriesModel, api, targetNode, onSelect) {
  43531. var model = seriesModel.getModel('breadcrumb');
  43532. var thisGroup = this.group;
  43533. thisGroup.removeAll();
  43534. if (!model.get('show') || !targetNode) {
  43535. return;
  43536. }
  43537. var normalStyleModel = model.getModel('itemStyle');
  43538. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  43539. var textStyleModel = normalStyleModel.getModel('textStyle');
  43540. var layoutParam = {
  43541. pos: {
  43542. left: model.get('left'),
  43543. right: model.get('right'),
  43544. top: model.get('top'),
  43545. bottom: model.get('bottom')
  43546. },
  43547. box: {
  43548. width: api.getWidth(),
  43549. height: api.getHeight()
  43550. },
  43551. emptyItemWidth: model.get('emptyItemWidth'),
  43552. totalWidth: 0,
  43553. renderList: []
  43554. };
  43555. this._prepare(targetNode, layoutParam, textStyleModel);
  43556. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  43557. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  43558. },
  43559. /**
  43560. * Prepare render list and total width
  43561. * @private
  43562. */
  43563. _prepare: function (targetNode, layoutParam, textStyleModel) {
  43564. for (var node = targetNode; node; node = node.parentNode) {
  43565. var text = node.getModel().get('name');
  43566. var textRect = textStyleModel.getTextRect(text);
  43567. var itemWidth = Math.max(
  43568. textRect.width + TEXT_PADDING * 2,
  43569. layoutParam.emptyItemWidth
  43570. );
  43571. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  43572. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  43573. }
  43574. },
  43575. /**
  43576. * @private
  43577. */
  43578. _renderContent: function (
  43579. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  43580. ) {
  43581. // Start rendering.
  43582. var lastX = 0;
  43583. var emptyItemWidth = layoutParam.emptyItemWidth;
  43584. var height = seriesModel.get('breadcrumb.height');
  43585. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  43586. var totalWidth = layoutParam.totalWidth;
  43587. var renderList = layoutParam.renderList;
  43588. for (var i = renderList.length - 1; i >= 0; i--) {
  43589. var item = renderList[i];
  43590. var itemNode = item.node;
  43591. var itemWidth = item.width;
  43592. var text = item.text;
  43593. // Hdie text and shorten width if necessary.
  43594. if (totalWidth > availableSize.width) {
  43595. totalWidth -= itemWidth - emptyItemWidth;
  43596. itemWidth = emptyItemWidth;
  43597. text = null;
  43598. }
  43599. var el = new Polygon({
  43600. shape: {
  43601. points: makeItemPoints(
  43602. lastX, 0, itemWidth, height,
  43603. i === renderList.length - 1, i === 0
  43604. )
  43605. },
  43606. style: defaults(
  43607. normalStyleModel.getItemStyle(),
  43608. {
  43609. lineJoin: 'bevel',
  43610. text: text,
  43611. textFill: textStyleModel.getTextColor(),
  43612. textFont: textStyleModel.getFont()
  43613. }
  43614. ),
  43615. z: 10,
  43616. onclick: curry(onSelect, itemNode)
  43617. });
  43618. this.group.add(el);
  43619. packEventData(el, seriesModel, itemNode);
  43620. lastX += itemWidth + ITEM_GAP;
  43621. }
  43622. },
  43623. /**
  43624. * @override
  43625. */
  43626. remove: function () {
  43627. this.group.removeAll();
  43628. }
  43629. };
  43630. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  43631. var points = [
  43632. [head ? x : x - ARRAY_LENGTH, y],
  43633. [x + itemWidth, y],
  43634. [x + itemWidth, y + itemHeight],
  43635. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  43636. ];
  43637. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  43638. !head && points.push([x, y + itemHeight / 2]);
  43639. return points;
  43640. }
  43641. // Package custom mouse event.
  43642. function packEventData(el, seriesModel, itemNode) {
  43643. el.eventData = {
  43644. componentType: 'series',
  43645. componentSubType: 'treemap',
  43646. componentIndex: seriesModel.componentIndex,
  43647. seriesIndex: seriesModel.componentIndex,
  43648. seriesName: seriesModel.name,
  43649. seriesType: 'treemap',
  43650. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  43651. nodeData: {
  43652. dataIndex: itemNode && itemNode.dataIndex,
  43653. name: itemNode && itemNode.name
  43654. },
  43655. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  43656. };
  43657. }
  43658. /*
  43659. * Licensed to the Apache Software Foundation (ASF) under one
  43660. * or more contributor license agreements. See the NOTICE file
  43661. * distributed with this work for additional information
  43662. * regarding copyright ownership. The ASF licenses this file
  43663. * to you under the Apache License, Version 2.0 (the
  43664. * "License"); you may not use this file except in compliance
  43665. * with the License. You may obtain a copy of the License at
  43666. *
  43667. * http://www.apache.org/licenses/LICENSE-2.0
  43668. *
  43669. * Unless required by applicable law or agreed to in writing,
  43670. * software distributed under the License is distributed on an
  43671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43672. * KIND, either express or implied. See the License for the
  43673. * specific language governing permissions and limitations
  43674. * under the License.
  43675. */
  43676. /**
  43677. * @param {number} [time=500] Time in ms
  43678. * @param {string} [easing='linear']
  43679. * @param {number} [delay=0]
  43680. * @param {Function} [callback]
  43681. *
  43682. * @example
  43683. * // Animate position
  43684. * animation
  43685. * .createWrap()
  43686. * .add(el1, {position: [10, 10]})
  43687. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  43688. * .done(function () { // done })
  43689. * .start('cubicOut');
  43690. */
  43691. function createWrap() {
  43692. var storage = [];
  43693. var elExistsMap = {};
  43694. var doneCallback;
  43695. return {
  43696. /**
  43697. * Caution: a el can only be added once, otherwise 'done'
  43698. * might not be called. This method checks this (by el.id),
  43699. * suppresses adding and returns false when existing el found.
  43700. *
  43701. * @param {modele:zrender/Element} el
  43702. * @param {Object} target
  43703. * @param {number} [time=500]
  43704. * @param {number} [delay=0]
  43705. * @param {string} [easing='linear']
  43706. * @return {boolean} Whether adding succeeded.
  43707. *
  43708. * @example
  43709. * add(el, target, time, delay, easing);
  43710. * add(el, target, time, easing);
  43711. * add(el, target, time);
  43712. * add(el, target);
  43713. */
  43714. add: function (el, target, time, delay, easing) {
  43715. if (isString(delay)) {
  43716. easing = delay;
  43717. delay = 0;
  43718. }
  43719. if (elExistsMap[el.id]) {
  43720. return false;
  43721. }
  43722. elExistsMap[el.id] = 1;
  43723. storage.push(
  43724. {el: el, target: target, time: time, delay: delay, easing: easing}
  43725. );
  43726. return true;
  43727. },
  43728. /**
  43729. * Only execute when animation finished. Will not execute when any
  43730. * of 'stop' or 'stopAnimation' called.
  43731. *
  43732. * @param {Function} callback
  43733. */
  43734. done: function (callback) {
  43735. doneCallback = callback;
  43736. return this;
  43737. },
  43738. /**
  43739. * Will stop exist animation firstly.
  43740. */
  43741. start: function () {
  43742. var count = storage.length;
  43743. for (var i = 0, len = storage.length; i < len; i++) {
  43744. var item = storage[i];
  43745. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  43746. }
  43747. return this;
  43748. function done() {
  43749. count--;
  43750. if (!count) {
  43751. storage.length = 0;
  43752. elExistsMap = {};
  43753. doneCallback && doneCallback();
  43754. }
  43755. }
  43756. }
  43757. };
  43758. }
  43759. /*
  43760. * Licensed to the Apache Software Foundation (ASF) under one
  43761. * or more contributor license agreements. See the NOTICE file
  43762. * distributed with this work for additional information
  43763. * regarding copyright ownership. The ASF licenses this file
  43764. * to you under the Apache License, Version 2.0 (the
  43765. * "License"); you may not use this file except in compliance
  43766. * with the License. You may obtain a copy of the License at
  43767. *
  43768. * http://www.apache.org/licenses/LICENSE-2.0
  43769. *
  43770. * Unless required by applicable law or agreed to in writing,
  43771. * software distributed under the License is distributed on an
  43772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43773. * KIND, either express or implied. See the License for the
  43774. * specific language governing permissions and limitations
  43775. * under the License.
  43776. */
  43777. var bind$1 = bind;
  43778. var Group$2 = Group;
  43779. var Rect$1 = Rect;
  43780. var each$8 = each$1;
  43781. var DRAG_THRESHOLD = 3;
  43782. var PATH_LABEL_NOAMAL = ['label'];
  43783. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  43784. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  43785. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  43786. var Z_BASE = 10; // Should bigger than every z.
  43787. var Z_BG = 1;
  43788. var Z_CONTENT = 2;
  43789. var getItemStyleEmphasis = makeStyleMapper([
  43790. ['fill', 'color'],
  43791. // `borderColor` and `borderWidth` has been occupied,
  43792. // so use `stroke` to indicate the stroke of the rect.
  43793. ['stroke', 'strokeColor'],
  43794. ['lineWidth', 'strokeWidth'],
  43795. ['shadowBlur'],
  43796. ['shadowOffsetX'],
  43797. ['shadowOffsetY'],
  43798. ['shadowColor']
  43799. ]);
  43800. var getItemStyleNormal = function (model) {
  43801. // Normal style props should include emphasis style props.
  43802. var itemStyle = getItemStyleEmphasis(model);
  43803. // Clear styles set by emphasis.
  43804. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  43805. return itemStyle;
  43806. };
  43807. extendChartView({
  43808. type: 'treemap',
  43809. /**
  43810. * @override
  43811. */
  43812. init: function (o, api) {
  43813. /**
  43814. * @private
  43815. * @type {module:zrender/container/Group}
  43816. */
  43817. this._containerGroup;
  43818. /**
  43819. * @private
  43820. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  43821. */
  43822. this._storage = createStorage();
  43823. /**
  43824. * @private
  43825. * @type {module:echarts/data/Tree}
  43826. */
  43827. this._oldTree;
  43828. /**
  43829. * @private
  43830. * @type {module:echarts/chart/treemap/Breadcrumb}
  43831. */
  43832. this._breadcrumb;
  43833. /**
  43834. * @private
  43835. * @type {module:echarts/component/helper/RoamController}
  43836. */
  43837. this._controller;
  43838. /**
  43839. * 'ready', 'animating'
  43840. * @private
  43841. */
  43842. this._state = 'ready';
  43843. },
  43844. /**
  43845. * @override
  43846. */
  43847. render: function (seriesModel, ecModel, api, payload) {
  43848. var models = ecModel.findComponents({
  43849. mainType: 'series', subType: 'treemap', query: payload
  43850. });
  43851. if (indexOf(models, seriesModel) < 0) {
  43852. return;
  43853. }
  43854. this.seriesModel = seriesModel;
  43855. this.api = api;
  43856. this.ecModel = ecModel;
  43857. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43858. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43859. var payloadType = payload && payload.type;
  43860. var layoutInfo = seriesModel.layoutInfo;
  43861. var isInit = !this._oldTree;
  43862. var thisStorage = this._storage;
  43863. // Mark new root when action is treemapRootToNode.
  43864. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  43865. ? {
  43866. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  43867. direction: payload.direction
  43868. }
  43869. : null;
  43870. var containerGroup = this._giveContainerGroup(layoutInfo);
  43871. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  43872. (
  43873. !isInit && (
  43874. !payloadType
  43875. || payloadType === 'treemapZoomToNode'
  43876. || payloadType === 'treemapRootToNode'
  43877. )
  43878. )
  43879. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  43880. : renderResult.renderFinally();
  43881. this._resetController(api);
  43882. this._renderBreadcrumb(seriesModel, api, targetInfo);
  43883. },
  43884. /**
  43885. * @private
  43886. */
  43887. _giveContainerGroup: function (layoutInfo) {
  43888. var containerGroup = this._containerGroup;
  43889. if (!containerGroup) {
  43890. // FIXME
  43891. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  43892. containerGroup = this._containerGroup = new Group$2();
  43893. this._initEvents(containerGroup);
  43894. this.group.add(containerGroup);
  43895. }
  43896. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  43897. return containerGroup;
  43898. },
  43899. /**
  43900. * @private
  43901. */
  43902. _doRender: function (containerGroup, seriesModel, reRoot) {
  43903. var thisTree = seriesModel.getData().tree;
  43904. var oldTree = this._oldTree;
  43905. // Clear last shape records.
  43906. var lastsForAnimation = createStorage();
  43907. var thisStorage = createStorage();
  43908. var oldStorage = this._storage;
  43909. var willInvisibleEls = [];
  43910. var doRenderNode = curry(
  43911. renderNode, seriesModel,
  43912. thisStorage, oldStorage, reRoot,
  43913. lastsForAnimation, willInvisibleEls
  43914. );
  43915. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  43916. // the oldTree is actually losted, so we can not find all of the old graphic
  43917. // elements from tree. So we use this stragegy: make element storage, move
  43918. // from old storage to new storage, clear old storage.
  43919. dualTravel(
  43920. thisTree.root ? [thisTree.root] : [],
  43921. (oldTree && oldTree.root) ? [oldTree.root] : [],
  43922. containerGroup,
  43923. thisTree === oldTree || !oldTree,
  43924. 0
  43925. );
  43926. // Process all removing.
  43927. var willDeleteEls = clearStorage(oldStorage);
  43928. this._oldTree = thisTree;
  43929. this._storage = thisStorage;
  43930. return {
  43931. lastsForAnimation: lastsForAnimation,
  43932. willDeleteEls: willDeleteEls,
  43933. renderFinally: renderFinally
  43934. };
  43935. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  43936. // When 'render' is triggered by action,
  43937. // 'this' and 'old' may be the same tree,
  43938. // we use rawIndex in that case.
  43939. if (sameTree) {
  43940. oldViewChildren = thisViewChildren;
  43941. each$8(thisViewChildren, function (child, index) {
  43942. !child.isRemoved() && processNode(index, index);
  43943. });
  43944. }
  43945. // Diff hierarchically (diff only in each subtree, but not whole).
  43946. // because, consistency of view is important.
  43947. else {
  43948. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  43949. .add(processNode)
  43950. .update(processNode)
  43951. .remove(curry(processNode, null))
  43952. .execute();
  43953. }
  43954. function getKey(node) {
  43955. // Identify by name or raw index.
  43956. return node.getId();
  43957. }
  43958. function processNode(newIndex, oldIndex) {
  43959. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  43960. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  43961. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  43962. group && dualTravel(
  43963. thisNode && thisNode.viewChildren || [],
  43964. oldNode && oldNode.viewChildren || [],
  43965. group,
  43966. sameTree,
  43967. depth + 1
  43968. );
  43969. }
  43970. }
  43971. function clearStorage(storage) {
  43972. var willDeleteEls = createStorage();
  43973. storage && each$8(storage, function (store, storageName) {
  43974. var delEls = willDeleteEls[storageName];
  43975. each$8(store, function (el) {
  43976. el && (delEls.push(el), el.__tmWillDelete = 1);
  43977. });
  43978. });
  43979. return willDeleteEls;
  43980. }
  43981. function renderFinally() {
  43982. each$8(willDeleteEls, function (els) {
  43983. each$8(els, function (el) {
  43984. el.parent && el.parent.remove(el);
  43985. });
  43986. });
  43987. each$8(willInvisibleEls, function (el) {
  43988. el.invisible = true;
  43989. // Setting invisible is for optimizing, so no need to set dirty,
  43990. // just mark as invisible.
  43991. el.dirty();
  43992. });
  43993. }
  43994. },
  43995. /**
  43996. * @private
  43997. */
  43998. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  43999. if (!seriesModel.get('animation')) {
  44000. return;
  44001. }
  44002. var duration = seriesModel.get('animationDurationUpdate');
  44003. var easing = seriesModel.get('animationEasing');
  44004. var animationWrap = createWrap();
  44005. // Make delete animations.
  44006. each$8(renderResult.willDeleteEls, function (store, storageName) {
  44007. each$8(store, function (el, rawIndex) {
  44008. if (el.invisible) {
  44009. return;
  44010. }
  44011. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  44012. var target;
  44013. if (reRoot && reRoot.direction === 'drillDown') {
  44014. target = parent === reRoot.rootNodeGroup
  44015. // This is the content element of view root.
  44016. // Only `content` will enter this branch, because
  44017. // `background` and `nodeGroup` will not be deleted.
  44018. ? {
  44019. shape: {
  44020. x: 0,
  44021. y: 0,
  44022. width: parent.__tmNodeWidth,
  44023. height: parent.__tmNodeHeight
  44024. },
  44025. style: {
  44026. opacity: 0
  44027. }
  44028. }
  44029. // Others.
  44030. : {style: {opacity: 0}};
  44031. }
  44032. else {
  44033. var targetX = 0;
  44034. var targetY = 0;
  44035. if (!parent.__tmWillDelete) {
  44036. // Let node animate to right-bottom corner, cooperating with fadeout,
  44037. // which is appropriate for user understanding.
  44038. // Divided by 2 for reRoot rolling up effect.
  44039. targetX = parent.__tmNodeWidth / 2;
  44040. targetY = parent.__tmNodeHeight / 2;
  44041. }
  44042. target = storageName === 'nodeGroup'
  44043. ? {position: [targetX, targetY], style: {opacity: 0}}
  44044. : {
  44045. shape: {x: targetX, y: targetY, width: 0, height: 0},
  44046. style: {opacity: 0}
  44047. };
  44048. }
  44049. target && animationWrap.add(el, target, duration, easing);
  44050. });
  44051. });
  44052. // Make other animations
  44053. each$8(this._storage, function (store, storageName) {
  44054. each$8(store, function (el, rawIndex) {
  44055. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  44056. var target = {};
  44057. if (!last) {
  44058. return;
  44059. }
  44060. if (storageName === 'nodeGroup') {
  44061. if (last.old) {
  44062. target.position = el.position.slice();
  44063. el.attr('position', last.old);
  44064. }
  44065. }
  44066. else {
  44067. if (last.old) {
  44068. target.shape = extend({}, el.shape);
  44069. el.setShape(last.old);
  44070. }
  44071. if (last.fadein) {
  44072. el.setStyle('opacity', 0);
  44073. target.style = {opacity: 1};
  44074. }
  44075. // When animation is stopped for succedent animation starting,
  44076. // el.style.opacity might not be 1
  44077. else if (el.style.opacity !== 1) {
  44078. target.style = {opacity: 1};
  44079. }
  44080. }
  44081. animationWrap.add(el, target, duration, easing);
  44082. });
  44083. }, this);
  44084. this._state = 'animating';
  44085. animationWrap
  44086. .done(bind$1(function () {
  44087. this._state = 'ready';
  44088. renderResult.renderFinally();
  44089. }, this))
  44090. .start();
  44091. },
  44092. /**
  44093. * @private
  44094. */
  44095. _resetController: function (api) {
  44096. var controller = this._controller;
  44097. // Init controller.
  44098. if (!controller) {
  44099. controller = this._controller = new RoamController(api.getZr());
  44100. controller.enable(this.seriesModel.get('roam'));
  44101. controller.on('pan', bind$1(this._onPan, this));
  44102. controller.on('zoom', bind$1(this._onZoom, this));
  44103. }
  44104. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  44105. controller.setPointerChecker(function (e, x, y) {
  44106. return rect.contain(x, y);
  44107. });
  44108. },
  44109. /**
  44110. * @private
  44111. */
  44112. _clearController: function () {
  44113. var controller = this._controller;
  44114. if (controller) {
  44115. controller.dispose();
  44116. controller = null;
  44117. }
  44118. },
  44119. /**
  44120. * @private
  44121. */
  44122. _onPan: function (e) {
  44123. if (this._state !== 'animating'
  44124. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  44125. ) {
  44126. // These param must not be cached.
  44127. var root = this.seriesModel.getData().tree.root;
  44128. if (!root) {
  44129. return;
  44130. }
  44131. var rootLayout = root.getLayout();
  44132. if (!rootLayout) {
  44133. return;
  44134. }
  44135. this.api.dispatchAction({
  44136. type: 'treemapMove',
  44137. from: this.uid,
  44138. seriesId: this.seriesModel.id,
  44139. rootRect: {
  44140. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  44141. width: rootLayout.width, height: rootLayout.height
  44142. }
  44143. });
  44144. }
  44145. },
  44146. /**
  44147. * @private
  44148. */
  44149. _onZoom: function (e) {
  44150. var mouseX = e.originX;
  44151. var mouseY = e.originY;
  44152. if (this._state !== 'animating') {
  44153. // These param must not be cached.
  44154. var root = this.seriesModel.getData().tree.root;
  44155. if (!root) {
  44156. return;
  44157. }
  44158. var rootLayout = root.getLayout();
  44159. if (!rootLayout) {
  44160. return;
  44161. }
  44162. var rect = new BoundingRect(
  44163. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  44164. );
  44165. var layoutInfo = this.seriesModel.layoutInfo;
  44166. // Transform mouse coord from global to containerGroup.
  44167. mouseX -= layoutInfo.x;
  44168. mouseY -= layoutInfo.y;
  44169. // Scale root bounding rect.
  44170. var m = create$1();
  44171. translate(m, m, [-mouseX, -mouseY]);
  44172. scale$1(m, m, [e.scale, e.scale]);
  44173. translate(m, m, [mouseX, mouseY]);
  44174. rect.applyTransform(m);
  44175. this.api.dispatchAction({
  44176. type: 'treemapRender',
  44177. from: this.uid,
  44178. seriesId: this.seriesModel.id,
  44179. rootRect: {
  44180. x: rect.x, y: rect.y,
  44181. width: rect.width, height: rect.height
  44182. }
  44183. });
  44184. }
  44185. },
  44186. /**
  44187. * @private
  44188. */
  44189. _initEvents: function (containerGroup) {
  44190. containerGroup.on('click', function (e) {
  44191. if (this._state !== 'ready') {
  44192. return;
  44193. }
  44194. var nodeClick = this.seriesModel.get('nodeClick', true);
  44195. if (!nodeClick) {
  44196. return;
  44197. }
  44198. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  44199. if (!targetInfo) {
  44200. return;
  44201. }
  44202. var node = targetInfo.node;
  44203. if (node.getLayout().isLeafRoot) {
  44204. this._rootToNode(targetInfo);
  44205. }
  44206. else {
  44207. if (nodeClick === 'zoomToNode') {
  44208. this._zoomToNode(targetInfo);
  44209. }
  44210. else if (nodeClick === 'link') {
  44211. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  44212. var link = itemModel.get('link', true);
  44213. var linkTarget = itemModel.get('target', true) || 'blank';
  44214. link && window.open(link, linkTarget);
  44215. }
  44216. }
  44217. }, this);
  44218. },
  44219. /**
  44220. * @private
  44221. */
  44222. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  44223. if (!targetInfo) {
  44224. targetInfo = seriesModel.get('leafDepth', true) != null
  44225. ? {node: seriesModel.getViewRoot()}
  44226. // FIXME
  44227. // better way?
  44228. // Find breadcrumb tail on center of containerGroup.
  44229. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  44230. if (!targetInfo) {
  44231. targetInfo = {node: seriesModel.getData().tree.root};
  44232. }
  44233. }
  44234. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  44235. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  44236. function onSelect(node) {
  44237. if (this._state !== 'animating') {
  44238. aboveViewRoot(seriesModel.getViewRoot(), node)
  44239. ? this._rootToNode({node: node})
  44240. : this._zoomToNode({node: node});
  44241. }
  44242. }
  44243. },
  44244. /**
  44245. * @override
  44246. */
  44247. remove: function () {
  44248. this._clearController();
  44249. this._containerGroup && this._containerGroup.removeAll();
  44250. this._storage = createStorage();
  44251. this._state = 'ready';
  44252. this._breadcrumb && this._breadcrumb.remove();
  44253. },
  44254. dispose: function () {
  44255. this._clearController();
  44256. },
  44257. /**
  44258. * @private
  44259. */
  44260. _zoomToNode: function (targetInfo) {
  44261. this.api.dispatchAction({
  44262. type: 'treemapZoomToNode',
  44263. from: this.uid,
  44264. seriesId: this.seriesModel.id,
  44265. targetNode: targetInfo.node
  44266. });
  44267. },
  44268. /**
  44269. * @private
  44270. */
  44271. _rootToNode: function (targetInfo) {
  44272. this.api.dispatchAction({
  44273. type: 'treemapRootToNode',
  44274. from: this.uid,
  44275. seriesId: this.seriesModel.id,
  44276. targetNode: targetInfo.node
  44277. });
  44278. },
  44279. /**
  44280. * @public
  44281. * @param {number} x Global coord x.
  44282. * @param {number} y Global coord y.
  44283. * @return {Object} info If not found, return undefined;
  44284. * @return {number} info.node Target node.
  44285. * @return {number} info.offsetX x refer to target node.
  44286. * @return {number} info.offsetY y refer to target node.
  44287. */
  44288. findTarget: function (x, y) {
  44289. var targetInfo;
  44290. var viewRoot = this.seriesModel.getViewRoot();
  44291. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  44292. var bgEl = this._storage.background[node.getRawIndex()];
  44293. // If invisible, there might be no element.
  44294. if (bgEl) {
  44295. var point = bgEl.transformCoordToLocal(x, y);
  44296. var shape = bgEl.shape;
  44297. // For performance consideration, dont use 'getBoundingRect'.
  44298. if (shape.x <= point[0]
  44299. && point[0] <= shape.x + shape.width
  44300. && shape.y <= point[1]
  44301. && point[1] <= shape.y + shape.height
  44302. ) {
  44303. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  44304. }
  44305. else {
  44306. return false; // Suppress visit subtree.
  44307. }
  44308. }
  44309. }, this);
  44310. return targetInfo;
  44311. }
  44312. });
  44313. /**
  44314. * @inner
  44315. */
  44316. function createStorage() {
  44317. return {nodeGroup: [], background: [], content: []};
  44318. }
  44319. /**
  44320. * @inner
  44321. * @return Return undefined means do not travel further.
  44322. */
  44323. function renderNode(
  44324. seriesModel, thisStorage, oldStorage, reRoot,
  44325. lastsForAnimation, willInvisibleEls,
  44326. thisNode, oldNode, parentGroup, depth
  44327. ) {
  44328. // Whether under viewRoot.
  44329. if (!thisNode) {
  44330. // Deleting nodes will be performed finally. This method just find
  44331. // element from old storage, or create new element, set them to new
  44332. // storage, and set styles.
  44333. return;
  44334. }
  44335. // -------------------------------------------------------------------
  44336. // Start of closure variables available in "Procedures in renderNode".
  44337. var thisLayout = thisNode.getLayout();
  44338. if (!thisLayout || !thisLayout.isInView) {
  44339. return;
  44340. }
  44341. var thisWidth = thisLayout.width;
  44342. var thisHeight = thisLayout.height;
  44343. var borderWidth = thisLayout.borderWidth;
  44344. var thisInvisible = thisLayout.invisible;
  44345. var thisRawIndex = thisNode.getRawIndex();
  44346. var oldRawIndex = oldNode && oldNode.getRawIndex();
  44347. var thisViewChildren = thisNode.viewChildren;
  44348. var upperHeight = thisLayout.upperHeight;
  44349. var isParent = thisViewChildren && thisViewChildren.length;
  44350. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  44351. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  44352. // End of closure ariables available in "Procedures in renderNode".
  44353. // -----------------------------------------------------------------
  44354. // Node group
  44355. var group = giveGraphic('nodeGroup', Group$2);
  44356. if (!group) {
  44357. return;
  44358. }
  44359. parentGroup.add(group);
  44360. // x,y are not set when el is above view root.
  44361. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  44362. group.__tmNodeWidth = thisWidth;
  44363. group.__tmNodeHeight = thisHeight;
  44364. if (thisLayout.isAboveViewRoot) {
  44365. return group;
  44366. }
  44367. // Background
  44368. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  44369. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  44370. // No children, render content.
  44371. if (!isParent) {
  44372. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  44373. content && renderContent(group, content);
  44374. }
  44375. return group;
  44376. // ----------------------------
  44377. // | Procedures in renderNode |
  44378. // ----------------------------
  44379. function renderBackground(group, bg, useUpperLabel) {
  44380. // For tooltip.
  44381. bg.dataIndex = thisNode.dataIndex;
  44382. bg.seriesIndex = seriesModel.seriesIndex;
  44383. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  44384. var visualBorderColor = thisNode.getVisual('borderColor', true);
  44385. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  44386. updateStyle(bg, function () {
  44387. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  44388. normalStyle.fill = visualBorderColor;
  44389. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  44390. emphasisStyle.fill = emphasisBorderColor;
  44391. if (useUpperLabel) {
  44392. var upperLabelWidth = thisWidth - 2 * borderWidth;
  44393. prepareText(
  44394. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  44395. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  44396. );
  44397. }
  44398. // For old bg.
  44399. else {
  44400. normalStyle.text = emphasisStyle.text = null;
  44401. }
  44402. bg.setStyle(normalStyle);
  44403. setHoverStyle(bg, emphasisStyle);
  44404. });
  44405. group.add(bg);
  44406. }
  44407. function renderContent(group, content) {
  44408. // For tooltip.
  44409. content.dataIndex = thisNode.dataIndex;
  44410. content.seriesIndex = seriesModel.seriesIndex;
  44411. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  44412. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  44413. content.culling = true;
  44414. content.setShape({
  44415. x: borderWidth,
  44416. y: borderWidth,
  44417. width: contentWidth,
  44418. height: contentHeight
  44419. });
  44420. var visualColor = thisNode.getVisual('color', true);
  44421. updateStyle(content, function () {
  44422. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  44423. normalStyle.fill = visualColor;
  44424. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  44425. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  44426. content.setStyle(normalStyle);
  44427. setHoverStyle(content, emphasisStyle);
  44428. });
  44429. group.add(content);
  44430. }
  44431. function updateStyle(element, cb) {
  44432. if (!thisInvisible) {
  44433. // If invisible, do not set visual, otherwise the element will
  44434. // change immediately before animation. We think it is OK to
  44435. // remain its origin color when moving out of the view window.
  44436. cb();
  44437. if (!element.__tmWillVisible) {
  44438. element.invisible = false;
  44439. }
  44440. }
  44441. else {
  44442. // Delay invisible setting utill animation finished,
  44443. // avoid element vanish suddenly before animation.
  44444. !element.invisible && willInvisibleEls.push(element);
  44445. }
  44446. }
  44447. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  44448. var nodeModel = thisNode.getModel();
  44449. var text = retrieve(
  44450. seriesModel.getFormattedLabel(
  44451. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  44452. ),
  44453. nodeModel.get('name')
  44454. );
  44455. if (!upperLabelRect && thisLayout.isLeafRoot) {
  44456. var iconChar = seriesModel.get('drillDownIcon', true);
  44457. text = iconChar ? iconChar + ' ' + text : text;
  44458. }
  44459. var normalLabelModel = nodeModel.getModel(
  44460. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  44461. );
  44462. var emphasisLabelModel = nodeModel.getModel(
  44463. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  44464. );
  44465. var isShow = normalLabelModel.getShallow('show');
  44466. setLabelStyle(
  44467. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  44468. {
  44469. defaultText: isShow ? text : null,
  44470. autoColor: visualColor,
  44471. isRectText: true
  44472. }
  44473. );
  44474. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  44475. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  44476. ? {
  44477. outerWidth: width,
  44478. outerHeight: height,
  44479. minChar: 2
  44480. }
  44481. : null;
  44482. }
  44483. function giveGraphic(storageName, Ctor, depth, z) {
  44484. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  44485. var lasts = lastsForAnimation[storageName];
  44486. if (element) {
  44487. // Remove from oldStorage
  44488. oldStorage[storageName][oldRawIndex] = null;
  44489. prepareAnimationWhenHasOld(lasts, element, storageName);
  44490. }
  44491. // If invisible and no old element, do not create new element (for optimizing).
  44492. else if (!thisInvisible) {
  44493. element = new Ctor({z: calculateZ(depth, z)});
  44494. element.__tmDepth = depth;
  44495. element.__tmStorageName = storageName;
  44496. prepareAnimationWhenNoOld(lasts, element, storageName);
  44497. }
  44498. // Set to thisStorage
  44499. return (thisStorage[storageName][thisRawIndex] = element);
  44500. }
  44501. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  44502. var lastCfg = lasts[thisRawIndex] = {};
  44503. lastCfg.old = storageName === 'nodeGroup'
  44504. ? element.position.slice()
  44505. : extend({}, element.shape);
  44506. }
  44507. // If a element is new, we need to find the animation start point carefully,
  44508. // otherwise it will looks strange when 'zoomToNode'.
  44509. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  44510. var lastCfg = lasts[thisRawIndex] = {};
  44511. var parentNode = thisNode.parentNode;
  44512. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  44513. var parentOldX = 0;
  44514. var parentOldY = 0;
  44515. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  44516. // For convenience, get old bounding rect from background.
  44517. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  44518. if (!reRoot && parentOldBg && parentOldBg.old) {
  44519. parentOldX = parentOldBg.old.width;
  44520. parentOldY = parentOldBg.old.height;
  44521. }
  44522. // When no parent old shape found, its parent is new too,
  44523. // so we can just use {x:0, y:0}.
  44524. lastCfg.old = storageName === 'nodeGroup'
  44525. ? [0, parentOldY]
  44526. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  44527. }
  44528. // Fade in, user can be aware that these nodes are new.
  44529. lastCfg.fadein = storageName !== 'nodeGroup';
  44530. }
  44531. }
  44532. // We can not set all backgroud with the same z, Because the behaviour of
  44533. // drill down and roll up differ background creation sequence from tree
  44534. // hierarchy sequence, which cause that lowser background element overlap
  44535. // upper ones. So we calculate z based on depth.
  44536. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  44537. // treemap with large z overlaps other components.
  44538. function calculateZ(depth, zInLevel) {
  44539. var zb = depth * Z_BASE + zInLevel;
  44540. return (zb - 1) / zb;
  44541. }
  44542. /*
  44543. * Licensed to the Apache Software Foundation (ASF) under one
  44544. * or more contributor license agreements. See the NOTICE file
  44545. * distributed with this work for additional information
  44546. * regarding copyright ownership. The ASF licenses this file
  44547. * to you under the Apache License, Version 2.0 (the
  44548. * "License"); you may not use this file except in compliance
  44549. * with the License. You may obtain a copy of the License at
  44550. *
  44551. * http://www.apache.org/licenses/LICENSE-2.0
  44552. *
  44553. * Unless required by applicable law or agreed to in writing,
  44554. * software distributed under the License is distributed on an
  44555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44556. * KIND, either express or implied. See the License for the
  44557. * specific language governing permissions and limitations
  44558. * under the License.
  44559. */
  44560. /**
  44561. * @file Treemap action
  44562. */
  44563. var noop$1 = function () {};
  44564. var actionTypes = [
  44565. 'treemapZoomToNode',
  44566. 'treemapRender',
  44567. 'treemapMove'
  44568. ];
  44569. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  44570. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  44571. }
  44572. registerAction(
  44573. {type: 'treemapRootToNode', update: 'updateView'},
  44574. function (payload, ecModel) {
  44575. ecModel.eachComponent(
  44576. {mainType: 'series', subType: 'treemap', query: payload},
  44577. handleRootToNode
  44578. );
  44579. function handleRootToNode(model, index) {
  44580. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  44581. var targetInfo = retrieveTargetInfo(payload, types, model);
  44582. if (targetInfo) {
  44583. var originViewRoot = model.getViewRoot();
  44584. if (originViewRoot) {
  44585. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  44586. ? 'rollUp' : 'drillDown';
  44587. }
  44588. model.resetViewRoot(targetInfo.node);
  44589. }
  44590. }
  44591. }
  44592. );
  44593. /*
  44594. * Licensed to the Apache Software Foundation (ASF) under one
  44595. * or more contributor license agreements. See the NOTICE file
  44596. * distributed with this work for additional information
  44597. * regarding copyright ownership. The ASF licenses this file
  44598. * to you under the Apache License, Version 2.0 (the
  44599. * "License"); you may not use this file except in compliance
  44600. * with the License. You may obtain a copy of the License at
  44601. *
  44602. * http://www.apache.org/licenses/LICENSE-2.0
  44603. *
  44604. * Unless required by applicable law or agreed to in writing,
  44605. * software distributed under the License is distributed on an
  44606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44607. * KIND, either express or implied. See the License for the
  44608. * specific language governing permissions and limitations
  44609. * under the License.
  44610. */
  44611. var each$9 = each$1;
  44612. var isObject$5 = isObject$1;
  44613. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  44614. /**
  44615. * @param {Object} option
  44616. * @param {string} [option.type] See visualHandlers.
  44617. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  44618. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  44619. * required when mappingMethod is 'linear'
  44620. * @param {Array.<Object>=} [option.pieceList] [
  44621. * {value: someValue},
  44622. * {interval: [min1, max1], visual: {...}},
  44623. * {interval: [min2, max2]}
  44624. * ],
  44625. * required when mappingMethod is 'piecewise'.
  44626. * Visual for only each piece can be specified.
  44627. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  44628. * required when mappingMethod is 'category'.
  44629. * If no option.categories, categories is set
  44630. * as [0, 1, 2, ...].
  44631. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  44632. * @param {(Array|Object|*)} [option.visual] Visual data.
  44633. * when mappingMethod is 'category',
  44634. * visual data can be array or object
  44635. * (like: {cate1: '#222', none: '#fff'})
  44636. * or primary types (which represents
  44637. * defualt category visual), otherwise visual
  44638. * can be array or primary (which will be
  44639. * normalized to array).
  44640. *
  44641. */
  44642. var VisualMapping = function (option) {
  44643. var mappingMethod = option.mappingMethod;
  44644. var visualType = option.type;
  44645. /**
  44646. * @readOnly
  44647. * @type {Object}
  44648. */
  44649. var thisOption = this.option = clone(option);
  44650. /**
  44651. * @readOnly
  44652. * @type {string}
  44653. */
  44654. this.type = visualType;
  44655. /**
  44656. * @readOnly
  44657. * @type {string}
  44658. */
  44659. this.mappingMethod = mappingMethod;
  44660. /**
  44661. * @private
  44662. * @type {Function}
  44663. */
  44664. this._normalizeData = normalizers[mappingMethod];
  44665. var visualHandler = visualHandlers[visualType];
  44666. /**
  44667. * @public
  44668. * @type {Function}
  44669. */
  44670. this.applyVisual = visualHandler.applyVisual;
  44671. /**
  44672. * @public
  44673. * @type {Function}
  44674. */
  44675. this.getColorMapper = visualHandler.getColorMapper;
  44676. /**
  44677. * @private
  44678. * @type {Function}
  44679. */
  44680. this._doMap = visualHandler._doMap[mappingMethod];
  44681. if (mappingMethod === 'piecewise') {
  44682. normalizeVisualRange(thisOption);
  44683. preprocessForPiecewise(thisOption);
  44684. }
  44685. else if (mappingMethod === 'category') {
  44686. thisOption.categories
  44687. ? preprocessForSpecifiedCategory(thisOption)
  44688. // categories is ordinal when thisOption.categories not specified,
  44689. // which need no more preprocess except normalize visual.
  44690. : normalizeVisualRange(thisOption, true);
  44691. }
  44692. else { // mappingMethod === 'linear' or 'fixed'
  44693. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  44694. normalizeVisualRange(thisOption);
  44695. }
  44696. };
  44697. VisualMapping.prototype = {
  44698. constructor: VisualMapping,
  44699. mapValueToVisual: function (value) {
  44700. var normalized = this._normalizeData(value);
  44701. return this._doMap(normalized, value);
  44702. },
  44703. getNormalizer: function () {
  44704. return bind(this._normalizeData, this);
  44705. }
  44706. };
  44707. var visualHandlers = VisualMapping.visualHandlers = {
  44708. color: {
  44709. applyVisual: makeApplyVisual('color'),
  44710. /**
  44711. * Create a mapper function
  44712. * @return {Function}
  44713. */
  44714. getColorMapper: function () {
  44715. var thisOption = this.option;
  44716. return bind(
  44717. thisOption.mappingMethod === 'category'
  44718. ? function (value, isNormalized) {
  44719. !isNormalized && (value = this._normalizeData(value));
  44720. return doMapCategory.call(this, value);
  44721. }
  44722. : function (value, isNormalized, out) {
  44723. // If output rgb array
  44724. // which will be much faster and useful in pixel manipulation
  44725. var returnRGBArray = !!out;
  44726. !isNormalized && (value = this._normalizeData(value));
  44727. out = fastLerp(value, thisOption.parsedVisual, out);
  44728. return returnRGBArray ? out : stringify(out, 'rgba');
  44729. },
  44730. this
  44731. );
  44732. },
  44733. _doMap: {
  44734. linear: function (normalized) {
  44735. return stringify(
  44736. fastLerp(normalized, this.option.parsedVisual),
  44737. 'rgba'
  44738. );
  44739. },
  44740. category: doMapCategory,
  44741. piecewise: function (normalized, value) {
  44742. var result = getSpecifiedVisual.call(this, value);
  44743. if (result == null) {
  44744. result = stringify(
  44745. fastLerp(normalized, this.option.parsedVisual),
  44746. 'rgba'
  44747. );
  44748. }
  44749. return result;
  44750. },
  44751. fixed: doMapFixed
  44752. }
  44753. },
  44754. colorHue: makePartialColorVisualHandler(function (color, value) {
  44755. return modifyHSL(color, value);
  44756. }),
  44757. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  44758. return modifyHSL(color, null, value);
  44759. }),
  44760. colorLightness: makePartialColorVisualHandler(function (color, value) {
  44761. return modifyHSL(color, null, null, value);
  44762. }),
  44763. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  44764. return modifyAlpha(color, value);
  44765. }),
  44766. opacity: {
  44767. applyVisual: makeApplyVisual('opacity'),
  44768. _doMap: makeDoMap([0, 1])
  44769. },
  44770. liftZ: {
  44771. applyVisual: makeApplyVisual('liftZ'),
  44772. _doMap: {
  44773. linear: doMapFixed,
  44774. category: doMapFixed,
  44775. piecewise: doMapFixed,
  44776. fixed: doMapFixed
  44777. }
  44778. },
  44779. symbol: {
  44780. applyVisual: function (value, getter, setter) {
  44781. var symbolCfg = this.mapValueToVisual(value);
  44782. if (isString(symbolCfg)) {
  44783. setter('symbol', symbolCfg);
  44784. }
  44785. else if (isObject$5(symbolCfg)) {
  44786. for (var name in symbolCfg) {
  44787. if (symbolCfg.hasOwnProperty(name)) {
  44788. setter(name, symbolCfg[name]);
  44789. }
  44790. }
  44791. }
  44792. },
  44793. _doMap: {
  44794. linear: doMapToArray,
  44795. category: doMapCategory,
  44796. piecewise: function (normalized, value) {
  44797. var result = getSpecifiedVisual.call(this, value);
  44798. if (result == null) {
  44799. result = doMapToArray.call(this, normalized);
  44800. }
  44801. return result;
  44802. },
  44803. fixed: doMapFixed
  44804. }
  44805. },
  44806. symbolSize: {
  44807. applyVisual: makeApplyVisual('symbolSize'),
  44808. _doMap: makeDoMap([0, 1])
  44809. }
  44810. };
  44811. function preprocessForPiecewise(thisOption) {
  44812. var pieceList = thisOption.pieceList;
  44813. thisOption.hasSpecialVisual = false;
  44814. each$1(pieceList, function (piece, index) {
  44815. piece.originIndex = index;
  44816. // piece.visual is "result visual value" but not
  44817. // a visual range, so it does not need to be normalized.
  44818. if (piece.visual != null) {
  44819. thisOption.hasSpecialVisual = true;
  44820. }
  44821. });
  44822. }
  44823. function preprocessForSpecifiedCategory(thisOption) {
  44824. // Hash categories.
  44825. var categories = thisOption.categories;
  44826. var visual = thisOption.visual;
  44827. var categoryMap = thisOption.categoryMap = {};
  44828. each$9(categories, function (cate, index) {
  44829. categoryMap[cate] = index;
  44830. });
  44831. // Process visual map input.
  44832. if (!isArray(visual)) {
  44833. var visualArr = [];
  44834. if (isObject$1(visual)) {
  44835. each$9(visual, function (v, cate) {
  44836. var index = categoryMap[cate];
  44837. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  44838. });
  44839. }
  44840. else { // Is primary type, represents default visual.
  44841. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  44842. }
  44843. visual = setVisualToOption(thisOption, visualArr);
  44844. }
  44845. // Remove categories that has no visual,
  44846. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  44847. for (var i = categories.length - 1; i >= 0; i--) {
  44848. if (visual[i] == null) {
  44849. delete categoryMap[categories[i]];
  44850. categories.pop();
  44851. }
  44852. }
  44853. }
  44854. function normalizeVisualRange(thisOption, isCategory) {
  44855. var visual = thisOption.visual;
  44856. var visualArr = [];
  44857. if (isObject$1(visual)) {
  44858. each$9(visual, function (v) {
  44859. visualArr.push(v);
  44860. });
  44861. }
  44862. else if (visual != null) {
  44863. visualArr.push(visual);
  44864. }
  44865. var doNotNeedPair = {color: 1, symbol: 1};
  44866. if (!isCategory
  44867. && visualArr.length === 1
  44868. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  44869. ) {
  44870. // Do not care visualArr.length === 0, which is illegal.
  44871. visualArr[1] = visualArr[0];
  44872. }
  44873. setVisualToOption(thisOption, visualArr);
  44874. }
  44875. function makePartialColorVisualHandler(applyValue) {
  44876. return {
  44877. applyVisual: function (value, getter, setter) {
  44878. value = this.mapValueToVisual(value);
  44879. // Must not be array value
  44880. setter('color', applyValue(getter('color'), value));
  44881. },
  44882. _doMap: makeDoMap([0, 1])
  44883. };
  44884. }
  44885. function doMapToArray(normalized) {
  44886. var visual = this.option.visual;
  44887. return visual[
  44888. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  44889. ] || {};
  44890. }
  44891. function makeApplyVisual(visualType) {
  44892. return function (value, getter, setter) {
  44893. setter(visualType, this.mapValueToVisual(value));
  44894. };
  44895. }
  44896. function doMapCategory(normalized) {
  44897. var visual = this.option.visual;
  44898. return visual[
  44899. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  44900. ? normalized % visual.length
  44901. : normalized
  44902. ];
  44903. }
  44904. function doMapFixed() {
  44905. return this.option.visual[0];
  44906. }
  44907. function makeDoMap(sourceExtent) {
  44908. return {
  44909. linear: function (normalized) {
  44910. return linearMap(normalized, sourceExtent, this.option.visual, true);
  44911. },
  44912. category: doMapCategory,
  44913. piecewise: function (normalized, value) {
  44914. var result = getSpecifiedVisual.call(this, value);
  44915. if (result == null) {
  44916. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  44917. }
  44918. return result;
  44919. },
  44920. fixed: doMapFixed
  44921. };
  44922. }
  44923. function getSpecifiedVisual(value) {
  44924. var thisOption = this.option;
  44925. var pieceList = thisOption.pieceList;
  44926. if (thisOption.hasSpecialVisual) {
  44927. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  44928. var piece = pieceList[pieceIndex];
  44929. if (piece && piece.visual) {
  44930. return piece.visual[this.type];
  44931. }
  44932. }
  44933. }
  44934. function setVisualToOption(thisOption, visualArr) {
  44935. thisOption.visual = visualArr;
  44936. if (thisOption.type === 'color') {
  44937. thisOption.parsedVisual = map(visualArr, function (item) {
  44938. return parse(item);
  44939. });
  44940. }
  44941. return visualArr;
  44942. }
  44943. /**
  44944. * Normalizers by mapping methods.
  44945. */
  44946. var normalizers = {
  44947. linear: function (value) {
  44948. return linearMap(value, this.option.dataExtent, [0, 1], true);
  44949. },
  44950. piecewise: function (value) {
  44951. var pieceList = this.option.pieceList;
  44952. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  44953. if (pieceIndex != null) {
  44954. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  44955. }
  44956. },
  44957. category: function (value) {
  44958. var index = this.option.categories
  44959. ? this.option.categoryMap[value]
  44960. : value; // ordinal
  44961. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  44962. },
  44963. fixed: noop
  44964. };
  44965. /**
  44966. * List available visual types.
  44967. *
  44968. * @public
  44969. * @return {Array.<string>}
  44970. */
  44971. VisualMapping.listVisualTypes = function () {
  44972. var visualTypes = [];
  44973. each$1(visualHandlers, function (handler, key) {
  44974. visualTypes.push(key);
  44975. });
  44976. return visualTypes;
  44977. };
  44978. /**
  44979. * @public
  44980. */
  44981. VisualMapping.addVisualHandler = function (name, handler) {
  44982. visualHandlers[name] = handler;
  44983. };
  44984. /**
  44985. * @public
  44986. */
  44987. VisualMapping.isValidType = function (visualType) {
  44988. return visualHandlers.hasOwnProperty(visualType);
  44989. };
  44990. /**
  44991. * Convinent method.
  44992. * Visual can be Object or Array or primary type.
  44993. *
  44994. * @public
  44995. */
  44996. VisualMapping.eachVisual = function (visual, callback, context) {
  44997. if (isObject$1(visual)) {
  44998. each$1(visual, callback, context);
  44999. }
  45000. else {
  45001. callback.call(context, visual);
  45002. }
  45003. };
  45004. VisualMapping.mapVisual = function (visual, callback, context) {
  45005. var isPrimary;
  45006. var newVisual = isArray(visual)
  45007. ? []
  45008. : isObject$1(visual)
  45009. ? {}
  45010. : (isPrimary = true, null);
  45011. VisualMapping.eachVisual(visual, function (v, key) {
  45012. var newVal = callback.call(context, v, key);
  45013. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  45014. });
  45015. return newVisual;
  45016. };
  45017. /**
  45018. * @public
  45019. * @param {Object} obj
  45020. * @return {Object} new object containers visual values.
  45021. * If no visuals, return null.
  45022. */
  45023. VisualMapping.retrieveVisuals = function (obj) {
  45024. var ret = {};
  45025. var hasVisual;
  45026. obj && each$9(visualHandlers, function (h, visualType) {
  45027. if (obj.hasOwnProperty(visualType)) {
  45028. ret[visualType] = obj[visualType];
  45029. hasVisual = true;
  45030. }
  45031. });
  45032. return hasVisual ? ret : null;
  45033. };
  45034. /**
  45035. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  45036. *
  45037. * @public
  45038. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  45039. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  45040. * @return {Array.<string>} Sorted visual types.
  45041. */
  45042. VisualMapping.prepareVisualTypes = function (visualTypes) {
  45043. if (isObject$5(visualTypes)) {
  45044. var types = [];
  45045. each$9(visualTypes, function (item, type) {
  45046. types.push(type);
  45047. });
  45048. visualTypes = types;
  45049. }
  45050. else if (isArray(visualTypes)) {
  45051. visualTypes = visualTypes.slice();
  45052. }
  45053. else {
  45054. return [];
  45055. }
  45056. visualTypes.sort(function (type1, type2) {
  45057. // color should be front of colorSaturation, colorAlpha, ...
  45058. // symbol and symbolSize do not matter.
  45059. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  45060. ? 1 : -1;
  45061. });
  45062. return visualTypes;
  45063. };
  45064. /**
  45065. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  45066. * Other visuals are only depends on themself.
  45067. *
  45068. * @public
  45069. * @param {string} visualType1
  45070. * @param {string} visualType2
  45071. * @return {boolean}
  45072. */
  45073. VisualMapping.dependsOn = function (visualType1, visualType2) {
  45074. return visualType2 === 'color'
  45075. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  45076. : visualType1 === visualType2;
  45077. };
  45078. /**
  45079. * @param {number} value
  45080. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  45081. * Always from small to big.
  45082. * @param {boolean} [findClosestWhenOutside=false]
  45083. * @return {number} index
  45084. */
  45085. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  45086. var possibleI;
  45087. var abs = Infinity;
  45088. // value has the higher priority.
  45089. for (var i = 0, len = pieceList.length; i < len; i++) {
  45090. var pieceValue = pieceList[i].value;
  45091. if (pieceValue != null) {
  45092. if (pieceValue === value
  45093. // FIXME
  45094. // It is supposed to compare value according to value type of dimension,
  45095. // but currently value type can exactly be string or number.
  45096. // Compromise for numeric-like string (like '12'), especially
  45097. // in the case that visualMap.categories is ['22', '33'].
  45098. || (typeof pieceValue === 'string' && pieceValue === value + '')
  45099. ) {
  45100. return i;
  45101. }
  45102. findClosestWhenOutside && updatePossible(pieceValue, i);
  45103. }
  45104. }
  45105. for (var i = 0, len = pieceList.length; i < len; i++) {
  45106. var piece = pieceList[i];
  45107. var interval = piece.interval;
  45108. var close = piece.close;
  45109. if (interval) {
  45110. if (interval[0] === -Infinity) {
  45111. if (littleThan(close[1], value, interval[1])) {
  45112. return i;
  45113. }
  45114. }
  45115. else if (interval[1] === Infinity) {
  45116. if (littleThan(close[0], interval[0], value)) {
  45117. return i;
  45118. }
  45119. }
  45120. else if (
  45121. littleThan(close[0], interval[0], value)
  45122. && littleThan(close[1], value, interval[1])
  45123. ) {
  45124. return i;
  45125. }
  45126. findClosestWhenOutside && updatePossible(interval[0], i);
  45127. findClosestWhenOutside && updatePossible(interval[1], i);
  45128. }
  45129. }
  45130. if (findClosestWhenOutside) {
  45131. return value === Infinity
  45132. ? pieceList.length - 1
  45133. : value === -Infinity
  45134. ? 0
  45135. : possibleI;
  45136. }
  45137. function updatePossible(val, index) {
  45138. var newAbs = Math.abs(val - value);
  45139. if (newAbs < abs) {
  45140. abs = newAbs;
  45141. possibleI = index;
  45142. }
  45143. }
  45144. };
  45145. function littleThan(close, a, b) {
  45146. return close ? a <= b : a < b;
  45147. }
  45148. /*
  45149. * Licensed to the Apache Software Foundation (ASF) under one
  45150. * or more contributor license agreements. See the NOTICE file
  45151. * distributed with this work for additional information
  45152. * regarding copyright ownership. The ASF licenses this file
  45153. * to you under the Apache License, Version 2.0 (the
  45154. * "License"); you may not use this file except in compliance
  45155. * with the License. You may obtain a copy of the License at
  45156. *
  45157. * http://www.apache.org/licenses/LICENSE-2.0
  45158. *
  45159. * Unless required by applicable law or agreed to in writing,
  45160. * software distributed under the License is distributed on an
  45161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45162. * KIND, either express or implied. See the License for the
  45163. * specific language governing permissions and limitations
  45164. * under the License.
  45165. */
  45166. var isArray$2 = isArray;
  45167. var ITEM_STYLE_NORMAL = 'itemStyle';
  45168. var treemapVisual = {
  45169. seriesType: 'treemap',
  45170. reset: function (seriesModel, ecModel, api, payload) {
  45171. var tree = seriesModel.getData().tree;
  45172. var root = tree.root;
  45173. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  45174. if (root.isRemoved()) {
  45175. return;
  45176. }
  45177. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  45178. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  45179. });
  45180. travelTree(
  45181. root, // Visual should calculate from tree root but not view root.
  45182. {},
  45183. levelItemStyles,
  45184. seriesItemStyleModel,
  45185. seriesModel.getViewRoot().getAncestors(),
  45186. seriesModel
  45187. );
  45188. }
  45189. };
  45190. function travelTree(
  45191. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  45192. viewRootAncestors, seriesModel
  45193. ) {
  45194. var nodeModel = node.getModel();
  45195. var nodeLayout = node.getLayout();
  45196. // Optimize
  45197. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  45198. return;
  45199. }
  45200. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  45201. var levelItemStyle = levelItemStyles[node.depth];
  45202. var visuals = buildVisuals(
  45203. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  45204. );
  45205. // calculate border color
  45206. var borderColor = nodeItemStyleModel.get('borderColor');
  45207. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  45208. var thisNodeColor;
  45209. if (borderColorSaturation != null) {
  45210. // For performance, do not always execute 'calculateColor'.
  45211. thisNodeColor = calculateColor(visuals, node);
  45212. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  45213. }
  45214. node.setVisual('borderColor', borderColor);
  45215. var viewChildren = node.viewChildren;
  45216. if (!viewChildren || !viewChildren.length) {
  45217. thisNodeColor = calculateColor(visuals, node);
  45218. // Apply visual to this node.
  45219. node.setVisual('color', thisNodeColor);
  45220. }
  45221. else {
  45222. var mapping = buildVisualMapping(
  45223. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  45224. );
  45225. // Designate visual to children.
  45226. each$1(viewChildren, function (child, index) {
  45227. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  45228. if (child.depth >= viewRootAncestors.length
  45229. || child === viewRootAncestors[child.depth]
  45230. ) {
  45231. var childVisual = mapVisual$1(
  45232. nodeModel, visuals, child, index, mapping, seriesModel
  45233. );
  45234. travelTree(
  45235. child, childVisual, levelItemStyles, seriesItemStyleModel,
  45236. viewRootAncestors, seriesModel
  45237. );
  45238. }
  45239. });
  45240. }
  45241. }
  45242. function buildVisuals(
  45243. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  45244. ) {
  45245. var visuals = extend({}, designatedVisual);
  45246. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  45247. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  45248. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  45249. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  45250. val == null && (val = designatedVisual[visualName]);
  45251. val == null && (val = seriesItemStyleModel.get(visualName));
  45252. val != null && (visuals[visualName] = val);
  45253. });
  45254. return visuals;
  45255. }
  45256. function calculateColor(visuals) {
  45257. var color = getValueVisualDefine(visuals, 'color');
  45258. if (color) {
  45259. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  45260. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  45261. if (colorSaturation) {
  45262. color = modifyHSL(color, null, null, colorSaturation);
  45263. }
  45264. if (colorAlpha) {
  45265. color = modifyAlpha(color, colorAlpha);
  45266. }
  45267. return color;
  45268. }
  45269. }
  45270. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  45271. return thisNodeColor != null
  45272. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  45273. : null;
  45274. }
  45275. function getValueVisualDefine(visuals, name) {
  45276. var value = visuals[name];
  45277. if (value != null && value !== 'none') {
  45278. return value;
  45279. }
  45280. }
  45281. function buildVisualMapping(
  45282. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  45283. ) {
  45284. if (!viewChildren || !viewChildren.length) {
  45285. return;
  45286. }
  45287. var rangeVisual = getRangeVisual(nodeModel, 'color')
  45288. || (
  45289. visuals.color != null
  45290. && visuals.color !== 'none'
  45291. && (
  45292. getRangeVisual(nodeModel, 'colorAlpha')
  45293. || getRangeVisual(nodeModel, 'colorSaturation')
  45294. )
  45295. );
  45296. if (!rangeVisual) {
  45297. return;
  45298. }
  45299. var visualMin = nodeModel.get('visualMin');
  45300. var visualMax = nodeModel.get('visualMax');
  45301. var dataExtent = nodeLayout.dataExtent.slice();
  45302. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  45303. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  45304. var colorMappingBy = nodeModel.get('colorMappingBy');
  45305. var opt = {
  45306. type: rangeVisual.name,
  45307. dataExtent: dataExtent,
  45308. visual: rangeVisual.range
  45309. };
  45310. if (opt.type === 'color'
  45311. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  45312. ) {
  45313. opt.mappingMethod = 'category';
  45314. opt.loop = true;
  45315. // categories is ordinal, so do not set opt.categories.
  45316. }
  45317. else {
  45318. opt.mappingMethod = 'linear';
  45319. }
  45320. var mapping = new VisualMapping(opt);
  45321. mapping.__drColorMappingBy = colorMappingBy;
  45322. return mapping;
  45323. }
  45324. // Notice: If we dont have the attribute 'colorRange', but only use
  45325. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  45326. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  45327. // this problem will be encountered:
  45328. // If a level-1 node dont have children, and its siblings has children,
  45329. // and colorRange is set on level-1, then the node can not be colored.
  45330. // So we separate 'colorRange' and 'color' to different attributes.
  45331. function getRangeVisual(nodeModel, name) {
  45332. // 'colorRange', 'colorARange', 'colorSRange'.
  45333. // If not exsits on this node, fetch from levels and series.
  45334. var range = nodeModel.get(name);
  45335. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  45336. }
  45337. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  45338. var childVisuals = extend({}, visuals);
  45339. if (mapping) {
  45340. var mappingType = mapping.type;
  45341. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  45342. var value = colorMappingBy === 'index'
  45343. ? index
  45344. : colorMappingBy === 'id'
  45345. ? seriesModel.mapIdToIndex(child.getId())
  45346. : child.getValue(nodeModel.get('visualDimension'));
  45347. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  45348. }
  45349. return childVisuals;
  45350. }
  45351. /*
  45352. * Licensed to the Apache Software Foundation (ASF) under one
  45353. * or more contributor license agreements. See the NOTICE file
  45354. * distributed with this work for additional information
  45355. * regarding copyright ownership. The ASF licenses this file
  45356. * to you under the Apache License, Version 2.0 (the
  45357. * "License"); you may not use this file except in compliance
  45358. * with the License. You may obtain a copy of the License at
  45359. *
  45360. * http://www.apache.org/licenses/LICENSE-2.0
  45361. *
  45362. * Unless required by applicable law or agreed to in writing,
  45363. * software distributed under the License is distributed on an
  45364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45365. * KIND, either express or implied. See the License for the
  45366. * specific language governing permissions and limitations
  45367. * under the License.
  45368. */
  45369. /*
  45370. * The treemap layout implementation references to the treemap
  45371. * layout of d3.js (d3/src/layout/treemap.js in v3). The use of
  45372. * the source code of this file is also subject to the terms
  45373. * and consitions of its license (BSD-3Clause, see
  45374. * <echarts/src/licenses/LICENSE-d3>).
  45375. */
  45376. var mathMax$4 = Math.max;
  45377. var mathMin$4 = Math.min;
  45378. var retrieveValue = retrieve;
  45379. var each$10 = each$1;
  45380. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  45381. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  45382. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  45383. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  45384. /**
  45385. * @public
  45386. */
  45387. var treemapLayout = {
  45388. seriesType: 'treemap',
  45389. reset: function (seriesModel, ecModel, api, payload) {
  45390. // Layout result in each node:
  45391. // {x, y, width, height, area, borderWidth}
  45392. var ecWidth = api.getWidth();
  45393. var ecHeight = api.getHeight();
  45394. var seriesOption = seriesModel.option;
  45395. var layoutInfo = getLayoutRect(
  45396. seriesModel.getBoxLayoutParams(),
  45397. {
  45398. width: api.getWidth(),
  45399. height: api.getHeight()
  45400. }
  45401. );
  45402. var size = seriesOption.size || []; // Compatible with ec2.
  45403. var containerWidth = parsePercent$1(
  45404. retrieveValue(layoutInfo.width, size[0]),
  45405. ecWidth
  45406. );
  45407. var containerHeight = parsePercent$1(
  45408. retrieveValue(layoutInfo.height, size[1]),
  45409. ecHeight
  45410. );
  45411. // Fetch payload info.
  45412. var payloadType = payload && payload.type;
  45413. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  45414. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  45415. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  45416. ? payload.rootRect : null;
  45417. var viewRoot = seriesModel.getViewRoot();
  45418. var viewAbovePath = getPathToRoot(viewRoot);
  45419. if (payloadType !== 'treemapMove') {
  45420. var rootSize = payloadType === 'treemapZoomToNode'
  45421. ? estimateRootSize(
  45422. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  45423. )
  45424. : rootRect
  45425. ? [rootRect.width, rootRect.height]
  45426. : [containerWidth, containerHeight];
  45427. var sort = seriesOption.sort;
  45428. if (sort && sort !== 'asc' && sort !== 'desc') {
  45429. sort = 'desc';
  45430. }
  45431. var options = {
  45432. squareRatio: seriesOption.squareRatio,
  45433. sort: sort,
  45434. leafDepth: seriesOption.leafDepth
  45435. };
  45436. // layout should be cleared because using updateView but not update.
  45437. viewRoot.hostTree.clearLayouts();
  45438. // TODO
  45439. // optimize: if out of view clip, do not layout.
  45440. // But take care that if do not render node out of view clip,
  45441. // how to calculate start po
  45442. var viewRootLayout = {
  45443. x: 0, y: 0,
  45444. width: rootSize[0], height: rootSize[1],
  45445. area: rootSize[0] * rootSize[1]
  45446. };
  45447. viewRoot.setLayout(viewRootLayout);
  45448. squarify(viewRoot, options, false, 0);
  45449. // Supplement layout.
  45450. var viewRootLayout = viewRoot.getLayout();
  45451. each$10(viewAbovePath, function (node, index) {
  45452. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  45453. node.setLayout(extend(
  45454. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  45455. viewRootLayout
  45456. ));
  45457. });
  45458. }
  45459. var treeRoot = seriesModel.getData().tree.root;
  45460. treeRoot.setLayout(
  45461. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  45462. true
  45463. );
  45464. seriesModel.setLayoutInfo(layoutInfo);
  45465. // FIXME
  45466. // 现在没有clip功能,暂时取ec高宽。
  45467. prunning(
  45468. treeRoot,
  45469. // Transform to base element coordinate system.
  45470. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  45471. viewAbovePath,
  45472. viewRoot,
  45473. 0
  45474. );
  45475. }
  45476. };
  45477. /**
  45478. * Layout treemap with squarify algorithm.
  45479. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  45480. * The implementation references to the treemap layout of d3.js.
  45481. * See the license statement at the head of this file.
  45482. *
  45483. * @protected
  45484. * @param {module:echarts/data/Tree~TreeNode} node
  45485. * @param {Object} options
  45486. * @param {string} options.sort 'asc' or 'desc'
  45487. * @param {number} options.squareRatio
  45488. * @param {boolean} hideChildren
  45489. * @param {number} depth
  45490. */
  45491. function squarify(node, options, hideChildren, depth) {
  45492. var width;
  45493. var height;
  45494. if (node.isRemoved()) {
  45495. return;
  45496. }
  45497. var thisLayout = node.getLayout();
  45498. width = thisLayout.width;
  45499. height = thisLayout.height;
  45500. // Considering border and gap
  45501. var nodeModel = node.getModel();
  45502. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  45503. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  45504. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  45505. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  45506. var layoutOffset = borderWidth - halfGapWidth;
  45507. var layoutOffsetUpper = upperHeight - halfGapWidth;
  45508. var nodeModel = node.getModel();
  45509. node.setLayout({
  45510. borderWidth: borderWidth,
  45511. upperHeight: upperHeight,
  45512. upperLabelHeight: upperLabelHeight
  45513. }, true);
  45514. width = mathMax$4(width - 2 * layoutOffset, 0);
  45515. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  45516. var totalArea = width * height;
  45517. var viewChildren = initChildren(
  45518. node, nodeModel, totalArea, options, hideChildren, depth
  45519. );
  45520. if (!viewChildren.length) {
  45521. return;
  45522. }
  45523. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  45524. var rowFixedLength = mathMin$4(width, height);
  45525. var best = Infinity; // the best row score so far
  45526. var row = [];
  45527. row.area = 0;
  45528. for (var i = 0, len = viewChildren.length; i < len;) {
  45529. var child = viewChildren[i];
  45530. row.push(child);
  45531. row.area += child.getLayout().area;
  45532. var score = worst(row, rowFixedLength, options.squareRatio);
  45533. // continue with this orientation
  45534. if (score <= best) {
  45535. i++;
  45536. best = score;
  45537. }
  45538. // abort, and try a different orientation
  45539. else {
  45540. row.area -= row.pop().getLayout().area;
  45541. position(row, rowFixedLength, rect, halfGapWidth, false);
  45542. rowFixedLength = mathMin$4(rect.width, rect.height);
  45543. row.length = row.area = 0;
  45544. best = Infinity;
  45545. }
  45546. }
  45547. if (row.length) {
  45548. position(row, rowFixedLength, rect, halfGapWidth, true);
  45549. }
  45550. if (!hideChildren) {
  45551. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  45552. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  45553. hideChildren = true;
  45554. }
  45555. }
  45556. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45557. squarify(viewChildren[i], options, hideChildren, depth + 1);
  45558. }
  45559. }
  45560. /**
  45561. * Set area to each child, and calculate data extent for visual coding.
  45562. */
  45563. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  45564. var viewChildren = node.children || [];
  45565. var orderBy = options.sort;
  45566. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  45567. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  45568. // leafDepth has higher priority.
  45569. if (hideChildren && !overLeafDepth) {
  45570. return (node.viewChildren = []);
  45571. }
  45572. // Sort children, order by desc.
  45573. viewChildren = filter(viewChildren, function (child) {
  45574. return !child.isRemoved();
  45575. });
  45576. sort$1(viewChildren, orderBy);
  45577. var info = statistic(nodeModel, viewChildren, orderBy);
  45578. if (info.sum === 0) {
  45579. return (node.viewChildren = []);
  45580. }
  45581. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  45582. if (info.sum === 0) {
  45583. return (node.viewChildren = []);
  45584. }
  45585. // Set area to each child.
  45586. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45587. var area = viewChildren[i].getValue() / info.sum * totalArea;
  45588. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  45589. viewChildren[i].setLayout({area: area});
  45590. }
  45591. if (overLeafDepth) {
  45592. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  45593. viewChildren.length = 0;
  45594. }
  45595. node.viewChildren = viewChildren;
  45596. node.setLayout({dataExtent: info.dataExtent}, true);
  45597. return viewChildren;
  45598. }
  45599. /**
  45600. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  45601. */
  45602. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  45603. // visibleMin is not supported yet when no option.sort.
  45604. if (!orderBy) {
  45605. return sum;
  45606. }
  45607. var visibleMin = nodeModel.get('visibleMin');
  45608. var len = orderedChildren.length;
  45609. var deletePoint = len;
  45610. // Always travel from little value to big value.
  45611. for (var i = len - 1; i >= 0; i--) {
  45612. var value = orderedChildren[
  45613. orderBy === 'asc' ? len - i - 1 : i
  45614. ].getValue();
  45615. if (value / sum * totalArea < visibleMin) {
  45616. deletePoint = i;
  45617. sum -= value;
  45618. }
  45619. }
  45620. orderBy === 'asc'
  45621. ? orderedChildren.splice(0, len - deletePoint)
  45622. : orderedChildren.splice(deletePoint, len - deletePoint);
  45623. return sum;
  45624. }
  45625. /**
  45626. * Sort
  45627. */
  45628. function sort$1(viewChildren, orderBy) {
  45629. if (orderBy) {
  45630. viewChildren.sort(function (a, b) {
  45631. var diff = orderBy === 'asc'
  45632. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  45633. return diff === 0
  45634. ? (orderBy === 'asc'
  45635. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  45636. )
  45637. : diff;
  45638. });
  45639. }
  45640. return viewChildren;
  45641. }
  45642. /**
  45643. * Statistic
  45644. */
  45645. function statistic(nodeModel, children, orderBy) {
  45646. // Calculate sum.
  45647. var sum = 0;
  45648. for (var i = 0, len = children.length; i < len; i++) {
  45649. sum += children[i].getValue();
  45650. }
  45651. // Statistic data extent for latter visual coding.
  45652. // Notice: data extent should be calculate based on raw children
  45653. // but not filtered view children, otherwise visual mapping will not
  45654. // be stable when zoom (where children is filtered by visibleMin).
  45655. var dimension = nodeModel.get('visualDimension');
  45656. var dataExtent;
  45657. // The same as area dimension.
  45658. if (!children || !children.length) {
  45659. dataExtent = [NaN, NaN];
  45660. }
  45661. else if (dimension === 'value' && orderBy) {
  45662. dataExtent = [
  45663. children[children.length - 1].getValue(),
  45664. children[0].getValue()
  45665. ];
  45666. orderBy === 'asc' && dataExtent.reverse();
  45667. }
  45668. // Other dimension.
  45669. else {
  45670. var dataExtent = [Infinity, -Infinity];
  45671. each$10(children, function (child) {
  45672. var value = child.getValue(dimension);
  45673. value < dataExtent[0] && (dataExtent[0] = value);
  45674. value > dataExtent[1] && (dataExtent[1] = value);
  45675. });
  45676. }
  45677. return {sum: sum, dataExtent: dataExtent};
  45678. }
  45679. /**
  45680. * Computes the score for the specified row,
  45681. * as the worst aspect ratio.
  45682. */
  45683. function worst(row, rowFixedLength, ratio) {
  45684. var areaMax = 0;
  45685. var areaMin = Infinity;
  45686. for (var i = 0, area, len = row.length; i < len; i++) {
  45687. area = row[i].getLayout().area;
  45688. if (area) {
  45689. area < areaMin && (areaMin = area);
  45690. area > areaMax && (areaMax = area);
  45691. }
  45692. }
  45693. var squareArea = row.area * row.area;
  45694. var f = rowFixedLength * rowFixedLength * ratio;
  45695. return squareArea
  45696. ? mathMax$4(
  45697. (f * areaMax) / squareArea,
  45698. squareArea / (f * areaMin)
  45699. )
  45700. : Infinity;
  45701. }
  45702. /**
  45703. * Positions the specified row of nodes. Modifies `rect`.
  45704. */
  45705. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  45706. // When rowFixedLength === rect.width,
  45707. // it is horizontal subdivision,
  45708. // rowFixedLength is the width of the subdivision,
  45709. // rowOtherLength is the height of the subdivision,
  45710. // and nodes will be positioned from left to right.
  45711. // wh[idx0WhenH] means: when horizontal,
  45712. // wh[idx0WhenH] => wh[0] => 'width'.
  45713. // xy[idx1WhenH] => xy[1] => 'y'.
  45714. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  45715. var idx1WhenH = 1 - idx0WhenH;
  45716. var xy = ['x', 'y'];
  45717. var wh = ['width', 'height'];
  45718. var last = rect[xy[idx0WhenH]];
  45719. var rowOtherLength = rowFixedLength
  45720. ? row.area / rowFixedLength : 0;
  45721. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  45722. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  45723. }
  45724. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  45725. var node = row[i];
  45726. var nodeLayout = {};
  45727. var step = rowOtherLength
  45728. ? node.getLayout().area / rowOtherLength : 0;
  45729. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  45730. // We use Math.max/min to avoid negative width/height when considering gap width.
  45731. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  45732. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  45733. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  45734. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  45735. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  45736. last += modWH;
  45737. node.setLayout(nodeLayout, true);
  45738. }
  45739. rect[xy[idx1WhenH]] += rowOtherLength;
  45740. rect[wh[idx1WhenH]] -= rowOtherLength;
  45741. }
  45742. // Return [containerWidth, containerHeight] as defualt.
  45743. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  45744. // If targetInfo.node exists, we zoom to the node,
  45745. // so estimate whold width and heigth by target node.
  45746. var currNode = (targetInfo || {}).node;
  45747. var defaultSize = [containerWidth, containerHeight];
  45748. if (!currNode || currNode === viewRoot) {
  45749. return defaultSize;
  45750. }
  45751. var parent;
  45752. var viewArea = containerWidth * containerHeight;
  45753. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  45754. while (parent = currNode.parentNode) { // jshint ignore:line
  45755. var sum = 0;
  45756. var siblings = parent.children;
  45757. for (var i = 0, len = siblings.length; i < len; i++) {
  45758. sum += siblings[i].getValue();
  45759. }
  45760. var currNodeValue = currNode.getValue();
  45761. if (currNodeValue === 0) {
  45762. return defaultSize;
  45763. }
  45764. area *= sum / currNodeValue;
  45765. // Considering border, suppose aspect ratio is 1.
  45766. var parentModel = parent.getModel();
  45767. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  45768. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  45769. area += 4 * borderWidth * borderWidth
  45770. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  45771. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  45772. currNode = parent;
  45773. }
  45774. area < viewArea && (area = viewArea);
  45775. var scale = Math.pow(area / viewArea, 0.5);
  45776. return [containerWidth * scale, containerHeight * scale];
  45777. }
  45778. // Root postion base on coord of containerGroup
  45779. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  45780. if (rootRect) {
  45781. return {x: rootRect.x, y: rootRect.y};
  45782. }
  45783. var defaultPosition = {x: 0, y: 0};
  45784. if (!targetInfo) {
  45785. return defaultPosition;
  45786. }
  45787. // If targetInfo is fetched by 'retrieveTargetInfo',
  45788. // old tree and new tree are the same tree,
  45789. // so the node still exists and we can visit it.
  45790. var targetNode = targetInfo.node;
  45791. var layout = targetNode.getLayout();
  45792. if (!layout) {
  45793. return defaultPosition;
  45794. }
  45795. // Transform coord from local to container.
  45796. var targetCenter = [layout.width / 2, layout.height / 2];
  45797. var node = targetNode;
  45798. while (node) {
  45799. var nodeLayout = node.getLayout();
  45800. targetCenter[0] += nodeLayout.x;
  45801. targetCenter[1] += nodeLayout.y;
  45802. node = node.parentNode;
  45803. }
  45804. return {
  45805. x: layoutInfo.width / 2 - targetCenter[0],
  45806. y: layoutInfo.height / 2 - targetCenter[1]
  45807. };
  45808. }
  45809. // Mark nodes visible for prunning when visual coding and rendering.
  45810. // Prunning depends on layout and root position, so we have to do it after layout.
  45811. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  45812. var nodeLayout = node.getLayout();
  45813. var nodeInViewAbovePath = viewAbovePath[depth];
  45814. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  45815. if (
  45816. (nodeInViewAbovePath && !isAboveViewRoot)
  45817. || (depth === viewAbovePath.length && node !== viewRoot)
  45818. ) {
  45819. return;
  45820. }
  45821. node.setLayout({
  45822. // isInView means: viewRoot sub tree + viewAbovePath
  45823. isInView: true,
  45824. // invisible only means: outside view clip so that the node can not
  45825. // see but still layout for animation preparation but not render.
  45826. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  45827. isAboveViewRoot: isAboveViewRoot
  45828. }, true);
  45829. // Transform to child coordinate.
  45830. var childClipRect = new BoundingRect(
  45831. clipRect.x - nodeLayout.x,
  45832. clipRect.y - nodeLayout.y,
  45833. clipRect.width,
  45834. clipRect.height
  45835. );
  45836. each$10(node.viewChildren || [], function (child) {
  45837. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  45838. });
  45839. }
  45840. function getUpperLabelHeight(model) {
  45841. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  45842. }
  45843. /*
  45844. * Licensed to the Apache Software Foundation (ASF) under one
  45845. * or more contributor license agreements. See the NOTICE file
  45846. * distributed with this work for additional information
  45847. * regarding copyright ownership. The ASF licenses this file
  45848. * to you under the Apache License, Version 2.0 (the
  45849. * "License"); you may not use this file except in compliance
  45850. * with the License. You may obtain a copy of the License at
  45851. *
  45852. * http://www.apache.org/licenses/LICENSE-2.0
  45853. *
  45854. * Unless required by applicable law or agreed to in writing,
  45855. * software distributed under the License is distributed on an
  45856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45857. * KIND, either express or implied. See the License for the
  45858. * specific language governing permissions and limitations
  45859. * under the License.
  45860. */
  45861. registerVisual(treemapVisual);
  45862. registerLayout(treemapLayout);
  45863. /*
  45864. * Licensed to the Apache Software Foundation (ASF) under one
  45865. * or more contributor license agreements. See the NOTICE file
  45866. * distributed with this work for additional information
  45867. * regarding copyright ownership. The ASF licenses this file
  45868. * to you under the Apache License, Version 2.0 (the
  45869. * "License"); you may not use this file except in compliance
  45870. * with the License. You may obtain a copy of the License at
  45871. *
  45872. * http://www.apache.org/licenses/LICENSE-2.0
  45873. *
  45874. * Unless required by applicable law or agreed to in writing,
  45875. * software distributed under the License is distributed on an
  45876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45877. * KIND, either express or implied. See the License for the
  45878. * specific language governing permissions and limitations
  45879. * under the License.
  45880. */
  45881. /**
  45882. * Graph data structure
  45883. *
  45884. * @module echarts/data/Graph
  45885. * @author Yi Shen(https://www.github.com/pissang)
  45886. */
  45887. // id may be function name of Object, add a prefix to avoid this problem.
  45888. function generateNodeKey(id) {
  45889. return '_EC_' + id;
  45890. }
  45891. /**
  45892. * @alias module:echarts/data/Graph
  45893. * @constructor
  45894. * @param {boolean} directed
  45895. */
  45896. var Graph = function (directed) {
  45897. /**
  45898. * 是否是有向图
  45899. * @type {boolean}
  45900. * @private
  45901. */
  45902. this._directed = directed || false;
  45903. /**
  45904. * @type {Array.<module:echarts/data/Graph.Node>}
  45905. * @readOnly
  45906. */
  45907. this.nodes = [];
  45908. /**
  45909. * @type {Array.<module:echarts/data/Graph.Edge>}
  45910. * @readOnly
  45911. */
  45912. this.edges = [];
  45913. /**
  45914. * @type {Object.<string, module:echarts/data/Graph.Node>}
  45915. * @private
  45916. */
  45917. this._nodesMap = {};
  45918. /**
  45919. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  45920. * @private
  45921. */
  45922. this._edgesMap = {};
  45923. /**
  45924. * @type {module:echarts/data/List}
  45925. * @readOnly
  45926. */
  45927. this.data;
  45928. /**
  45929. * @type {module:echarts/data/List}
  45930. * @readOnly
  45931. */
  45932. this.edgeData;
  45933. };
  45934. var graphProto = Graph.prototype;
  45935. /**
  45936. * @type {string}
  45937. */
  45938. graphProto.type = 'graph';
  45939. /**
  45940. * If is directed graph
  45941. * @return {boolean}
  45942. */
  45943. graphProto.isDirected = function () {
  45944. return this._directed;
  45945. };
  45946. /**
  45947. * Add a new node
  45948. * @param {string} id
  45949. * @param {number} [dataIndex]
  45950. */
  45951. graphProto.addNode = function (id, dataIndex) {
  45952. id = id || ('' + dataIndex);
  45953. var nodesMap = this._nodesMap;
  45954. if (nodesMap[generateNodeKey(id)]) {
  45955. if (__DEV__) {
  45956. console.error('Graph nodes have duplicate name or id');
  45957. }
  45958. return;
  45959. }
  45960. var node = new Node(id, dataIndex);
  45961. node.hostGraph = this;
  45962. this.nodes.push(node);
  45963. nodesMap[generateNodeKey(id)] = node;
  45964. return node;
  45965. };
  45966. /**
  45967. * Get node by data index
  45968. * @param {number} dataIndex
  45969. * @return {module:echarts/data/Graph~Node}
  45970. */
  45971. graphProto.getNodeByIndex = function (dataIndex) {
  45972. var rawIdx = this.data.getRawIndex(dataIndex);
  45973. return this.nodes[rawIdx];
  45974. };
  45975. /**
  45976. * Get node by id
  45977. * @param {string} id
  45978. * @return {module:echarts/data/Graph.Node}
  45979. */
  45980. graphProto.getNodeById = function (id) {
  45981. return this._nodesMap[generateNodeKey(id)];
  45982. };
  45983. /**
  45984. * Add a new edge
  45985. * @param {number|string|module:echarts/data/Graph.Node} n1
  45986. * @param {number|string|module:echarts/data/Graph.Node} n2
  45987. * @param {number} [dataIndex=-1]
  45988. * @return {module:echarts/data/Graph.Edge}
  45989. */
  45990. graphProto.addEdge = function (n1, n2, dataIndex) {
  45991. var nodesMap = this._nodesMap;
  45992. var edgesMap = this._edgesMap;
  45993. // PNEDING
  45994. if (typeof n1 === 'number') {
  45995. n1 = this.nodes[n1];
  45996. }
  45997. if (typeof n2 === 'number') {
  45998. n2 = this.nodes[n2];
  45999. }
  46000. if (!Node.isInstance(n1)) {
  46001. n1 = nodesMap[generateNodeKey(n1)];
  46002. }
  46003. if (!Node.isInstance(n2)) {
  46004. n2 = nodesMap[generateNodeKey(n2)];
  46005. }
  46006. if (!n1 || !n2) {
  46007. return;
  46008. }
  46009. var key = n1.id + '-' + n2.id;
  46010. // PENDING
  46011. if (edgesMap[key]) {
  46012. return;
  46013. }
  46014. var edge = new Edge(n1, n2, dataIndex);
  46015. edge.hostGraph = this;
  46016. if (this._directed) {
  46017. n1.outEdges.push(edge);
  46018. n2.inEdges.push(edge);
  46019. }
  46020. n1.edges.push(edge);
  46021. if (n1 !== n2) {
  46022. n2.edges.push(edge);
  46023. }
  46024. this.edges.push(edge);
  46025. edgesMap[key] = edge;
  46026. return edge;
  46027. };
  46028. /**
  46029. * Get edge by data index
  46030. * @param {number} dataIndex
  46031. * @return {module:echarts/data/Graph~Node}
  46032. */
  46033. graphProto.getEdgeByIndex = function (dataIndex) {
  46034. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  46035. return this.edges[rawIdx];
  46036. };
  46037. /**
  46038. * Get edge by two linked nodes
  46039. * @param {module:echarts/data/Graph.Node|string} n1
  46040. * @param {module:echarts/data/Graph.Node|string} n2
  46041. * @return {module:echarts/data/Graph.Edge}
  46042. */
  46043. graphProto.getEdge = function (n1, n2) {
  46044. if (Node.isInstance(n1)) {
  46045. n1 = n1.id;
  46046. }
  46047. if (Node.isInstance(n2)) {
  46048. n2 = n2.id;
  46049. }
  46050. var edgesMap = this._edgesMap;
  46051. if (this._directed) {
  46052. return edgesMap[n1 + '-' + n2];
  46053. }
  46054. else {
  46055. return edgesMap[n1 + '-' + n2]
  46056. || edgesMap[n2 + '-' + n1];
  46057. }
  46058. };
  46059. /**
  46060. * Iterate all nodes
  46061. * @param {Function} cb
  46062. * @param {*} [context]
  46063. */
  46064. graphProto.eachNode = function (cb, context) {
  46065. var nodes = this.nodes;
  46066. var len = nodes.length;
  46067. for (var i = 0; i < len; i++) {
  46068. if (nodes[i].dataIndex >= 0) {
  46069. cb.call(context, nodes[i], i);
  46070. }
  46071. }
  46072. };
  46073. /**
  46074. * Iterate all edges
  46075. * @param {Function} cb
  46076. * @param {*} [context]
  46077. */
  46078. graphProto.eachEdge = function (cb, context) {
  46079. var edges = this.edges;
  46080. var len = edges.length;
  46081. for (var i = 0; i < len; i++) {
  46082. if (edges[i].dataIndex >= 0
  46083. && edges[i].node1.dataIndex >= 0
  46084. && edges[i].node2.dataIndex >= 0
  46085. ) {
  46086. cb.call(context, edges[i], i);
  46087. }
  46088. }
  46089. };
  46090. /**
  46091. * Breadth first traverse
  46092. * @param {Function} cb
  46093. * @param {module:echarts/data/Graph.Node} startNode
  46094. * @param {string} [direction='none'] 'none'|'in'|'out'
  46095. * @param {*} [context]
  46096. */
  46097. graphProto.breadthFirstTraverse = function (
  46098. cb, startNode, direction, context
  46099. ) {
  46100. if (!Node.isInstance(startNode)) {
  46101. startNode = this._nodesMap[generateNodeKey(startNode)];
  46102. }
  46103. if (!startNode) {
  46104. return;
  46105. }
  46106. var edgeType = direction === 'out'
  46107. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  46108. for (var i = 0; i < this.nodes.length; i++) {
  46109. this.nodes[i].__visited = false;
  46110. }
  46111. if (cb.call(context, startNode, null)) {
  46112. return;
  46113. }
  46114. var queue = [startNode];
  46115. while (queue.length) {
  46116. var currentNode = queue.shift();
  46117. var edges = currentNode[edgeType];
  46118. for (var i = 0; i < edges.length; i++) {
  46119. var e = edges[i];
  46120. var otherNode = e.node1 === currentNode
  46121. ? e.node2 : e.node1;
  46122. if (!otherNode.__visited) {
  46123. if (cb.call(context, otherNode, currentNode)) {
  46124. // Stop traversing
  46125. return;
  46126. }
  46127. queue.push(otherNode);
  46128. otherNode.__visited = true;
  46129. }
  46130. }
  46131. }
  46132. };
  46133. // TODO
  46134. // graphProto.depthFirstTraverse = function (
  46135. // cb, startNode, direction, context
  46136. // ) {
  46137. // };
  46138. // Filter update
  46139. graphProto.update = function () {
  46140. var data = this.data;
  46141. var edgeData = this.edgeData;
  46142. var nodes = this.nodes;
  46143. var edges = this.edges;
  46144. for (var i = 0, len = nodes.length; i < len; i++) {
  46145. nodes[i].dataIndex = -1;
  46146. }
  46147. for (var i = 0, len = data.count(); i < len; i++) {
  46148. nodes[data.getRawIndex(i)].dataIndex = i;
  46149. }
  46150. edgeData.filterSelf(function (idx) {
  46151. var edge = edges[edgeData.getRawIndex(idx)];
  46152. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  46153. });
  46154. // Update edge
  46155. for (var i = 0, len = edges.length; i < len; i++) {
  46156. edges[i].dataIndex = -1;
  46157. }
  46158. for (var i = 0, len = edgeData.count(); i < len; i++) {
  46159. edges[edgeData.getRawIndex(i)].dataIndex = i;
  46160. }
  46161. };
  46162. /**
  46163. * @return {module:echarts/data/Graph}
  46164. */
  46165. graphProto.clone = function () {
  46166. var graph = new Graph(this._directed);
  46167. var nodes = this.nodes;
  46168. var edges = this.edges;
  46169. for (var i = 0; i < nodes.length; i++) {
  46170. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  46171. }
  46172. for (var i = 0; i < edges.length; i++) {
  46173. var e = edges[i];
  46174. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  46175. }
  46176. return graph;
  46177. };
  46178. /**
  46179. * @alias module:echarts/data/Graph.Node
  46180. */
  46181. function Node(id, dataIndex) {
  46182. /**
  46183. * @type {string}
  46184. */
  46185. this.id = id == null ? '' : id;
  46186. /**
  46187. * @type {Array.<module:echarts/data/Graph.Edge>}
  46188. */
  46189. this.inEdges = [];
  46190. /**
  46191. * @type {Array.<module:echarts/data/Graph.Edge>}
  46192. */
  46193. this.outEdges = [];
  46194. /**
  46195. * @type {Array.<module:echarts/data/Graph.Edge>}
  46196. */
  46197. this.edges = [];
  46198. /**
  46199. * @type {module:echarts/data/Graph}
  46200. */
  46201. this.hostGraph;
  46202. /**
  46203. * @type {number}
  46204. */
  46205. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  46206. }
  46207. Node.prototype = {
  46208. constructor: Node,
  46209. /**
  46210. * @return {number}
  46211. */
  46212. degree: function () {
  46213. return this.edges.length;
  46214. },
  46215. /**
  46216. * @return {number}
  46217. */
  46218. inDegree: function () {
  46219. return this.inEdges.length;
  46220. },
  46221. /**
  46222. * @return {number}
  46223. */
  46224. outDegree: function () {
  46225. return this.outEdges.length;
  46226. },
  46227. /**
  46228. * @param {string} [path]
  46229. * @return {module:echarts/model/Model}
  46230. */
  46231. getModel: function (path) {
  46232. if (this.dataIndex < 0) {
  46233. return;
  46234. }
  46235. var graph = this.hostGraph;
  46236. var itemModel = graph.data.getItemModel(this.dataIndex);
  46237. return itemModel.getModel(path);
  46238. }
  46239. };
  46240. /**
  46241. * 图边
  46242. * @alias module:echarts/data/Graph.Edge
  46243. * @param {module:echarts/data/Graph.Node} n1
  46244. * @param {module:echarts/data/Graph.Node} n2
  46245. * @param {number} [dataIndex=-1]
  46246. */
  46247. function Edge(n1, n2, dataIndex) {
  46248. /**
  46249. * 节点1,如果是有向图则为源节点
  46250. * @type {module:echarts/data/Graph.Node}
  46251. */
  46252. this.node1 = n1;
  46253. /**
  46254. * 节点2,如果是有向图则为目标节点
  46255. * @type {module:echarts/data/Graph.Node}
  46256. */
  46257. this.node2 = n2;
  46258. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  46259. }
  46260. /**
  46261. * @param {string} [path]
  46262. * @return {module:echarts/model/Model}
  46263. */
  46264. Edge.prototype.getModel = function (path) {
  46265. if (this.dataIndex < 0) {
  46266. return;
  46267. }
  46268. var graph = this.hostGraph;
  46269. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  46270. return itemModel.getModel(path);
  46271. };
  46272. var createGraphDataProxyMixin = function (hostName, dataName) {
  46273. return {
  46274. /**
  46275. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  46276. * @return {number}
  46277. */
  46278. getValue: function (dimension) {
  46279. var data = this[hostName][dataName];
  46280. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  46281. },
  46282. /**
  46283. * @param {Object|string} key
  46284. * @param {*} [value]
  46285. */
  46286. setVisual: function (key, value) {
  46287. this.dataIndex >= 0
  46288. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  46289. },
  46290. /**
  46291. * @param {string} key
  46292. * @return {boolean}
  46293. */
  46294. getVisual: function (key, ignoreParent) {
  46295. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  46296. },
  46297. /**
  46298. * @param {Object} layout
  46299. * @return {boolean} [merge=false]
  46300. */
  46301. setLayout: function (layout, merge$$1) {
  46302. this.dataIndex >= 0
  46303. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  46304. },
  46305. /**
  46306. * @return {Object}
  46307. */
  46308. getLayout: function () {
  46309. return this[hostName][dataName].getItemLayout(this.dataIndex);
  46310. },
  46311. /**
  46312. * @return {module:zrender/Element}
  46313. */
  46314. getGraphicEl: function () {
  46315. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  46316. },
  46317. /**
  46318. * @return {number}
  46319. */
  46320. getRawIndex: function () {
  46321. return this[hostName][dataName].getRawIndex(this.dataIndex);
  46322. }
  46323. };
  46324. };
  46325. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  46326. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  46327. Graph.Node = Node;
  46328. Graph.Edge = Edge;
  46329. enableClassCheck(Node);
  46330. enableClassCheck(Edge);
  46331. /*
  46332. * Licensed to the Apache Software Foundation (ASF) under one
  46333. * or more contributor license agreements. See the NOTICE file
  46334. * distributed with this work for additional information
  46335. * regarding copyright ownership. The ASF licenses this file
  46336. * to you under the Apache License, Version 2.0 (the
  46337. * "License"); you may not use this file except in compliance
  46338. * with the License. You may obtain a copy of the License at
  46339. *
  46340. * http://www.apache.org/licenses/LICENSE-2.0
  46341. *
  46342. * Unless required by applicable law or agreed to in writing,
  46343. * software distributed under the License is distributed on an
  46344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46345. * KIND, either express or implied. See the License for the
  46346. * specific language governing permissions and limitations
  46347. * under the License.
  46348. */
  46349. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  46350. // ??? TODO
  46351. // support dataset?
  46352. var graph = new Graph(directed);
  46353. for (var i = 0; i < nodes.length; i++) {
  46354. graph.addNode(retrieve(
  46355. // Id, name, dataIndex
  46356. nodes[i].id, nodes[i].name, i
  46357. ), i);
  46358. }
  46359. var linkNameList = [];
  46360. var validEdges = [];
  46361. var linkCount = 0;
  46362. for (var i = 0; i < edges.length; i++) {
  46363. var link = edges[i];
  46364. var source = link.source;
  46365. var target = link.target;
  46366. // addEdge may fail when source or target not exists
  46367. if (graph.addEdge(source, target, linkCount)) {
  46368. validEdges.push(link);
  46369. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  46370. linkCount++;
  46371. }
  46372. }
  46373. var coordSys = seriesModel.get('coordinateSystem');
  46374. var nodeData;
  46375. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  46376. nodeData = createListFromArray(nodes, seriesModel);
  46377. }
  46378. else {
  46379. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  46380. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  46381. ? (coordSysCtor.dimensions || []) : [];
  46382. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  46383. // `value` dimension, but graph need `value` dimension. It's better to
  46384. // uniform this behavior.
  46385. if (indexOf(coordDimensions, 'value') < 0) {
  46386. coordDimensions.concat(['value']);
  46387. }
  46388. var dimensionNames = createDimensions(nodes, {
  46389. coordDimensions: coordDimensions
  46390. });
  46391. nodeData = new List(dimensionNames, seriesModel);
  46392. nodeData.initData(nodes);
  46393. }
  46394. var edgeData = new List(['value'], seriesModel);
  46395. edgeData.initData(validEdges, linkNameList);
  46396. beforeLink && beforeLink(nodeData, edgeData);
  46397. linkList({
  46398. mainData: nodeData,
  46399. struct: graph,
  46400. structAttr: 'graph',
  46401. datas: {node: nodeData, edge: edgeData},
  46402. datasAttr: {node: 'data', edge: 'edgeData'}
  46403. });
  46404. // Update dataIndex of nodes and edges because invalid edge may be removed
  46405. graph.update();
  46406. return graph;
  46407. };
  46408. /*
  46409. * Licensed to the Apache Software Foundation (ASF) under one
  46410. * or more contributor license agreements. See the NOTICE file
  46411. * distributed with this work for additional information
  46412. * regarding copyright ownership. The ASF licenses this file
  46413. * to you under the Apache License, Version 2.0 (the
  46414. * "License"); you may not use this file except in compliance
  46415. * with the License. You may obtain a copy of the License at
  46416. *
  46417. * http://www.apache.org/licenses/LICENSE-2.0
  46418. *
  46419. * Unless required by applicable law or agreed to in writing,
  46420. * software distributed under the License is distributed on an
  46421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46422. * KIND, either express or implied. See the License for the
  46423. * specific language governing permissions and limitations
  46424. * under the License.
  46425. */
  46426. var GraphSeries = extendSeriesModel({
  46427. type: 'series.graph',
  46428. init: function (option) {
  46429. GraphSeries.superApply(this, 'init', arguments);
  46430. // Provide data for legend select
  46431. this.legendDataProvider = function () {
  46432. return this._categoriesData;
  46433. };
  46434. this.fillDataTextStyle(option.edges || option.links);
  46435. this._updateCategoriesData();
  46436. },
  46437. mergeOption: function (option) {
  46438. GraphSeries.superApply(this, 'mergeOption', arguments);
  46439. this.fillDataTextStyle(option.edges || option.links);
  46440. this._updateCategoriesData();
  46441. },
  46442. mergeDefaultAndTheme: function (option) {
  46443. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  46444. defaultEmphasis(option, ['edgeLabel'], ['show']);
  46445. },
  46446. getInitialData: function (option, ecModel) {
  46447. var edges = option.edges || option.links || [];
  46448. var nodes = option.data || option.nodes || [];
  46449. var self = this;
  46450. if (nodes && edges) {
  46451. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  46452. }
  46453. function beforeLink(nodeData, edgeData) {
  46454. // Overwrite nodeData.getItemModel to
  46455. nodeData.wrapMethod('getItemModel', function (model) {
  46456. var categoriesModels = self._categoriesModels;
  46457. var categoryIdx = model.getShallow('category');
  46458. var categoryModel = categoriesModels[categoryIdx];
  46459. if (categoryModel) {
  46460. categoryModel.parentModel = model.parentModel;
  46461. model.parentModel = categoryModel;
  46462. }
  46463. return model;
  46464. });
  46465. var edgeLabelModel = self.getModel('edgeLabel');
  46466. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  46467. var fakeSeriesModel = new Model(
  46468. {label: edgeLabelModel.option},
  46469. edgeLabelModel.parentModel,
  46470. ecModel
  46471. );
  46472. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  46473. var emphasisFakeSeriesModel = new Model(
  46474. {emphasis: {label: emphasisEdgeLabelModel.option}},
  46475. emphasisEdgeLabelModel.parentModel,
  46476. ecModel
  46477. );
  46478. edgeData.wrapMethod('getItemModel', function (model) {
  46479. model.customizeGetParent(edgeGetParent);
  46480. return model;
  46481. });
  46482. function edgeGetParent(path) {
  46483. path = this.parsePath(path);
  46484. return (path && path[0] === 'label')
  46485. ? fakeSeriesModel
  46486. : (path && path[0] === 'emphasis' && path[1] === 'label')
  46487. ? emphasisFakeSeriesModel
  46488. : this.parentModel;
  46489. }
  46490. }
  46491. },
  46492. /**
  46493. * @return {module:echarts/data/Graph}
  46494. */
  46495. getGraph: function () {
  46496. return this.getData().graph;
  46497. },
  46498. /**
  46499. * @return {module:echarts/data/List}
  46500. */
  46501. getEdgeData: function () {
  46502. return this.getGraph().edgeData;
  46503. },
  46504. /**
  46505. * @return {module:echarts/data/List}
  46506. */
  46507. getCategoriesData: function () {
  46508. return this._categoriesData;
  46509. },
  46510. /**
  46511. * @override
  46512. */
  46513. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  46514. if (dataType === 'edge') {
  46515. var nodeData = this.getData();
  46516. var params = this.getDataParams(dataIndex, dataType);
  46517. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  46518. var sourceName = nodeData.getName(edge.node1.dataIndex);
  46519. var targetName = nodeData.getName(edge.node2.dataIndex);
  46520. var html = [];
  46521. sourceName != null && html.push(sourceName);
  46522. targetName != null && html.push(targetName);
  46523. html = encodeHTML(html.join(' > '));
  46524. if (params.value) {
  46525. html += ' : ' + encodeHTML(params.value);
  46526. }
  46527. return html;
  46528. }
  46529. else { // dataType === 'node' or empty
  46530. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  46531. }
  46532. },
  46533. _updateCategoriesData: function () {
  46534. var categories = map(this.option.categories || [], function (category) {
  46535. // Data must has value
  46536. return category.value != null ? category : extend({
  46537. value: 0
  46538. }, category);
  46539. });
  46540. var categoriesData = new List(['value'], this);
  46541. categoriesData.initData(categories);
  46542. this._categoriesData = categoriesData;
  46543. this._categoriesModels = categoriesData.mapArray(function (idx) {
  46544. return categoriesData.getItemModel(idx, true);
  46545. });
  46546. },
  46547. setZoom: function (zoom) {
  46548. this.option.zoom = zoom;
  46549. },
  46550. setCenter: function (center) {
  46551. this.option.center = center;
  46552. },
  46553. isAnimationEnabled: function () {
  46554. return GraphSeries.superCall(this, 'isAnimationEnabled')
  46555. // Not enable animation when do force layout
  46556. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  46557. },
  46558. defaultOption: {
  46559. zlevel: 0,
  46560. z: 2,
  46561. coordinateSystem: 'view',
  46562. // Default option for all coordinate systems
  46563. // xAxisIndex: 0,
  46564. // yAxisIndex: 0,
  46565. // polarIndex: 0,
  46566. // geoIndex: 0,
  46567. legendHoverLink: true,
  46568. hoverAnimation: true,
  46569. layout: null,
  46570. focusNodeAdjacency: false,
  46571. // Configuration of circular layout
  46572. circular: {
  46573. rotateLabel: false
  46574. },
  46575. // Configuration of force directed layout
  46576. force: {
  46577. initLayout: null,
  46578. // Node repulsion. Can be an array to represent range.
  46579. repulsion: [0, 50],
  46580. gravity: 0.1,
  46581. // Edge length. Can be an array to represent range.
  46582. edgeLength: 30,
  46583. layoutAnimation: true
  46584. },
  46585. left: 'center',
  46586. top: 'center',
  46587. // right: null,
  46588. // bottom: null,
  46589. // width: '80%',
  46590. // height: '80%',
  46591. symbol: 'circle',
  46592. symbolSize: 10,
  46593. edgeSymbol: ['none', 'none'],
  46594. edgeSymbolSize: 10,
  46595. edgeLabel: {
  46596. position: 'middle'
  46597. },
  46598. draggable: false,
  46599. roam: false,
  46600. // Default on center of graph
  46601. center: null,
  46602. zoom: 1,
  46603. // Symbol size scale ratio in roam
  46604. nodeScaleRatio: 0.6,
  46605. // cursor: null,
  46606. // categories: [],
  46607. // data: []
  46608. // Or
  46609. // nodes: []
  46610. //
  46611. // links: []
  46612. // Or
  46613. // edges: []
  46614. label: {
  46615. show: false,
  46616. formatter: '{b}'
  46617. },
  46618. itemStyle: {},
  46619. lineStyle: {
  46620. color: '#aaa',
  46621. width: 1,
  46622. curveness: 0,
  46623. opacity: 0.5
  46624. },
  46625. emphasis: {
  46626. label: {
  46627. show: true
  46628. }
  46629. }
  46630. }
  46631. });
  46632. /*
  46633. * Licensed to the Apache Software Foundation (ASF) under one
  46634. * or more contributor license agreements. See the NOTICE file
  46635. * distributed with this work for additional information
  46636. * regarding copyright ownership. The ASF licenses this file
  46637. * to you under the Apache License, Version 2.0 (the
  46638. * "License"); you may not use this file except in compliance
  46639. * with the License. You may obtain a copy of the License at
  46640. *
  46641. * http://www.apache.org/licenses/LICENSE-2.0
  46642. *
  46643. * Unless required by applicable law or agreed to in writing,
  46644. * software distributed under the License is distributed on an
  46645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46646. * KIND, either express or implied. See the License for the
  46647. * specific language governing permissions and limitations
  46648. * under the License.
  46649. */
  46650. /**
  46651. * Line path for bezier and straight line draw
  46652. */
  46653. var straightLineProto = Line.prototype;
  46654. var bezierCurveProto = BezierCurve.prototype;
  46655. function isLine(shape) {
  46656. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  46657. }
  46658. var LinePath = extendShape({
  46659. type: 'ec-line',
  46660. style: {
  46661. stroke: '#000',
  46662. fill: null
  46663. },
  46664. shape: {
  46665. x1: 0,
  46666. y1: 0,
  46667. x2: 0,
  46668. y2: 0,
  46669. percent: 1,
  46670. cpx1: null,
  46671. cpy1: null
  46672. },
  46673. buildPath: function (ctx, shape) {
  46674. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  46675. },
  46676. pointAt: function (t) {
  46677. return isLine(this.shape)
  46678. ? straightLineProto.pointAt.call(this, t)
  46679. : bezierCurveProto.pointAt.call(this, t);
  46680. },
  46681. tangentAt: function (t) {
  46682. var shape = this.shape;
  46683. var p = isLine(shape)
  46684. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  46685. : bezierCurveProto.tangentAt.call(this, t);
  46686. return normalize(p, p);
  46687. }
  46688. });
  46689. /*
  46690. * Licensed to the Apache Software Foundation (ASF) under one
  46691. * or more contributor license agreements. See the NOTICE file
  46692. * distributed with this work for additional information
  46693. * regarding copyright ownership. The ASF licenses this file
  46694. * to you under the Apache License, Version 2.0 (the
  46695. * "License"); you may not use this file except in compliance
  46696. * with the License. You may obtain a copy of the License at
  46697. *
  46698. * http://www.apache.org/licenses/LICENSE-2.0
  46699. *
  46700. * Unless required by applicable law or agreed to in writing,
  46701. * software distributed under the License is distributed on an
  46702. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46703. * KIND, either express or implied. See the License for the
  46704. * specific language governing permissions and limitations
  46705. * under the License.
  46706. */
  46707. /**
  46708. * @module echarts/chart/helper/Line
  46709. */
  46710. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  46711. function makeSymbolTypeKey(symbolCategory) {
  46712. return '_' + symbolCategory + 'Type';
  46713. }
  46714. /**
  46715. * @inner
  46716. */
  46717. function createSymbol$1(name, lineData, idx) {
  46718. var color = lineData.getItemVisual(idx, 'color');
  46719. var symbolType = lineData.getItemVisual(idx, name);
  46720. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  46721. if (!symbolType || symbolType === 'none') {
  46722. return;
  46723. }
  46724. if (!isArray(symbolSize)) {
  46725. symbolSize = [symbolSize, symbolSize];
  46726. }
  46727. var symbolPath = createSymbol(
  46728. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  46729. symbolSize[0], symbolSize[1], color
  46730. );
  46731. symbolPath.name = name;
  46732. return symbolPath;
  46733. }
  46734. function createLine(points) {
  46735. var line = new LinePath({
  46736. name: 'line'
  46737. });
  46738. setLinePoints(line.shape, points);
  46739. return line;
  46740. }
  46741. function setLinePoints(targetShape, points) {
  46742. var p1 = points[0];
  46743. var p2 = points[1];
  46744. var cp1 = points[2];
  46745. targetShape.x1 = p1[0];
  46746. targetShape.y1 = p1[1];
  46747. targetShape.x2 = p2[0];
  46748. targetShape.y2 = p2[1];
  46749. targetShape.percent = 1;
  46750. if (cp1) {
  46751. targetShape.cpx1 = cp1[0];
  46752. targetShape.cpy1 = cp1[1];
  46753. }
  46754. else {
  46755. targetShape.cpx1 = NaN;
  46756. targetShape.cpy1 = NaN;
  46757. }
  46758. }
  46759. function updateSymbolAndLabelBeforeLineUpdate() {
  46760. var lineGroup = this;
  46761. var symbolFrom = lineGroup.childOfName('fromSymbol');
  46762. var symbolTo = lineGroup.childOfName('toSymbol');
  46763. var label = lineGroup.childOfName('label');
  46764. // Quick reject
  46765. if (!symbolFrom && !symbolTo && label.ignore) {
  46766. return;
  46767. }
  46768. var invScale = 1;
  46769. var parentNode = this.parent;
  46770. while (parentNode) {
  46771. if (parentNode.scale) {
  46772. invScale /= parentNode.scale[0];
  46773. }
  46774. parentNode = parentNode.parent;
  46775. }
  46776. var line = lineGroup.childOfName('line');
  46777. // If line not changed
  46778. // FIXME Parent scale changed
  46779. if (!this.__dirty && !line.__dirty) {
  46780. return;
  46781. }
  46782. var percent = line.shape.percent;
  46783. var fromPos = line.pointAt(0);
  46784. var toPos = line.pointAt(percent);
  46785. var d = sub([], toPos, fromPos);
  46786. normalize(d, d);
  46787. if (symbolFrom) {
  46788. symbolFrom.attr('position', fromPos);
  46789. var tangent = line.tangentAt(0);
  46790. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  46791. tangent[1], tangent[0]
  46792. ));
  46793. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  46794. }
  46795. if (symbolTo) {
  46796. symbolTo.attr('position', toPos);
  46797. var tangent = line.tangentAt(1);
  46798. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  46799. tangent[1], tangent[0]
  46800. ));
  46801. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  46802. }
  46803. if (!label.ignore) {
  46804. label.attr('position', toPos);
  46805. var textPosition;
  46806. var textAlign;
  46807. var textVerticalAlign;
  46808. var distance$$1 = 5 * invScale;
  46809. // End
  46810. if (label.__position === 'end') {
  46811. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  46812. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  46813. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  46814. }
  46815. // Middle
  46816. else if (label.__position === 'middle') {
  46817. var halfPercent = percent / 2;
  46818. var tangent = line.tangentAt(halfPercent);
  46819. var n = [tangent[1], -tangent[0]];
  46820. var cp = line.pointAt(halfPercent);
  46821. if (n[1] > 0) {
  46822. n[0] = -n[0];
  46823. n[1] = -n[1];
  46824. }
  46825. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  46826. textAlign = 'center';
  46827. textVerticalAlign = 'bottom';
  46828. var rotation = -Math.atan2(tangent[1], tangent[0]);
  46829. if (toPos[0] < fromPos[0]) {
  46830. rotation = Math.PI + rotation;
  46831. }
  46832. label.attr('rotation', rotation);
  46833. }
  46834. // Start
  46835. else {
  46836. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  46837. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  46838. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  46839. }
  46840. label.attr({
  46841. style: {
  46842. // Use the user specified text align and baseline first
  46843. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  46844. textAlign: label.__textAlign || textAlign
  46845. },
  46846. position: textPosition,
  46847. scale: [invScale, invScale]
  46848. });
  46849. }
  46850. }
  46851. /**
  46852. * @constructor
  46853. * @extends {module:zrender/graphic/Group}
  46854. * @alias {module:echarts/chart/helper/Line}
  46855. */
  46856. function Line$1(lineData, idx, seriesScope) {
  46857. Group.call(this);
  46858. this._createLine(lineData, idx, seriesScope);
  46859. }
  46860. var lineProto = Line$1.prototype;
  46861. // Update symbol position and rotation
  46862. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  46863. lineProto._createLine = function (lineData, idx, seriesScope) {
  46864. var seriesModel = lineData.hostModel;
  46865. var linePoints = lineData.getItemLayout(idx);
  46866. var line = createLine(linePoints);
  46867. line.shape.percent = 0;
  46868. initProps(line, {
  46869. shape: {
  46870. percent: 1
  46871. }
  46872. }, seriesModel, idx);
  46873. this.add(line);
  46874. var label = new Text({
  46875. name: 'label',
  46876. // FIXME
  46877. // Temporary solution for `focusNodeAdjacency`.
  46878. // line label do not use the opacity of lineStyle.
  46879. lineLabelOriginalOpacity: 1
  46880. });
  46881. this.add(label);
  46882. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46883. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46884. // symbols must added after line to make sure
  46885. // it will be updated after line#update.
  46886. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  46887. this.add(symbol);
  46888. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  46889. }, this);
  46890. this._updateCommonStl(lineData, idx, seriesScope);
  46891. };
  46892. lineProto.updateData = function (lineData, idx, seriesScope) {
  46893. var seriesModel = lineData.hostModel;
  46894. var line = this.childOfName('line');
  46895. var linePoints = lineData.getItemLayout(idx);
  46896. var target = {
  46897. shape: {}
  46898. };
  46899. setLinePoints(target.shape, linePoints);
  46900. updateProps(line, target, seriesModel, idx);
  46901. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46902. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  46903. var key = makeSymbolTypeKey(symbolCategory);
  46904. // Symbol changed
  46905. if (this[key] !== symbolType) {
  46906. this.remove(this.childOfName(symbolCategory));
  46907. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46908. this.add(symbol);
  46909. }
  46910. this[key] = symbolType;
  46911. }, this);
  46912. this._updateCommonStl(lineData, idx, seriesScope);
  46913. };
  46914. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46915. var seriesModel = lineData.hostModel;
  46916. var line = this.childOfName('line');
  46917. var lineStyle = seriesScope && seriesScope.lineStyle;
  46918. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46919. var labelModel = seriesScope && seriesScope.labelModel;
  46920. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  46921. // Optimization for large dataset
  46922. if (!seriesScope || lineData.hasItemOption) {
  46923. var itemModel = lineData.getItemModel(idx);
  46924. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46925. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46926. labelModel = itemModel.getModel('label');
  46927. hoverLabelModel = itemModel.getModel('emphasis.label');
  46928. }
  46929. var visualColor = lineData.getItemVisual(idx, 'color');
  46930. var visualOpacity = retrieve3(
  46931. lineData.getItemVisual(idx, 'opacity'),
  46932. lineStyle.opacity,
  46933. 1
  46934. );
  46935. line.useStyle(defaults(
  46936. {
  46937. strokeNoScale: true,
  46938. fill: 'none',
  46939. stroke: visualColor,
  46940. opacity: visualOpacity
  46941. },
  46942. lineStyle
  46943. ));
  46944. line.hoverStyle = hoverLineStyle;
  46945. // Update symbol
  46946. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46947. var symbol = this.childOfName(symbolCategory);
  46948. if (symbol) {
  46949. symbol.setColor(visualColor);
  46950. symbol.setStyle({
  46951. opacity: visualOpacity
  46952. });
  46953. }
  46954. }, this);
  46955. var showLabel = labelModel.getShallow('show');
  46956. var hoverShowLabel = hoverLabelModel.getShallow('show');
  46957. var label = this.childOfName('label');
  46958. var defaultLabelColor;
  46959. var baseText;
  46960. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  46961. if (showLabel || hoverShowLabel) {
  46962. defaultLabelColor = visualColor || '#000';
  46963. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  46964. if (baseText == null) {
  46965. var rawVal = seriesModel.getRawValue(idx);
  46966. baseText = rawVal == null
  46967. ? lineData.getName(idx)
  46968. : isFinite(rawVal)
  46969. ? round$2(rawVal)
  46970. : rawVal;
  46971. }
  46972. }
  46973. var normalText = showLabel ? baseText : null;
  46974. var emphasisText = hoverShowLabel
  46975. ? retrieve2(
  46976. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  46977. baseText
  46978. )
  46979. : null;
  46980. var labelStyle = label.style;
  46981. // Always set `textStyle` even if `normalStyle.text` is null, because default
  46982. // values have to be set on `normalStyle`.
  46983. if (normalText != null || emphasisText != null) {
  46984. setTextStyle(label.style, labelModel, {
  46985. text: normalText
  46986. }, {
  46987. autoColor: defaultLabelColor
  46988. });
  46989. label.__textAlign = labelStyle.textAlign;
  46990. label.__verticalAlign = labelStyle.textVerticalAlign;
  46991. // 'start', 'middle', 'end'
  46992. label.__position = labelModel.get('position') || 'middle';
  46993. }
  46994. if (emphasisText != null) {
  46995. // Only these properties supported in this emphasis style here.
  46996. label.hoverStyle = {
  46997. text: emphasisText,
  46998. textFill: hoverLabelModel.getTextColor(true),
  46999. // For merging hover style to normal style, do not use
  47000. // `hoverLabelModel.getFont()` here.
  47001. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  47002. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  47003. fontSize: hoverLabelModel.getShallow('fontSize'),
  47004. fontFamily: hoverLabelModel.getShallow('fontFamily')
  47005. };
  47006. }
  47007. else {
  47008. label.hoverStyle = {
  47009. text: null
  47010. };
  47011. }
  47012. label.ignore = !showLabel && !hoverShowLabel;
  47013. setHoverStyle(this);
  47014. };
  47015. lineProto.highlight = function () {
  47016. this.trigger('emphasis');
  47017. };
  47018. lineProto.downplay = function () {
  47019. this.trigger('normal');
  47020. };
  47021. lineProto.updateLayout = function (lineData, idx) {
  47022. this.setLinePoints(lineData.getItemLayout(idx));
  47023. };
  47024. lineProto.setLinePoints = function (points) {
  47025. var linePath = this.childOfName('line');
  47026. setLinePoints(linePath.shape, points);
  47027. linePath.dirty();
  47028. };
  47029. inherits(Line$1, Group);
  47030. /*
  47031. * Licensed to the Apache Software Foundation (ASF) under one
  47032. * or more contributor license agreements. See the NOTICE file
  47033. * distributed with this work for additional information
  47034. * regarding copyright ownership. The ASF licenses this file
  47035. * to you under the Apache License, Version 2.0 (the
  47036. * "License"); you may not use this file except in compliance
  47037. * with the License. You may obtain a copy of the License at
  47038. *
  47039. * http://www.apache.org/licenses/LICENSE-2.0
  47040. *
  47041. * Unless required by applicable law or agreed to in writing,
  47042. * software distributed under the License is distributed on an
  47043. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47044. * KIND, either express or implied. See the License for the
  47045. * specific language governing permissions and limitations
  47046. * under the License.
  47047. */
  47048. /**
  47049. * @module echarts/chart/helper/LineDraw
  47050. */
  47051. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  47052. /**
  47053. * @alias module:echarts/component/marker/LineDraw
  47054. * @constructor
  47055. */
  47056. function LineDraw(ctor) {
  47057. this._ctor = ctor || Line$1;
  47058. this.group = new Group();
  47059. }
  47060. var lineDrawProto = LineDraw.prototype;
  47061. lineDrawProto.isPersistent = function () {
  47062. return true;
  47063. };
  47064. /**
  47065. * @param {module:echarts/data/List} lineData
  47066. */
  47067. lineDrawProto.updateData = function (lineData) {
  47068. var lineDraw = this;
  47069. var group = lineDraw.group;
  47070. var oldLineData = lineDraw._lineData;
  47071. lineDraw._lineData = lineData;
  47072. // There is no oldLineData only when first rendering or switching from
  47073. // stream mode to normal mode, where previous elements should be removed.
  47074. if (!oldLineData) {
  47075. group.removeAll();
  47076. }
  47077. var seriesScope = makeSeriesScope$1(lineData);
  47078. lineData.diff(oldLineData)
  47079. .add(function (idx) {
  47080. doAdd(lineDraw, lineData, idx, seriesScope);
  47081. })
  47082. .update(function (newIdx, oldIdx) {
  47083. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  47084. })
  47085. .remove(function (idx) {
  47086. group.remove(oldLineData.getItemGraphicEl(idx));
  47087. })
  47088. .execute();
  47089. };
  47090. function doAdd(lineDraw, lineData, idx, seriesScope) {
  47091. var itemLayout = lineData.getItemLayout(idx);
  47092. if (!lineNeedsDraw(itemLayout)) {
  47093. return;
  47094. }
  47095. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  47096. lineData.setItemGraphicEl(idx, el);
  47097. lineDraw.group.add(el);
  47098. }
  47099. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  47100. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  47101. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  47102. lineDraw.group.remove(itemEl);
  47103. return;
  47104. }
  47105. if (!itemEl) {
  47106. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  47107. }
  47108. else {
  47109. itemEl.updateData(newLineData, newIdx, seriesScope);
  47110. }
  47111. newLineData.setItemGraphicEl(newIdx, itemEl);
  47112. lineDraw.group.add(itemEl);
  47113. }
  47114. lineDrawProto.updateLayout = function () {
  47115. var lineData = this._lineData;
  47116. // Do not support update layout in incremental mode.
  47117. if (!lineData) {
  47118. return;
  47119. }
  47120. lineData.eachItemGraphicEl(function (el, idx) {
  47121. el.updateLayout(lineData, idx);
  47122. }, this);
  47123. };
  47124. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  47125. this._seriesScope = makeSeriesScope$1(lineData);
  47126. this._lineData = null;
  47127. this.group.removeAll();
  47128. };
  47129. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  47130. function updateIncrementalAndHover(el) {
  47131. if (!el.isGroup) {
  47132. el.incremental = el.useHoverLayer = true;
  47133. }
  47134. }
  47135. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  47136. var itemLayout = lineData.getItemLayout(idx);
  47137. if (lineNeedsDraw(itemLayout)) {
  47138. var el = new this._ctor(lineData, idx, this._seriesScope);
  47139. el.traverse(updateIncrementalAndHover);
  47140. this.group.add(el);
  47141. lineData.setItemGraphicEl(idx, el);
  47142. }
  47143. }
  47144. };
  47145. function makeSeriesScope$1(lineData) {
  47146. var hostModel = lineData.hostModel;
  47147. return {
  47148. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  47149. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  47150. labelModel: hostModel.getModel('label'),
  47151. hoverLabelModel: hostModel.getModel('emphasis.label')
  47152. };
  47153. }
  47154. lineDrawProto.remove = function () {
  47155. this._clearIncremental();
  47156. this._incremental = null;
  47157. this.group.removeAll();
  47158. };
  47159. lineDrawProto._clearIncremental = function () {
  47160. var incremental = this._incremental;
  47161. if (incremental) {
  47162. incremental.clearDisplaybles();
  47163. }
  47164. };
  47165. function isPointNaN(pt) {
  47166. return isNaN(pt[0]) || isNaN(pt[1]);
  47167. }
  47168. function lineNeedsDraw(pts) {
  47169. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  47170. }
  47171. /*
  47172. * Licensed to the Apache Software Foundation (ASF) under one
  47173. * or more contributor license agreements. See the NOTICE file
  47174. * distributed with this work for additional information
  47175. * regarding copyright ownership. The ASF licenses this file
  47176. * to you under the Apache License, Version 2.0 (the
  47177. * "License"); you may not use this file except in compliance
  47178. * with the License. You may obtain a copy of the License at
  47179. *
  47180. * http://www.apache.org/licenses/LICENSE-2.0
  47181. *
  47182. * Unless required by applicable law or agreed to in writing,
  47183. * software distributed under the License is distributed on an
  47184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47185. * KIND, either express or implied. See the License for the
  47186. * specific language governing permissions and limitations
  47187. * under the License.
  47188. */
  47189. var v1 = [];
  47190. var v2 = [];
  47191. var v3 = [];
  47192. var quadraticAt$1 = quadraticAt;
  47193. var v2DistSquare = distSquare;
  47194. var mathAbs$1 = Math.abs;
  47195. function intersectCurveCircle(curvePoints, center, radius) {
  47196. var p0 = curvePoints[0];
  47197. var p1 = curvePoints[1];
  47198. var p2 = curvePoints[2];
  47199. var d = Infinity;
  47200. var t;
  47201. var radiusSquare = radius * radius;
  47202. var interval = 0.1;
  47203. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  47204. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  47205. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  47206. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  47207. if (diff < d) {
  47208. d = diff;
  47209. t = _t;
  47210. }
  47211. }
  47212. // Assume the segment is monotone,Find root through Bisection method
  47213. // At most 32 iteration
  47214. for (var i = 0; i < 32; i++) {
  47215. // var prev = t - interval;
  47216. var next = t + interval;
  47217. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  47218. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  47219. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  47220. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  47221. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  47222. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  47223. var diff = v2DistSquare(v2, center) - radiusSquare;
  47224. if (mathAbs$1(diff) < 1e-2) {
  47225. break;
  47226. }
  47227. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  47228. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  47229. interval /= 2;
  47230. if (diff < 0) {
  47231. if (nextDiff >= 0) {
  47232. t = t + interval;
  47233. }
  47234. else {
  47235. t = t - interval;
  47236. }
  47237. }
  47238. else {
  47239. if (nextDiff >= 0) {
  47240. t = t - interval;
  47241. }
  47242. else {
  47243. t = t + interval;
  47244. }
  47245. }
  47246. }
  47247. return t;
  47248. }
  47249. // Adjust edge to avoid
  47250. var adjustEdge = function (graph, scale$$1) {
  47251. var tmp0 = [];
  47252. var quadraticSubdivide$$1 = quadraticSubdivide;
  47253. var pts = [[], [], []];
  47254. var pts2 = [[], []];
  47255. var v = [];
  47256. scale$$1 /= 2;
  47257. function getSymbolSize(node) {
  47258. var symbolSize = node.getVisual('symbolSize');
  47259. if (symbolSize instanceof Array) {
  47260. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  47261. }
  47262. return symbolSize;
  47263. }
  47264. graph.eachEdge(function (edge, idx) {
  47265. var linePoints = edge.getLayout();
  47266. var fromSymbol = edge.getVisual('fromSymbol');
  47267. var toSymbol = edge.getVisual('toSymbol');
  47268. if (!linePoints.__original) {
  47269. linePoints.__original = [
  47270. clone$1(linePoints[0]),
  47271. clone$1(linePoints[1])
  47272. ];
  47273. if (linePoints[2]) {
  47274. linePoints.__original.push(clone$1(linePoints[2]));
  47275. }
  47276. }
  47277. var originalPoints = linePoints.__original;
  47278. // Quadratic curve
  47279. if (linePoints[2] != null) {
  47280. copy(pts[0], originalPoints[0]);
  47281. copy(pts[1], originalPoints[2]);
  47282. copy(pts[2], originalPoints[1]);
  47283. if (fromSymbol && fromSymbol !== 'none') {
  47284. var symbolSize = getSymbolSize(edge.node1);
  47285. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  47286. // Subdivide and get the second
  47287. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  47288. pts[0][0] = tmp0[3];
  47289. pts[1][0] = tmp0[4];
  47290. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  47291. pts[0][1] = tmp0[3];
  47292. pts[1][1] = tmp0[4];
  47293. }
  47294. if (toSymbol && toSymbol !== 'none') {
  47295. var symbolSize = getSymbolSize(edge.node2);
  47296. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  47297. // Subdivide and get the first
  47298. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  47299. pts[1][0] = tmp0[1];
  47300. pts[2][0] = tmp0[2];
  47301. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  47302. pts[1][1] = tmp0[1];
  47303. pts[2][1] = tmp0[2];
  47304. }
  47305. // Copy back to layout
  47306. copy(linePoints[0], pts[0]);
  47307. copy(linePoints[1], pts[2]);
  47308. copy(linePoints[2], pts[1]);
  47309. }
  47310. // Line
  47311. else {
  47312. copy(pts2[0], originalPoints[0]);
  47313. copy(pts2[1], originalPoints[1]);
  47314. sub(v, pts2[1], pts2[0]);
  47315. normalize(v, v);
  47316. if (fromSymbol && fromSymbol !== 'none') {
  47317. var symbolSize = getSymbolSize(edge.node1);
  47318. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  47319. }
  47320. if (toSymbol && toSymbol !== 'none') {
  47321. var symbolSize = getSymbolSize(edge.node2);
  47322. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  47323. }
  47324. copy(linePoints[0], pts2[0]);
  47325. copy(linePoints[1], pts2[1]);
  47326. }
  47327. });
  47328. };
  47329. /*
  47330. * Licensed to the Apache Software Foundation (ASF) under one
  47331. * or more contributor license agreements. See the NOTICE file
  47332. * distributed with this work for additional information
  47333. * regarding copyright ownership. The ASF licenses this file
  47334. * to you under the Apache License, Version 2.0 (the
  47335. * "License"); you may not use this file except in compliance
  47336. * with the License. You may obtain a copy of the License at
  47337. *
  47338. * http://www.apache.org/licenses/LICENSE-2.0
  47339. *
  47340. * Unless required by applicable law or agreed to in writing,
  47341. * software distributed under the License is distributed on an
  47342. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47343. * KIND, either express or implied. See the License for the
  47344. * specific language governing permissions and limitations
  47345. * under the License.
  47346. */
  47347. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  47348. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  47349. var nodeOpacityPath = ['itemStyle', 'opacity'];
  47350. var lineOpacityPath = ['lineStyle', 'opacity'];
  47351. function getItemOpacity(item, opacityPath) {
  47352. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  47353. }
  47354. function fadeOutItem(item, opacityPath, opacityRatio) {
  47355. var el = item.getGraphicEl();
  47356. var opacity = getItemOpacity(item, opacityPath);
  47357. if (opacityRatio != null) {
  47358. opacity == null && (opacity = 1);
  47359. opacity *= opacityRatio;
  47360. }
  47361. el.downplay && el.downplay();
  47362. el.traverse(function (child) {
  47363. if (child.type !== 'group') {
  47364. var opct = child.lineLabelOriginalOpacity;
  47365. if (opct == null || opacityRatio != null) {
  47366. opct = opacity;
  47367. }
  47368. child.setStyle('opacity', opct);
  47369. }
  47370. });
  47371. }
  47372. function fadeInItem(item, opacityPath) {
  47373. var opacity = getItemOpacity(item, opacityPath);
  47374. var el = item.getGraphicEl();
  47375. el.highlight && el.highlight();
  47376. el.traverse(function (child) {
  47377. if (child.type !== 'group') {
  47378. child.setStyle('opacity', opacity);
  47379. }
  47380. });
  47381. }
  47382. extendChartView({
  47383. type: 'graph',
  47384. init: function (ecModel, api) {
  47385. var symbolDraw = new SymbolDraw();
  47386. var lineDraw = new LineDraw();
  47387. var group = this.group;
  47388. this._controller = new RoamController(api.getZr());
  47389. this._controllerHost = {target: group};
  47390. group.add(symbolDraw.group);
  47391. group.add(lineDraw.group);
  47392. this._symbolDraw = symbolDraw;
  47393. this._lineDraw = lineDraw;
  47394. this._firstRender = true;
  47395. },
  47396. render: function (seriesModel, ecModel, api) {
  47397. var coordSys = seriesModel.coordinateSystem;
  47398. this._model = seriesModel;
  47399. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  47400. var symbolDraw = this._symbolDraw;
  47401. var lineDraw = this._lineDraw;
  47402. var group = this.group;
  47403. if (coordSys.type === 'view') {
  47404. var groupNewProp = {
  47405. position: coordSys.position,
  47406. scale: coordSys.scale
  47407. };
  47408. if (this._firstRender) {
  47409. group.attr(groupNewProp);
  47410. }
  47411. else {
  47412. updateProps(group, groupNewProp, seriesModel);
  47413. }
  47414. }
  47415. // Fix edge contact point with node
  47416. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47417. var data = seriesModel.getData();
  47418. symbolDraw.updateData(data);
  47419. var edgeData = seriesModel.getEdgeData();
  47420. lineDraw.updateData(edgeData);
  47421. this._updateNodeAndLinkScale();
  47422. this._updateController(seriesModel, ecModel, api);
  47423. clearTimeout(this._layoutTimeout);
  47424. var forceLayout = seriesModel.forceLayout;
  47425. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  47426. if (forceLayout) {
  47427. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  47428. }
  47429. data.eachItemGraphicEl(function (el, idx) {
  47430. var itemModel = data.getItemModel(idx);
  47431. // Update draggable
  47432. el.off('drag').off('dragend');
  47433. var draggable = itemModel.get('draggable');
  47434. if (draggable) {
  47435. el.on('drag', function () {
  47436. if (forceLayout) {
  47437. forceLayout.warmUp();
  47438. !this._layouting
  47439. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  47440. forceLayout.setFixed(idx);
  47441. // Write position back to layout
  47442. data.setItemLayout(idx, el.position);
  47443. }
  47444. }, this).on('dragend', function () {
  47445. if (forceLayout) {
  47446. forceLayout.setUnfixed(idx);
  47447. }
  47448. }, this);
  47449. }
  47450. el.setDraggable(draggable && forceLayout);
  47451. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  47452. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  47453. if (itemModel.get('focusNodeAdjacency')) {
  47454. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  47455. api.dispatchAction({
  47456. type: 'focusNodeAdjacency',
  47457. seriesId: seriesModel.id,
  47458. dataIndex: el.dataIndex
  47459. });
  47460. });
  47461. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  47462. api.dispatchAction({
  47463. type: 'unfocusNodeAdjacency',
  47464. seriesId: seriesModel.id
  47465. });
  47466. });
  47467. }
  47468. }, this);
  47469. data.graph.eachEdge(function (edge) {
  47470. var el = edge.getGraphicEl();
  47471. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  47472. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  47473. if (edge.getModel().get('focusNodeAdjacency')) {
  47474. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  47475. api.dispatchAction({
  47476. type: 'focusNodeAdjacency',
  47477. seriesId: seriesModel.id,
  47478. edgeDataIndex: edge.dataIndex
  47479. });
  47480. });
  47481. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  47482. api.dispatchAction({
  47483. type: 'unfocusNodeAdjacency',
  47484. seriesId: seriesModel.id
  47485. });
  47486. });
  47487. }
  47488. });
  47489. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  47490. && seriesModel.get('circular.rotateLabel');
  47491. var cx = data.getLayout('cx');
  47492. var cy = data.getLayout('cy');
  47493. data.eachItemGraphicEl(function (el, idx) {
  47494. var symbolPath = el.getSymbolPath();
  47495. if (circularRotateLabel) {
  47496. var pos = data.getItemLayout(idx);
  47497. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  47498. if (rad < 0) {
  47499. rad = Math.PI * 2 + rad;
  47500. }
  47501. var isLeft = pos[0] < cx;
  47502. if (isLeft) {
  47503. rad = rad - Math.PI;
  47504. }
  47505. var textPosition = isLeft ? 'left' : 'right';
  47506. symbolPath.setStyle({
  47507. textRotation: -rad,
  47508. textPosition: textPosition,
  47509. textOrigin: 'center'
  47510. });
  47511. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  47512. }
  47513. else {
  47514. symbolPath.setStyle({
  47515. textRotation: 0
  47516. });
  47517. }
  47518. });
  47519. this._firstRender = false;
  47520. },
  47521. dispose: function () {
  47522. this._controller && this._controller.dispose();
  47523. this._controllerHost = {};
  47524. },
  47525. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47526. var data = this._model.getData();
  47527. var graph = data.graph;
  47528. var dataIndex = payload.dataIndex;
  47529. var edgeDataIndex = payload.edgeDataIndex;
  47530. var node = graph.getNodeByIndex(dataIndex);
  47531. var edge = graph.getEdgeByIndex(edgeDataIndex);
  47532. if (!node && !edge) {
  47533. return;
  47534. }
  47535. graph.eachNode(function (node) {
  47536. fadeOutItem(node, nodeOpacityPath, 0.1);
  47537. });
  47538. graph.eachEdge(function (edge) {
  47539. fadeOutItem(edge, lineOpacityPath, 0.1);
  47540. });
  47541. if (node) {
  47542. fadeInItem(node, nodeOpacityPath);
  47543. each$1(node.edges, function (adjacentEdge) {
  47544. if (adjacentEdge.dataIndex < 0) {
  47545. return;
  47546. }
  47547. fadeInItem(adjacentEdge, lineOpacityPath);
  47548. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  47549. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  47550. });
  47551. }
  47552. if (edge) {
  47553. fadeInItem(edge, lineOpacityPath);
  47554. fadeInItem(edge.node1, nodeOpacityPath);
  47555. fadeInItem(edge.node2, nodeOpacityPath);
  47556. }
  47557. },
  47558. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47559. var graph = this._model.getData().graph;
  47560. graph.eachNode(function (node) {
  47561. fadeOutItem(node, nodeOpacityPath);
  47562. });
  47563. graph.eachEdge(function (edge) {
  47564. fadeOutItem(edge, lineOpacityPath);
  47565. });
  47566. },
  47567. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  47568. var self = this;
  47569. (function step() {
  47570. forceLayout.step(function (stopped) {
  47571. self.updateLayout(self._model);
  47572. (self._layouting = !stopped) && (
  47573. layoutAnimation
  47574. ? (self._layoutTimeout = setTimeout(step, 16))
  47575. : step()
  47576. );
  47577. });
  47578. })();
  47579. },
  47580. _updateController: function (seriesModel, ecModel, api) {
  47581. var controller = this._controller;
  47582. var controllerHost = this._controllerHost;
  47583. var group = this.group;
  47584. controller.setPointerChecker(function (e, x, y) {
  47585. var rect = group.getBoundingRect();
  47586. rect.applyTransform(group.transform);
  47587. return rect.contain(x, y)
  47588. && !onIrrelevantElement(e, api, seriesModel);
  47589. });
  47590. if (seriesModel.coordinateSystem.type !== 'view') {
  47591. controller.disable();
  47592. return;
  47593. }
  47594. controller.enable(seriesModel.get('roam'));
  47595. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  47596. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  47597. controller
  47598. .off('pan')
  47599. .off('zoom')
  47600. .on('pan', function (e) {
  47601. updateViewOnPan(controllerHost, e.dx, e.dy);
  47602. api.dispatchAction({
  47603. seriesId: seriesModel.id,
  47604. type: 'graphRoam',
  47605. dx: e.dx,
  47606. dy: e.dy
  47607. });
  47608. })
  47609. .on('zoom', function (e) {
  47610. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  47611. api.dispatchAction({
  47612. seriesId: seriesModel.id,
  47613. type: 'graphRoam',
  47614. zoom: e.scale,
  47615. originX: e.originX,
  47616. originY: e.originY
  47617. });
  47618. this._updateNodeAndLinkScale();
  47619. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47620. this._lineDraw.updateLayout();
  47621. }, this);
  47622. },
  47623. _updateNodeAndLinkScale: function () {
  47624. var seriesModel = this._model;
  47625. var data = seriesModel.getData();
  47626. var nodeScale = this._getNodeGlobalScale(seriesModel);
  47627. var invScale = [nodeScale, nodeScale];
  47628. data.eachItemGraphicEl(function (el, idx) {
  47629. el.attr('scale', invScale);
  47630. });
  47631. },
  47632. _getNodeGlobalScale: function (seriesModel) {
  47633. var coordSys = seriesModel.coordinateSystem;
  47634. if (coordSys.type !== 'view') {
  47635. return 1;
  47636. }
  47637. var nodeScaleRatio = this._nodeScaleRatio;
  47638. var groupScale = coordSys.scale;
  47639. var groupZoom = (groupScale && groupScale[0]) || 1;
  47640. // Scale node when zoom changes
  47641. var roamZoom = coordSys.getZoom();
  47642. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  47643. return nodeScale / groupZoom;
  47644. },
  47645. updateLayout: function (seriesModel) {
  47646. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47647. this._symbolDraw.updateLayout();
  47648. this._lineDraw.updateLayout();
  47649. },
  47650. remove: function (ecModel, api) {
  47651. this._symbolDraw && this._symbolDraw.remove();
  47652. this._lineDraw && this._lineDraw.remove();
  47653. }
  47654. });
  47655. /*
  47656. * Licensed to the Apache Software Foundation (ASF) under one
  47657. * or more contributor license agreements. See the NOTICE file
  47658. * distributed with this work for additional information
  47659. * regarding copyright ownership. The ASF licenses this file
  47660. * to you under the Apache License, Version 2.0 (the
  47661. * "License"); you may not use this file except in compliance
  47662. * with the License. You may obtain a copy of the License at
  47663. *
  47664. * http://www.apache.org/licenses/LICENSE-2.0
  47665. *
  47666. * Unless required by applicable law or agreed to in writing,
  47667. * software distributed under the License is distributed on an
  47668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47669. * KIND, either express or implied. See the License for the
  47670. * specific language governing permissions and limitations
  47671. * under the License.
  47672. */
  47673. /**
  47674. * @payload
  47675. * @property {number} [seriesIndex]
  47676. * @property {string} [seriesId]
  47677. * @property {string} [seriesName]
  47678. * @property {number} [dataIndex]
  47679. */
  47680. registerAction({
  47681. type: 'focusNodeAdjacency',
  47682. event: 'focusNodeAdjacency',
  47683. update: 'series:focusNodeAdjacency'
  47684. }, function () {});
  47685. /**
  47686. * @payload
  47687. * @property {number} [seriesIndex]
  47688. * @property {string} [seriesId]
  47689. * @property {string} [seriesName]
  47690. */
  47691. registerAction({
  47692. type: 'unfocusNodeAdjacency',
  47693. event: 'unfocusNodeAdjacency',
  47694. update: 'series:unfocusNodeAdjacency'
  47695. }, function () {});
  47696. /*
  47697. * Licensed to the Apache Software Foundation (ASF) under one
  47698. * or more contributor license agreements. See the NOTICE file
  47699. * distributed with this work for additional information
  47700. * regarding copyright ownership. The ASF licenses this file
  47701. * to you under the Apache License, Version 2.0 (the
  47702. * "License"); you may not use this file except in compliance
  47703. * with the License. You may obtain a copy of the License at
  47704. *
  47705. * http://www.apache.org/licenses/LICENSE-2.0
  47706. *
  47707. * Unless required by applicable law or agreed to in writing,
  47708. * software distributed under the License is distributed on an
  47709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47710. * KIND, either express or implied. See the License for the
  47711. * specific language governing permissions and limitations
  47712. * under the License.
  47713. */
  47714. var actionInfo = {
  47715. type: 'graphRoam',
  47716. event: 'graphRoam',
  47717. update: 'none'
  47718. };
  47719. /**
  47720. * @payload
  47721. * @property {string} name Series name
  47722. * @property {number} [dx]
  47723. * @property {number} [dy]
  47724. * @property {number} [zoom]
  47725. * @property {number} [originX]
  47726. * @property {number} [originY]
  47727. */
  47728. registerAction(actionInfo, function (payload, ecModel) {
  47729. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  47730. var coordSys = seriesModel.coordinateSystem;
  47731. var res = updateCenterAndZoom(coordSys, payload);
  47732. seriesModel.setCenter
  47733. && seriesModel.setCenter(res.center);
  47734. seriesModel.setZoom
  47735. && seriesModel.setZoom(res.zoom);
  47736. });
  47737. });
  47738. /*
  47739. * Licensed to the Apache Software Foundation (ASF) under one
  47740. * or more contributor license agreements. See the NOTICE file
  47741. * distributed with this work for additional information
  47742. * regarding copyright ownership. The ASF licenses this file
  47743. * to you under the Apache License, Version 2.0 (the
  47744. * "License"); you may not use this file except in compliance
  47745. * with the License. You may obtain a copy of the License at
  47746. *
  47747. * http://www.apache.org/licenses/LICENSE-2.0
  47748. *
  47749. * Unless required by applicable law or agreed to in writing,
  47750. * software distributed under the License is distributed on an
  47751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47752. * KIND, either express or implied. See the License for the
  47753. * specific language governing permissions and limitations
  47754. * under the License.
  47755. */
  47756. var categoryFilter = function (ecModel) {
  47757. var legendModels = ecModel.findComponents({
  47758. mainType: 'legend'
  47759. });
  47760. if (!legendModels || !legendModels.length) {
  47761. return;
  47762. }
  47763. ecModel.eachSeriesByType('graph', function (graphSeries) {
  47764. var categoriesData = graphSeries.getCategoriesData();
  47765. var graph = graphSeries.getGraph();
  47766. var data = graph.data;
  47767. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  47768. data.filterSelf(function (idx) {
  47769. var model = data.getItemModel(idx);
  47770. var category = model.getShallow('category');
  47771. if (category != null) {
  47772. if (typeof category === 'number') {
  47773. category = categoryNames[category];
  47774. }
  47775. // If in any legend component the status is not selected.
  47776. for (var i = 0; i < legendModels.length; i++) {
  47777. if (!legendModels[i].isSelected(category)) {
  47778. return false;
  47779. }
  47780. }
  47781. }
  47782. return true;
  47783. });
  47784. }, this);
  47785. };
  47786. /*
  47787. * Licensed to the Apache Software Foundation (ASF) under one
  47788. * or more contributor license agreements. See the NOTICE file
  47789. * distributed with this work for additional information
  47790. * regarding copyright ownership. The ASF licenses this file
  47791. * to you under the Apache License, Version 2.0 (the
  47792. * "License"); you may not use this file except in compliance
  47793. * with the License. You may obtain a copy of the License at
  47794. *
  47795. * http://www.apache.org/licenses/LICENSE-2.0
  47796. *
  47797. * Unless required by applicable law or agreed to in writing,
  47798. * software distributed under the License is distributed on an
  47799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47800. * KIND, either express or implied. See the License for the
  47801. * specific language governing permissions and limitations
  47802. * under the License.
  47803. */
  47804. var categoryVisual = function (ecModel) {
  47805. var paletteScope = {};
  47806. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47807. var categoriesData = seriesModel.getCategoriesData();
  47808. var data = seriesModel.getData();
  47809. var categoryNameIdxMap = {};
  47810. categoriesData.each(function (idx) {
  47811. var name = categoriesData.getName(idx);
  47812. // Add prefix to avoid conflict with Object.prototype.
  47813. categoryNameIdxMap['ec-' + name] = idx;
  47814. var itemModel = categoriesData.getItemModel(idx);
  47815. var color = itemModel.get('itemStyle.color')
  47816. || seriesModel.getColorFromPalette(name, paletteScope);
  47817. categoriesData.setItemVisual(idx, 'color', color);
  47818. });
  47819. // Assign category color to visual
  47820. if (categoriesData.count()) {
  47821. data.each(function (idx) {
  47822. var model = data.getItemModel(idx);
  47823. var category = model.getShallow('category');
  47824. if (category != null) {
  47825. if (typeof category === 'string') {
  47826. category = categoryNameIdxMap['ec-' + category];
  47827. }
  47828. if (!data.getItemVisual(idx, 'color', true)) {
  47829. data.setItemVisual(
  47830. idx, 'color',
  47831. categoriesData.getItemVisual(category, 'color')
  47832. );
  47833. }
  47834. }
  47835. });
  47836. }
  47837. });
  47838. };
  47839. /*
  47840. * Licensed to the Apache Software Foundation (ASF) under one
  47841. * or more contributor license agreements. See the NOTICE file
  47842. * distributed with this work for additional information
  47843. * regarding copyright ownership. The ASF licenses this file
  47844. * to you under the Apache License, Version 2.0 (the
  47845. * "License"); you may not use this file except in compliance
  47846. * with the License. You may obtain a copy of the License at
  47847. *
  47848. * http://www.apache.org/licenses/LICENSE-2.0
  47849. *
  47850. * Unless required by applicable law or agreed to in writing,
  47851. * software distributed under the License is distributed on an
  47852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47853. * KIND, either express or implied. See the License for the
  47854. * specific language governing permissions and limitations
  47855. * under the License.
  47856. */
  47857. function normalize$1(a) {
  47858. if (!(a instanceof Array)) {
  47859. a = [a, a];
  47860. }
  47861. return a;
  47862. }
  47863. var edgeVisual = function (ecModel) {
  47864. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47865. var graph = seriesModel.getGraph();
  47866. var edgeData = seriesModel.getEdgeData();
  47867. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  47868. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  47869. var colorQuery = 'lineStyle.color'.split('.');
  47870. var opacityQuery = 'lineStyle.opacity'.split('.');
  47871. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  47872. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  47873. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  47874. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  47875. edgeData.setVisual('color', seriesModel.get(colorQuery));
  47876. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  47877. edgeData.each(function (idx) {
  47878. var itemModel = edgeData.getItemModel(idx);
  47879. var edge = graph.getEdgeByIndex(idx);
  47880. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  47881. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  47882. // Edge visual must after node visual
  47883. var color = itemModel.get(colorQuery);
  47884. var opacity = itemModel.get(opacityQuery);
  47885. switch (color) {
  47886. case 'source':
  47887. color = edge.node1.getVisual('color');
  47888. break;
  47889. case 'target':
  47890. color = edge.node2.getVisual('color');
  47891. break;
  47892. }
  47893. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  47894. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  47895. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  47896. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  47897. edge.setVisual('color', color);
  47898. edge.setVisual('opacity', opacity);
  47899. });
  47900. });
  47901. };
  47902. /*
  47903. * Licensed to the Apache Software Foundation (ASF) under one
  47904. * or more contributor license agreements. See the NOTICE file
  47905. * distributed with this work for additional information
  47906. * regarding copyright ownership. The ASF licenses this file
  47907. * to you under the Apache License, Version 2.0 (the
  47908. * "License"); you may not use this file except in compliance
  47909. * with the License. You may obtain a copy of the License at
  47910. *
  47911. * http://www.apache.org/licenses/LICENSE-2.0
  47912. *
  47913. * Unless required by applicable law or agreed to in writing,
  47914. * software distributed under the License is distributed on an
  47915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47916. * KIND, either express or implied. See the License for the
  47917. * specific language governing permissions and limitations
  47918. * under the License.
  47919. */
  47920. function simpleLayout$1(seriesModel) {
  47921. var coordSys = seriesModel.coordinateSystem;
  47922. if (coordSys && coordSys.type !== 'view') {
  47923. return;
  47924. }
  47925. var graph = seriesModel.getGraph();
  47926. graph.eachNode(function (node) {
  47927. var model = node.getModel();
  47928. node.setLayout([+model.get('x'), +model.get('y')]);
  47929. });
  47930. simpleLayoutEdge(graph);
  47931. }
  47932. function simpleLayoutEdge(graph) {
  47933. graph.eachEdge(function (edge) {
  47934. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  47935. var p1 = clone$1(edge.node1.getLayout());
  47936. var p2 = clone$1(edge.node2.getLayout());
  47937. var points = [p1, p2];
  47938. if (+curveness) {
  47939. points.push([
  47940. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  47941. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  47942. ]);
  47943. }
  47944. edge.setLayout(points);
  47945. });
  47946. }
  47947. /*
  47948. * Licensed to the Apache Software Foundation (ASF) under one
  47949. * or more contributor license agreements. See the NOTICE file
  47950. * distributed with this work for additional information
  47951. * regarding copyright ownership. The ASF licenses this file
  47952. * to you under the Apache License, Version 2.0 (the
  47953. * "License"); you may not use this file except in compliance
  47954. * with the License. You may obtain a copy of the License at
  47955. *
  47956. * http://www.apache.org/licenses/LICENSE-2.0
  47957. *
  47958. * Unless required by applicable law or agreed to in writing,
  47959. * software distributed under the License is distributed on an
  47960. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47961. * KIND, either express or implied. See the License for the
  47962. * specific language governing permissions and limitations
  47963. * under the License.
  47964. */
  47965. var simpleLayout = function (ecModel, api) {
  47966. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47967. var layout = seriesModel.get('layout');
  47968. var coordSys = seriesModel.coordinateSystem;
  47969. if (coordSys && coordSys.type !== 'view') {
  47970. var data = seriesModel.getData();
  47971. var dimensions = [];
  47972. each$1(coordSys.dimensions, function (coordDim) {
  47973. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  47974. });
  47975. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  47976. var value = [];
  47977. var hasValue = false;
  47978. for (var i = 0; i < dimensions.length; i++) {
  47979. var val = data.get(dimensions[i], dataIndex);
  47980. if (!isNaN(val)) {
  47981. hasValue = true;
  47982. }
  47983. value.push(val);
  47984. }
  47985. if (hasValue) {
  47986. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  47987. }
  47988. else {
  47989. // Also {Array.<number>}, not undefined to avoid if...else... statement
  47990. data.setItemLayout(dataIndex, [NaN, NaN]);
  47991. }
  47992. }
  47993. simpleLayoutEdge(data.graph);
  47994. }
  47995. else if (!layout || layout === 'none') {
  47996. simpleLayout$1(seriesModel);
  47997. }
  47998. });
  47999. };
  48000. /*
  48001. * Licensed to the Apache Software Foundation (ASF) under one
  48002. * or more contributor license agreements. See the NOTICE file
  48003. * distributed with this work for additional information
  48004. * regarding copyright ownership. The ASF licenses this file
  48005. * to you under the Apache License, Version 2.0 (the
  48006. * "License"); you may not use this file except in compliance
  48007. * with the License. You may obtain a copy of the License at
  48008. *
  48009. * http://www.apache.org/licenses/LICENSE-2.0
  48010. *
  48011. * Unless required by applicable law or agreed to in writing,
  48012. * software distributed under the License is distributed on an
  48013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48014. * KIND, either express or implied. See the License for the
  48015. * specific language governing permissions and limitations
  48016. * under the License.
  48017. */
  48018. function circularLayout$1(seriesModel) {
  48019. var coordSys = seriesModel.coordinateSystem;
  48020. if (coordSys && coordSys.type !== 'view') {
  48021. return;
  48022. }
  48023. var rect = coordSys.getBoundingRect();
  48024. var nodeData = seriesModel.getData();
  48025. var graph = nodeData.graph;
  48026. var angle = 0;
  48027. var sum = nodeData.getSum('value');
  48028. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  48029. var cx = rect.width / 2 + rect.x;
  48030. var cy = rect.height / 2 + rect.y;
  48031. var r = Math.min(rect.width, rect.height) / 2;
  48032. graph.eachNode(function (node) {
  48033. var value = node.getValue('value');
  48034. angle += unitAngle * (sum ? value : 1) / 2;
  48035. node.setLayout([
  48036. r * Math.cos(angle) + cx,
  48037. r * Math.sin(angle) + cy
  48038. ]);
  48039. angle += unitAngle * (sum ? value : 1) / 2;
  48040. });
  48041. nodeData.setLayout({
  48042. cx: cx,
  48043. cy: cy
  48044. });
  48045. graph.eachEdge(function (edge) {
  48046. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  48047. var p1 = clone$1(edge.node1.getLayout());
  48048. var p2 = clone$1(edge.node2.getLayout());
  48049. var cp1;
  48050. var x12 = (p1[0] + p2[0]) / 2;
  48051. var y12 = (p1[1] + p2[1]) / 2;
  48052. if (+curveness) {
  48053. curveness *= 3;
  48054. cp1 = [
  48055. cx * curveness + x12 * (1 - curveness),
  48056. cy * curveness + y12 * (1 - curveness)
  48057. ];
  48058. }
  48059. edge.setLayout([p1, p2, cp1]);
  48060. });
  48061. }
  48062. /*
  48063. * Licensed to the Apache Software Foundation (ASF) under one
  48064. * or more contributor license agreements. See the NOTICE file
  48065. * distributed with this work for additional information
  48066. * regarding copyright ownership. The ASF licenses this file
  48067. * to you under the Apache License, Version 2.0 (the
  48068. * "License"); you may not use this file except in compliance
  48069. * with the License. You may obtain a copy of the License at
  48070. *
  48071. * http://www.apache.org/licenses/LICENSE-2.0
  48072. *
  48073. * Unless required by applicable law or agreed to in writing,
  48074. * software distributed under the License is distributed on an
  48075. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48076. * KIND, either express or implied. See the License for the
  48077. * specific language governing permissions and limitations
  48078. * under the License.
  48079. */
  48080. var circularLayout = function (ecModel) {
  48081. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48082. if (seriesModel.get('layout') === 'circular') {
  48083. circularLayout$1(seriesModel);
  48084. }
  48085. });
  48086. };
  48087. /*
  48088. * Licensed to the Apache Software Foundation (ASF) under one
  48089. * or more contributor license agreements. See the NOTICE file
  48090. * distributed with this work for additional information
  48091. * regarding copyright ownership. The ASF licenses this file
  48092. * to you under the Apache License, Version 2.0 (the
  48093. * "License"); you may not use this file except in compliance
  48094. * with the License. You may obtain a copy of the License at
  48095. *
  48096. * http://www.apache.org/licenses/LICENSE-2.0
  48097. *
  48098. * Unless required by applicable law or agreed to in writing,
  48099. * software distributed under the License is distributed on an
  48100. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48101. * KIND, either express or implied. See the License for the
  48102. * specific language governing permissions and limitations
  48103. * under the License.
  48104. */
  48105. /*
  48106. * The layout implementation references to d3.js. The use of
  48107. * the source code of this file is also subject to the terms
  48108. * and consitions of its license (BSD-3Clause, see
  48109. * <echarts/src/licenses/LICENSE-d3>).
  48110. */
  48111. var scaleAndAdd$2 = scaleAndAdd;
  48112. // function adjacentNode(n, e) {
  48113. // return e.n1 === n ? e.n2 : e.n1;
  48114. // }
  48115. function forceLayout$1(nodes, edges, opts) {
  48116. var rect = opts.rect;
  48117. var width = rect.width;
  48118. var height = rect.height;
  48119. var center = [rect.x + width / 2, rect.y + height / 2];
  48120. // var scale = opts.scale || 1;
  48121. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  48122. // for (var i = 0; i < edges.length; i++) {
  48123. // var e = edges[i];
  48124. // var n1 = e.n1;
  48125. // var n2 = e.n2;
  48126. // n1.edges = n1.edges || [];
  48127. // n2.edges = n2.edges || [];
  48128. // n1.edges.push(e);
  48129. // n2.edges.push(e);
  48130. // }
  48131. // Init position
  48132. for (var i = 0; i < nodes.length; i++) {
  48133. var n = nodes[i];
  48134. if (!n.p) {
  48135. // Use the position from first adjecent node with defined position
  48136. // Or use a random position
  48137. // From d3
  48138. // if (n.edges) {
  48139. // var j = -1;
  48140. // while (++j < n.edges.length) {
  48141. // var e = n.edges[j];
  48142. // var other = adjacentNode(n, e);
  48143. // if (other.p) {
  48144. // n.p = vec2.clone(other.p);
  48145. // break;
  48146. // }
  48147. // }
  48148. // }
  48149. // if (!n.p) {
  48150. n.p = create(
  48151. width * (Math.random() - 0.5) + center[0],
  48152. height * (Math.random() - 0.5) + center[1]
  48153. );
  48154. // }
  48155. }
  48156. n.pp = clone$1(n.p);
  48157. n.edges = null;
  48158. }
  48159. // Formula in 'Graph Drawing by Force-directed Placement'
  48160. // var k = scale * Math.sqrt(width * height / nodes.length);
  48161. // var k2 = k * k;
  48162. var friction = 0.6;
  48163. return {
  48164. warmUp: function () {
  48165. friction = 0.5;
  48166. },
  48167. setFixed: function (idx) {
  48168. nodes[idx].fixed = true;
  48169. },
  48170. setUnfixed: function (idx) {
  48171. nodes[idx].fixed = false;
  48172. },
  48173. step: function (cb) {
  48174. var v12 = [];
  48175. var nLen = nodes.length;
  48176. for (var i = 0; i < edges.length; i++) {
  48177. var e = edges[i];
  48178. var n1 = e.n1;
  48179. var n2 = e.n2;
  48180. sub(v12, n2.p, n1.p);
  48181. var d = len(v12) - e.d;
  48182. var w = n2.w / (n1.w + n2.w);
  48183. if (isNaN(w)) {
  48184. w = 0;
  48185. }
  48186. normalize(v12, v12);
  48187. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  48188. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  48189. }
  48190. // Gravity
  48191. for (var i = 0; i < nLen; i++) {
  48192. var n = nodes[i];
  48193. if (!n.fixed) {
  48194. sub(v12, center, n.p);
  48195. // var d = vec2.len(v12);
  48196. // vec2.scale(v12, v12, 1 / d);
  48197. // var gravityFactor = gravity;
  48198. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  48199. }
  48200. }
  48201. // Repulsive
  48202. // PENDING
  48203. for (var i = 0; i < nLen; i++) {
  48204. var n1 = nodes[i];
  48205. for (var j = i + 1; j < nLen; j++) {
  48206. var n2 = nodes[j];
  48207. sub(v12, n2.p, n1.p);
  48208. var d = len(v12);
  48209. if (d === 0) {
  48210. // Random repulse
  48211. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  48212. d = 1;
  48213. }
  48214. var repFact = (n1.rep + n2.rep) / d / d;
  48215. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  48216. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  48217. }
  48218. }
  48219. var v = [];
  48220. for (var i = 0; i < nLen; i++) {
  48221. var n = nodes[i];
  48222. if (!n.fixed) {
  48223. sub(v, n.p, n.pp);
  48224. scaleAndAdd$2(n.p, n.p, v, friction);
  48225. copy(n.pp, n.p);
  48226. }
  48227. }
  48228. friction = friction * 0.992;
  48229. cb && cb(nodes, edges, friction < 0.01);
  48230. }
  48231. };
  48232. }
  48233. /*
  48234. * Licensed to the Apache Software Foundation (ASF) under one
  48235. * or more contributor license agreements. See the NOTICE file
  48236. * distributed with this work for additional information
  48237. * regarding copyright ownership. The ASF licenses this file
  48238. * to you under the Apache License, Version 2.0 (the
  48239. * "License"); you may not use this file except in compliance
  48240. * with the License. You may obtain a copy of the License at
  48241. *
  48242. * http://www.apache.org/licenses/LICENSE-2.0
  48243. *
  48244. * Unless required by applicable law or agreed to in writing,
  48245. * software distributed under the License is distributed on an
  48246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48247. * KIND, either express or implied. See the License for the
  48248. * specific language governing permissions and limitations
  48249. * under the License.
  48250. */
  48251. var forceLayout = function (ecModel) {
  48252. ecModel.eachSeriesByType('graph', function (graphSeries) {
  48253. var coordSys = graphSeries.coordinateSystem;
  48254. if (coordSys && coordSys.type !== 'view') {
  48255. return;
  48256. }
  48257. if (graphSeries.get('layout') === 'force') {
  48258. var preservedPoints = graphSeries.preservedPoints || {};
  48259. var graph = graphSeries.getGraph();
  48260. var nodeData = graph.data;
  48261. var edgeData = graph.edgeData;
  48262. var forceModel = graphSeries.getModel('force');
  48263. var initLayout = forceModel.get('initLayout');
  48264. if (graphSeries.preservedPoints) {
  48265. nodeData.each(function (idx) {
  48266. var id = nodeData.getId(idx);
  48267. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  48268. });
  48269. }
  48270. else if (!initLayout || initLayout === 'none') {
  48271. simpleLayout$1(graphSeries);
  48272. }
  48273. else if (initLayout === 'circular') {
  48274. circularLayout$1(graphSeries);
  48275. }
  48276. var nodeDataExtent = nodeData.getDataExtent('value');
  48277. var edgeDataExtent = edgeData.getDataExtent('value');
  48278. // var edgeDataExtent = edgeData.getDataExtent('value');
  48279. var repulsion = forceModel.get('repulsion');
  48280. var edgeLength = forceModel.get('edgeLength');
  48281. if (!isArray(repulsion)) {
  48282. repulsion = [repulsion, repulsion];
  48283. }
  48284. if (!isArray(edgeLength)) {
  48285. edgeLength = [edgeLength, edgeLength];
  48286. }
  48287. // Larger value has smaller length
  48288. edgeLength = [edgeLength[1], edgeLength[0]];
  48289. var nodes = nodeData.mapArray('value', function (value, idx) {
  48290. var point = nodeData.getItemLayout(idx);
  48291. var rep = linearMap(value, nodeDataExtent, repulsion);
  48292. if (isNaN(rep)) {
  48293. rep = (repulsion[0] + repulsion[1]) / 2;
  48294. }
  48295. return {
  48296. w: rep,
  48297. rep: rep,
  48298. fixed: nodeData.getItemModel(idx).get('fixed'),
  48299. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  48300. };
  48301. });
  48302. var edges = edgeData.mapArray('value', function (value, idx) {
  48303. var edge = graph.getEdgeByIndex(idx);
  48304. var d = linearMap(value, edgeDataExtent, edgeLength);
  48305. if (isNaN(d)) {
  48306. d = (edgeLength[0] + edgeLength[1]) / 2;
  48307. }
  48308. return {
  48309. n1: nodes[edge.node1.dataIndex],
  48310. n2: nodes[edge.node2.dataIndex],
  48311. d: d,
  48312. curveness: edge.getModel().get('lineStyle.curveness') || 0
  48313. };
  48314. });
  48315. var coordSys = graphSeries.coordinateSystem;
  48316. var rect = coordSys.getBoundingRect();
  48317. var forceInstance = forceLayout$1(nodes, edges, {
  48318. rect: rect,
  48319. gravity: forceModel.get('gravity')
  48320. });
  48321. var oldStep = forceInstance.step;
  48322. forceInstance.step = function (cb) {
  48323. for (var i = 0, l = nodes.length; i < l; i++) {
  48324. if (nodes[i].fixed) {
  48325. // Write back to layout instance
  48326. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  48327. }
  48328. }
  48329. oldStep(function (nodes, edges, stopped) {
  48330. for (var i = 0, l = nodes.length; i < l; i++) {
  48331. if (!nodes[i].fixed) {
  48332. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  48333. }
  48334. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  48335. }
  48336. for (var i = 0, l = edges.length; i < l; i++) {
  48337. var e = edges[i];
  48338. var edge = graph.getEdgeByIndex(i);
  48339. var p1 = e.n1.p;
  48340. var p2 = e.n2.p;
  48341. var points = edge.getLayout();
  48342. points = points ? points.slice() : [];
  48343. points[0] = points[0] || [];
  48344. points[1] = points[1] || [];
  48345. copy(points[0], p1);
  48346. copy(points[1], p2);
  48347. if (+e.curveness) {
  48348. points[2] = [
  48349. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  48350. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  48351. ];
  48352. }
  48353. edge.setLayout(points);
  48354. }
  48355. // Update layout
  48356. cb && cb(stopped);
  48357. });
  48358. };
  48359. graphSeries.forceLayout = forceInstance;
  48360. graphSeries.preservedPoints = preservedPoints;
  48361. // Step to get the layout
  48362. forceInstance.step();
  48363. }
  48364. else {
  48365. // Remove prev injected forceLayout instance
  48366. graphSeries.forceLayout = null;
  48367. }
  48368. });
  48369. };
  48370. /*
  48371. * Licensed to the Apache Software Foundation (ASF) under one
  48372. * or more contributor license agreements. See the NOTICE file
  48373. * distributed with this work for additional information
  48374. * regarding copyright ownership. The ASF licenses this file
  48375. * to you under the Apache License, Version 2.0 (the
  48376. * "License"); you may not use this file except in compliance
  48377. * with the License. You may obtain a copy of the License at
  48378. *
  48379. * http://www.apache.org/licenses/LICENSE-2.0
  48380. *
  48381. * Unless required by applicable law or agreed to in writing,
  48382. * software distributed under the License is distributed on an
  48383. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48384. * KIND, either express or implied. See the License for the
  48385. * specific language governing permissions and limitations
  48386. * under the License.
  48387. */
  48388. // FIXME Where to create the simple view coordinate system
  48389. function getViewRect$1(seriesModel, api, aspect) {
  48390. var option = seriesModel.getBoxLayoutParams();
  48391. option.aspect = aspect;
  48392. return getLayoutRect(option, {
  48393. width: api.getWidth(),
  48394. height: api.getHeight()
  48395. });
  48396. }
  48397. var createView = function (ecModel, api) {
  48398. var viewList = [];
  48399. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48400. var coordSysType = seriesModel.get('coordinateSystem');
  48401. if (!coordSysType || coordSysType === 'view') {
  48402. var data = seriesModel.getData();
  48403. var positions = data.mapArray(function (idx) {
  48404. var itemModel = data.getItemModel(idx);
  48405. return [+itemModel.get('x'), +itemModel.get('y')];
  48406. });
  48407. var min = [];
  48408. var max = [];
  48409. fromPoints(positions, min, max);
  48410. // If width or height is 0
  48411. if (max[0] - min[0] === 0) {
  48412. max[0] += 1;
  48413. min[0] -= 1;
  48414. }
  48415. if (max[1] - min[1] === 0) {
  48416. max[1] += 1;
  48417. min[1] -= 1;
  48418. }
  48419. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  48420. // FIXME If get view rect after data processed?
  48421. var viewRect = getViewRect$1(seriesModel, api, aspect);
  48422. // Position may be NaN, use view rect instead
  48423. if (isNaN(aspect)) {
  48424. min = [viewRect.x, viewRect.y];
  48425. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  48426. }
  48427. var bbWidth = max[0] - min[0];
  48428. var bbHeight = max[1] - min[1];
  48429. var viewWidth = viewRect.width;
  48430. var viewHeight = viewRect.height;
  48431. var viewCoordSys = seriesModel.coordinateSystem = new View();
  48432. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  48433. viewCoordSys.setBoundingRect(
  48434. min[0], min[1], bbWidth, bbHeight
  48435. );
  48436. viewCoordSys.setViewRect(
  48437. viewRect.x, viewRect.y, viewWidth, viewHeight
  48438. );
  48439. // Update roam info
  48440. viewCoordSys.setCenter(seriesModel.get('center'));
  48441. viewCoordSys.setZoom(seriesModel.get('zoom'));
  48442. viewList.push(viewCoordSys);
  48443. }
  48444. });
  48445. return viewList;
  48446. };
  48447. /*
  48448. * Licensed to the Apache Software Foundation (ASF) under one
  48449. * or more contributor license agreements. See the NOTICE file
  48450. * distributed with this work for additional information
  48451. * regarding copyright ownership. The ASF licenses this file
  48452. * to you under the Apache License, Version 2.0 (the
  48453. * "License"); you may not use this file except in compliance
  48454. * with the License. You may obtain a copy of the License at
  48455. *
  48456. * http://www.apache.org/licenses/LICENSE-2.0
  48457. *
  48458. * Unless required by applicable law or agreed to in writing,
  48459. * software distributed under the License is distributed on an
  48460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48461. * KIND, either express or implied. See the License for the
  48462. * specific language governing permissions and limitations
  48463. * under the License.
  48464. */
  48465. registerProcessor(categoryFilter);
  48466. registerVisual(visualSymbol('graph', 'circle', null));
  48467. registerVisual(categoryVisual);
  48468. registerVisual(edgeVisual);
  48469. registerLayout(simpleLayout);
  48470. registerLayout(circularLayout);
  48471. registerLayout(forceLayout);
  48472. // Graph view coordinate system
  48473. registerCoordinateSystem('graphView', {
  48474. create: createView
  48475. });
  48476. /*
  48477. * Licensed to the Apache Software Foundation (ASF) under one
  48478. * or more contributor license agreements. See the NOTICE file
  48479. * distributed with this work for additional information
  48480. * regarding copyright ownership. The ASF licenses this file
  48481. * to you under the Apache License, Version 2.0 (the
  48482. * "License"); you may not use this file except in compliance
  48483. * with the License. You may obtain a copy of the License at
  48484. *
  48485. * http://www.apache.org/licenses/LICENSE-2.0
  48486. *
  48487. * Unless required by applicable law or agreed to in writing,
  48488. * software distributed under the License is distributed on an
  48489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48490. * KIND, either express or implied. See the License for the
  48491. * specific language governing permissions and limitations
  48492. * under the License.
  48493. */
  48494. var GaugeSeries = SeriesModel.extend({
  48495. type: 'series.gauge',
  48496. getInitialData: function (option, ecModel) {
  48497. var dataOpt = option.data || [];
  48498. if (!isArray(dataOpt)) {
  48499. dataOpt = [dataOpt];
  48500. }
  48501. option.data = dataOpt;
  48502. return createListSimply(this, ['value']);
  48503. },
  48504. defaultOption: {
  48505. zlevel: 0,
  48506. z: 2,
  48507. // 默认全局居中
  48508. center: ['50%', '50%'],
  48509. legendHoverLink: true,
  48510. radius: '75%',
  48511. startAngle: 225,
  48512. endAngle: -45,
  48513. clockwise: true,
  48514. // 最小值
  48515. min: 0,
  48516. // 最大值
  48517. max: 100,
  48518. // 分割段数,默认为10
  48519. splitNumber: 10,
  48520. // 坐标轴线
  48521. axisLine: {
  48522. // 默认显示,属性show控制显示与否
  48523. show: true,
  48524. lineStyle: { // 属性lineStyle控制线条样式
  48525. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  48526. width: 30
  48527. }
  48528. },
  48529. // 分隔线
  48530. splitLine: {
  48531. // 默认显示,属性show控制显示与否
  48532. show: true,
  48533. // 属性length控制线长
  48534. length: 30,
  48535. // 属性lineStyle(详见lineStyle)控制线条样式
  48536. lineStyle: {
  48537. color: '#eee',
  48538. width: 2,
  48539. type: 'solid'
  48540. }
  48541. },
  48542. // 坐标轴小标记
  48543. axisTick: {
  48544. // 属性show控制显示与否,默认不显示
  48545. show: true,
  48546. // 每份split细分多少段
  48547. splitNumber: 5,
  48548. // 属性length控制线长
  48549. length: 8,
  48550. // 属性lineStyle控制线条样式
  48551. lineStyle: {
  48552. color: '#eee',
  48553. width: 1,
  48554. type: 'solid'
  48555. }
  48556. },
  48557. axisLabel: {
  48558. show: true,
  48559. distance: 5,
  48560. // formatter: null,
  48561. color: 'auto'
  48562. },
  48563. pointer: {
  48564. show: true,
  48565. length: '80%',
  48566. width: 8
  48567. },
  48568. itemStyle: {
  48569. color: 'auto'
  48570. },
  48571. title: {
  48572. show: true,
  48573. // x, y,单位px
  48574. offsetCenter: [0, '-40%'],
  48575. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48576. color: '#333',
  48577. fontSize: 15
  48578. },
  48579. detail: {
  48580. show: true,
  48581. backgroundColor: 'rgba(0,0,0,0)',
  48582. borderWidth: 0,
  48583. borderColor: '#ccc',
  48584. width: 100,
  48585. height: null, // self-adaption
  48586. padding: [5, 10],
  48587. // x, y,单位px
  48588. offsetCenter: [0, '40%'],
  48589. // formatter: null,
  48590. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48591. color: 'auto',
  48592. fontSize: 30
  48593. }
  48594. }
  48595. });
  48596. /*
  48597. * Licensed to the Apache Software Foundation (ASF) under one
  48598. * or more contributor license agreements. See the NOTICE file
  48599. * distributed with this work for additional information
  48600. * regarding copyright ownership. The ASF licenses this file
  48601. * to you under the Apache License, Version 2.0 (the
  48602. * "License"); you may not use this file except in compliance
  48603. * with the License. You may obtain a copy of the License at
  48604. *
  48605. * http://www.apache.org/licenses/LICENSE-2.0
  48606. *
  48607. * Unless required by applicable law or agreed to in writing,
  48608. * software distributed under the License is distributed on an
  48609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48610. * KIND, either express or implied. See the License for the
  48611. * specific language governing permissions and limitations
  48612. * under the License.
  48613. */
  48614. var PointerPath = Path.extend({
  48615. type: 'echartsGaugePointer',
  48616. shape: {
  48617. angle: 0,
  48618. width: 10,
  48619. r: 10,
  48620. x: 0,
  48621. y: 0
  48622. },
  48623. buildPath: function (ctx, shape) {
  48624. var mathCos = Math.cos;
  48625. var mathSin = Math.sin;
  48626. var r = shape.r;
  48627. var width = shape.width;
  48628. var angle = shape.angle;
  48629. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  48630. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  48631. angle = shape.angle - Math.PI / 2;
  48632. ctx.moveTo(x, y);
  48633. ctx.lineTo(
  48634. shape.x + mathCos(angle) * width,
  48635. shape.y + mathSin(angle) * width
  48636. );
  48637. ctx.lineTo(
  48638. shape.x + mathCos(shape.angle) * r,
  48639. shape.y + mathSin(shape.angle) * r
  48640. );
  48641. ctx.lineTo(
  48642. shape.x - mathCos(angle) * width,
  48643. shape.y - mathSin(angle) * width
  48644. );
  48645. ctx.lineTo(x, y);
  48646. return;
  48647. }
  48648. });
  48649. /*
  48650. * Licensed to the Apache Software Foundation (ASF) under one
  48651. * or more contributor license agreements. See the NOTICE file
  48652. * distributed with this work for additional information
  48653. * regarding copyright ownership. The ASF licenses this file
  48654. * to you under the Apache License, Version 2.0 (the
  48655. * "License"); you may not use this file except in compliance
  48656. * with the License. You may obtain a copy of the License at
  48657. *
  48658. * http://www.apache.org/licenses/LICENSE-2.0
  48659. *
  48660. * Unless required by applicable law or agreed to in writing,
  48661. * software distributed under the License is distributed on an
  48662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48663. * KIND, either express or implied. See the License for the
  48664. * specific language governing permissions and limitations
  48665. * under the License.
  48666. */
  48667. function parsePosition(seriesModel, api) {
  48668. var center = seriesModel.get('center');
  48669. var width = api.getWidth();
  48670. var height = api.getHeight();
  48671. var size = Math.min(width, height);
  48672. var cx = parsePercent$1(center[0], api.getWidth());
  48673. var cy = parsePercent$1(center[1], api.getHeight());
  48674. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  48675. return {
  48676. cx: cx,
  48677. cy: cy,
  48678. r: r
  48679. };
  48680. }
  48681. function formatLabel(label, labelFormatter) {
  48682. if (labelFormatter) {
  48683. if (typeof labelFormatter === 'string') {
  48684. label = labelFormatter.replace('{value}', label != null ? label : '');
  48685. }
  48686. else if (typeof labelFormatter === 'function') {
  48687. label = labelFormatter(label);
  48688. }
  48689. }
  48690. return label;
  48691. }
  48692. var PI2$5 = Math.PI * 2;
  48693. var GaugeView = Chart.extend({
  48694. type: 'gauge',
  48695. render: function (seriesModel, ecModel, api) {
  48696. this.group.removeAll();
  48697. var colorList = seriesModel.get('axisLine.lineStyle.color');
  48698. var posInfo = parsePosition(seriesModel, api);
  48699. this._renderMain(
  48700. seriesModel, ecModel, api, colorList, posInfo
  48701. );
  48702. },
  48703. dispose: function () {},
  48704. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  48705. var group = this.group;
  48706. var axisLineModel = seriesModel.getModel('axisLine');
  48707. var lineStyleModel = axisLineModel.getModel('lineStyle');
  48708. var clockwise = seriesModel.get('clockwise');
  48709. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  48710. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  48711. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  48712. var prevEndAngle = startAngle;
  48713. var axisLineWidth = lineStyleModel.get('width');
  48714. for (var i = 0; i < colorList.length; i++) {
  48715. // Clamp
  48716. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  48717. var endAngle = startAngle + angleRangeSpan * percent;
  48718. var sector = new Sector({
  48719. shape: {
  48720. startAngle: prevEndAngle,
  48721. endAngle: endAngle,
  48722. cx: posInfo.cx,
  48723. cy: posInfo.cy,
  48724. clockwise: clockwise,
  48725. r0: posInfo.r - axisLineWidth,
  48726. r: posInfo.r
  48727. },
  48728. silent: true
  48729. });
  48730. sector.setStyle({
  48731. fill: colorList[i][1]
  48732. });
  48733. sector.setStyle(lineStyleModel.getLineStyle(
  48734. // Because we use sector to simulate arc
  48735. // so the properties for stroking are useless
  48736. ['color', 'borderWidth', 'borderColor']
  48737. ));
  48738. group.add(sector);
  48739. prevEndAngle = endAngle;
  48740. }
  48741. var getColor = function (percent) {
  48742. // Less than 0
  48743. if (percent <= 0) {
  48744. return colorList[0][1];
  48745. }
  48746. for (var i = 0; i < colorList.length; i++) {
  48747. if (colorList[i][0] >= percent
  48748. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  48749. ) {
  48750. return colorList[i][1];
  48751. }
  48752. }
  48753. // More than 1
  48754. return colorList[i - 1][1];
  48755. };
  48756. if (!clockwise) {
  48757. var tmp = startAngle;
  48758. startAngle = endAngle;
  48759. endAngle = tmp;
  48760. }
  48761. this._renderTicks(
  48762. seriesModel, ecModel, api, getColor, posInfo,
  48763. startAngle, endAngle, clockwise
  48764. );
  48765. this._renderPointer(
  48766. seriesModel, ecModel, api, getColor, posInfo,
  48767. startAngle, endAngle, clockwise
  48768. );
  48769. this._renderTitle(
  48770. seriesModel, ecModel, api, getColor, posInfo
  48771. );
  48772. this._renderDetail(
  48773. seriesModel, ecModel, api, getColor, posInfo
  48774. );
  48775. },
  48776. _renderTicks: function (
  48777. seriesModel, ecModel, api, getColor, posInfo,
  48778. startAngle, endAngle, clockwise
  48779. ) {
  48780. var group = this.group;
  48781. var cx = posInfo.cx;
  48782. var cy = posInfo.cy;
  48783. var r = posInfo.r;
  48784. var minVal = +seriesModel.get('min');
  48785. var maxVal = +seriesModel.get('max');
  48786. var splitLineModel = seriesModel.getModel('splitLine');
  48787. var tickModel = seriesModel.getModel('axisTick');
  48788. var labelModel = seriesModel.getModel('axisLabel');
  48789. var splitNumber = seriesModel.get('splitNumber');
  48790. var subSplitNumber = tickModel.get('splitNumber');
  48791. var splitLineLen = parsePercent$1(
  48792. splitLineModel.get('length'), r
  48793. );
  48794. var tickLen = parsePercent$1(
  48795. tickModel.get('length'), r
  48796. );
  48797. var angle = startAngle;
  48798. var step = (endAngle - startAngle) / splitNumber;
  48799. var subStep = step / subSplitNumber;
  48800. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  48801. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  48802. for (var i = 0; i <= splitNumber; i++) {
  48803. var unitX = Math.cos(angle);
  48804. var unitY = Math.sin(angle);
  48805. // Split line
  48806. if (splitLineModel.get('show')) {
  48807. var splitLine = new Line({
  48808. shape: {
  48809. x1: unitX * r + cx,
  48810. y1: unitY * r + cy,
  48811. x2: unitX * (r - splitLineLen) + cx,
  48812. y2: unitY * (r - splitLineLen) + cy
  48813. },
  48814. style: splitLineStyle,
  48815. silent: true
  48816. });
  48817. if (splitLineStyle.stroke === 'auto') {
  48818. splitLine.setStyle({
  48819. stroke: getColor(i / splitNumber)
  48820. });
  48821. }
  48822. group.add(splitLine);
  48823. }
  48824. // Label
  48825. if (labelModel.get('show')) {
  48826. var label = formatLabel(
  48827. round$2(i / splitNumber * (maxVal - minVal) + minVal),
  48828. labelModel.get('formatter')
  48829. );
  48830. var distance = labelModel.get('distance');
  48831. var autoColor = getColor(i / splitNumber);
  48832. group.add(new Text({
  48833. style: setTextStyle({}, labelModel, {
  48834. text: label,
  48835. x: unitX * (r - splitLineLen - distance) + cx,
  48836. y: unitY * (r - splitLineLen - distance) + cy,
  48837. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  48838. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  48839. }, {autoColor: autoColor}),
  48840. silent: true
  48841. }));
  48842. }
  48843. // Axis tick
  48844. if (tickModel.get('show') && i !== splitNumber) {
  48845. for (var j = 0; j <= subSplitNumber; j++) {
  48846. var unitX = Math.cos(angle);
  48847. var unitY = Math.sin(angle);
  48848. var tickLine = new Line({
  48849. shape: {
  48850. x1: unitX * r + cx,
  48851. y1: unitY * r + cy,
  48852. x2: unitX * (r - tickLen) + cx,
  48853. y2: unitY * (r - tickLen) + cy
  48854. },
  48855. silent: true,
  48856. style: tickLineStyle
  48857. });
  48858. if (tickLineStyle.stroke === 'auto') {
  48859. tickLine.setStyle({
  48860. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  48861. });
  48862. }
  48863. group.add(tickLine);
  48864. angle += subStep;
  48865. }
  48866. angle -= subStep;
  48867. }
  48868. else {
  48869. angle += step;
  48870. }
  48871. }
  48872. },
  48873. _renderPointer: function (
  48874. seriesModel, ecModel, api, getColor, posInfo,
  48875. startAngle, endAngle, clockwise
  48876. ) {
  48877. var group = this.group;
  48878. var oldData = this._data;
  48879. if (!seriesModel.get('pointer.show')) {
  48880. // Remove old element
  48881. oldData && oldData.eachItemGraphicEl(function (el) {
  48882. group.remove(el);
  48883. });
  48884. return;
  48885. }
  48886. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  48887. var angleExtent = [startAngle, endAngle];
  48888. var data = seriesModel.getData();
  48889. var valueDim = data.mapDimension('value');
  48890. data.diff(oldData)
  48891. .add(function (idx) {
  48892. var pointer = new PointerPath({
  48893. shape: {
  48894. angle: startAngle
  48895. }
  48896. });
  48897. initProps(pointer, {
  48898. shape: {
  48899. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  48900. }
  48901. }, seriesModel);
  48902. group.add(pointer);
  48903. data.setItemGraphicEl(idx, pointer);
  48904. })
  48905. .update(function (newIdx, oldIdx) {
  48906. var pointer = oldData.getItemGraphicEl(oldIdx);
  48907. updateProps(pointer, {
  48908. shape: {
  48909. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  48910. }
  48911. }, seriesModel);
  48912. group.add(pointer);
  48913. data.setItemGraphicEl(newIdx, pointer);
  48914. })
  48915. .remove(function (idx) {
  48916. var pointer = oldData.getItemGraphicEl(idx);
  48917. group.remove(pointer);
  48918. })
  48919. .execute();
  48920. data.eachItemGraphicEl(function (pointer, idx) {
  48921. var itemModel = data.getItemModel(idx);
  48922. var pointerModel = itemModel.getModel('pointer');
  48923. pointer.setShape({
  48924. x: posInfo.cx,
  48925. y: posInfo.cy,
  48926. width: parsePercent$1(
  48927. pointerModel.get('width'), posInfo.r
  48928. ),
  48929. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  48930. });
  48931. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  48932. if (pointer.style.fill === 'auto') {
  48933. pointer.setStyle('fill', getColor(
  48934. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  48935. ));
  48936. }
  48937. setHoverStyle(
  48938. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  48939. );
  48940. });
  48941. this._data = data;
  48942. },
  48943. _renderTitle: function (
  48944. seriesModel, ecModel, api, getColor, posInfo
  48945. ) {
  48946. var data = seriesModel.getData();
  48947. var valueDim = data.mapDimension('value');
  48948. var titleModel = seriesModel.getModel('title');
  48949. if (titleModel.get('show')) {
  48950. var offsetCenter = titleModel.get('offsetCenter');
  48951. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  48952. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  48953. var minVal = +seriesModel.get('min');
  48954. var maxVal = +seriesModel.get('max');
  48955. var value = seriesModel.getData().get(valueDim, 0);
  48956. var autoColor = getColor(
  48957. linearMap(value, [minVal, maxVal], [0, 1], true)
  48958. );
  48959. this.group.add(new Text({
  48960. silent: true,
  48961. style: setTextStyle({}, titleModel, {
  48962. x: x,
  48963. y: y,
  48964. // FIXME First data name ?
  48965. text: data.getName(0),
  48966. textAlign: 'center',
  48967. textVerticalAlign: 'middle'
  48968. }, {autoColor: autoColor, forceRich: true})
  48969. }));
  48970. }
  48971. },
  48972. _renderDetail: function (
  48973. seriesModel, ecModel, api, getColor, posInfo
  48974. ) {
  48975. var detailModel = seriesModel.getModel('detail');
  48976. var minVal = +seriesModel.get('min');
  48977. var maxVal = +seriesModel.get('max');
  48978. if (detailModel.get('show')) {
  48979. var offsetCenter = detailModel.get('offsetCenter');
  48980. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  48981. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  48982. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  48983. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  48984. var data = seriesModel.getData();
  48985. var value = data.get(data.mapDimension('value'), 0);
  48986. var autoColor = getColor(
  48987. linearMap(value, [minVal, maxVal], [0, 1], true)
  48988. );
  48989. this.group.add(new Text({
  48990. silent: true,
  48991. style: setTextStyle({}, detailModel, {
  48992. x: x,
  48993. y: y,
  48994. text: formatLabel(
  48995. // FIXME First data name ?
  48996. value, detailModel.get('formatter')
  48997. ),
  48998. textWidth: isNaN(width) ? null : width,
  48999. textHeight: isNaN(height) ? null : height,
  49000. textAlign: 'center',
  49001. textVerticalAlign: 'middle'
  49002. }, {autoColor: autoColor, forceRich: true})
  49003. }));
  49004. }
  49005. }
  49006. });
  49007. /*
  49008. * Licensed to the Apache Software Foundation (ASF) under one
  49009. * or more contributor license agreements. See the NOTICE file
  49010. * distributed with this work for additional information
  49011. * regarding copyright ownership. The ASF licenses this file
  49012. * to you under the Apache License, Version 2.0 (the
  49013. * "License"); you may not use this file except in compliance
  49014. * with the License. You may obtain a copy of the License at
  49015. *
  49016. * http://www.apache.org/licenses/LICENSE-2.0
  49017. *
  49018. * Unless required by applicable law or agreed to in writing,
  49019. * software distributed under the License is distributed on an
  49020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49021. * KIND, either express or implied. See the License for the
  49022. * specific language governing permissions and limitations
  49023. * under the License.
  49024. */
  49025. /*
  49026. * Licensed to the Apache Software Foundation (ASF) under one
  49027. * or more contributor license agreements. See the NOTICE file
  49028. * distributed with this work for additional information
  49029. * regarding copyright ownership. The ASF licenses this file
  49030. * to you under the Apache License, Version 2.0 (the
  49031. * "License"); you may not use this file except in compliance
  49032. * with the License. You may obtain a copy of the License at
  49033. *
  49034. * http://www.apache.org/licenses/LICENSE-2.0
  49035. *
  49036. * Unless required by applicable law or agreed to in writing,
  49037. * software distributed under the License is distributed on an
  49038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49039. * KIND, either express or implied. See the License for the
  49040. * specific language governing permissions and limitations
  49041. * under the License.
  49042. */
  49043. var FunnelSeries = extendSeriesModel({
  49044. type: 'series.funnel',
  49045. init: function (option) {
  49046. FunnelSeries.superApply(this, 'init', arguments);
  49047. // Enable legend selection for each data item
  49048. // Use a function instead of direct access because data reference may changed
  49049. this.legendDataProvider = function () {
  49050. return this.getRawData();
  49051. };
  49052. // Extend labelLine emphasis
  49053. this._defaultLabelLine(option);
  49054. },
  49055. getInitialData: function (option, ecModel) {
  49056. return createListSimply(this, ['value']);
  49057. },
  49058. _defaultLabelLine: function (option) {
  49059. // Extend labelLine emphasis
  49060. defaultEmphasis(option, 'labelLine', ['show']);
  49061. var labelLineNormalOpt = option.labelLine;
  49062. var labelLineEmphasisOpt = option.emphasis.labelLine;
  49063. // Not show label line if `label.normal.show = false`
  49064. labelLineNormalOpt.show = labelLineNormalOpt.show
  49065. && option.label.show;
  49066. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  49067. && option.emphasis.label.show;
  49068. },
  49069. // Overwrite
  49070. getDataParams: function (dataIndex) {
  49071. var data = this.getData();
  49072. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  49073. var valueDim = data.mapDimension('value');
  49074. var sum = data.getSum(valueDim);
  49075. // Percent is 0 if sum is 0
  49076. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  49077. params.$vars.push('percent');
  49078. return params;
  49079. },
  49080. defaultOption: {
  49081. zlevel: 0, // 一级层叠
  49082. z: 2, // 二级层叠
  49083. legendHoverLink: true,
  49084. left: 80,
  49085. top: 60,
  49086. right: 80,
  49087. bottom: 60,
  49088. // width: {totalWidth} - left - right,
  49089. // height: {totalHeight} - top - bottom,
  49090. // 默认取数据最小最大值
  49091. // min: 0,
  49092. // max: 100,
  49093. minSize: '0%',
  49094. maxSize: '100%',
  49095. sort: 'descending', // 'ascending', 'descending'
  49096. gap: 0,
  49097. funnelAlign: 'center',
  49098. label: {
  49099. show: true,
  49100. position: 'outer'
  49101. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  49102. },
  49103. labelLine: {
  49104. show: true,
  49105. length: 20,
  49106. lineStyle: {
  49107. // color: 各异,
  49108. width: 1,
  49109. type: 'solid'
  49110. }
  49111. },
  49112. itemStyle: {
  49113. // color: 各异,
  49114. borderColor: '#fff',
  49115. borderWidth: 1
  49116. },
  49117. emphasis: {
  49118. label: {
  49119. show: true
  49120. }
  49121. }
  49122. }
  49123. });
  49124. /*
  49125. * Licensed to the Apache Software Foundation (ASF) under one
  49126. * or more contributor license agreements. See the NOTICE file
  49127. * distributed with this work for additional information
  49128. * regarding copyright ownership. The ASF licenses this file
  49129. * to you under the Apache License, Version 2.0 (the
  49130. * "License"); you may not use this file except in compliance
  49131. * with the License. You may obtain a copy of the License at
  49132. *
  49133. * http://www.apache.org/licenses/LICENSE-2.0
  49134. *
  49135. * Unless required by applicable law or agreed to in writing,
  49136. * software distributed under the License is distributed on an
  49137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49138. * KIND, either express or implied. See the License for the
  49139. * specific language governing permissions and limitations
  49140. * under the License.
  49141. */
  49142. /**
  49143. * Piece of pie including Sector, Label, LabelLine
  49144. * @constructor
  49145. * @extends {module:zrender/graphic/Group}
  49146. */
  49147. function FunnelPiece(data, idx) {
  49148. Group.call(this);
  49149. var polygon = new Polygon();
  49150. var labelLine = new Polyline();
  49151. var text = new Text();
  49152. this.add(polygon);
  49153. this.add(labelLine);
  49154. this.add(text);
  49155. this.updateData(data, idx, true);
  49156. // Hover to change label and labelLine
  49157. function onEmphasis() {
  49158. labelLine.ignore = labelLine.hoverIgnore;
  49159. text.ignore = text.hoverIgnore;
  49160. }
  49161. function onNormal() {
  49162. labelLine.ignore = labelLine.normalIgnore;
  49163. text.ignore = text.normalIgnore;
  49164. }
  49165. this.on('emphasis', onEmphasis)
  49166. .on('normal', onNormal)
  49167. .on('mouseover', onEmphasis)
  49168. .on('mouseout', onNormal);
  49169. }
  49170. var funnelPieceProto = FunnelPiece.prototype;
  49171. var opacityAccessPath = ['itemStyle', 'opacity'];
  49172. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  49173. var polygon = this.childAt(0);
  49174. var seriesModel = data.hostModel;
  49175. var itemModel = data.getItemModel(idx);
  49176. var layout = data.getItemLayout(idx);
  49177. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  49178. opacity = opacity == null ? 1 : opacity;
  49179. // Reset style
  49180. polygon.useStyle({});
  49181. if (firstCreate) {
  49182. polygon.setShape({
  49183. points: layout.points
  49184. });
  49185. polygon.setStyle({opacity: 0});
  49186. initProps(polygon, {
  49187. style: {
  49188. opacity: opacity
  49189. }
  49190. }, seriesModel, idx);
  49191. }
  49192. else {
  49193. updateProps(polygon, {
  49194. style: {
  49195. opacity: opacity
  49196. },
  49197. shape: {
  49198. points: layout.points
  49199. }
  49200. }, seriesModel, idx);
  49201. }
  49202. // Update common style
  49203. var itemStyleModel = itemModel.getModel('itemStyle');
  49204. var visualColor = data.getItemVisual(idx, 'color');
  49205. polygon.setStyle(
  49206. defaults(
  49207. {
  49208. lineJoin: 'round',
  49209. fill: visualColor
  49210. },
  49211. itemStyleModel.getItemStyle(['opacity'])
  49212. )
  49213. );
  49214. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  49215. this._updateLabel(data, idx);
  49216. setHoverStyle(this);
  49217. };
  49218. funnelPieceProto._updateLabel = function (data, idx) {
  49219. var labelLine = this.childAt(1);
  49220. var labelText = this.childAt(2);
  49221. var seriesModel = data.hostModel;
  49222. var itemModel = data.getItemModel(idx);
  49223. var layout = data.getItemLayout(idx);
  49224. var labelLayout = layout.label;
  49225. var visualColor = data.getItemVisual(idx, 'color');
  49226. updateProps(labelLine, {
  49227. shape: {
  49228. points: labelLayout.linePoints || labelLayout.linePoints
  49229. }
  49230. }, seriesModel, idx);
  49231. updateProps(labelText, {
  49232. style: {
  49233. x: labelLayout.x,
  49234. y: labelLayout.y
  49235. }
  49236. }, seriesModel, idx);
  49237. labelText.attr({
  49238. rotation: labelLayout.rotation,
  49239. origin: [labelLayout.x, labelLayout.y],
  49240. z2: 10
  49241. });
  49242. var labelModel = itemModel.getModel('label');
  49243. var labelHoverModel = itemModel.getModel('emphasis.label');
  49244. var labelLineModel = itemModel.getModel('labelLine');
  49245. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  49246. var visualColor = data.getItemVisual(idx, 'color');
  49247. setLabelStyle(
  49248. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  49249. {
  49250. labelFetcher: data.hostModel,
  49251. labelDataIndex: idx,
  49252. defaultText: data.getName(idx),
  49253. autoColor: visualColor,
  49254. useInsideStyle: !!labelLayout.inside
  49255. },
  49256. {
  49257. textAlign: labelLayout.textAlign,
  49258. textVerticalAlign: labelLayout.verticalAlign
  49259. }
  49260. );
  49261. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  49262. labelText.hoverIgnore = !labelHoverModel.get('show');
  49263. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  49264. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  49265. // Default use item visual color
  49266. labelLine.setStyle({
  49267. stroke: visualColor
  49268. });
  49269. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  49270. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  49271. };
  49272. inherits(FunnelPiece, Group);
  49273. var FunnelView = Chart.extend({
  49274. type: 'funnel',
  49275. render: function (seriesModel, ecModel, api) {
  49276. var data = seriesModel.getData();
  49277. var oldData = this._data;
  49278. var group = this.group;
  49279. data.diff(oldData)
  49280. .add(function (idx) {
  49281. var funnelPiece = new FunnelPiece(data, idx);
  49282. data.setItemGraphicEl(idx, funnelPiece);
  49283. group.add(funnelPiece);
  49284. })
  49285. .update(function (newIdx, oldIdx) {
  49286. var piePiece = oldData.getItemGraphicEl(oldIdx);
  49287. piePiece.updateData(data, newIdx);
  49288. group.add(piePiece);
  49289. data.setItemGraphicEl(newIdx, piePiece);
  49290. })
  49291. .remove(function (idx) {
  49292. var piePiece = oldData.getItemGraphicEl(idx);
  49293. group.remove(piePiece);
  49294. })
  49295. .execute();
  49296. this._data = data;
  49297. },
  49298. remove: function () {
  49299. this.group.removeAll();
  49300. this._data = null;
  49301. },
  49302. dispose: function () {}
  49303. });
  49304. /*
  49305. * Licensed to the Apache Software Foundation (ASF) under one
  49306. * or more contributor license agreements. See the NOTICE file
  49307. * distributed with this work for additional information
  49308. * regarding copyright ownership. The ASF licenses this file
  49309. * to you under the Apache License, Version 2.0 (the
  49310. * "License"); you may not use this file except in compliance
  49311. * with the License. You may obtain a copy of the License at
  49312. *
  49313. * http://www.apache.org/licenses/LICENSE-2.0
  49314. *
  49315. * Unless required by applicable law or agreed to in writing,
  49316. * software distributed under the License is distributed on an
  49317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49318. * KIND, either express or implied. See the License for the
  49319. * specific language governing permissions and limitations
  49320. * under the License.
  49321. */
  49322. function getViewRect$2(seriesModel, api) {
  49323. return getLayoutRect(
  49324. seriesModel.getBoxLayoutParams(), {
  49325. width: api.getWidth(),
  49326. height: api.getHeight()
  49327. }
  49328. );
  49329. }
  49330. function getSortedIndices(data, sort) {
  49331. var valueDim = data.mapDimension('value');
  49332. var valueArr = data.mapArray(valueDim, function (val) {
  49333. return val;
  49334. });
  49335. var indices = [];
  49336. var isAscending = sort === 'ascending';
  49337. for (var i = 0, len = data.count(); i < len; i++) {
  49338. indices[i] = i;
  49339. }
  49340. // Add custom sortable function & none sortable opetion by "options.sort"
  49341. if (typeof sort === 'function') {
  49342. indices.sort(sort);
  49343. }
  49344. else if (sort !== 'none') {
  49345. indices.sort(function (a, b) {
  49346. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  49347. });
  49348. }
  49349. return indices;
  49350. }
  49351. function labelLayout$1(data) {
  49352. data.each(function (idx) {
  49353. var itemModel = data.getItemModel(idx);
  49354. var labelModel = itemModel.getModel('label');
  49355. var labelPosition = labelModel.get('position');
  49356. var labelLineModel = itemModel.getModel('labelLine');
  49357. var layout = data.getItemLayout(idx);
  49358. var points = layout.points;
  49359. var isLabelInside = labelPosition === 'inner'
  49360. || labelPosition === 'inside' || labelPosition === 'center';
  49361. var textAlign;
  49362. var textX;
  49363. var textY;
  49364. var linePoints;
  49365. if (isLabelInside) {
  49366. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  49367. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  49368. textAlign = 'center';
  49369. linePoints = [
  49370. [textX, textY], [textX, textY]
  49371. ];
  49372. }
  49373. else {
  49374. var x1;
  49375. var y1;
  49376. var x2;
  49377. var labelLineLen = labelLineModel.get('length');
  49378. if (labelPosition === 'left') {
  49379. // Left side
  49380. x1 = (points[3][0] + points[0][0]) / 2;
  49381. y1 = (points[3][1] + points[0][1]) / 2;
  49382. x2 = x1 - labelLineLen;
  49383. textX = x2 - 5;
  49384. textAlign = 'right';
  49385. }
  49386. else {
  49387. // Right side
  49388. x1 = (points[1][0] + points[2][0]) / 2;
  49389. y1 = (points[1][1] + points[2][1]) / 2;
  49390. x2 = x1 + labelLineLen;
  49391. textX = x2 + 5;
  49392. textAlign = 'left';
  49393. }
  49394. var y2 = y1;
  49395. linePoints = [[x1, y1], [x2, y2]];
  49396. textY = y2;
  49397. }
  49398. layout.label = {
  49399. linePoints: linePoints,
  49400. x: textX,
  49401. y: textY,
  49402. verticalAlign: 'middle',
  49403. textAlign: textAlign,
  49404. inside: isLabelInside
  49405. };
  49406. });
  49407. }
  49408. var funnelLayout = function (ecModel, api, payload) {
  49409. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  49410. var data = seriesModel.getData();
  49411. var valueDim = data.mapDimension('value');
  49412. var sort = seriesModel.get('sort');
  49413. var viewRect = getViewRect$2(seriesModel, api);
  49414. var indices = getSortedIndices(data, sort);
  49415. var sizeExtent = [
  49416. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  49417. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  49418. ];
  49419. var dataExtent = data.getDataExtent(valueDim);
  49420. var min = seriesModel.get('min');
  49421. var max = seriesModel.get('max');
  49422. if (min == null) {
  49423. min = Math.min(dataExtent[0], 0);
  49424. }
  49425. if (max == null) {
  49426. max = dataExtent[1];
  49427. }
  49428. var funnelAlign = seriesModel.get('funnelAlign');
  49429. var gap = seriesModel.get('gap');
  49430. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  49431. var y = viewRect.y;
  49432. var getLinePoints = function (idx, offY) {
  49433. // End point index is data.count() and we assign it 0
  49434. var val = data.get(valueDim, idx) || 0;
  49435. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  49436. var x0;
  49437. switch (funnelAlign) {
  49438. case 'left':
  49439. x0 = viewRect.x;
  49440. break;
  49441. case 'center':
  49442. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  49443. break;
  49444. case 'right':
  49445. x0 = viewRect.x + viewRect.width - itemWidth;
  49446. break;
  49447. }
  49448. return [
  49449. [x0, offY],
  49450. [x0 + itemWidth, offY]
  49451. ];
  49452. };
  49453. if (sort === 'ascending') {
  49454. // From bottom to top
  49455. itemHeight = -itemHeight;
  49456. gap = -gap;
  49457. y += viewRect.height;
  49458. indices = indices.reverse();
  49459. }
  49460. for (var i = 0; i < indices.length; i++) {
  49461. var idx = indices[i];
  49462. var nextIdx = indices[i + 1];
  49463. var itemModel = data.getItemModel(idx);
  49464. var height = itemModel.get('itemStyle.height');
  49465. if (height == null) {
  49466. height = itemHeight;
  49467. }
  49468. else {
  49469. height = parsePercent$1(height, viewRect.height);
  49470. if (sort === 'ascending') {
  49471. height = -height;
  49472. }
  49473. }
  49474. var start = getLinePoints(idx, y);
  49475. var end = getLinePoints(nextIdx, y + height);
  49476. y += height + gap;
  49477. data.setItemLayout(idx, {
  49478. points: start.concat(end.slice().reverse())
  49479. });
  49480. }
  49481. labelLayout$1(data);
  49482. });
  49483. };
  49484. /*
  49485. * Licensed to the Apache Software Foundation (ASF) under one
  49486. * or more contributor license agreements. See the NOTICE file
  49487. * distributed with this work for additional information
  49488. * regarding copyright ownership. The ASF licenses this file
  49489. * to you under the Apache License, Version 2.0 (the
  49490. * "License"); you may not use this file except in compliance
  49491. * with the License. You may obtain a copy of the License at
  49492. *
  49493. * http://www.apache.org/licenses/LICENSE-2.0
  49494. *
  49495. * Unless required by applicable law or agreed to in writing,
  49496. * software distributed under the License is distributed on an
  49497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49498. * KIND, either express or implied. See the License for the
  49499. * specific language governing permissions and limitations
  49500. * under the License.
  49501. */
  49502. registerVisual(dataColor('funnel'));
  49503. registerLayout(funnelLayout);
  49504. registerProcessor(dataFilter('funnel'));
  49505. /*
  49506. * Licensed to the Apache Software Foundation (ASF) under one
  49507. * or more contributor license agreements. See the NOTICE file
  49508. * distributed with this work for additional information
  49509. * regarding copyright ownership. The ASF licenses this file
  49510. * to you under the Apache License, Version 2.0 (the
  49511. * "License"); you may not use this file except in compliance
  49512. * with the License. You may obtain a copy of the License at
  49513. *
  49514. * http://www.apache.org/licenses/LICENSE-2.0
  49515. *
  49516. * Unless required by applicable law or agreed to in writing,
  49517. * software distributed under the License is distributed on an
  49518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49519. * KIND, either express or implied. See the License for the
  49520. * specific language governing permissions and limitations
  49521. * under the License.
  49522. */
  49523. var parallelPreprocessor = function (option) {
  49524. createParallelIfNeeded(option);
  49525. mergeAxisOptionFromParallel(option);
  49526. };
  49527. /**
  49528. * Create a parallel coordinate if not exists.
  49529. * @inner
  49530. */
  49531. function createParallelIfNeeded(option) {
  49532. if (option.parallel) {
  49533. return;
  49534. }
  49535. var hasParallelSeries = false;
  49536. each$1(option.series, function (seriesOpt) {
  49537. if (seriesOpt && seriesOpt.type === 'parallel') {
  49538. hasParallelSeries = true;
  49539. }
  49540. });
  49541. if (hasParallelSeries) {
  49542. option.parallel = [{}];
  49543. }
  49544. }
  49545. /**
  49546. * Merge aixs definition from parallel option (if exists) to axis option.
  49547. * @inner
  49548. */
  49549. function mergeAxisOptionFromParallel(option) {
  49550. var axes = normalizeToArray(option.parallelAxis);
  49551. each$1(axes, function (axisOption) {
  49552. if (!isObject$1(axisOption)) {
  49553. return;
  49554. }
  49555. var parallelIndex = axisOption.parallelIndex || 0;
  49556. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  49557. if (parallelOption && parallelOption.parallelAxisDefault) {
  49558. merge(axisOption, parallelOption.parallelAxisDefault, false);
  49559. }
  49560. });
  49561. }
  49562. /*
  49563. * Licensed to the Apache Software Foundation (ASF) under one
  49564. * or more contributor license agreements. See the NOTICE file
  49565. * distributed with this work for additional information
  49566. * regarding copyright ownership. The ASF licenses this file
  49567. * to you under the Apache License, Version 2.0 (the
  49568. * "License"); you may not use this file except in compliance
  49569. * with the License. You may obtain a copy of the License at
  49570. *
  49571. * http://www.apache.org/licenses/LICENSE-2.0
  49572. *
  49573. * Unless required by applicable law or agreed to in writing,
  49574. * software distributed under the License is distributed on an
  49575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49576. * KIND, either express or implied. See the License for the
  49577. * specific language governing permissions and limitations
  49578. * under the License.
  49579. */
  49580. /**
  49581. * @constructor module:echarts/coord/parallel/ParallelAxis
  49582. * @extends {module:echarts/coord/Axis}
  49583. * @param {string} dim
  49584. * @param {*} scale
  49585. * @param {Array.<number>} coordExtent
  49586. * @param {string} axisType
  49587. */
  49588. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  49589. Axis.call(this, dim, scale, coordExtent);
  49590. /**
  49591. * Axis type
  49592. * - 'category'
  49593. * - 'value'
  49594. * - 'time'
  49595. * - 'log'
  49596. * @type {string}
  49597. */
  49598. this.type = axisType || 'value';
  49599. /**
  49600. * @type {number}
  49601. * @readOnly
  49602. */
  49603. this.axisIndex = axisIndex;
  49604. };
  49605. ParallelAxis.prototype = {
  49606. constructor: ParallelAxis,
  49607. /**
  49608. * Axis model
  49609. * @param {module:echarts/coord/parallel/AxisModel}
  49610. */
  49611. model: null,
  49612. /**
  49613. * @override
  49614. */
  49615. isHorizontal: function () {
  49616. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  49617. }
  49618. };
  49619. inherits(ParallelAxis, Axis);
  49620. /*
  49621. * Licensed to the Apache Software Foundation (ASF) under one
  49622. * or more contributor license agreements. See the NOTICE file
  49623. * distributed with this work for additional information
  49624. * regarding copyright ownership. The ASF licenses this file
  49625. * to you under the Apache License, Version 2.0 (the
  49626. * "License"); you may not use this file except in compliance
  49627. * with the License. You may obtain a copy of the License at
  49628. *
  49629. * http://www.apache.org/licenses/LICENSE-2.0
  49630. *
  49631. * Unless required by applicable law or agreed to in writing,
  49632. * software distributed under the License is distributed on an
  49633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49634. * KIND, either express or implied. See the License for the
  49635. * specific language governing permissions and limitations
  49636. * under the License.
  49637. */
  49638. /**
  49639. * Calculate slider move result.
  49640. * Usage:
  49641. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  49642. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  49643. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  49644. *
  49645. * @param {number} delta Move length.
  49646. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  49647. * handleEnds will be modified in this method.
  49648. * @param {Array.<number>} extent handleEnds is restricted by extent.
  49649. * extent[0] should less or equals than extent[1].
  49650. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  49651. * where the input minSpan and maxSpan will not work.
  49652. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  49653. * If not set, handle0 and cross handle1. If set as a non-negative
  49654. * number (including `0`), handles will push each other when reaching
  49655. * the minSpan.
  49656. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  49657. * @return {Array.<number>} The input handleEnds.
  49658. */
  49659. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  49660. // Normalize firstly.
  49661. handleEnds[0] = restrict$1(handleEnds[0], extent);
  49662. handleEnds[1] = restrict$1(handleEnds[1], extent);
  49663. delta = delta || 0;
  49664. var extentSpan = extent[1] - extent[0];
  49665. // Notice maxSpan and minSpan can be null/undefined.
  49666. if (minSpan != null) {
  49667. minSpan = restrict$1(minSpan, [0, extentSpan]);
  49668. }
  49669. if (maxSpan != null) {
  49670. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  49671. }
  49672. if (handleIndex === 'all') {
  49673. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  49674. handleIndex = 0;
  49675. }
  49676. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  49677. handleEnds[handleIndex] += delta;
  49678. // Restrict in extent.
  49679. var extentMinSpan = minSpan || 0;
  49680. var realExtent = extent.slice();
  49681. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  49682. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  49683. // Expand span.
  49684. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49685. if (minSpan != null && (
  49686. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  49687. )) {
  49688. // If minSpan exists, 'cross' is forbinden.
  49689. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  49690. }
  49691. // Shrink span.
  49692. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49693. if (maxSpan != null && currDistSign.span > maxSpan) {
  49694. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  49695. }
  49696. return handleEnds;
  49697. };
  49698. function getSpanSign(handleEnds, handleIndex) {
  49699. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  49700. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  49701. // is at left of handleEnds[1] for non-cross case.
  49702. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  49703. }
  49704. function restrict$1(value, extend) {
  49705. return Math.min(extend[1], Math.max(extend[0], value));
  49706. }
  49707. /*
  49708. * Licensed to the Apache Software Foundation (ASF) under one
  49709. * or more contributor license agreements. See the NOTICE file
  49710. * distributed with this work for additional information
  49711. * regarding copyright ownership. The ASF licenses this file
  49712. * to you under the Apache License, Version 2.0 (the
  49713. * "License"); you may not use this file except in compliance
  49714. * with the License. You may obtain a copy of the License at
  49715. *
  49716. * http://www.apache.org/licenses/LICENSE-2.0
  49717. *
  49718. * Unless required by applicable law or agreed to in writing,
  49719. * software distributed under the License is distributed on an
  49720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49721. * KIND, either express or implied. See the License for the
  49722. * specific language governing permissions and limitations
  49723. * under the License.
  49724. */
  49725. /**
  49726. * Parallel Coordinates
  49727. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  49728. */
  49729. var each$11 = each$1;
  49730. var mathMin$5 = Math.min;
  49731. var mathMax$5 = Math.max;
  49732. var mathFloor$2 = Math.floor;
  49733. var mathCeil$2 = Math.ceil;
  49734. var round$3 = round$2;
  49735. var PI$3 = Math.PI;
  49736. function Parallel(parallelModel, ecModel, api) {
  49737. /**
  49738. * key: dimension
  49739. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  49740. * @private
  49741. */
  49742. this._axesMap = createHashMap();
  49743. /**
  49744. * key: dimension
  49745. * value: {position: [], rotation, }
  49746. * @type {Object.<string, Object>}
  49747. * @private
  49748. */
  49749. this._axesLayout = {};
  49750. /**
  49751. * Always follow axis order.
  49752. * @type {Array.<string>}
  49753. * @readOnly
  49754. */
  49755. this.dimensions = parallelModel.dimensions;
  49756. /**
  49757. * @type {module:zrender/core/BoundingRect}
  49758. */
  49759. this._rect;
  49760. /**
  49761. * @type {module:echarts/coord/parallel/ParallelModel}
  49762. */
  49763. this._model = parallelModel;
  49764. this._init(parallelModel, ecModel, api);
  49765. }
  49766. Parallel.prototype = {
  49767. type: 'parallel',
  49768. constructor: Parallel,
  49769. /**
  49770. * Initialize cartesian coordinate systems
  49771. * @private
  49772. */
  49773. _init: function (parallelModel, ecModel, api) {
  49774. var dimensions = parallelModel.dimensions;
  49775. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  49776. each$11(dimensions, function (dim, idx) {
  49777. var axisIndex = parallelAxisIndex[idx];
  49778. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  49779. var axis = this._axesMap.set(dim, new ParallelAxis(
  49780. dim,
  49781. createScaleByModel(axisModel),
  49782. [0, 0],
  49783. axisModel.get('type'),
  49784. axisIndex
  49785. ));
  49786. var isCategory = axis.type === 'category';
  49787. axis.onBand = isCategory && axisModel.get('boundaryGap');
  49788. axis.inverse = axisModel.get('inverse');
  49789. // Injection
  49790. axisModel.axis = axis;
  49791. axis.model = axisModel;
  49792. axis.coordinateSystem = axisModel.coordinateSystem = this;
  49793. }, this);
  49794. },
  49795. /**
  49796. * Update axis scale after data processed
  49797. * @param {module:echarts/model/Global} ecModel
  49798. * @param {module:echarts/ExtensionAPI} api
  49799. */
  49800. update: function (ecModel, api) {
  49801. this._updateAxesFromSeries(this._model, ecModel);
  49802. },
  49803. /**
  49804. * @override
  49805. */
  49806. containPoint: function (point) {
  49807. var layoutInfo = this._makeLayoutInfo();
  49808. var axisBase = layoutInfo.axisBase;
  49809. var layoutBase = layoutInfo.layoutBase;
  49810. var pixelDimIndex = layoutInfo.pixelDimIndex;
  49811. var pAxis = point[1 - pixelDimIndex];
  49812. var pLayout = point[pixelDimIndex];
  49813. return pAxis >= axisBase
  49814. && pAxis <= axisBase + layoutInfo.axisLength
  49815. && pLayout >= layoutBase
  49816. && pLayout <= layoutBase + layoutInfo.layoutLength;
  49817. },
  49818. getModel: function () {
  49819. return this._model;
  49820. },
  49821. /**
  49822. * Update properties from series
  49823. * @private
  49824. */
  49825. _updateAxesFromSeries: function (parallelModel, ecModel) {
  49826. ecModel.eachSeries(function (seriesModel) {
  49827. if (!parallelModel.contains(seriesModel, ecModel)) {
  49828. return;
  49829. }
  49830. var data = seriesModel.getData();
  49831. each$11(this.dimensions, function (dim) {
  49832. var axis = this._axesMap.get(dim);
  49833. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  49834. niceScaleExtent(axis.scale, axis.model);
  49835. }, this);
  49836. }, this);
  49837. },
  49838. /**
  49839. * Resize the parallel coordinate system.
  49840. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  49841. * @param {module:echarts/ExtensionAPI} api
  49842. */
  49843. resize: function (parallelModel, api) {
  49844. this._rect = getLayoutRect(
  49845. parallelModel.getBoxLayoutParams(),
  49846. {
  49847. width: api.getWidth(),
  49848. height: api.getHeight()
  49849. }
  49850. );
  49851. this._layoutAxes();
  49852. },
  49853. /**
  49854. * @return {module:zrender/core/BoundingRect}
  49855. */
  49856. getRect: function () {
  49857. return this._rect;
  49858. },
  49859. /**
  49860. * @private
  49861. */
  49862. _makeLayoutInfo: function () {
  49863. var parallelModel = this._model;
  49864. var rect = this._rect;
  49865. var xy = ['x', 'y'];
  49866. var wh = ['width', 'height'];
  49867. var layout = parallelModel.get('layout');
  49868. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  49869. var layoutLength = rect[wh[pixelDimIndex]];
  49870. var layoutExtent = [0, layoutLength];
  49871. var axisCount = this.dimensions.length;
  49872. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  49873. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  49874. var axisExpandable = parallelModel.get('axisExpandable')
  49875. && axisCount > 3
  49876. && axisCount > axisExpandCount
  49877. && axisExpandCount > 1
  49878. && axisExpandWidth > 0
  49879. && layoutLength > 0;
  49880. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  49881. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  49882. // where collapsed axes should be overlapped.
  49883. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  49884. var winSize;
  49885. if (!axisExpandWindow) {
  49886. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  49887. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  49888. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  49889. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49890. }
  49891. else {
  49892. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  49893. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49894. }
  49895. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  49896. // Avoid axisCollapseWidth is too small.
  49897. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  49898. // Find the first and last indices > ewin[0] and < ewin[1].
  49899. var winInnerIndices = [
  49900. mathFloor$2(round$3(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  49901. mathCeil$2(round$3(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  49902. ];
  49903. // Pos in ec coordinates.
  49904. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  49905. return {
  49906. layout: layout,
  49907. pixelDimIndex: pixelDimIndex,
  49908. layoutBase: rect[xy[pixelDimIndex]],
  49909. layoutLength: layoutLength,
  49910. axisBase: rect[xy[1 - pixelDimIndex]],
  49911. axisLength: rect[wh[1 - pixelDimIndex]],
  49912. axisExpandable: axisExpandable,
  49913. axisExpandWidth: axisExpandWidth,
  49914. axisCollapseWidth: axisCollapseWidth,
  49915. axisExpandWindow: axisExpandWindow,
  49916. axisCount: axisCount,
  49917. winInnerIndices: winInnerIndices,
  49918. axisExpandWindow0Pos: axisExpandWindow0Pos
  49919. };
  49920. },
  49921. /**
  49922. * @private
  49923. */
  49924. _layoutAxes: function () {
  49925. var rect = this._rect;
  49926. var axes = this._axesMap;
  49927. var dimensions = this.dimensions;
  49928. var layoutInfo = this._makeLayoutInfo();
  49929. var layout = layoutInfo.layout;
  49930. axes.each(function (axis) {
  49931. var axisExtent = [0, layoutInfo.axisLength];
  49932. var idx = axis.inverse ? 1 : 0;
  49933. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  49934. });
  49935. each$11(dimensions, function (dim, idx) {
  49936. var posInfo = (layoutInfo.axisExpandable
  49937. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  49938. )(idx, layoutInfo);
  49939. var positionTable = {
  49940. horizontal: {
  49941. x: posInfo.position,
  49942. y: layoutInfo.axisLength
  49943. },
  49944. vertical: {
  49945. x: 0,
  49946. y: posInfo.position
  49947. }
  49948. };
  49949. var rotationTable = {
  49950. horizontal: PI$3 / 2,
  49951. vertical: 0
  49952. };
  49953. var position = [
  49954. positionTable[layout].x + rect.x,
  49955. positionTable[layout].y + rect.y
  49956. ];
  49957. var rotation = rotationTable[layout];
  49958. var transform = create$1();
  49959. rotate(transform, transform, rotation);
  49960. translate(transform, transform, position);
  49961. // TODO
  49962. // tick等排布信息。
  49963. // TODO
  49964. // 根据axis order 更新 dimensions顺序。
  49965. this._axesLayout[dim] = {
  49966. position: position,
  49967. rotation: rotation,
  49968. transform: transform,
  49969. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  49970. axisLabelShow: posInfo.axisLabelShow,
  49971. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  49972. tickDirection: 1,
  49973. labelDirection: 1
  49974. };
  49975. }, this);
  49976. },
  49977. /**
  49978. * Get axis by dim.
  49979. * @param {string} dim
  49980. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  49981. */
  49982. getAxis: function (dim) {
  49983. return this._axesMap.get(dim);
  49984. },
  49985. /**
  49986. * Convert a dim value of a single item of series data to Point.
  49987. * @param {*} value
  49988. * @param {string} dim
  49989. * @return {Array}
  49990. */
  49991. dataToPoint: function (value, dim) {
  49992. return this.axisCoordToPoint(
  49993. this._axesMap.get(dim).dataToCoord(value),
  49994. dim
  49995. );
  49996. },
  49997. /**
  49998. * Travel data for one time, get activeState of each data item.
  49999. * @param {module:echarts/data/List} data
  50000. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  50001. * {number} dataIndex
  50002. * @param {number} [start=0] the start dataIndex that travel from.
  50003. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  50004. */
  50005. eachActiveState: function (data, callback, start, end) {
  50006. start == null && (start = 0);
  50007. end == null && (end = data.count());
  50008. var axesMap = this._axesMap;
  50009. var dimensions = this.dimensions;
  50010. var dataDimensions = [];
  50011. var axisModels = [];
  50012. each$1(dimensions, function (axisDim) {
  50013. dataDimensions.push(data.mapDimension(axisDim));
  50014. axisModels.push(axesMap.get(axisDim).model);
  50015. });
  50016. var hasActiveSet = this.hasAxisBrushed();
  50017. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  50018. var activeState;
  50019. if (!hasActiveSet) {
  50020. activeState = 'normal';
  50021. }
  50022. else {
  50023. activeState = 'active';
  50024. var values = data.getValues(dataDimensions, dataIndex);
  50025. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  50026. var state = axisModels[j].getActiveState(values[j]);
  50027. if (state === 'inactive') {
  50028. activeState = 'inactive';
  50029. break;
  50030. }
  50031. }
  50032. }
  50033. callback(activeState, dataIndex);
  50034. }
  50035. },
  50036. /**
  50037. * Whether has any activeSet.
  50038. * @return {boolean}
  50039. */
  50040. hasAxisBrushed: function () {
  50041. var dimensions = this.dimensions;
  50042. var axesMap = this._axesMap;
  50043. var hasActiveSet = false;
  50044. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  50045. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  50046. hasActiveSet = true;
  50047. }
  50048. }
  50049. return hasActiveSet;
  50050. },
  50051. /**
  50052. * Convert coords of each axis to Point.
  50053. * Return point. For example: [10, 20]
  50054. * @param {Array.<number>} coords
  50055. * @param {string} dim
  50056. * @return {Array.<number>}
  50057. */
  50058. axisCoordToPoint: function (coord, dim) {
  50059. var axisLayout = this._axesLayout[dim];
  50060. return applyTransform$1([coord, 0], axisLayout.transform);
  50061. },
  50062. /**
  50063. * Get axis layout.
  50064. */
  50065. getAxisLayout: function (dim) {
  50066. return clone(this._axesLayout[dim]);
  50067. },
  50068. /**
  50069. * @param {Array.<number>} point
  50070. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  50071. */
  50072. getSlidedAxisExpandWindow: function (point) {
  50073. var layoutInfo = this._makeLayoutInfo();
  50074. var pixelDimIndex = layoutInfo.pixelDimIndex;
  50075. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  50076. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  50077. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  50078. // Out of the area of coordinate system.
  50079. if (!this.containPoint(point)) {
  50080. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  50081. }
  50082. // Conver the point from global to expand coordinates.
  50083. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  50084. // For dragging operation convenience, the window should not be
  50085. // slided when mouse is the center area of the window.
  50086. var delta;
  50087. var behavior = 'slide';
  50088. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  50089. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  50090. // But consider touch device, jump is necessary.
  50091. var useJump = triggerArea[0] != null;
  50092. if (axisCollapseWidth) {
  50093. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  50094. behavior = 'jump';
  50095. delta = pointCoord - winSize * triggerArea[2];
  50096. }
  50097. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  50098. behavior = 'jump';
  50099. delta = pointCoord - winSize * (1 - triggerArea[2]);
  50100. }
  50101. else {
  50102. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  50103. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  50104. && (delta = 0);
  50105. }
  50106. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  50107. delta
  50108. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  50109. // Avoid nonsense triger on mousemove.
  50110. : (behavior = 'none');
  50111. }
  50112. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  50113. else {
  50114. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  50115. var pos = extent[1] * pointCoord / winSize;
  50116. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  50117. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  50118. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  50119. }
  50120. return {
  50121. axisExpandWindow: axisExpandWindow,
  50122. behavior: behavior
  50123. };
  50124. }
  50125. };
  50126. function restrict(len, extent) {
  50127. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  50128. }
  50129. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  50130. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  50131. return {
  50132. position: step * axisIndex,
  50133. axisNameAvailableWidth: step,
  50134. axisLabelShow: true
  50135. };
  50136. }
  50137. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  50138. var layoutLength = layoutInfo.layoutLength;
  50139. var axisExpandWidth = layoutInfo.axisExpandWidth;
  50140. var axisCount = layoutInfo.axisCount;
  50141. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  50142. var winInnerIndices = layoutInfo.winInnerIndices;
  50143. var position;
  50144. var axisNameAvailableWidth = axisCollapseWidth;
  50145. var axisLabelShow = false;
  50146. var nameTruncateMaxWidth;
  50147. if (axisIndex < winInnerIndices[0]) {
  50148. position = axisIndex * axisCollapseWidth;
  50149. nameTruncateMaxWidth = axisCollapseWidth;
  50150. }
  50151. else if (axisIndex <= winInnerIndices[1]) {
  50152. position = layoutInfo.axisExpandWindow0Pos
  50153. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  50154. axisNameAvailableWidth = axisExpandWidth;
  50155. axisLabelShow = true;
  50156. }
  50157. else {
  50158. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  50159. nameTruncateMaxWidth = axisCollapseWidth;
  50160. }
  50161. return {
  50162. position: position,
  50163. axisNameAvailableWidth: axisNameAvailableWidth,
  50164. axisLabelShow: axisLabelShow,
  50165. nameTruncateMaxWidth: nameTruncateMaxWidth
  50166. };
  50167. }
  50168. /*
  50169. * Licensed to the Apache Software Foundation (ASF) under one
  50170. * or more contributor license agreements. See the NOTICE file
  50171. * distributed with this work for additional information
  50172. * regarding copyright ownership. The ASF licenses this file
  50173. * to you under the Apache License, Version 2.0 (the
  50174. * "License"); you may not use this file except in compliance
  50175. * with the License. You may obtain a copy of the License at
  50176. *
  50177. * http://www.apache.org/licenses/LICENSE-2.0
  50178. *
  50179. * Unless required by applicable law or agreed to in writing,
  50180. * software distributed under the License is distributed on an
  50181. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50182. * KIND, either express or implied. See the License for the
  50183. * specific language governing permissions and limitations
  50184. * under the License.
  50185. */
  50186. /**
  50187. * Parallel coordinate system creater.
  50188. */
  50189. function create$2(ecModel, api) {
  50190. var coordSysList = [];
  50191. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  50192. var coordSys = new Parallel(parallelModel, ecModel, api);
  50193. coordSys.name = 'parallel_' + idx;
  50194. coordSys.resize(parallelModel, api);
  50195. parallelModel.coordinateSystem = coordSys;
  50196. coordSys.model = parallelModel;
  50197. coordSysList.push(coordSys);
  50198. });
  50199. // Inject the coordinateSystems into seriesModel
  50200. ecModel.eachSeries(function (seriesModel) {
  50201. if (seriesModel.get('coordinateSystem') === 'parallel') {
  50202. var parallelModel = ecModel.queryComponents({
  50203. mainType: 'parallel',
  50204. index: seriesModel.get('parallelIndex'),
  50205. id: seriesModel.get('parallelId')
  50206. })[0];
  50207. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  50208. }
  50209. });
  50210. return coordSysList;
  50211. }
  50212. CoordinateSystemManager.register('parallel', {create: create$2});
  50213. /*
  50214. * Licensed to the Apache Software Foundation (ASF) under one
  50215. * or more contributor license agreements. See the NOTICE file
  50216. * distributed with this work for additional information
  50217. * regarding copyright ownership. The ASF licenses this file
  50218. * to you under the Apache License, Version 2.0 (the
  50219. * "License"); you may not use this file except in compliance
  50220. * with the License. You may obtain a copy of the License at
  50221. *
  50222. * http://www.apache.org/licenses/LICENSE-2.0
  50223. *
  50224. * Unless required by applicable law or agreed to in writing,
  50225. * software distributed under the License is distributed on an
  50226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50227. * KIND, either express or implied. See the License for the
  50228. * specific language governing permissions and limitations
  50229. * under the License.
  50230. */
  50231. var AxisModel$2 = ComponentModel.extend({
  50232. type: 'baseParallelAxis',
  50233. /**
  50234. * @type {module:echarts/coord/parallel/Axis}
  50235. */
  50236. axis: null,
  50237. /**
  50238. * @type {Array.<Array.<number>}
  50239. * @readOnly
  50240. */
  50241. activeIntervals: [],
  50242. /**
  50243. * @return {Object}
  50244. */
  50245. getAreaSelectStyle: function () {
  50246. return makeStyleMapper(
  50247. [
  50248. ['fill', 'color'],
  50249. ['lineWidth', 'borderWidth'],
  50250. ['stroke', 'borderColor'],
  50251. ['width', 'width'],
  50252. ['opacity', 'opacity']
  50253. ]
  50254. )(this.getModel('areaSelectStyle'));
  50255. },
  50256. /**
  50257. * The code of this feature is put on AxisModel but not ParallelAxis,
  50258. * because axisModel can be alive after echarts updating but instance of
  50259. * ParallelAxis having been disposed. this._activeInterval should be kept
  50260. * when action dispatched (i.e. legend click).
  50261. *
  50262. * @param {Array.<Array<number>>} intervals interval.length === 0
  50263. * means set all active.
  50264. * @public
  50265. */
  50266. setActiveIntervals: function (intervals) {
  50267. var activeIntervals = this.activeIntervals = clone(intervals);
  50268. // Normalize
  50269. if (activeIntervals) {
  50270. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  50271. asc(activeIntervals[i]);
  50272. }
  50273. }
  50274. },
  50275. /**
  50276. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  50277. * value can not be input.
  50278. * @return {string} 'normal': no activeIntervals set,
  50279. * 'active',
  50280. * 'inactive'.
  50281. * @public
  50282. */
  50283. getActiveState: function (value) {
  50284. var activeIntervals = this.activeIntervals;
  50285. if (!activeIntervals.length) {
  50286. return 'normal';
  50287. }
  50288. if (value == null || isNaN(value)) {
  50289. return 'inactive';
  50290. }
  50291. // Simple optimization
  50292. if (activeIntervals.length === 1) {
  50293. var interval = activeIntervals[0];
  50294. if (interval[0] <= value && value <= interval[1]) {
  50295. return 'active';
  50296. }
  50297. }
  50298. else {
  50299. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  50300. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  50301. return 'active';
  50302. }
  50303. }
  50304. }
  50305. return 'inactive';
  50306. }
  50307. });
  50308. var defaultOption$1 = {
  50309. type: 'value',
  50310. /**
  50311. * @type {Array.<number>}
  50312. */
  50313. dim: null, // 0, 1, 2, ...
  50314. // parallelIndex: null,
  50315. areaSelectStyle: {
  50316. width: 20,
  50317. borderWidth: 1,
  50318. borderColor: 'rgba(160,197,232)',
  50319. color: 'rgba(160,197,232)',
  50320. opacity: 0.3
  50321. },
  50322. realtime: true, // Whether realtime update view when select.
  50323. z: 10
  50324. };
  50325. merge(AxisModel$2.prototype, axisModelCommonMixin);
  50326. function getAxisType$1(axisName, option) {
  50327. return option.type || (option.data ? 'category' : 'value');
  50328. }
  50329. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  50330. /*
  50331. * Licensed to the Apache Software Foundation (ASF) under one
  50332. * or more contributor license agreements. See the NOTICE file
  50333. * distributed with this work for additional information
  50334. * regarding copyright ownership. The ASF licenses this file
  50335. * to you under the Apache License, Version 2.0 (the
  50336. * "License"); you may not use this file except in compliance
  50337. * with the License. You may obtain a copy of the License at
  50338. *
  50339. * http://www.apache.org/licenses/LICENSE-2.0
  50340. *
  50341. * Unless required by applicable law or agreed to in writing,
  50342. * software distributed under the License is distributed on an
  50343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50344. * KIND, either express or implied. See the License for the
  50345. * specific language governing permissions and limitations
  50346. * under the License.
  50347. */
  50348. ComponentModel.extend({
  50349. type: 'parallel',
  50350. dependencies: ['parallelAxis'],
  50351. /**
  50352. * @type {module:echarts/coord/parallel/Parallel}
  50353. */
  50354. coordinateSystem: null,
  50355. /**
  50356. * Each item like: 'dim0', 'dim1', 'dim2', ...
  50357. * @type {Array.<string>}
  50358. * @readOnly
  50359. */
  50360. dimensions: null,
  50361. /**
  50362. * Coresponding to dimensions.
  50363. * @type {Array.<number>}
  50364. * @readOnly
  50365. */
  50366. parallelAxisIndex: null,
  50367. layoutMode: 'box',
  50368. defaultOption: {
  50369. zlevel: 0,
  50370. z: 0,
  50371. left: 80,
  50372. top: 60,
  50373. right: 80,
  50374. bottom: 60,
  50375. // width: {totalWidth} - left - right,
  50376. // height: {totalHeight} - top - bottom,
  50377. layout: 'horizontal', // 'horizontal' or 'vertical'
  50378. // FIXME
  50379. // naming?
  50380. axisExpandable: false,
  50381. axisExpandCenter: null,
  50382. axisExpandCount: 0,
  50383. axisExpandWidth: 50, // FIXME '10%' ?
  50384. axisExpandRate: 17,
  50385. axisExpandDebounce: 50,
  50386. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  50387. // Do not doc to user until necessary.
  50388. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  50389. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  50390. parallelAxisDefault: null
  50391. },
  50392. /**
  50393. * @override
  50394. */
  50395. init: function () {
  50396. ComponentModel.prototype.init.apply(this, arguments);
  50397. this.mergeOption({});
  50398. },
  50399. /**
  50400. * @override
  50401. */
  50402. mergeOption: function (newOption) {
  50403. var thisOption = this.option;
  50404. newOption && merge(thisOption, newOption, true);
  50405. this._initDimensions();
  50406. },
  50407. /**
  50408. * Whether series or axis is in this coordinate system.
  50409. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  50410. * @param {module:echarts/model/Global} ecModel
  50411. */
  50412. contains: function (model, ecModel) {
  50413. var parallelIndex = model.get('parallelIndex');
  50414. return parallelIndex != null
  50415. && ecModel.getComponent('parallel', parallelIndex) === this;
  50416. },
  50417. setAxisExpand: function (opt) {
  50418. each$1(
  50419. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  50420. function (name) {
  50421. if (opt.hasOwnProperty(name)) {
  50422. this.option[name] = opt[name];
  50423. }
  50424. },
  50425. this
  50426. );
  50427. },
  50428. /**
  50429. * @private
  50430. */
  50431. _initDimensions: function () {
  50432. var dimensions = this.dimensions = [];
  50433. var parallelAxisIndex = this.parallelAxisIndex = [];
  50434. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  50435. // Can not use this.contains here, because
  50436. // initialization has not been completed yet.
  50437. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  50438. }, this);
  50439. each$1(axisModels, function (axisModel) {
  50440. dimensions.push('dim' + axisModel.get('dim'));
  50441. parallelAxisIndex.push(axisModel.componentIndex);
  50442. });
  50443. }
  50444. });
  50445. /*
  50446. * Licensed to the Apache Software Foundation (ASF) under one
  50447. * or more contributor license agreements. See the NOTICE file
  50448. * distributed with this work for additional information
  50449. * regarding copyright ownership. The ASF licenses this file
  50450. * to you under the Apache License, Version 2.0 (the
  50451. * "License"); you may not use this file except in compliance
  50452. * with the License. You may obtain a copy of the License at
  50453. *
  50454. * http://www.apache.org/licenses/LICENSE-2.0
  50455. *
  50456. * Unless required by applicable law or agreed to in writing,
  50457. * software distributed under the License is distributed on an
  50458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50459. * KIND, either express or implied. See the License for the
  50460. * specific language governing permissions and limitations
  50461. * under the License.
  50462. */
  50463. /**
  50464. * @payload
  50465. * @property {string} parallelAxisId
  50466. * @property {Array.<Array.<number>>} intervals
  50467. */
  50468. var actionInfo$1 = {
  50469. type: 'axisAreaSelect',
  50470. event: 'axisAreaSelected'
  50471. // update: 'updateVisual'
  50472. };
  50473. registerAction(actionInfo$1, function (payload, ecModel) {
  50474. ecModel.eachComponent(
  50475. {mainType: 'parallelAxis', query: payload},
  50476. function (parallelAxisModel) {
  50477. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  50478. }
  50479. );
  50480. });
  50481. /**
  50482. * @payload
  50483. */
  50484. registerAction('parallelAxisExpand', function (payload, ecModel) {
  50485. ecModel.eachComponent(
  50486. {mainType: 'parallel', query: payload},
  50487. function (parallelModel) {
  50488. parallelModel.setAxisExpand(payload);
  50489. }
  50490. );
  50491. });
  50492. /*
  50493. * Licensed to the Apache Software Foundation (ASF) under one
  50494. * or more contributor license agreements. See the NOTICE file
  50495. * distributed with this work for additional information
  50496. * regarding copyright ownership. The ASF licenses this file
  50497. * to you under the Apache License, Version 2.0 (the
  50498. * "License"); you may not use this file except in compliance
  50499. * with the License. You may obtain a copy of the License at
  50500. *
  50501. * http://www.apache.org/licenses/LICENSE-2.0
  50502. *
  50503. * Unless required by applicable law or agreed to in writing,
  50504. * software distributed under the License is distributed on an
  50505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50506. * KIND, either express or implied. See the License for the
  50507. * specific language governing permissions and limitations
  50508. * under the License.
  50509. */
  50510. var curry$2 = curry;
  50511. var each$12 = each$1;
  50512. var map$2 = map;
  50513. var mathMin$6 = Math.min;
  50514. var mathMax$6 = Math.max;
  50515. var mathPow$2 = Math.pow;
  50516. var COVER_Z = 10000;
  50517. var UNSELECT_THRESHOLD = 6;
  50518. var MIN_RESIZE_LINE_WIDTH = 6;
  50519. var MUTEX_RESOURCE_KEY = 'globalPan';
  50520. var DIRECTION_MAP = {
  50521. w: [0, 0],
  50522. e: [0, 1],
  50523. n: [1, 0],
  50524. s: [1, 1]
  50525. };
  50526. var CURSOR_MAP = {
  50527. w: 'ew',
  50528. e: 'ew',
  50529. n: 'ns',
  50530. s: 'ns',
  50531. ne: 'nesw',
  50532. sw: 'nesw',
  50533. nw: 'nwse',
  50534. se: 'nwse'
  50535. };
  50536. var DEFAULT_BRUSH_OPT = {
  50537. brushStyle: {
  50538. lineWidth: 2,
  50539. stroke: 'rgba(0,0,0,0.3)',
  50540. fill: 'rgba(0,0,0,0.1)'
  50541. },
  50542. transformable: true,
  50543. brushMode: 'single',
  50544. removeOnClick: false
  50545. };
  50546. var baseUID = 0;
  50547. /**
  50548. * @alias module:echarts/component/helper/BrushController
  50549. * @constructor
  50550. * @mixin {module:zrender/mixin/Eventful}
  50551. * @event module:echarts/component/helper/BrushController#brush
  50552. * params:
  50553. * areas: Array.<Array>, coord relates to container group,
  50554. * If no container specified, to global.
  50555. * opt {
  50556. * isEnd: boolean,
  50557. * removeOnClick: boolean
  50558. * }
  50559. *
  50560. * @param {module:zrender/zrender~ZRender} zr
  50561. */
  50562. function BrushController(zr) {
  50563. if (__DEV__) {
  50564. assert$1(zr);
  50565. }
  50566. Eventful.call(this);
  50567. /**
  50568. * @type {module:zrender/zrender~ZRender}
  50569. * @private
  50570. */
  50571. this._zr = zr;
  50572. /**
  50573. * @type {module:zrender/container/Group}
  50574. * @readOnly
  50575. */
  50576. this.group = new Group();
  50577. /**
  50578. * Only for drawing (after enabledBrush).
  50579. * 'line', 'rect', 'polygon' or false
  50580. * If passing false/null/undefined, disable brush.
  50581. * If passing 'auto', determined by panel.defaultBrushType
  50582. * @private
  50583. * @type {string}
  50584. */
  50585. this._brushType;
  50586. /**
  50587. * Only for drawing (after enabledBrush).
  50588. *
  50589. * @private
  50590. * @type {Object}
  50591. */
  50592. this._brushOption;
  50593. /**
  50594. * @private
  50595. * @type {Object}
  50596. */
  50597. this._panels;
  50598. /**
  50599. * @private
  50600. * @type {Array.<nubmer>}
  50601. */
  50602. this._track = [];
  50603. /**
  50604. * @private
  50605. * @type {boolean}
  50606. */
  50607. this._dragging;
  50608. /**
  50609. * @private
  50610. * @type {Array}
  50611. */
  50612. this._covers = [];
  50613. /**
  50614. * @private
  50615. * @type {moudule:zrender/container/Group}
  50616. */
  50617. this._creatingCover;
  50618. /**
  50619. * `true` means global panel
  50620. * @private
  50621. * @type {module:zrender/container/Group|boolean}
  50622. */
  50623. this._creatingPanel;
  50624. /**
  50625. * @private
  50626. * @type {boolean}
  50627. */
  50628. this._enableGlobalPan;
  50629. /**
  50630. * @private
  50631. * @type {boolean}
  50632. */
  50633. if (__DEV__) {
  50634. this._mounted;
  50635. }
  50636. /**
  50637. * @private
  50638. * @type {string}
  50639. */
  50640. this._uid = 'brushController_' + baseUID++;
  50641. /**
  50642. * @private
  50643. * @type {Object}
  50644. */
  50645. this._handlers = {};
  50646. each$12(mouseHandlers, function (handler, eventName) {
  50647. this._handlers[eventName] = bind(handler, this);
  50648. }, this);
  50649. }
  50650. BrushController.prototype = {
  50651. constructor: BrushController,
  50652. /**
  50653. * If set to null/undefined/false, select disabled.
  50654. * @param {Object} brushOption
  50655. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  50656. * If passing false/null/undefined, disable brush.
  50657. * If passing 'auto', determined by panel.defaultBrushType.
  50658. * ('auto' can not be used in global panel)
  50659. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  50660. * @param {boolean} [brushOption.transformable=true]
  50661. * @param {boolean} [brushOption.removeOnClick=false]
  50662. * @param {Object} [brushOption.brushStyle]
  50663. * @param {number} [brushOption.brushStyle.width]
  50664. * @param {number} [brushOption.brushStyle.lineWidth]
  50665. * @param {string} [brushOption.brushStyle.stroke]
  50666. * @param {string} [brushOption.brushStyle.fill]
  50667. * @param {number} [brushOption.z]
  50668. */
  50669. enableBrush: function (brushOption) {
  50670. if (__DEV__) {
  50671. assert$1(this._mounted);
  50672. }
  50673. this._brushType && doDisableBrush(this);
  50674. brushOption.brushType && doEnableBrush(this, brushOption);
  50675. return this;
  50676. },
  50677. /**
  50678. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  50679. * Each items: {
  50680. * panelId, // mandatory.
  50681. * clipPath, // mandatory. function.
  50682. * isTargetByCursor, // mandatory. function.
  50683. * defaultBrushType, // optional, only used when brushType is 'auto'.
  50684. * getLinearBrushOtherExtent, // optional. function.
  50685. * }
  50686. */
  50687. setPanels: function (panelOpts) {
  50688. if (panelOpts && panelOpts.length) {
  50689. var panels = this._panels = {};
  50690. each$1(panelOpts, function (panelOpts) {
  50691. panels[panelOpts.panelId] = clone(panelOpts);
  50692. });
  50693. }
  50694. else {
  50695. this._panels = null;
  50696. }
  50697. return this;
  50698. },
  50699. /**
  50700. * @param {Object} [opt]
  50701. * @return {boolean} [opt.enableGlobalPan=false]
  50702. */
  50703. mount: function (opt) {
  50704. opt = opt || {};
  50705. if (__DEV__) {
  50706. this._mounted = true; // should be at first.
  50707. }
  50708. this._enableGlobalPan = opt.enableGlobalPan;
  50709. var thisGroup = this.group;
  50710. this._zr.add(thisGroup);
  50711. thisGroup.attr({
  50712. position: opt.position || [0, 0],
  50713. rotation: opt.rotation || 0,
  50714. scale: opt.scale || [1, 1]
  50715. });
  50716. this._transform = thisGroup.getLocalTransform();
  50717. return this;
  50718. },
  50719. eachCover: function (cb, context) {
  50720. each$12(this._covers, cb, context);
  50721. },
  50722. /**
  50723. * Update covers.
  50724. * @param {Array.<Object>} brushOptionList Like:
  50725. * [
  50726. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  50727. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  50728. * ...
  50729. * ]
  50730. * `brushType` is required in each cover info. (can not be 'auto')
  50731. * `id` is not mandatory.
  50732. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  50733. * If brushOptionList is null/undefined, all covers removed.
  50734. */
  50735. updateCovers: function (brushOptionList) {
  50736. if (__DEV__) {
  50737. assert$1(this._mounted);
  50738. }
  50739. brushOptionList = map(brushOptionList, function (brushOption) {
  50740. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50741. });
  50742. var tmpIdPrefix = '\0-brush-index-';
  50743. var oldCovers = this._covers;
  50744. var newCovers = this._covers = [];
  50745. var controller = this;
  50746. var creatingCover = this._creatingCover;
  50747. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  50748. .add(addOrUpdate)
  50749. .update(addOrUpdate)
  50750. .remove(remove)
  50751. .execute();
  50752. return this;
  50753. function getKey(brushOption, index) {
  50754. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  50755. + '-' + brushOption.brushType;
  50756. }
  50757. function oldGetKey(cover, index) {
  50758. return getKey(cover.__brushOption, index);
  50759. }
  50760. function addOrUpdate(newIndex, oldIndex) {
  50761. var newBrushOption = brushOptionList[newIndex];
  50762. // Consider setOption in event listener of brushSelect,
  50763. // where updating cover when creating should be forbiden.
  50764. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  50765. newCovers[newIndex] = oldCovers[oldIndex];
  50766. }
  50767. else {
  50768. var cover = newCovers[newIndex] = oldIndex != null
  50769. ? (
  50770. oldCovers[oldIndex].__brushOption = newBrushOption,
  50771. oldCovers[oldIndex]
  50772. )
  50773. : endCreating(controller, createCover(controller, newBrushOption));
  50774. updateCoverAfterCreation(controller, cover);
  50775. }
  50776. }
  50777. function remove(oldIndex) {
  50778. if (oldCovers[oldIndex] !== creatingCover) {
  50779. controller.group.remove(oldCovers[oldIndex]);
  50780. }
  50781. }
  50782. },
  50783. unmount: function () {
  50784. if (__DEV__) {
  50785. if (!this._mounted) {
  50786. return;
  50787. }
  50788. }
  50789. this.enableBrush(false);
  50790. // container may 'removeAll' outside.
  50791. clearCovers(this);
  50792. this._zr.remove(this.group);
  50793. if (__DEV__) {
  50794. this._mounted = false; // should be at last.
  50795. }
  50796. return this;
  50797. },
  50798. dispose: function () {
  50799. this.unmount();
  50800. this.off();
  50801. }
  50802. };
  50803. mixin(BrushController, Eventful);
  50804. function doEnableBrush(controller, brushOption) {
  50805. var zr = controller._zr;
  50806. // Consider roam, which takes globalPan too.
  50807. if (!controller._enableGlobalPan) {
  50808. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50809. }
  50810. each$12(controller._handlers, function (handler, eventName) {
  50811. zr.on(eventName, handler);
  50812. });
  50813. controller._brushType = brushOption.brushType;
  50814. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50815. }
  50816. function doDisableBrush(controller) {
  50817. var zr = controller._zr;
  50818. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50819. each$12(controller._handlers, function (handler, eventName) {
  50820. zr.off(eventName, handler);
  50821. });
  50822. controller._brushType = controller._brushOption = null;
  50823. }
  50824. function createCover(controller, brushOption) {
  50825. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  50826. cover.__brushOption = brushOption;
  50827. updateZ$1(cover, brushOption);
  50828. controller.group.add(cover);
  50829. return cover;
  50830. }
  50831. function endCreating(controller, creatingCover) {
  50832. var coverRenderer = getCoverRenderer(creatingCover);
  50833. if (coverRenderer.endCreating) {
  50834. coverRenderer.endCreating(controller, creatingCover);
  50835. updateZ$1(creatingCover, creatingCover.__brushOption);
  50836. }
  50837. return creatingCover;
  50838. }
  50839. function updateCoverShape(controller, cover) {
  50840. var brushOption = cover.__brushOption;
  50841. getCoverRenderer(cover).updateCoverShape(
  50842. controller, cover, brushOption.range, brushOption
  50843. );
  50844. }
  50845. function updateZ$1(cover, brushOption) {
  50846. var z = brushOption.z;
  50847. z == null && (z = COVER_Z);
  50848. cover.traverse(function (el) {
  50849. el.z = z;
  50850. el.z2 = z; // Consider in given container.
  50851. });
  50852. }
  50853. function updateCoverAfterCreation(controller, cover) {
  50854. getCoverRenderer(cover).updateCommon(controller, cover);
  50855. updateCoverShape(controller, cover);
  50856. }
  50857. function getCoverRenderer(cover) {
  50858. return coverRenderers[cover.__brushOption.brushType];
  50859. }
  50860. // return target panel or `true` (means global panel)
  50861. function getPanelByPoint(controller, e, localCursorPoint) {
  50862. var panels = controller._panels;
  50863. if (!panels) {
  50864. return true; // Global panel
  50865. }
  50866. var panel;
  50867. var transform = controller._transform;
  50868. each$12(panels, function (pn) {
  50869. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  50870. });
  50871. return panel;
  50872. }
  50873. // Return a panel or true
  50874. function getPanelByCover(controller, cover) {
  50875. var panels = controller._panels;
  50876. if (!panels) {
  50877. return true; // Global panel
  50878. }
  50879. var panelId = cover.__brushOption.panelId;
  50880. // User may give cover without coord sys info,
  50881. // which is then treated as global panel.
  50882. return panelId != null ? panels[panelId] : true;
  50883. }
  50884. function clearCovers(controller) {
  50885. var covers = controller._covers;
  50886. var originalLength = covers.length;
  50887. each$12(covers, function (cover) {
  50888. controller.group.remove(cover);
  50889. }, controller);
  50890. covers.length = 0;
  50891. return !!originalLength;
  50892. }
  50893. function trigger$1(controller, opt) {
  50894. var areas = map$2(controller._covers, function (cover) {
  50895. var brushOption = cover.__brushOption;
  50896. var range = clone(brushOption.range);
  50897. return {
  50898. brushType: brushOption.brushType,
  50899. panelId: brushOption.panelId,
  50900. range: range
  50901. };
  50902. });
  50903. controller.trigger('brush', areas, {
  50904. isEnd: !!opt.isEnd,
  50905. removeOnClick: !!opt.removeOnClick
  50906. });
  50907. }
  50908. function shouldShowCover(controller) {
  50909. var track = controller._track;
  50910. if (!track.length) {
  50911. return false;
  50912. }
  50913. var p2 = track[track.length - 1];
  50914. var p1 = track[0];
  50915. var dx = p2[0] - p1[0];
  50916. var dy = p2[1] - p1[1];
  50917. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  50918. return dist > UNSELECT_THRESHOLD;
  50919. }
  50920. function getTrackEnds(track) {
  50921. var tail = track.length - 1;
  50922. tail < 0 && (tail = 0);
  50923. return [track[0], track[tail]];
  50924. }
  50925. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  50926. var cover = new Group();
  50927. cover.add(new Rect({
  50928. name: 'main',
  50929. style: makeStyle(brushOption),
  50930. silent: true,
  50931. draggable: true,
  50932. cursor: 'move',
  50933. drift: curry$2(doDrift, controller, cover, 'nswe'),
  50934. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50935. }));
  50936. each$12(
  50937. edgeNames,
  50938. function (name) {
  50939. cover.add(new Rect({
  50940. name: name,
  50941. style: {opacity: 0},
  50942. draggable: true,
  50943. silent: true,
  50944. invisible: true,
  50945. drift: curry$2(doDrift, controller, cover, name),
  50946. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50947. }));
  50948. }
  50949. );
  50950. return cover;
  50951. }
  50952. function updateBaseRect(controller, cover, localRange, brushOption) {
  50953. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  50954. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  50955. var x = localRange[0][0];
  50956. var y = localRange[1][0];
  50957. var xa = x - lineWidth / 2;
  50958. var ya = y - lineWidth / 2;
  50959. var x2 = localRange[0][1];
  50960. var y2 = localRange[1][1];
  50961. var x2a = x2 - handleSize + lineWidth / 2;
  50962. var y2a = y2 - handleSize + lineWidth / 2;
  50963. var width = x2 - x;
  50964. var height = y2 - y;
  50965. var widtha = width + lineWidth;
  50966. var heighta = height + lineWidth;
  50967. updateRectShape(controller, cover, 'main', x, y, width, height);
  50968. if (brushOption.transformable) {
  50969. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  50970. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  50971. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  50972. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  50973. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  50974. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  50975. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  50976. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  50977. }
  50978. }
  50979. function updateCommon(controller, cover) {
  50980. var brushOption = cover.__brushOption;
  50981. var transformable = brushOption.transformable;
  50982. var mainEl = cover.childAt(0);
  50983. mainEl.useStyle(makeStyle(brushOption));
  50984. mainEl.attr({
  50985. silent: !transformable,
  50986. cursor: transformable ? 'move' : 'default'
  50987. });
  50988. each$12(
  50989. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  50990. function (name) {
  50991. var el = cover.childOfName(name);
  50992. var globalDir = getGlobalDirection(controller, name);
  50993. el && el.attr({
  50994. silent: !transformable,
  50995. invisible: !transformable,
  50996. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  50997. });
  50998. }
  50999. );
  51000. }
  51001. function updateRectShape(controller, cover, name, x, y, w, h) {
  51002. var el = cover.childOfName(name);
  51003. el && el.setShape(pointsToRect(
  51004. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51005. ));
  51006. }
  51007. function makeStyle(brushOption) {
  51008. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51009. }
  51010. function formatRectRange(x, y, x2, y2) {
  51011. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  51012. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  51013. return [
  51014. [min[0], max[0]], // x range
  51015. [min[1], max[1]] // y range
  51016. ];
  51017. }
  51018. function getTransform$1(controller) {
  51019. return getTransform(controller.group);
  51020. }
  51021. function getGlobalDirection(controller, localDirection) {
  51022. if (localDirection.length > 1) {
  51023. localDirection = localDirection.split('');
  51024. var globalDir = [
  51025. getGlobalDirection(controller, localDirection[0]),
  51026. getGlobalDirection(controller, localDirection[1])
  51027. ];
  51028. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51029. return globalDir.join('');
  51030. }
  51031. else {
  51032. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  51033. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  51034. var globalDir = transformDirection(
  51035. map$$1[localDirection], getTransform$1(controller)
  51036. );
  51037. return inverseMap[globalDir];
  51038. }
  51039. }
  51040. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  51041. var brushOption = cover.__brushOption;
  51042. var rectRange = toRectRange(brushOption.range);
  51043. var localDelta = toLocalDelta(controller, dx, dy);
  51044. each$12(name.split(''), function (namePart) {
  51045. var ind = DIRECTION_MAP[namePart];
  51046. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51047. });
  51048. brushOption.range = fromRectRange(formatRectRange(
  51049. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  51050. ));
  51051. updateCoverAfterCreation(controller, cover);
  51052. trigger$1(controller, {isEnd: false});
  51053. }
  51054. function driftPolygon(controller, cover, dx, dy, e) {
  51055. var range = cover.__brushOption.range;
  51056. var localDelta = toLocalDelta(controller, dx, dy);
  51057. each$12(range, function (point) {
  51058. point[0] += localDelta[0];
  51059. point[1] += localDelta[1];
  51060. });
  51061. updateCoverAfterCreation(controller, cover);
  51062. trigger$1(controller, {isEnd: false});
  51063. }
  51064. function toLocalDelta(controller, dx, dy) {
  51065. var thisGroup = controller.group;
  51066. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51067. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51068. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51069. }
  51070. function clipByPanel(controller, cover, data) {
  51071. var panel = getPanelByCover(controller, cover);
  51072. return (panel && panel !== true)
  51073. ? panel.clipPath(data, controller._transform)
  51074. : clone(data);
  51075. }
  51076. function pointsToRect(points) {
  51077. var xmin = mathMin$6(points[0][0], points[1][0]);
  51078. var ymin = mathMin$6(points[0][1], points[1][1]);
  51079. var xmax = mathMax$6(points[0][0], points[1][0]);
  51080. var ymax = mathMax$6(points[0][1], points[1][1]);
  51081. return {
  51082. x: xmin,
  51083. y: ymin,
  51084. width: xmax - xmin,
  51085. height: ymax - ymin
  51086. };
  51087. }
  51088. function resetCursor(controller, e, localCursorPoint) {
  51089. // Check active
  51090. if (!controller._brushType) {
  51091. return;
  51092. }
  51093. var zr = controller._zr;
  51094. var covers = controller._covers;
  51095. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51096. // Check whether in covers.
  51097. if (!controller._dragging) {
  51098. for (var i = 0; i < covers.length; i++) {
  51099. var brushOption = covers[i].__brushOption;
  51100. if (currPanel
  51101. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  51102. && coverRenderers[brushOption.brushType].contain(
  51103. covers[i], localCursorPoint[0], localCursorPoint[1]
  51104. )
  51105. ) {
  51106. // Use cursor style set on cover.
  51107. return;
  51108. }
  51109. }
  51110. }
  51111. currPanel && zr.setCursorStyle('crosshair');
  51112. }
  51113. function preventDefault(e) {
  51114. var rawE = e.event;
  51115. rawE.preventDefault && rawE.preventDefault();
  51116. }
  51117. function mainShapeContain(cover, x, y) {
  51118. return cover.childOfName('main').contain(x, y);
  51119. }
  51120. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51121. var creatingCover = controller._creatingCover;
  51122. var panel = controller._creatingPanel;
  51123. var thisBrushOption = controller._brushOption;
  51124. var eventParams;
  51125. controller._track.push(localCursorPoint.slice());
  51126. if (shouldShowCover(controller) || creatingCover) {
  51127. if (panel && !creatingCover) {
  51128. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51129. var brushOption = clone(thisBrushOption);
  51130. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51131. brushOption.panelId = panel === true ? null : panel.panelId;
  51132. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51133. controller._covers.push(creatingCover);
  51134. }
  51135. if (creatingCover) {
  51136. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51137. var coverBrushOption = creatingCover.__brushOption;
  51138. coverBrushOption.range = coverRenderer.getCreatingRange(
  51139. clipByPanel(controller, creatingCover, controller._track)
  51140. );
  51141. if (isEnd) {
  51142. endCreating(controller, creatingCover);
  51143. coverRenderer.updateCommon(controller, creatingCover);
  51144. }
  51145. updateCoverShape(controller, creatingCover);
  51146. eventParams = {isEnd: isEnd};
  51147. }
  51148. }
  51149. else if (
  51150. isEnd
  51151. && thisBrushOption.brushMode === 'single'
  51152. && thisBrushOption.removeOnClick
  51153. ) {
  51154. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51155. // But a single click do not clear covers, because user may have casual
  51156. // clicks (for example, click on other component and do not expect covers
  51157. // disappear).
  51158. // Only some cover removed, trigger action, but not every click trigger action.
  51159. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51160. eventParams = {isEnd: isEnd, removeOnClick: true};
  51161. }
  51162. }
  51163. return eventParams;
  51164. }
  51165. function determineBrushType(brushType, panel) {
  51166. if (brushType === 'auto') {
  51167. if (__DEV__) {
  51168. assert$1(
  51169. panel && panel.defaultBrushType,
  51170. 'MUST have defaultBrushType when brushType is "atuo"'
  51171. );
  51172. }
  51173. return panel.defaultBrushType;
  51174. }
  51175. return brushType;
  51176. }
  51177. var mouseHandlers = {
  51178. mousedown: function (e) {
  51179. if (this._dragging) {
  51180. // In case some browser do not support globalOut,
  51181. // and release mose out side the browser.
  51182. handleDragEnd.call(this, e);
  51183. }
  51184. else if (!e.target || !e.target.draggable) {
  51185. preventDefault(e);
  51186. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51187. this._creatingCover = null;
  51188. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  51189. if (panel) {
  51190. this._dragging = true;
  51191. this._track = [localCursorPoint.slice()];
  51192. }
  51193. }
  51194. },
  51195. mousemove: function (e) {
  51196. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51197. resetCursor(this, e, localCursorPoint);
  51198. if (this._dragging) {
  51199. preventDefault(e);
  51200. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  51201. eventParams && trigger$1(this, eventParams);
  51202. }
  51203. },
  51204. mouseup: handleDragEnd //,
  51205. // FIXME
  51206. // in tooltip, globalout should not be triggered.
  51207. // globalout: handleDragEnd
  51208. };
  51209. function handleDragEnd(e) {
  51210. if (this._dragging) {
  51211. preventDefault(e);
  51212. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51213. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  51214. this._dragging = false;
  51215. this._track = [];
  51216. this._creatingCover = null;
  51217. // trigger event shoule be at final, after procedure will be nested.
  51218. eventParams && trigger$1(this, eventParams);
  51219. }
  51220. }
  51221. /**
  51222. * key: brushType
  51223. * @type {Object}
  51224. */
  51225. var coverRenderers = {
  51226. lineX: getLineRenderer(0),
  51227. lineY: getLineRenderer(1),
  51228. rect: {
  51229. createCover: function (controller, brushOption) {
  51230. return createBaseRectCover(
  51231. curry$2(
  51232. driftRect,
  51233. function (range) {
  51234. return range;
  51235. },
  51236. function (range) {
  51237. return range;
  51238. }
  51239. ),
  51240. controller,
  51241. brushOption,
  51242. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  51243. );
  51244. },
  51245. getCreatingRange: function (localTrack) {
  51246. var ends = getTrackEnds(localTrack);
  51247. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  51248. },
  51249. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51250. updateBaseRect(controller, cover, localRange, brushOption);
  51251. },
  51252. updateCommon: updateCommon,
  51253. contain: mainShapeContain
  51254. },
  51255. polygon: {
  51256. createCover: function (controller, brushOption) {
  51257. var cover = new Group();
  51258. // Do not use graphic.Polygon because graphic.Polyline do not close the
  51259. // border of the shape when drawing, which is a better experience for user.
  51260. cover.add(new Polyline({
  51261. name: 'main',
  51262. style: makeStyle(brushOption),
  51263. silent: true
  51264. }));
  51265. return cover;
  51266. },
  51267. getCreatingRange: function (localTrack) {
  51268. return localTrack;
  51269. },
  51270. endCreating: function (controller, cover) {
  51271. cover.remove(cover.childAt(0));
  51272. // Use graphic.Polygon close the shape.
  51273. cover.add(new Polygon({
  51274. name: 'main',
  51275. draggable: true,
  51276. drift: curry$2(driftPolygon, controller, cover),
  51277. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  51278. }));
  51279. },
  51280. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51281. cover.childAt(0).setShape({
  51282. points: clipByPanel(controller, cover, localRange)
  51283. });
  51284. },
  51285. updateCommon: updateCommon,
  51286. contain: mainShapeContain
  51287. }
  51288. };
  51289. function getLineRenderer(xyIndex) {
  51290. return {
  51291. createCover: function (controller, brushOption) {
  51292. return createBaseRectCover(
  51293. curry$2(
  51294. driftRect,
  51295. function (range) {
  51296. var rectRange = [range, [0, 100]];
  51297. xyIndex && rectRange.reverse();
  51298. return rectRange;
  51299. },
  51300. function (rectRange) {
  51301. return rectRange[xyIndex];
  51302. }
  51303. ),
  51304. controller,
  51305. brushOption,
  51306. [['w', 'e'], ['n', 's']][xyIndex]
  51307. );
  51308. },
  51309. getCreatingRange: function (localTrack) {
  51310. var ends = getTrackEnds(localTrack);
  51311. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  51312. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  51313. return [min, max];
  51314. },
  51315. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51316. var otherExtent;
  51317. // If brushWidth not specified, fit the panel.
  51318. var panel = getPanelByCover(controller, cover);
  51319. if (panel !== true && panel.getLinearBrushOtherExtent) {
  51320. otherExtent = panel.getLinearBrushOtherExtent(
  51321. xyIndex, controller._transform
  51322. );
  51323. }
  51324. else {
  51325. var zr = controller._zr;
  51326. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  51327. }
  51328. var rectRange = [localRange, otherExtent];
  51329. xyIndex && rectRange.reverse();
  51330. updateBaseRect(controller, cover, rectRange, brushOption);
  51331. },
  51332. updateCommon: updateCommon,
  51333. contain: mainShapeContain
  51334. };
  51335. }
  51336. /*
  51337. * Licensed to the Apache Software Foundation (ASF) under one
  51338. * or more contributor license agreements. See the NOTICE file
  51339. * distributed with this work for additional information
  51340. * regarding copyright ownership. The ASF licenses this file
  51341. * to you under the Apache License, Version 2.0 (the
  51342. * "License"); you may not use this file except in compliance
  51343. * with the License. You may obtain a copy of the License at
  51344. *
  51345. * http://www.apache.org/licenses/LICENSE-2.0
  51346. *
  51347. * Unless required by applicable law or agreed to in writing,
  51348. * software distributed under the License is distributed on an
  51349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51350. * KIND, either express or implied. See the License for the
  51351. * specific language governing permissions and limitations
  51352. * under the License.
  51353. */
  51354. function makeRectPanelClipPath(rect) {
  51355. rect = normalizeRect(rect);
  51356. return function (localPoints, transform) {
  51357. return clipPointsByRect(localPoints, rect);
  51358. };
  51359. }
  51360. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  51361. rect = normalizeRect(rect);
  51362. return function (xyIndex) {
  51363. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  51364. var brushWidth = idx ? rect.width : rect.height;
  51365. var base = idx ? rect.x : rect.y;
  51366. return [base, base + (brushWidth || 0)];
  51367. };
  51368. }
  51369. function makeRectIsTargetByCursor(rect, api, targetModel) {
  51370. rect = normalizeRect(rect);
  51371. return function (e, localCursorPoint, transform) {
  51372. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  51373. && !onIrrelevantElement(e, api, targetModel);
  51374. };
  51375. }
  51376. // Consider width/height is negative.
  51377. function normalizeRect(rect) {
  51378. return BoundingRect.create(rect);
  51379. }
  51380. /*
  51381. * Licensed to the Apache Software Foundation (ASF) under one
  51382. * or more contributor license agreements. See the NOTICE file
  51383. * distributed with this work for additional information
  51384. * regarding copyright ownership. The ASF licenses this file
  51385. * to you under the Apache License, Version 2.0 (the
  51386. * "License"); you may not use this file except in compliance
  51387. * with the License. You may obtain a copy of the License at
  51388. *
  51389. * http://www.apache.org/licenses/LICENSE-2.0
  51390. *
  51391. * Unless required by applicable law or agreed to in writing,
  51392. * software distributed under the License is distributed on an
  51393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51394. * KIND, either express or implied. See the License for the
  51395. * specific language governing permissions and limitations
  51396. * under the License.
  51397. */
  51398. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  51399. var AxisView$2 = extendComponentView({
  51400. type: 'parallelAxis',
  51401. /**
  51402. * @override
  51403. */
  51404. init: function (ecModel, api) {
  51405. AxisView$2.superApply(this, 'init', arguments);
  51406. /**
  51407. * @type {module:echarts/component/helper/BrushController}
  51408. */
  51409. (this._brushController = new BrushController(api.getZr()))
  51410. .on('brush', bind(this._onBrush, this));
  51411. },
  51412. /**
  51413. * @override
  51414. */
  51415. render: function (axisModel, ecModel, api, payload) {
  51416. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  51417. return;
  51418. }
  51419. this.axisModel = axisModel;
  51420. this.api = api;
  51421. this.group.removeAll();
  51422. var oldAxisGroup = this._axisGroup;
  51423. this._axisGroup = new Group();
  51424. this.group.add(this._axisGroup);
  51425. if (!axisModel.get('show')) {
  51426. return;
  51427. }
  51428. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  51429. var coordSys = coordSysModel.coordinateSystem;
  51430. var areaSelectStyle = axisModel.getAreaSelectStyle();
  51431. var areaWidth = areaSelectStyle.width;
  51432. var dim = axisModel.axis.dim;
  51433. var axisLayout = coordSys.getAxisLayout(dim);
  51434. var builderOpt = extend(
  51435. {strokeContainThreshold: areaWidth},
  51436. axisLayout
  51437. );
  51438. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  51439. each$1(elementList, axisBuilder.add, axisBuilder);
  51440. this._axisGroup.add(axisBuilder.getGroup());
  51441. this._refreshBrushController(
  51442. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  51443. );
  51444. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  51445. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  51446. },
  51447. // /**
  51448. // * @override
  51449. // */
  51450. // updateVisual: function (axisModel, ecModel, api, payload) {
  51451. // this._brushController && this._brushController
  51452. // .updateCovers(getCoverInfoList(axisModel));
  51453. // },
  51454. _refreshBrushController: function (
  51455. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  51456. ) {
  51457. // After filtering, axis may change, select area needs to be update.
  51458. var extent = axisModel.axis.getExtent();
  51459. var extentLen = extent[1] - extent[0];
  51460. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  51461. // width/height might be negative, which will be
  51462. // normalized in BoundingRect.
  51463. var rect = BoundingRect.create({
  51464. x: extent[0],
  51465. y: -areaWidth / 2,
  51466. width: extentLen,
  51467. height: areaWidth
  51468. });
  51469. rect.x -= extra;
  51470. rect.width += 2 * extra;
  51471. this._brushController
  51472. .mount({
  51473. enableGlobalPan: true,
  51474. rotation: builderOpt.rotation,
  51475. position: builderOpt.position
  51476. })
  51477. .setPanels([{
  51478. panelId: 'pl',
  51479. clipPath: makeRectPanelClipPath(rect),
  51480. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  51481. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  51482. }])
  51483. .enableBrush({
  51484. brushType: 'lineX',
  51485. brushStyle: areaSelectStyle,
  51486. removeOnClick: true
  51487. })
  51488. .updateCovers(getCoverInfoList(axisModel));
  51489. },
  51490. _onBrush: function (coverInfoList, opt) {
  51491. // Do not cache these object, because the mey be changed.
  51492. var axisModel = this.axisModel;
  51493. var axis = axisModel.axis;
  51494. var intervals = map(coverInfoList, function (coverInfo) {
  51495. return [
  51496. axis.coordToData(coverInfo.range[0], true),
  51497. axis.coordToData(coverInfo.range[1], true)
  51498. ];
  51499. });
  51500. // If realtime is true, action is not dispatched on drag end, because
  51501. // the drag end emits the same params with the last drag move event,
  51502. // and may have some delay when using touch pad.
  51503. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  51504. this.api.dispatchAction({
  51505. type: 'axisAreaSelect',
  51506. parallelAxisId: axisModel.id,
  51507. intervals: intervals
  51508. });
  51509. }
  51510. },
  51511. /**
  51512. * @override
  51513. */
  51514. dispose: function () {
  51515. this._brushController.dispose();
  51516. }
  51517. });
  51518. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  51519. return payload
  51520. && payload.type === 'axisAreaSelect'
  51521. && ecModel.findComponents(
  51522. {mainType: 'parallelAxis', query: payload}
  51523. )[0] === axisModel;
  51524. }
  51525. function getCoverInfoList(axisModel) {
  51526. var axis = axisModel.axis;
  51527. return map(axisModel.activeIntervals, function (interval) {
  51528. return {
  51529. brushType: 'lineX',
  51530. panelId: 'pl',
  51531. range: [
  51532. axis.dataToCoord(interval[0], true),
  51533. axis.dataToCoord(interval[1], true)
  51534. ]
  51535. };
  51536. });
  51537. }
  51538. function getCoordSysModel(axisModel, ecModel) {
  51539. return ecModel.getComponent(
  51540. 'parallel', axisModel.get('parallelIndex')
  51541. );
  51542. }
  51543. /*
  51544. * Licensed to the Apache Software Foundation (ASF) under one
  51545. * or more contributor license agreements. See the NOTICE file
  51546. * distributed with this work for additional information
  51547. * regarding copyright ownership. The ASF licenses this file
  51548. * to you under the Apache License, Version 2.0 (the
  51549. * "License"); you may not use this file except in compliance
  51550. * with the License. You may obtain a copy of the License at
  51551. *
  51552. * http://www.apache.org/licenses/LICENSE-2.0
  51553. *
  51554. * Unless required by applicable law or agreed to in writing,
  51555. * software distributed under the License is distributed on an
  51556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51557. * KIND, either express or implied. See the License for the
  51558. * specific language governing permissions and limitations
  51559. * under the License.
  51560. */
  51561. /*
  51562. * Licensed to the Apache Software Foundation (ASF) under one
  51563. * or more contributor license agreements. See the NOTICE file
  51564. * distributed with this work for additional information
  51565. * regarding copyright ownership. The ASF licenses this file
  51566. * to you under the Apache License, Version 2.0 (the
  51567. * "License"); you may not use this file except in compliance
  51568. * with the License. You may obtain a copy of the License at
  51569. *
  51570. * http://www.apache.org/licenses/LICENSE-2.0
  51571. *
  51572. * Unless required by applicable law or agreed to in writing,
  51573. * software distributed under the License is distributed on an
  51574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51575. * KIND, either express or implied. See the License for the
  51576. * specific language governing permissions and limitations
  51577. * under the License.
  51578. */
  51579. var CLICK_THRESHOLD = 5; // > 4
  51580. // Parallel view
  51581. extendComponentView({
  51582. type: 'parallel',
  51583. render: function (parallelModel, ecModel, api) {
  51584. this._model = parallelModel;
  51585. this._api = api;
  51586. if (!this._handlers) {
  51587. this._handlers = {};
  51588. each$1(handlers, function (handler, eventName) {
  51589. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  51590. }, this);
  51591. }
  51592. createOrUpdate(
  51593. this,
  51594. '_throttledDispatchExpand',
  51595. parallelModel.get('axisExpandRate'),
  51596. 'fixRate'
  51597. );
  51598. },
  51599. dispose: function (ecModel, api) {
  51600. each$1(this._handlers, function (handler, eventName) {
  51601. api.getZr().off(eventName, handler);
  51602. });
  51603. this._handlers = null;
  51604. },
  51605. /**
  51606. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  51607. */
  51608. _throttledDispatchExpand: function (opt) {
  51609. this._dispatchExpand(opt);
  51610. },
  51611. _dispatchExpand: function (opt) {
  51612. opt && this._api.dispatchAction(
  51613. extend({type: 'parallelAxisExpand'}, opt)
  51614. );
  51615. }
  51616. });
  51617. var handlers = {
  51618. mousedown: function (e) {
  51619. if (checkTrigger(this, 'click')) {
  51620. this._mouseDownPoint = [e.offsetX, e.offsetY];
  51621. }
  51622. },
  51623. mouseup: function (e) {
  51624. var mouseDownPoint = this._mouseDownPoint;
  51625. if (checkTrigger(this, 'click') && mouseDownPoint) {
  51626. var point = [e.offsetX, e.offsetY];
  51627. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  51628. + Math.pow(mouseDownPoint[1] - point[1], 2);
  51629. if (dist > CLICK_THRESHOLD) {
  51630. return;
  51631. }
  51632. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  51633. [e.offsetX, e.offsetY]
  51634. );
  51635. result.behavior !== 'none' && this._dispatchExpand({
  51636. axisExpandWindow: result.axisExpandWindow
  51637. });
  51638. }
  51639. this._mouseDownPoint = null;
  51640. },
  51641. mousemove: function (e) {
  51642. // Should do nothing when brushing.
  51643. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  51644. return;
  51645. }
  51646. var model = this._model;
  51647. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  51648. [e.offsetX, e.offsetY]
  51649. );
  51650. var behavior = result.behavior;
  51651. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  51652. this._throttledDispatchExpand(
  51653. behavior === 'none'
  51654. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  51655. : {
  51656. axisExpandWindow: result.axisExpandWindow,
  51657. // Jumping uses animation, and sliding suppresses animation.
  51658. animation: behavior === 'jump' ? null : false
  51659. }
  51660. );
  51661. }
  51662. };
  51663. function checkTrigger(view, triggerOn) {
  51664. var model = view._model;
  51665. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  51666. }
  51667. registerPreprocessor(parallelPreprocessor);
  51668. /*
  51669. * Licensed to the Apache Software Foundation (ASF) under one
  51670. * or more contributor license agreements. See the NOTICE file
  51671. * distributed with this work for additional information
  51672. * regarding copyright ownership. The ASF licenses this file
  51673. * to you under the Apache License, Version 2.0 (the
  51674. * "License"); you may not use this file except in compliance
  51675. * with the License. You may obtain a copy of the License at
  51676. *
  51677. * http://www.apache.org/licenses/LICENSE-2.0
  51678. *
  51679. * Unless required by applicable law or agreed to in writing,
  51680. * software distributed under the License is distributed on an
  51681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51682. * KIND, either express or implied. See the License for the
  51683. * specific language governing permissions and limitations
  51684. * under the License.
  51685. */
  51686. SeriesModel.extend({
  51687. type: 'series.parallel',
  51688. dependencies: ['parallel'],
  51689. visualColorAccessPath: 'lineStyle.color',
  51690. getInitialData: function (option, ecModel) {
  51691. var source = this.getSource();
  51692. setEncodeAndDimensions(source, this);
  51693. return createListFromArray(source, this);
  51694. },
  51695. /**
  51696. * User can get data raw indices on 'axisAreaSelected' event received.
  51697. *
  51698. * @public
  51699. * @param {string} activeState 'active' or 'inactive' or 'normal'
  51700. * @return {Array.<number>} Raw indices
  51701. */
  51702. getRawIndicesByActiveState: function (activeState) {
  51703. var coordSys = this.coordinateSystem;
  51704. var data = this.getData();
  51705. var indices = [];
  51706. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  51707. if (activeState === theActiveState) {
  51708. indices.push(data.getRawIndex(dataIndex));
  51709. }
  51710. });
  51711. return indices;
  51712. },
  51713. defaultOption: {
  51714. zlevel: 0, // 一级层叠
  51715. z: 2, // 二级层叠
  51716. coordinateSystem: 'parallel',
  51717. parallelIndex: 0,
  51718. label: {
  51719. show: false
  51720. },
  51721. inactiveOpacity: 0.05,
  51722. activeOpacity: 1,
  51723. lineStyle: {
  51724. width: 1,
  51725. opacity: 0.45,
  51726. type: 'solid'
  51727. },
  51728. emphasis: {
  51729. label: {
  51730. show: false
  51731. }
  51732. },
  51733. progressive: 500,
  51734. smooth: false, // true | false | number
  51735. animationEasing: 'linear'
  51736. }
  51737. });
  51738. function setEncodeAndDimensions(source, seriesModel) {
  51739. // The mapping of parallelAxis dimension to data dimension can
  51740. // be specified in parallelAxis.option.dim. For example, if
  51741. // parallelAxis.option.dim is 'dim3', it mapping to the third
  51742. // dimension of data. But `data.encode` has higher priority.
  51743. // Moreover, parallelModel.dimension should not be regarded as data
  51744. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  51745. if (source.encodeDefine) {
  51746. return;
  51747. }
  51748. var parallelModel = seriesModel.ecModel.getComponent(
  51749. 'parallel', seriesModel.get('parallelIndex')
  51750. );
  51751. if (!parallelModel) {
  51752. return;
  51753. }
  51754. var encodeDefine = source.encodeDefine = createHashMap();
  51755. each$1(parallelModel.dimensions, function (axisDim) {
  51756. var dataDimIndex = convertDimNameToNumber(axisDim);
  51757. encodeDefine.set(axisDim, dataDimIndex);
  51758. });
  51759. }
  51760. function convertDimNameToNumber(dimName) {
  51761. return +dimName.replace('dim', '');
  51762. }
  51763. /*
  51764. * Licensed to the Apache Software Foundation (ASF) under one
  51765. * or more contributor license agreements. See the NOTICE file
  51766. * distributed with this work for additional information
  51767. * regarding copyright ownership. The ASF licenses this file
  51768. * to you under the Apache License, Version 2.0 (the
  51769. * "License"); you may not use this file except in compliance
  51770. * with the License. You may obtain a copy of the License at
  51771. *
  51772. * http://www.apache.org/licenses/LICENSE-2.0
  51773. *
  51774. * Unless required by applicable law or agreed to in writing,
  51775. * software distributed under the License is distributed on an
  51776. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51777. * KIND, either express or implied. See the License for the
  51778. * specific language governing permissions and limitations
  51779. * under the License.
  51780. */
  51781. var DEFAULT_SMOOTH = 0.3;
  51782. var ParallelView = Chart.extend({
  51783. type: 'parallel',
  51784. init: function () {
  51785. /**
  51786. * @type {module:zrender/container/Group}
  51787. * @private
  51788. */
  51789. this._dataGroup = new Group();
  51790. this.group.add(this._dataGroup);
  51791. /**
  51792. * @type {module:echarts/data/List}
  51793. */
  51794. this._data;
  51795. /**
  51796. * @type {boolean}
  51797. */
  51798. this._initialized;
  51799. },
  51800. /**
  51801. * @override
  51802. */
  51803. render: function (seriesModel, ecModel, api, payload) {
  51804. var dataGroup = this._dataGroup;
  51805. var data = seriesModel.getData();
  51806. var oldData = this._data;
  51807. var coordSys = seriesModel.coordinateSystem;
  51808. var dimensions = coordSys.dimensions;
  51809. var seriesScope = makeSeriesScope$2(seriesModel);
  51810. data.diff(oldData)
  51811. .add(add)
  51812. .update(update)
  51813. .remove(remove)
  51814. .execute();
  51815. function add(newDataIndex) {
  51816. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  51817. updateElCommon(line, data, newDataIndex, seriesScope);
  51818. }
  51819. function update(newDataIndex, oldDataIndex) {
  51820. var line = oldData.getItemGraphicEl(oldDataIndex);
  51821. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  51822. data.setItemGraphicEl(newDataIndex, line);
  51823. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  51824. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  51825. updateElCommon(line, data, newDataIndex, seriesScope);
  51826. }
  51827. function remove(oldDataIndex) {
  51828. var line = oldData.getItemGraphicEl(oldDataIndex);
  51829. dataGroup.remove(line);
  51830. }
  51831. // First create
  51832. if (!this._initialized) {
  51833. this._initialized = true;
  51834. var clipPath = createGridClipShape$1(
  51835. coordSys, seriesModel, function () {
  51836. // Callback will be invoked immediately if there is no animation
  51837. setTimeout(function () {
  51838. dataGroup.removeClipPath();
  51839. });
  51840. }
  51841. );
  51842. dataGroup.setClipPath(clipPath);
  51843. }
  51844. this._data = data;
  51845. },
  51846. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51847. this._initialized = true;
  51848. this._data = null;
  51849. this._dataGroup.removeAll();
  51850. },
  51851. incrementalRender: function (taskParams, seriesModel, ecModel) {
  51852. var data = seriesModel.getData();
  51853. var coordSys = seriesModel.coordinateSystem;
  51854. var dimensions = coordSys.dimensions;
  51855. var seriesScope = makeSeriesScope$2(seriesModel);
  51856. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  51857. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  51858. line.incremental = true;
  51859. updateElCommon(line, data, dataIndex, seriesScope);
  51860. }
  51861. },
  51862. dispose: function () {},
  51863. // _renderForProgressive: function (seriesModel) {
  51864. // var dataGroup = this._dataGroup;
  51865. // var data = seriesModel.getData();
  51866. // var oldData = this._data;
  51867. // var coordSys = seriesModel.coordinateSystem;
  51868. // var dimensions = coordSys.dimensions;
  51869. // var option = seriesModel.option;
  51870. // var progressive = option.progressive;
  51871. // var smooth = option.smooth ? SMOOTH : null;
  51872. // // In progressive animation is disabled, so use simple data diff,
  51873. // // which effects performance less.
  51874. // // (Typically performance for data with length 7000+ like:
  51875. // // simpleDiff: 60ms, addEl: 184ms,
  51876. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  51877. // if (simpleDiff(oldData, data, dimensions)) {
  51878. // dataGroup.removeAll();
  51879. // data.each(function (dataIndex) {
  51880. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  51881. // });
  51882. // }
  51883. // updateElCommon(data, progressive, smooth);
  51884. // // Consider switch between progressive and not.
  51885. // data.__plProgressive = true;
  51886. // this._data = data;
  51887. // },
  51888. /**
  51889. * @override
  51890. */
  51891. remove: function () {
  51892. this._dataGroup && this._dataGroup.removeAll();
  51893. this._data = null;
  51894. }
  51895. });
  51896. function createGridClipShape$1(coordSys, seriesModel, cb) {
  51897. var parallelModel = coordSys.model;
  51898. var rect = coordSys.getRect();
  51899. var rectEl = new Rect({
  51900. shape: {
  51901. x: rect.x,
  51902. y: rect.y,
  51903. width: rect.width,
  51904. height: rect.height
  51905. }
  51906. });
  51907. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  51908. rectEl.setShape(dim, 0);
  51909. initProps(rectEl, {
  51910. shape: {
  51911. width: rect.width,
  51912. height: rect.height
  51913. }
  51914. }, seriesModel, cb);
  51915. return rectEl;
  51916. }
  51917. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  51918. var points = [];
  51919. for (var i = 0; i < dimensions.length; i++) {
  51920. var dimName = dimensions[i];
  51921. var value = data.get(data.mapDimension(dimName), dataIndex);
  51922. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  51923. points.push(coordSys.dataToPoint(value, dimName));
  51924. }
  51925. }
  51926. return points;
  51927. }
  51928. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  51929. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  51930. var line = new Polyline({
  51931. shape: {points: points},
  51932. silent: true,
  51933. z2: 10
  51934. });
  51935. dataGroup.add(line);
  51936. data.setItemGraphicEl(dataIndex, line);
  51937. return line;
  51938. }
  51939. function makeSeriesScope$2(seriesModel) {
  51940. var smooth = seriesModel.get('smooth', true);
  51941. smooth === true && (smooth = DEFAULT_SMOOTH);
  51942. return {
  51943. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  51944. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  51945. };
  51946. }
  51947. function updateElCommon(el, data, dataIndex, seriesScope) {
  51948. var lineStyle = seriesScope.lineStyle;
  51949. if (data.hasItemOption) {
  51950. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  51951. lineStyle = lineStyleModel.getLineStyle();
  51952. }
  51953. el.useStyle(lineStyle);
  51954. var elStyle = el.style;
  51955. elStyle.fill = null;
  51956. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  51957. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  51958. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  51959. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  51960. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  51961. }
  51962. // function simpleDiff(oldData, newData, dimensions) {
  51963. // var oldLen;
  51964. // if (!oldData
  51965. // || !oldData.__plProgressive
  51966. // || (oldLen = oldData.count()) !== newData.count()
  51967. // ) {
  51968. // return true;
  51969. // }
  51970. // var dimLen = dimensions.length;
  51971. // for (var i = 0; i < oldLen; i++) {
  51972. // for (var j = 0; j < dimLen; j++) {
  51973. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  51974. // return true;
  51975. // }
  51976. // }
  51977. // }
  51978. // return false;
  51979. // }
  51980. // FIXME
  51981. // 公用方法?
  51982. function isEmptyValue(val, axisType) {
  51983. return axisType === 'category'
  51984. ? val == null
  51985. : (val == null || isNaN(val)); // axisType === 'value'
  51986. }
  51987. /*
  51988. * Licensed to the Apache Software Foundation (ASF) under one
  51989. * or more contributor license agreements. See the NOTICE file
  51990. * distributed with this work for additional information
  51991. * regarding copyright ownership. The ASF licenses this file
  51992. * to you under the Apache License, Version 2.0 (the
  51993. * "License"); you may not use this file except in compliance
  51994. * with the License. You may obtain a copy of the License at
  51995. *
  51996. * http://www.apache.org/licenses/LICENSE-2.0
  51997. *
  51998. * Unless required by applicable law or agreed to in writing,
  51999. * software distributed under the License is distributed on an
  52000. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52001. * KIND, either express or implied. See the License for the
  52002. * specific language governing permissions and limitations
  52003. * under the License.
  52004. */
  52005. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  52006. var parallelVisual = {
  52007. seriesType: 'parallel',
  52008. reset: function (seriesModel, ecModel, api) {
  52009. var itemStyleModel = seriesModel.getModel('itemStyle');
  52010. var lineStyleModel = seriesModel.getModel('lineStyle');
  52011. var globalColors = ecModel.get('color');
  52012. var color = lineStyleModel.get('color')
  52013. || itemStyleModel.get('color')
  52014. || globalColors[seriesModel.seriesIndex % globalColors.length];
  52015. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  52016. var activeOpacity = seriesModel.get('activeOpacity');
  52017. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  52018. var coordSys = seriesModel.coordinateSystem;
  52019. var data = seriesModel.getData();
  52020. var opacityMap = {
  52021. normal: lineStyle.opacity,
  52022. active: activeOpacity,
  52023. inactive: inactiveOpacity
  52024. };
  52025. data.setVisual('color', color);
  52026. function progress(params, data) {
  52027. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  52028. var opacity = opacityMap[activeState];
  52029. if (activeState === 'normal' && data.hasItemOption) {
  52030. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  52031. itemOpacity != null && (opacity = itemOpacity);
  52032. }
  52033. data.setItemVisual(dataIndex, 'opacity', opacity);
  52034. }, params.start, params.end);
  52035. }
  52036. return {progress: progress};
  52037. }
  52038. };
  52039. /*
  52040. * Licensed to the Apache Software Foundation (ASF) under one
  52041. * or more contributor license agreements. See the NOTICE file
  52042. * distributed with this work for additional information
  52043. * regarding copyright ownership. The ASF licenses this file
  52044. * to you under the Apache License, Version 2.0 (the
  52045. * "License"); you may not use this file except in compliance
  52046. * with the License. You may obtain a copy of the License at
  52047. *
  52048. * http://www.apache.org/licenses/LICENSE-2.0
  52049. *
  52050. * Unless required by applicable law or agreed to in writing,
  52051. * software distributed under the License is distributed on an
  52052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52053. * KIND, either express or implied. See the License for the
  52054. * specific language governing permissions and limitations
  52055. * under the License.
  52056. */
  52057. registerVisual(parallelVisual);
  52058. /*
  52059. * Licensed to the Apache Software Foundation (ASF) under one
  52060. * or more contributor license agreements. See the NOTICE file
  52061. * distributed with this work for additional information
  52062. * regarding copyright ownership. The ASF licenses this file
  52063. * to you under the Apache License, Version 2.0 (the
  52064. * "License"); you may not use this file except in compliance
  52065. * with the License. You may obtain a copy of the License at
  52066. *
  52067. * http://www.apache.org/licenses/LICENSE-2.0
  52068. *
  52069. * Unless required by applicable law or agreed to in writing,
  52070. * software distributed under the License is distributed on an
  52071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52072. * KIND, either express or implied. See the License for the
  52073. * specific language governing permissions and limitations
  52074. * under the License.
  52075. */
  52076. /**
  52077. * @file Get initial data and define sankey view's series model
  52078. * @author Deqing Li(annong035@gmail.com)
  52079. */
  52080. var SankeySeries = SeriesModel.extend({
  52081. type: 'series.sankey',
  52082. layoutInfo: null,
  52083. /**
  52084. * Init a graph data structure from data in option series
  52085. *
  52086. * @param {Object} option the object used to config echarts view
  52087. * @return {module:echarts/data/List} storage initial data
  52088. */
  52089. getInitialData: function (option) {
  52090. var links = option.edges || option.links;
  52091. var nodes = option.data || option.nodes;
  52092. if (nodes && links) {
  52093. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  52094. return graph.data;
  52095. }
  52096. },
  52097. setNodePosition: function (dataIndex, localPosition) {
  52098. var dataItem = this.option.data[dataIndex];
  52099. dataItem.localX = localPosition[0];
  52100. dataItem.localY = localPosition[1];
  52101. },
  52102. /**
  52103. * Return the graphic data structure
  52104. *
  52105. * @return {module:echarts/data/Graph} graphic data structure
  52106. */
  52107. getGraph: function () {
  52108. return this.getData().graph;
  52109. },
  52110. /**
  52111. * Get edge data of graphic data structure
  52112. *
  52113. * @return {module:echarts/data/List} data structure of list
  52114. */
  52115. getEdgeData: function () {
  52116. return this.getGraph().edgeData;
  52117. },
  52118. /**
  52119. * @override
  52120. */
  52121. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  52122. // dataType === 'node' or empty do not show tooltip by default
  52123. if (dataType === 'edge') {
  52124. var params = this.getDataParams(dataIndex, dataType);
  52125. var rawDataOpt = params.data;
  52126. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  52127. if (params.value) {
  52128. html += ' : ' + params.value;
  52129. }
  52130. return encodeHTML(html);
  52131. }
  52132. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  52133. },
  52134. optionUpdated: function () {
  52135. var option = this.option;
  52136. if (option.focusNodeAdjacency === true) {
  52137. option.focusNodeAdjacency = 'allEdges';
  52138. }
  52139. },
  52140. defaultOption: {
  52141. zlevel: 0,
  52142. z: 2,
  52143. coordinateSystem: 'view',
  52144. layout: null,
  52145. // The position of the whole view
  52146. left: '5%',
  52147. top: '5%',
  52148. right: '20%',
  52149. bottom: '5%',
  52150. // Value can be 'vertical'
  52151. orient: 'horizontal',
  52152. // The dx of the node
  52153. nodeWidth: 20,
  52154. // The vertical distance between two nodes
  52155. nodeGap: 8,
  52156. // Control if the node can move or not
  52157. draggable: true,
  52158. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  52159. focusNodeAdjacency: false,
  52160. // The number of iterations to change the position of the node
  52161. layoutIterations: 32,
  52162. label: {
  52163. show: true,
  52164. position: 'right',
  52165. color: '#000',
  52166. fontSize: 12
  52167. },
  52168. itemStyle: {
  52169. borderWidth: 1,
  52170. borderColor: '#333'
  52171. },
  52172. lineStyle: {
  52173. color: '#314656',
  52174. opacity: 0.2,
  52175. curveness: 0.5
  52176. },
  52177. emphasis: {
  52178. label: {
  52179. show: true
  52180. },
  52181. lineStyle: {
  52182. opacity: 0.6
  52183. }
  52184. },
  52185. animationEasing: 'linear',
  52186. animationDuration: 1000
  52187. }
  52188. });
  52189. /*
  52190. * Licensed to the Apache Software Foundation (ASF) under one
  52191. * or more contributor license agreements. See the NOTICE file
  52192. * distributed with this work for additional information
  52193. * regarding copyright ownership. The ASF licenses this file
  52194. * to you under the Apache License, Version 2.0 (the
  52195. * "License"); you may not use this file except in compliance
  52196. * with the License. You may obtain a copy of the License at
  52197. *
  52198. * http://www.apache.org/licenses/LICENSE-2.0
  52199. *
  52200. * Unless required by applicable law or agreed to in writing,
  52201. * software distributed under the License is distributed on an
  52202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52203. * KIND, either express or implied. See the License for the
  52204. * specific language governing permissions and limitations
  52205. * under the License.
  52206. */
  52207. /**
  52208. * @file The file used to draw sankey view
  52209. * @author Deqing Li(annong035@gmail.com)
  52210. */
  52211. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  52212. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  52213. function getItemOpacity$1(item, opacityPath) {
  52214. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  52215. }
  52216. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  52217. var el = item.getGraphicEl();
  52218. var opacity = getItemOpacity$1(item, opacityPath);
  52219. if (opacityRatio != null) {
  52220. opacity == null && (opacity = 1);
  52221. opacity *= opacityRatio;
  52222. }
  52223. el.downplay && el.downplay();
  52224. el.traverse(function (child) {
  52225. if (child.type !== 'group') {
  52226. child.setStyle('opacity', opacity);
  52227. }
  52228. });
  52229. }
  52230. function fadeInItem$1(item, opacityPath) {
  52231. var opacity = getItemOpacity$1(item, opacityPath);
  52232. var el = item.getGraphicEl();
  52233. el.highlight && el.highlight();
  52234. el.traverse(function (child) {
  52235. if (child.type !== 'group') {
  52236. child.setStyle('opacity', opacity);
  52237. }
  52238. });
  52239. }
  52240. var SankeyShape = extendShape({
  52241. shape: {
  52242. x1: 0, y1: 0,
  52243. x2: 0, y2: 0,
  52244. cpx1: 0, cpy1: 0,
  52245. cpx2: 0, cpy2: 0,
  52246. extent: 0,
  52247. orient: ''
  52248. },
  52249. buildPath: function (ctx, shape) {
  52250. var extent = shape.extent;
  52251. var orient = shape.orient;
  52252. if (orient === 'vertical') {
  52253. ctx.moveTo(shape.x1, shape.y1);
  52254. ctx.bezierCurveTo(
  52255. shape.cpx1, shape.cpy1,
  52256. shape.cpx2, shape.cpy2,
  52257. shape.x2, shape.y2
  52258. );
  52259. ctx.lineTo(shape.x2 + extent, shape.y2);
  52260. ctx.bezierCurveTo(
  52261. shape.cpx2 + extent, shape.cpy2,
  52262. shape.cpx1 + extent, shape.cpy1,
  52263. shape.x1 + extent, shape.y1
  52264. );
  52265. }
  52266. else {
  52267. ctx.moveTo(shape.x1, shape.y1);
  52268. ctx.bezierCurveTo(
  52269. shape.cpx1, shape.cpy1,
  52270. shape.cpx2, shape.cpy2,
  52271. shape.x2, shape.y2
  52272. );
  52273. ctx.lineTo(shape.x2, shape.y2 + extent);
  52274. ctx.bezierCurveTo(
  52275. shape.cpx2, shape.cpy2 + extent,
  52276. shape.cpx1, shape.cpy1 + extent,
  52277. shape.x1, shape.y1 + extent
  52278. );
  52279. }
  52280. ctx.closePath();
  52281. }
  52282. });
  52283. extendChartView({
  52284. type: 'sankey',
  52285. /**
  52286. * @private
  52287. * @type {module:echarts/chart/sankey/SankeySeries}
  52288. */
  52289. _model: null,
  52290. /**
  52291. * @private
  52292. * @type {boolean}
  52293. */
  52294. _focusAdjacencyDisabled: false,
  52295. render: function (seriesModel, ecModel, api) {
  52296. var sankeyView = this;
  52297. var graph = seriesModel.getGraph();
  52298. var group = this.group;
  52299. var layoutInfo = seriesModel.layoutInfo;
  52300. // view width
  52301. var width = layoutInfo.width;
  52302. // view height
  52303. var height = layoutInfo.height;
  52304. var nodeData = seriesModel.getData();
  52305. var edgeData = seriesModel.getData('edge');
  52306. var orient = seriesModel.get('orient');
  52307. this._model = seriesModel;
  52308. group.removeAll();
  52309. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  52310. // generate a bezire Curve for each edge
  52311. graph.eachEdge(function (edge) {
  52312. var curve = new SankeyShape();
  52313. curve.dataIndex = edge.dataIndex;
  52314. curve.seriesIndex = seriesModel.seriesIndex;
  52315. curve.dataType = 'edge';
  52316. var lineStyleModel = edge.getModel('lineStyle');
  52317. var curvature = lineStyleModel.get('curveness');
  52318. var n1Layout = edge.node1.getLayout();
  52319. var node1Model = edge.node1.getModel();
  52320. var dragX1 = node1Model.get('localX');
  52321. var dragY1 = node1Model.get('localY');
  52322. var n2Layout = edge.node2.getLayout();
  52323. var node2Model = edge.node2.getModel();
  52324. var dragX2 = node2Model.get('localX');
  52325. var dragY2 = node2Model.get('localY');
  52326. var edgeLayout = edge.getLayout();
  52327. var x1;
  52328. var y1;
  52329. var x2;
  52330. var y2;
  52331. var cpx1;
  52332. var cpy1;
  52333. var cpx2;
  52334. var cpy2;
  52335. curve.shape.extent = Math.max(1, edgeLayout.dy);
  52336. curve.shape.orient = orient;
  52337. if (orient === 'vertical') {
  52338. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  52339. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  52340. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  52341. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  52342. cpx1 = x1;
  52343. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  52344. cpx2 = x2;
  52345. cpy2 = y1 * curvature + y2 * (1 - curvature);
  52346. }
  52347. else {
  52348. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  52349. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  52350. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  52351. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  52352. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  52353. cpy1 = y1;
  52354. cpx2 = x1 * curvature + x2 * (1 - curvature);
  52355. cpy2 = y2;
  52356. }
  52357. curve.setShape({
  52358. x1: x1,
  52359. y1: y1,
  52360. x2: x2,
  52361. y2: y2,
  52362. cpx1: cpx1,
  52363. cpy1: cpy1,
  52364. cpx2: cpx2,
  52365. cpy2: cpy2
  52366. });
  52367. curve.setStyle(lineStyleModel.getItemStyle());
  52368. // Special color, use source node color or target node color
  52369. switch (curve.style.fill) {
  52370. case 'source':
  52371. curve.style.fill = edge.node1.getVisual('color');
  52372. break;
  52373. case 'target':
  52374. curve.style.fill = edge.node2.getVisual('color');
  52375. break;
  52376. }
  52377. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  52378. group.add(curve);
  52379. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  52380. });
  52381. // Generate a rect for each node
  52382. graph.eachNode(function (node) {
  52383. var layout = node.getLayout();
  52384. var itemModel = node.getModel();
  52385. var dragX = itemModel.get('localX');
  52386. var dragY = itemModel.get('localY');
  52387. var labelModel = itemModel.getModel('label');
  52388. var labelHoverModel = itemModel.getModel('emphasis.label');
  52389. var rect = new Rect({
  52390. shape: {
  52391. x: dragX != null ? dragX * width : layout.x,
  52392. y: dragY != null ? dragY * height : layout.y,
  52393. width: layout.dx,
  52394. height: layout.dy
  52395. },
  52396. style: itemModel.getModel('itemStyle').getItemStyle()
  52397. });
  52398. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  52399. setLabelStyle(
  52400. rect.style, hoverStyle, labelModel, labelHoverModel,
  52401. {
  52402. labelFetcher: seriesModel,
  52403. labelDataIndex: node.dataIndex,
  52404. defaultText: node.id,
  52405. isRectText: true
  52406. }
  52407. );
  52408. rect.setStyle('fill', node.getVisual('color'));
  52409. setHoverStyle(rect, hoverStyle);
  52410. group.add(rect);
  52411. nodeData.setItemGraphicEl(node.dataIndex, rect);
  52412. rect.dataType = 'node';
  52413. });
  52414. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  52415. var itemModel = nodeData.getItemModel(dataIndex);
  52416. if (itemModel.get('draggable')) {
  52417. el.drift = function (dx, dy) {
  52418. sankeyView._focusAdjacencyDisabled = true;
  52419. this.shape.x += dx;
  52420. this.shape.y += dy;
  52421. this.dirty();
  52422. api.dispatchAction({
  52423. type: 'dragNode',
  52424. seriesId: seriesModel.id,
  52425. dataIndex: nodeData.getRawIndex(dataIndex),
  52426. localX: this.shape.x / width,
  52427. localY: this.shape.y / height
  52428. });
  52429. };
  52430. el.ondragend = function () {
  52431. sankeyView._focusAdjacencyDisabled = false;
  52432. };
  52433. el.draggable = true;
  52434. el.cursor = 'move';
  52435. }
  52436. if (itemModel.get('focusNodeAdjacency')) {
  52437. el.off('mouseover').on('mouseover', function () {
  52438. if (!sankeyView._focusAdjacencyDisabled) {
  52439. api.dispatchAction({
  52440. type: 'focusNodeAdjacency',
  52441. seriesId: seriesModel.id,
  52442. dataIndex: el.dataIndex
  52443. });
  52444. }
  52445. });
  52446. el.off('mouseout').on('mouseout', function () {
  52447. if (!sankeyView._focusAdjacencyDisabled) {
  52448. api.dispatchAction({
  52449. type: 'unfocusNodeAdjacency',
  52450. seriesId: seriesModel.id
  52451. });
  52452. }
  52453. });
  52454. }
  52455. });
  52456. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  52457. var edgeModel = edgeData.getItemModel(dataIndex);
  52458. if (edgeModel.get('focusNodeAdjacency')) {
  52459. el.off('mouseover').on('mouseover', function () {
  52460. if (!sankeyView._focusAdjacencyDisabled) {
  52461. api.dispatchAction({
  52462. type: 'focusNodeAdjacency',
  52463. seriesId: seriesModel.id,
  52464. edgeDataIndex: el.dataIndex
  52465. });
  52466. }
  52467. });
  52468. el.off('mouseout').on('mouseout', function () {
  52469. if (!sankeyView._focusAdjacencyDisabled) {
  52470. api.dispatchAction({
  52471. type: 'unfocusNodeAdjacency',
  52472. seriesId: seriesModel.id
  52473. });
  52474. }
  52475. });
  52476. }
  52477. });
  52478. if (!this._data && seriesModel.get('animation')) {
  52479. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  52480. group.removeClipPath();
  52481. }));
  52482. }
  52483. this._data = seriesModel.getData();
  52484. },
  52485. dispose: function () {},
  52486. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52487. var data = this._model.getData();
  52488. var graph = data.graph;
  52489. var dataIndex = payload.dataIndex;
  52490. var itemModel = data.getItemModel(dataIndex);
  52491. var edgeDataIndex = payload.edgeDataIndex;
  52492. if (dataIndex == null && edgeDataIndex == null) {
  52493. return;
  52494. }
  52495. var node = graph.getNodeByIndex(dataIndex);
  52496. var edge = graph.getEdgeByIndex(edgeDataIndex);
  52497. graph.eachNode(function (node) {
  52498. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  52499. });
  52500. graph.eachEdge(function (edge) {
  52501. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  52502. });
  52503. if (node) {
  52504. fadeInItem$1(node, nodeOpacityPath$1);
  52505. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  52506. if (focusNodeAdj === 'outEdges') {
  52507. each$1(node.outEdges, function (edge) {
  52508. if (edge.dataIndex < 0) {
  52509. return;
  52510. }
  52511. fadeInItem$1(edge, lineOpacityPath$1);
  52512. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52513. });
  52514. }
  52515. else if (focusNodeAdj === 'inEdges') {
  52516. each$1(node.inEdges, function (edge) {
  52517. if (edge.dataIndex < 0) {
  52518. return;
  52519. }
  52520. fadeInItem$1(edge, lineOpacityPath$1);
  52521. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52522. });
  52523. }
  52524. else if (focusNodeAdj === 'allEdges') {
  52525. each$1(node.edges, function (edge) {
  52526. if (edge.dataIndex < 0) {
  52527. return;
  52528. }
  52529. fadeInItem$1(edge, lineOpacityPath$1);
  52530. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52531. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52532. });
  52533. }
  52534. }
  52535. if (edge) {
  52536. fadeInItem$1(edge, lineOpacityPath$1);
  52537. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52538. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52539. }
  52540. },
  52541. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52542. var graph = this._model.getGraph();
  52543. graph.eachNode(function (node) {
  52544. fadeOutItem$1(node, nodeOpacityPath$1);
  52545. });
  52546. graph.eachEdge(function (edge) {
  52547. fadeOutItem$1(edge, lineOpacityPath$1);
  52548. });
  52549. }
  52550. });
  52551. // Add animation to the view
  52552. function createGridClipShape$2(rect, seriesModel, cb) {
  52553. var rectEl = new Rect({
  52554. shape: {
  52555. x: rect.x - 10,
  52556. y: rect.y - 10,
  52557. width: 0,
  52558. height: rect.height + 20
  52559. }
  52560. });
  52561. initProps(rectEl, {
  52562. shape: {
  52563. width: rect.width + 20,
  52564. height: rect.height + 20
  52565. }
  52566. }, seriesModel, cb);
  52567. return rectEl;
  52568. }
  52569. /*
  52570. * Licensed to the Apache Software Foundation (ASF) under one
  52571. * or more contributor license agreements. See the NOTICE file
  52572. * distributed with this work for additional information
  52573. * regarding copyright ownership. The ASF licenses this file
  52574. * to you under the Apache License, Version 2.0 (the
  52575. * "License"); you may not use this file except in compliance
  52576. * with the License. You may obtain a copy of the License at
  52577. *
  52578. * http://www.apache.org/licenses/LICENSE-2.0
  52579. *
  52580. * Unless required by applicable law or agreed to in writing,
  52581. * software distributed under the License is distributed on an
  52582. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52583. * KIND, either express or implied. See the License for the
  52584. * specific language governing permissions and limitations
  52585. * under the License.
  52586. */
  52587. /**
  52588. * @file The interactive action of sankey view
  52589. * @author Deqing Li(annong035@gmail.com)
  52590. */
  52591. registerAction({
  52592. type: 'dragNode',
  52593. event: 'dragNode',
  52594. // here can only use 'update' now, other value is not support in echarts.
  52595. update: 'update'
  52596. }, function (payload, ecModel) {
  52597. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  52598. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  52599. });
  52600. });
  52601. /*
  52602. * Licensed to the Apache Software Foundation (ASF) under one
  52603. * or more contributor license agreements. See the NOTICE file
  52604. * distributed with this work for additional information
  52605. * regarding copyright ownership. The ASF licenses this file
  52606. * to you under the Apache License, Version 2.0 (the
  52607. * "License"); you may not use this file except in compliance
  52608. * with the License. You may obtain a copy of the License at
  52609. *
  52610. * http://www.apache.org/licenses/LICENSE-2.0
  52611. *
  52612. * Unless required by applicable law or agreed to in writing,
  52613. * software distributed under the License is distributed on an
  52614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52615. * KIND, either express or implied. See the License for the
  52616. * specific language governing permissions and limitations
  52617. * under the License.
  52618. */
  52619. /*
  52620. * The implementation references to d3.js. The use of the source
  52621. * code of this file is also subject to the terms and consitions
  52622. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  52623. */
  52624. /**
  52625. * nest helper used to group by the array.
  52626. * can specified the keys and sort the keys.
  52627. */
  52628. function nest() {
  52629. var keysFunction = [];
  52630. var sortKeysFunction = [];
  52631. /**
  52632. * map an Array into the mapObject.
  52633. * @param {Array} array
  52634. * @param {number} depth
  52635. */
  52636. function map$$1(array, depth) {
  52637. if (depth >= keysFunction.length) {
  52638. return array;
  52639. }
  52640. var i = -1;
  52641. var n = array.length;
  52642. var keyFunction = keysFunction[depth++];
  52643. var mapObject = {};
  52644. var valuesByKey = {};
  52645. while (++i < n) {
  52646. var keyValue = keyFunction(array[i]);
  52647. var values = valuesByKey[keyValue];
  52648. if (values) {
  52649. values.push(array[i]);
  52650. }
  52651. else {
  52652. valuesByKey[keyValue] = [array[i]];
  52653. }
  52654. }
  52655. each$1(valuesByKey, function (value, key) {
  52656. mapObject[key] = map$$1(value, depth);
  52657. });
  52658. return mapObject;
  52659. }
  52660. /**
  52661. * transform the Map Object to multidimensional Array
  52662. * @param {Object} map
  52663. * @param {number} depth
  52664. */
  52665. function entriesMap(mapObject, depth) {
  52666. if (depth >= keysFunction.length) {
  52667. return mapObject;
  52668. }
  52669. var array = [];
  52670. var sortKeyFunction = sortKeysFunction[depth++];
  52671. each$1(mapObject, function (value, key) {
  52672. array.push({
  52673. key: key, values: entriesMap(value, depth)
  52674. });
  52675. });
  52676. if (sortKeyFunction) {
  52677. return array.sort(function (a, b) {
  52678. return sortKeyFunction(a.key, b.key);
  52679. });
  52680. }
  52681. return array;
  52682. }
  52683. return {
  52684. /**
  52685. * specified the key to groupby the arrays.
  52686. * users can specified one more keys.
  52687. * @param {Function} d
  52688. */
  52689. key: function (d) {
  52690. keysFunction.push(d);
  52691. return this;
  52692. },
  52693. /**
  52694. * specified the comparator to sort the keys
  52695. * @param {Function} order
  52696. */
  52697. sortKeys: function (order) {
  52698. sortKeysFunction[keysFunction.length - 1] = order;
  52699. return this;
  52700. },
  52701. /**
  52702. * the array to be grouped by.
  52703. * @param {Array} array
  52704. */
  52705. entries: function (array) {
  52706. return entriesMap(map$$1(array, 0), 0);
  52707. }
  52708. };
  52709. }
  52710. /*
  52711. * Licensed to the Apache Software Foundation (ASF) under one
  52712. * or more contributor license agreements. See the NOTICE file
  52713. * distributed with this work for additional information
  52714. * regarding copyright ownership. The ASF licenses this file
  52715. * to you under the Apache License, Version 2.0 (the
  52716. * "License"); you may not use this file except in compliance
  52717. * with the License. You may obtain a copy of the License at
  52718. *
  52719. * http://www.apache.org/licenses/LICENSE-2.0
  52720. *
  52721. * Unless required by applicable law or agreed to in writing,
  52722. * software distributed under the License is distributed on an
  52723. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52724. * KIND, either express or implied. See the License for the
  52725. * specific language governing permissions and limitations
  52726. * under the License.
  52727. */
  52728. /**
  52729. * @file The layout algorithm of sankey view
  52730. * @author Deqing Li(annong035@gmail.com)
  52731. */
  52732. var sankeyLayout = function (ecModel, api, payload) {
  52733. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  52734. var nodeWidth = seriesModel.get('nodeWidth');
  52735. var nodeGap = seriesModel.get('nodeGap');
  52736. var layoutInfo = getViewRect$3(seriesModel, api);
  52737. seriesModel.layoutInfo = layoutInfo;
  52738. var width = layoutInfo.width;
  52739. var height = layoutInfo.height;
  52740. var graph = seriesModel.getGraph();
  52741. var nodes = graph.nodes;
  52742. var edges = graph.edges;
  52743. computeNodeValues(nodes);
  52744. var filteredNodes = filter(nodes, function (node) {
  52745. return node.getLayout().value === 0;
  52746. });
  52747. var iterations = filteredNodes.length !== 0
  52748. ? 0 : seriesModel.get('layoutIterations');
  52749. var orient = seriesModel.get('orient');
  52750. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient);
  52751. });
  52752. };
  52753. /**
  52754. * Get the layout position of the whole view
  52755. *
  52756. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  52757. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  52758. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  52759. */
  52760. function getViewRect$3(seriesModel, api) {
  52761. return getLayoutRect(
  52762. seriesModel.getBoxLayoutParams(), {
  52763. width: api.getWidth(),
  52764. height: api.getHeight()
  52765. }
  52766. );
  52767. }
  52768. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient) {
  52769. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient);
  52770. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  52771. computeEdgeDepths(nodes, orient);
  52772. }
  52773. /**
  52774. * Compute the value of each node by summing the associated edge's value
  52775. *
  52776. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52777. */
  52778. function computeNodeValues(nodes) {
  52779. each$1(nodes, function (node) {
  52780. var value1 = sum(node.outEdges, getEdgeValue);
  52781. var value2 = sum(node.inEdges, getEdgeValue);
  52782. var value = Math.max(value1, value2);
  52783. node.setLayout({value: value}, true);
  52784. });
  52785. }
  52786. /**
  52787. * Compute the x-position for each node.
  52788. *
  52789. * Here we use Kahn algorithm to detect cycle when we traverse
  52790. * the node to computer the initial x position.
  52791. *
  52792. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52793. * @param {number} nodeWidth the dx of the node
  52794. * @param {number} width the whole width of the area to draw the view
  52795. */
  52796. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient) {
  52797. // Used to mark whether the edge is deleted. if it is deleted,
  52798. // the value is 0, otherwise it is 1.
  52799. var remainEdges = [];
  52800. // Storage each node's indegree.
  52801. var indegreeArr = [];
  52802. //Used to storage the node with indegree is equal to 0.
  52803. var zeroIndegrees = [];
  52804. var nextNode = [];
  52805. var x = 0;
  52806. var kx = 0;
  52807. for (var i = 0; i < edges.length; i++) {
  52808. remainEdges[i] = 1;
  52809. }
  52810. for (i = 0; i < nodes.length; i++) {
  52811. indegreeArr[i] = nodes[i].inEdges.length;
  52812. if (indegreeArr[i] === 0) {
  52813. zeroIndegrees.push(nodes[i]);
  52814. }
  52815. }
  52816. while (zeroIndegrees.length) {
  52817. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  52818. var node = zeroIndegrees[idx];
  52819. if (orient === 'vertical') {
  52820. node.setLayout({y: x}, true);
  52821. node.setLayout({dy: nodeWidth}, true);
  52822. }
  52823. else {
  52824. node.setLayout({x: x}, true);
  52825. node.setLayout({dx: nodeWidth}, true);
  52826. }
  52827. for (var oidx = 0; oidx < node.outEdges.length; oidx++) {
  52828. var edge = node.outEdges[oidx];
  52829. var indexEdge = edges.indexOf(edge);
  52830. remainEdges[indexEdge] = 0;
  52831. var targetNode = edge.node2;
  52832. var nodeIndex = nodes.indexOf(targetNode);
  52833. if (--indegreeArr[nodeIndex] === 0) {
  52834. nextNode.push(targetNode);
  52835. }
  52836. }
  52837. }
  52838. ++x;
  52839. zeroIndegrees = nextNode;
  52840. nextNode = [];
  52841. }
  52842. for (i = 0; i < remainEdges.length; i++) {
  52843. if (__DEV__) {
  52844. if (remainEdges[i] === 1) {
  52845. throw new Error('Sankey is a DAG, the original data has cycle!');
  52846. }
  52847. }
  52848. }
  52849. moveSinksRight(nodes, x, orient);
  52850. if (orient === 'vertical') {
  52851. kx = (height - nodeWidth) / (x - 1);
  52852. }
  52853. else {
  52854. kx = (width - nodeWidth) / (x - 1);
  52855. }
  52856. scaleNodeBreadths(nodes, kx, orient);
  52857. }
  52858. /**
  52859. * All the node without outEgdes are assigned maximum x-position and
  52860. * be aligned in the last column.
  52861. *
  52862. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52863. * @param {number} x value (x-1) use to assign to node without outEdges
  52864. * as x-position
  52865. */
  52866. function moveSinksRight(nodes, x, orient) {
  52867. each$1(nodes, function (node) {
  52868. if (!node.outEdges.length) {
  52869. if (orient === 'vertical') {
  52870. node.setLayout({y: x - 1}, true);
  52871. }
  52872. else {
  52873. node.setLayout({x: x - 1}, true);
  52874. }
  52875. }
  52876. });
  52877. }
  52878. /**
  52879. * Scale node x-position to the width
  52880. *
  52881. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52882. * @param {number} kx multiple used to scale nodes
  52883. */
  52884. function scaleNodeBreadths(nodes, kx, orient) {
  52885. each$1(nodes, function (node) {
  52886. if (orient === 'vertical') {
  52887. var nodeY = node.getLayout().y * kx;
  52888. node.setLayout({y: nodeY}, true);
  52889. }
  52890. else {
  52891. var nodeX = node.getLayout().x * kx;
  52892. node.setLayout({x: nodeX}, true);
  52893. }
  52894. });
  52895. }
  52896. /**
  52897. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  52898. *
  52899. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52900. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52901. * @param {number} height the whole height of the area to draw the view
  52902. * @param {number} nodeGap the vertical distance between two nodes
  52903. * in the same column.
  52904. * @param {number} iterations the number of iterations for the algorithm
  52905. */
  52906. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  52907. var nodesByBreadth = nest()
  52908. .key(getKeyFunction(orient))
  52909. .sortKeys(function (a, b) {
  52910. return a - b;
  52911. })
  52912. .entries(nodes)
  52913. .map(function (d) {
  52914. return d.values;
  52915. });
  52916. initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient);
  52917. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52918. for (var alpha = 1; iterations > 0; iterations--) {
  52919. // 0.99 is a experience parameter, ensure that each iterations of
  52920. // changes as small as possible.
  52921. alpha *= 0.99;
  52922. relaxRightToLeft(nodesByBreadth, alpha, orient);
  52923. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52924. relaxLeftToRight(nodesByBreadth, alpha, orient);
  52925. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52926. }
  52927. }
  52928. function getKeyFunction(orient) {
  52929. if (orient === 'vertical') {
  52930. return function (d) {
  52931. return d.getLayout().y;
  52932. };
  52933. }
  52934. return function (d) {
  52935. return d.getLayout().x;
  52936. };
  52937. }
  52938. /**
  52939. * Compute the original y-position for each node
  52940. *
  52941. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52942. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52943. * group by the array of all sankey nodes based on the nodes x-position.
  52944. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52945. * @param {number} height the whole height of the area to draw the view
  52946. * @param {number} nodeGap the vertical distance between two nodes
  52947. */
  52948. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient) {
  52949. var kyArray = [];
  52950. each$1(nodesByBreadth, function (nodes) {
  52951. var n = nodes.length;
  52952. var sum = 0;
  52953. var ky = 0;
  52954. each$1(nodes, function (node) {
  52955. sum += node.getLayout().value;
  52956. });
  52957. if (orient === 'vertical') {
  52958. ky = (width - (n - 1) * nodeGap) / sum;
  52959. }
  52960. else {
  52961. ky = (height - (n - 1) * nodeGap) / sum;
  52962. }
  52963. kyArray.push(ky);
  52964. });
  52965. kyArray.sort(function (a, b) {
  52966. return a - b;
  52967. });
  52968. var ky0 = kyArray[0];
  52969. each$1(nodesByBreadth, function (nodes) {
  52970. each$1(nodes, function (node, i) {
  52971. var nodeDy = node.getLayout().value * ky0;
  52972. if (orient === 'vertical') {
  52973. node.setLayout({x: i}, true);
  52974. node.setLayout({dx: nodeDy}, true);
  52975. }
  52976. else {
  52977. node.setLayout({y: i}, true);
  52978. node.setLayout({dy: nodeDy}, true);
  52979. }
  52980. });
  52981. });
  52982. each$1(edges, function (edge) {
  52983. var edgeDy = +edge.getValue() * ky0;
  52984. edge.setLayout({dy: edgeDy}, true);
  52985. });
  52986. }
  52987. /**
  52988. * Resolve the collision of initialized depth (y-position)
  52989. *
  52990. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52991. * group by the array of all sankey nodes based on the nodes x-position.
  52992. * @param {number} nodeGap the vertical distance between two nodes
  52993. * @param {number} height the whole height of the area to draw the view
  52994. */
  52995. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  52996. each$1(nodesByBreadth, function (nodes) {
  52997. var node;
  52998. var dy;
  52999. var y0 = 0;
  53000. var n = nodes.length;
  53001. var i;
  53002. if (orient === 'vertical') {
  53003. var nodeX;
  53004. nodes.sort(function (a, b) {
  53005. return a.getLayout().x - b.getLayout().x;
  53006. });
  53007. for (i = 0; i < n; i++) {
  53008. node = nodes[i];
  53009. dy = y0 - node.getLayout().x;
  53010. if (dy > 0) {
  53011. nodeX = node.getLayout().x + dy;
  53012. node.setLayout({x: nodeX}, true);
  53013. }
  53014. y0 = node.getLayout().x + node.getLayout().dx + nodeGap;
  53015. }
  53016. // If the bottommost node goes outside the bounds, push it back up
  53017. dy = y0 - nodeGap - width;
  53018. if (dy > 0) {
  53019. nodeX = node.getLayout().x - dy;
  53020. node.setLayout({x: nodeX}, true);
  53021. y0 = nodeX;
  53022. for (i = n - 2; i >= 0; --i) {
  53023. node = nodes[i];
  53024. dy = node.getLayout().x + node.getLayout().dx + nodeGap - y0;
  53025. if (dy > 0) {
  53026. nodeX = node.getLayout().x - dy;
  53027. node.setLayout({x: nodeX}, true);
  53028. }
  53029. y0 = node.getLayout().x;
  53030. }
  53031. }
  53032. }
  53033. else {
  53034. var nodeY;
  53035. nodes.sort(function (a, b) {
  53036. return a.getLayout().y - b.getLayout().y;
  53037. });
  53038. for (i = 0; i < n; i++) {
  53039. node = nodes[i];
  53040. dy = y0 - node.getLayout().y;
  53041. if (dy > 0) {
  53042. nodeY = node.getLayout().y + dy;
  53043. node.setLayout({y: nodeY}, true);
  53044. }
  53045. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  53046. }
  53047. // If the bottommost node goes outside the bounds, push it back up
  53048. dy = y0 - nodeGap - height;
  53049. if (dy > 0) {
  53050. nodeY = node.getLayout().y - dy;
  53051. node.setLayout({y: nodeY}, true);
  53052. y0 = nodeY;
  53053. for (i = n - 2; i >= 0; --i) {
  53054. node = nodes[i];
  53055. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  53056. if (dy > 0) {
  53057. nodeY = node.getLayout().y - dy;
  53058. node.setLayout({y: nodeY}, true);
  53059. }
  53060. y0 = node.getLayout().y;
  53061. }
  53062. }
  53063. }
  53064. });
  53065. }
  53066. /**
  53067. * Change the y-position of the nodes, except most the right side nodes
  53068. *
  53069. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  53070. * group by the array of all sankey nodes based on the node x-position.
  53071. * @param {number} alpha parameter used to adjust the nodes y-position
  53072. */
  53073. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  53074. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  53075. each$1(nodes, function (node) {
  53076. if (node.outEdges.length) {
  53077. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue, orient);
  53078. if (orient === 'vertical') {
  53079. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  53080. node.setLayout({x: nodeX}, true);
  53081. }
  53082. else {
  53083. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  53084. node.setLayout({y: nodeY}, true);
  53085. }
  53086. }
  53087. });
  53088. });
  53089. }
  53090. function weightedTarget(edge, orient) {
  53091. return center$1(edge.node2, orient) * edge.getValue();
  53092. }
  53093. function weightedSource(edge, orient) {
  53094. return center$1(edge.node1, orient) * edge.getValue();
  53095. }
  53096. function center$1(node, orient) {
  53097. if (orient === 'vertical') {
  53098. return node.getLayout().x + node.getLayout().dx / 2;
  53099. }
  53100. return node.getLayout().y + node.getLayout().dy / 2;
  53101. }
  53102. function getEdgeValue(edge) {
  53103. return edge.getValue();
  53104. }
  53105. function sum(array, f, orient) {
  53106. var sum = 0;
  53107. var len = array.length;
  53108. var i = -1;
  53109. while (++i < len) {
  53110. var value = +f.call(array, array[i], orient);
  53111. if (!isNaN(value)) {
  53112. sum += value;
  53113. }
  53114. }
  53115. return sum;
  53116. }
  53117. /**
  53118. * Change the y-position of the nodes, except most the left side nodes
  53119. *
  53120. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  53121. * group by the array of all sankey nodes based on the node x-position.
  53122. * @param {number} alpha parameter used to adjust the nodes y-position
  53123. */
  53124. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  53125. each$1(nodesByBreadth, function (nodes) {
  53126. each$1(nodes, function (node) {
  53127. if (node.inEdges.length) {
  53128. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue, orient);
  53129. if (orient === 'vertical') {
  53130. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  53131. node.setLayout({x: nodeX}, true);
  53132. }
  53133. else {
  53134. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  53135. node.setLayout({y: nodeY}, true);
  53136. }
  53137. }
  53138. });
  53139. });
  53140. }
  53141. /**
  53142. * Compute the depth(y-position) of each edge
  53143. *
  53144. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  53145. */
  53146. function computeEdgeDepths(nodes, orient) {
  53147. each$1(nodes, function (node) {
  53148. if (orient === 'vertical') {
  53149. node.outEdges.sort(function (a, b) {
  53150. return a.node2.getLayout().x - b.node2.getLayout().x;
  53151. });
  53152. node.inEdges.sort(function (a, b) {
  53153. return a.node1.getLayout().x - b.node1.getLayout().x;
  53154. });
  53155. }
  53156. else {
  53157. node.outEdges.sort(function (a, b) {
  53158. return a.node2.getLayout().y - b.node2.getLayout().y;
  53159. });
  53160. node.inEdges.sort(function (a, b) {
  53161. return a.node1.getLayout().y - b.node1.getLayout().y;
  53162. });
  53163. }
  53164. });
  53165. each$1(nodes, function (node) {
  53166. var sy = 0;
  53167. var ty = 0;
  53168. each$1(node.outEdges, function (edge) {
  53169. edge.setLayout({sy: sy}, true);
  53170. sy += edge.getLayout().dy;
  53171. });
  53172. each$1(node.inEdges, function (edge) {
  53173. edge.setLayout({ty: ty}, true);
  53174. ty += edge.getLayout().dy;
  53175. });
  53176. });
  53177. }
  53178. /*
  53179. * Licensed to the Apache Software Foundation (ASF) under one
  53180. * or more contributor license agreements. See the NOTICE file
  53181. * distributed with this work for additional information
  53182. * regarding copyright ownership. The ASF licenses this file
  53183. * to you under the Apache License, Version 2.0 (the
  53184. * "License"); you may not use this file except in compliance
  53185. * with the License. You may obtain a copy of the License at
  53186. *
  53187. * http://www.apache.org/licenses/LICENSE-2.0
  53188. *
  53189. * Unless required by applicable law or agreed to in writing,
  53190. * software distributed under the License is distributed on an
  53191. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53192. * KIND, either express or implied. See the License for the
  53193. * specific language governing permissions and limitations
  53194. * under the License.
  53195. */
  53196. /**
  53197. * @file Visual encoding for sankey view
  53198. * @author Deqing Li(annong035@gmail.com)
  53199. */
  53200. var sankeyVisual = function (ecModel, payload) {
  53201. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  53202. var graph = seriesModel.getGraph();
  53203. var nodes = graph.nodes;
  53204. if (nodes.length) {
  53205. var minValue = Infinity;
  53206. var maxValue = -Infinity;
  53207. each$1(nodes, function (node) {
  53208. var nodeValue = node.getLayout().value;
  53209. if (nodeValue < minValue) {
  53210. minValue = nodeValue;
  53211. }
  53212. if (nodeValue > maxValue) {
  53213. maxValue = nodeValue;
  53214. }
  53215. });
  53216. each$1(nodes, function (node) {
  53217. var mapping = new VisualMapping({
  53218. type: 'color',
  53219. mappingMethod: 'linear',
  53220. dataExtent: [minValue, maxValue],
  53221. visual: seriesModel.get('color')
  53222. });
  53223. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  53224. node.setVisual('color', mapValueToColor);
  53225. // If set itemStyle.normal.color
  53226. var itemModel = node.getModel();
  53227. var customColor = itemModel.get('itemStyle.color');
  53228. if (customColor != null) {
  53229. node.setVisual('color', customColor);
  53230. }
  53231. });
  53232. }
  53233. });
  53234. };
  53235. /*
  53236. * Licensed to the Apache Software Foundation (ASF) under one
  53237. * or more contributor license agreements. See the NOTICE file
  53238. * distributed with this work for additional information
  53239. * regarding copyright ownership. The ASF licenses this file
  53240. * to you under the Apache License, Version 2.0 (the
  53241. * "License"); you may not use this file except in compliance
  53242. * with the License. You may obtain a copy of the License at
  53243. *
  53244. * http://www.apache.org/licenses/LICENSE-2.0
  53245. *
  53246. * Unless required by applicable law or agreed to in writing,
  53247. * software distributed under the License is distributed on an
  53248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53249. * KIND, either express or implied. See the License for the
  53250. * specific language governing permissions and limitations
  53251. * under the License.
  53252. */
  53253. registerLayout(sankeyLayout);
  53254. registerVisual(sankeyVisual);
  53255. /*
  53256. * Licensed to the Apache Software Foundation (ASF) under one
  53257. * or more contributor license agreements. See the NOTICE file
  53258. * distributed with this work for additional information
  53259. * regarding copyright ownership. The ASF licenses this file
  53260. * to you under the Apache License, Version 2.0 (the
  53261. * "License"); you may not use this file except in compliance
  53262. * with the License. You may obtain a copy of the License at
  53263. *
  53264. * http://www.apache.org/licenses/LICENSE-2.0
  53265. *
  53266. * Unless required by applicable law or agreed to in writing,
  53267. * software distributed under the License is distributed on an
  53268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53269. * KIND, either express or implied. See the License for the
  53270. * specific language governing permissions and limitations
  53271. * under the License.
  53272. */
  53273. var seriesModelMixin = {
  53274. /**
  53275. * @private
  53276. * @type {string}
  53277. */
  53278. _baseAxisDim: null,
  53279. /**
  53280. * @override
  53281. */
  53282. getInitialData: function (option, ecModel) {
  53283. // When both types of xAxis and yAxis are 'value', layout is
  53284. // needed to be specified by user. Otherwise, layout can be
  53285. // judged by which axis is category.
  53286. var ordinalMeta;
  53287. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  53288. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  53289. var xAxisType = xAxisModel.get('type');
  53290. var yAxisType = yAxisModel.get('type');
  53291. var addOrdinal;
  53292. // FIXME
  53293. // 考虑时间轴
  53294. if (xAxisType === 'category') {
  53295. option.layout = 'horizontal';
  53296. ordinalMeta = xAxisModel.getOrdinalMeta();
  53297. addOrdinal = true;
  53298. }
  53299. else if (yAxisType === 'category') {
  53300. option.layout = 'vertical';
  53301. ordinalMeta = yAxisModel.getOrdinalMeta();
  53302. addOrdinal = true;
  53303. }
  53304. else {
  53305. option.layout = option.layout || 'horizontal';
  53306. }
  53307. var coordDims = ['x', 'y'];
  53308. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  53309. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  53310. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  53311. var axisModels = [xAxisModel, yAxisModel];
  53312. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  53313. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  53314. var data = option.data;
  53315. // ??? FIXME make a stage to perform data transfrom.
  53316. // MUST create a new data, consider setOption({}) again.
  53317. if (data && addOrdinal) {
  53318. var newOptionData = [];
  53319. each$1(data, function (item, index) {
  53320. var newItem;
  53321. if (item.value && isArray(item.value)) {
  53322. newItem = item.value.slice();
  53323. item.value.unshift(index);
  53324. }
  53325. else if (isArray(item)) {
  53326. newItem = item.slice();
  53327. item.unshift(index);
  53328. }
  53329. else {
  53330. newItem = item;
  53331. }
  53332. newOptionData.push(newItem);
  53333. });
  53334. option.data = newOptionData;
  53335. }
  53336. var defaultValueDimensions = this.defaultValueDimensions;
  53337. return createListSimply(
  53338. this,
  53339. {
  53340. coordDimensions: [{
  53341. name: baseAxisDim,
  53342. type: getDimensionTypeByAxis(baseAxisType),
  53343. ordinalMeta: ordinalMeta,
  53344. otherDims: {
  53345. tooltip: false,
  53346. itemName: 0
  53347. },
  53348. dimsDef: ['base']
  53349. }, {
  53350. name: otherAxisDim,
  53351. type: getDimensionTypeByAxis(otherAxisType),
  53352. dimsDef: defaultValueDimensions.slice()
  53353. }],
  53354. dimensionsCount: defaultValueDimensions.length + 1
  53355. }
  53356. );
  53357. },
  53358. /**
  53359. * If horizontal, base axis is x, otherwise y.
  53360. * @override
  53361. */
  53362. getBaseAxis: function () {
  53363. var dim = this._baseAxisDim;
  53364. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  53365. }
  53366. };
  53367. /*
  53368. * Licensed to the Apache Software Foundation (ASF) under one
  53369. * or more contributor license agreements. See the NOTICE file
  53370. * distributed with this work for additional information
  53371. * regarding copyright ownership. The ASF licenses this file
  53372. * to you under the Apache License, Version 2.0 (the
  53373. * "License"); you may not use this file except in compliance
  53374. * with the License. You may obtain a copy of the License at
  53375. *
  53376. * http://www.apache.org/licenses/LICENSE-2.0
  53377. *
  53378. * Unless required by applicable law or agreed to in writing,
  53379. * software distributed under the License is distributed on an
  53380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53381. * KIND, either express or implied. See the License for the
  53382. * specific language governing permissions and limitations
  53383. * under the License.
  53384. */
  53385. var BoxplotSeries = SeriesModel.extend({
  53386. type: 'series.boxplot',
  53387. dependencies: ['xAxis', 'yAxis', 'grid'],
  53388. // TODO
  53389. // box width represents group size, so dimension should have 'size'.
  53390. /**
  53391. * @see <https://en.wikipedia.org/wiki/Box_plot>
  53392. * The meanings of 'min' and 'max' depend on user,
  53393. * and echarts do not need to know it.
  53394. * @readOnly
  53395. */
  53396. defaultValueDimensions: [
  53397. {name: 'min', defaultTooltip: true},
  53398. {name: 'Q1', defaultTooltip: true},
  53399. {name: 'median', defaultTooltip: true},
  53400. {name: 'Q3', defaultTooltip: true},
  53401. {name: 'max', defaultTooltip: true}
  53402. ],
  53403. /**
  53404. * @type {Array.<string>}
  53405. * @readOnly
  53406. */
  53407. dimensions: null,
  53408. /**
  53409. * @override
  53410. */
  53411. defaultOption: {
  53412. zlevel: 0, // 一级层叠
  53413. z: 2, // 二级层叠
  53414. coordinateSystem: 'cartesian2d',
  53415. legendHoverLink: true,
  53416. hoverAnimation: true,
  53417. // xAxisIndex: 0,
  53418. // yAxisIndex: 0,
  53419. layout: null, // 'horizontal' or 'vertical'
  53420. boxWidth: [7, 50], // [min, max] can be percent of band width.
  53421. itemStyle: {
  53422. color: '#fff',
  53423. borderWidth: 1
  53424. },
  53425. emphasis: {
  53426. itemStyle: {
  53427. borderWidth: 2,
  53428. shadowBlur: 5,
  53429. shadowOffsetX: 2,
  53430. shadowOffsetY: 2,
  53431. shadowColor: 'rgba(0,0,0,0.4)'
  53432. }
  53433. },
  53434. animationEasing: 'elasticOut',
  53435. animationDuration: 800
  53436. }
  53437. });
  53438. mixin(BoxplotSeries, seriesModelMixin, true);
  53439. /*
  53440. * Licensed to the Apache Software Foundation (ASF) under one
  53441. * or more contributor license agreements. See the NOTICE file
  53442. * distributed with this work for additional information
  53443. * regarding copyright ownership. The ASF licenses this file
  53444. * to you under the Apache License, Version 2.0 (the
  53445. * "License"); you may not use this file except in compliance
  53446. * with the License. You may obtain a copy of the License at
  53447. *
  53448. * http://www.apache.org/licenses/LICENSE-2.0
  53449. *
  53450. * Unless required by applicable law or agreed to in writing,
  53451. * software distributed under the License is distributed on an
  53452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53453. * KIND, either express or implied. See the License for the
  53454. * specific language governing permissions and limitations
  53455. * under the License.
  53456. */
  53457. // Update common properties
  53458. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  53459. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  53460. var BoxplotView = Chart.extend({
  53461. type: 'boxplot',
  53462. render: function (seriesModel, ecModel, api) {
  53463. var data = seriesModel.getData();
  53464. var group = this.group;
  53465. var oldData = this._data;
  53466. // There is no old data only when first rendering or switching from
  53467. // stream mode to normal mode, where previous elements should be removed.
  53468. if (!this._data) {
  53469. group.removeAll();
  53470. }
  53471. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  53472. data.diff(oldData)
  53473. .add(function (newIdx) {
  53474. if (data.hasValue(newIdx)) {
  53475. var itemLayout = data.getItemLayout(newIdx);
  53476. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  53477. data.setItemGraphicEl(newIdx, symbolEl);
  53478. group.add(symbolEl);
  53479. }
  53480. })
  53481. .update(function (newIdx, oldIdx) {
  53482. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  53483. // Empty data
  53484. if (!data.hasValue(newIdx)) {
  53485. group.remove(symbolEl);
  53486. return;
  53487. }
  53488. var itemLayout = data.getItemLayout(newIdx);
  53489. if (!symbolEl) {
  53490. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  53491. }
  53492. else {
  53493. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  53494. }
  53495. group.add(symbolEl);
  53496. data.setItemGraphicEl(newIdx, symbolEl);
  53497. })
  53498. .remove(function (oldIdx) {
  53499. var el = oldData.getItemGraphicEl(oldIdx);
  53500. el && group.remove(el);
  53501. })
  53502. .execute();
  53503. this._data = data;
  53504. },
  53505. remove: function (ecModel) {
  53506. var group = this.group;
  53507. var data = this._data;
  53508. this._data = null;
  53509. data && data.eachItemGraphicEl(function (el) {
  53510. el && group.remove(el);
  53511. });
  53512. },
  53513. dispose: noop
  53514. });
  53515. var BoxPath = Path.extend({
  53516. type: 'boxplotBoxPath',
  53517. shape: {},
  53518. buildPath: function (ctx, shape) {
  53519. var ends = shape.points;
  53520. var i = 0;
  53521. ctx.moveTo(ends[i][0], ends[i][1]);
  53522. i++;
  53523. for (; i < 4; i++) {
  53524. ctx.lineTo(ends[i][0], ends[i][1]);
  53525. }
  53526. ctx.closePath();
  53527. for (; i < ends.length; i++) {
  53528. ctx.moveTo(ends[i][0], ends[i][1]);
  53529. i++;
  53530. ctx.lineTo(ends[i][0], ends[i][1]);
  53531. }
  53532. }
  53533. });
  53534. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  53535. var ends = itemLayout.ends;
  53536. var el = new BoxPath({
  53537. shape: {
  53538. points: isInit
  53539. ? transInit(ends, constDim, itemLayout)
  53540. : ends
  53541. }
  53542. });
  53543. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  53544. return el;
  53545. }
  53546. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  53547. var seriesModel = data.hostModel;
  53548. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  53549. updateMethod(
  53550. el,
  53551. {shape: {points: itemLayout.ends}},
  53552. seriesModel,
  53553. dataIndex
  53554. );
  53555. var itemModel = data.getItemModel(dataIndex);
  53556. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  53557. var borderColor = data.getItemVisual(dataIndex, 'color');
  53558. // Exclude borderColor.
  53559. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  53560. itemStyle.stroke = borderColor;
  53561. itemStyle.strokeNoScale = true;
  53562. el.useStyle(itemStyle);
  53563. el.z2 = 100;
  53564. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  53565. setHoverStyle(el, hoverStyle);
  53566. }
  53567. function transInit(points, dim, itemLayout) {
  53568. return map(points, function (point) {
  53569. point = point.slice();
  53570. point[dim] = itemLayout.initBaseline;
  53571. return point;
  53572. });
  53573. }
  53574. /*
  53575. * Licensed to the Apache Software Foundation (ASF) under one
  53576. * or more contributor license agreements. See the NOTICE file
  53577. * distributed with this work for additional information
  53578. * regarding copyright ownership. The ASF licenses this file
  53579. * to you under the Apache License, Version 2.0 (the
  53580. * "License"); you may not use this file except in compliance
  53581. * with the License. You may obtain a copy of the License at
  53582. *
  53583. * http://www.apache.org/licenses/LICENSE-2.0
  53584. *
  53585. * Unless required by applicable law or agreed to in writing,
  53586. * software distributed under the License is distributed on an
  53587. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53588. * KIND, either express or implied. See the License for the
  53589. * specific language governing permissions and limitations
  53590. * under the License.
  53591. */
  53592. var borderColorQuery = ['itemStyle', 'borderColor'];
  53593. var boxplotVisual = function (ecModel, api) {
  53594. var globalColors = ecModel.get('color');
  53595. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  53596. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  53597. var data = seriesModel.getData();
  53598. data.setVisual({
  53599. legendSymbol: 'roundRect',
  53600. // Use name 'color' but not 'borderColor' for legend usage and
  53601. // visual coding from other component like dataRange.
  53602. color: seriesModel.get(borderColorQuery) || defaulColor
  53603. });
  53604. // Only visible series has each data be visual encoded
  53605. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53606. data.each(function (idx) {
  53607. var itemModel = data.getItemModel(idx);
  53608. data.setItemVisual(
  53609. idx,
  53610. {color: itemModel.get(borderColorQuery, true)}
  53611. );
  53612. });
  53613. }
  53614. });
  53615. };
  53616. /*
  53617. * Licensed to the Apache Software Foundation (ASF) under one
  53618. * or more contributor license agreements. See the NOTICE file
  53619. * distributed with this work for additional information
  53620. * regarding copyright ownership. The ASF licenses this file
  53621. * to you under the Apache License, Version 2.0 (the
  53622. * "License"); you may not use this file except in compliance
  53623. * with the License. You may obtain a copy of the License at
  53624. *
  53625. * http://www.apache.org/licenses/LICENSE-2.0
  53626. *
  53627. * Unless required by applicable law or agreed to in writing,
  53628. * software distributed under the License is distributed on an
  53629. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53630. * KIND, either express or implied. See the License for the
  53631. * specific language governing permissions and limitations
  53632. * under the License.
  53633. */
  53634. var each$13 = each$1;
  53635. var boxplotLayout = function (ecModel) {
  53636. var groupResult = groupSeriesByAxis(ecModel);
  53637. each$13(groupResult, function (groupItem) {
  53638. var seriesModels = groupItem.seriesModels;
  53639. if (!seriesModels.length) {
  53640. return;
  53641. }
  53642. calculateBase(groupItem);
  53643. each$13(seriesModels, function (seriesModel, idx) {
  53644. layoutSingleSeries(
  53645. seriesModel,
  53646. groupItem.boxOffsetList[idx],
  53647. groupItem.boxWidthList[idx]
  53648. );
  53649. });
  53650. });
  53651. };
  53652. /**
  53653. * Group series by axis.
  53654. */
  53655. function groupSeriesByAxis(ecModel) {
  53656. var result = [];
  53657. var axisList = [];
  53658. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  53659. var baseAxis = seriesModel.getBaseAxis();
  53660. var idx = indexOf(axisList, baseAxis);
  53661. if (idx < 0) {
  53662. idx = axisList.length;
  53663. axisList[idx] = baseAxis;
  53664. result[idx] = {axis: baseAxis, seriesModels: []};
  53665. }
  53666. result[idx].seriesModels.push(seriesModel);
  53667. });
  53668. return result;
  53669. }
  53670. /**
  53671. * Calculate offset and box width for each series.
  53672. */
  53673. function calculateBase(groupItem) {
  53674. var extent;
  53675. var baseAxis = groupItem.axis;
  53676. var seriesModels = groupItem.seriesModels;
  53677. var seriesCount = seriesModels.length;
  53678. var boxWidthList = groupItem.boxWidthList = [];
  53679. var boxOffsetList = groupItem.boxOffsetList = [];
  53680. var boundList = [];
  53681. var bandWidth;
  53682. if (baseAxis.type === 'category') {
  53683. bandWidth = baseAxis.getBandWidth();
  53684. }
  53685. else {
  53686. var maxDataCount = 0;
  53687. each$13(seriesModels, function (seriesModel) {
  53688. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  53689. });
  53690. extent = baseAxis.getExtent(),
  53691. Math.abs(extent[1] - extent[0]) / maxDataCount;
  53692. }
  53693. each$13(seriesModels, function (seriesModel) {
  53694. var boxWidthBound = seriesModel.get('boxWidth');
  53695. if (!isArray(boxWidthBound)) {
  53696. boxWidthBound = [boxWidthBound, boxWidthBound];
  53697. }
  53698. boundList.push([
  53699. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  53700. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  53701. ]);
  53702. });
  53703. var availableWidth = bandWidth * 0.8 - 2;
  53704. var boxGap = availableWidth / seriesCount * 0.3;
  53705. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  53706. var base = boxWidth / 2 - availableWidth / 2;
  53707. each$13(seriesModels, function (seriesModel, idx) {
  53708. boxOffsetList.push(base);
  53709. base += boxGap + boxWidth;
  53710. boxWidthList.push(
  53711. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  53712. );
  53713. });
  53714. }
  53715. /**
  53716. * Calculate points location for each series.
  53717. */
  53718. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  53719. var coordSys = seriesModel.coordinateSystem;
  53720. var data = seriesModel.getData();
  53721. var halfWidth = boxWidth / 2;
  53722. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  53723. var vDimIdx = 1 - cDimIdx;
  53724. var coordDims = ['x', 'y'];
  53725. var cDim = data.mapDimension(coordDims[cDimIdx]);
  53726. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  53727. if (cDim == null || vDims.length < 5) {
  53728. return;
  53729. }
  53730. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  53731. var axisDimVal = data.get(cDim, dataIndex);
  53732. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  53733. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  53734. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  53735. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  53736. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  53737. var ends = [];
  53738. addBodyEnd(ends, end2, 0);
  53739. addBodyEnd(ends, end4, 1);
  53740. ends.push(end1, end2, end5, end4);
  53741. layEndLine(ends, end1);
  53742. layEndLine(ends, end5);
  53743. layEndLine(ends, median);
  53744. data.setItemLayout(dataIndex, {
  53745. initBaseline: median[vDimIdx],
  53746. ends: ends
  53747. });
  53748. }
  53749. function getPoint(axisDimVal, dimIdx, dataIndex) {
  53750. var val = data.get(dimIdx, dataIndex);
  53751. var p = [];
  53752. p[cDimIdx] = axisDimVal;
  53753. p[vDimIdx] = val;
  53754. var point;
  53755. if (isNaN(axisDimVal) || isNaN(val)) {
  53756. point = [NaN, NaN];
  53757. }
  53758. else {
  53759. point = coordSys.dataToPoint(p);
  53760. point[cDimIdx] += offset;
  53761. }
  53762. return point;
  53763. }
  53764. function addBodyEnd(ends, point, start) {
  53765. var point1 = point.slice();
  53766. var point2 = point.slice();
  53767. point1[cDimIdx] += halfWidth;
  53768. point2[cDimIdx] -= halfWidth;
  53769. start
  53770. ? ends.push(point1, point2)
  53771. : ends.push(point2, point1);
  53772. }
  53773. function layEndLine(ends, endCenter) {
  53774. var from = endCenter.slice();
  53775. var to = endCenter.slice();
  53776. from[cDimIdx] -= halfWidth;
  53777. to[cDimIdx] += halfWidth;
  53778. ends.push(from, to);
  53779. }
  53780. }
  53781. /*
  53782. * Licensed to the Apache Software Foundation (ASF) under one
  53783. * or more contributor license agreements. See the NOTICE file
  53784. * distributed with this work for additional information
  53785. * regarding copyright ownership. The ASF licenses this file
  53786. * to you under the Apache License, Version 2.0 (the
  53787. * "License"); you may not use this file except in compliance
  53788. * with the License. You may obtain a copy of the License at
  53789. *
  53790. * http://www.apache.org/licenses/LICENSE-2.0
  53791. *
  53792. * Unless required by applicable law or agreed to in writing,
  53793. * software distributed under the License is distributed on an
  53794. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53795. * KIND, either express or implied. See the License for the
  53796. * specific language governing permissions and limitations
  53797. * under the License.
  53798. */
  53799. registerVisual(boxplotVisual);
  53800. registerLayout(boxplotLayout);
  53801. /*
  53802. * Licensed to the Apache Software Foundation (ASF) under one
  53803. * or more contributor license agreements. See the NOTICE file
  53804. * distributed with this work for additional information
  53805. * regarding copyright ownership. The ASF licenses this file
  53806. * to you under the Apache License, Version 2.0 (the
  53807. * "License"); you may not use this file except in compliance
  53808. * with the License. You may obtain a copy of the License at
  53809. *
  53810. * http://www.apache.org/licenses/LICENSE-2.0
  53811. *
  53812. * Unless required by applicable law or agreed to in writing,
  53813. * software distributed under the License is distributed on an
  53814. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53815. * KIND, either express or implied. See the License for the
  53816. * specific language governing permissions and limitations
  53817. * under the License.
  53818. */
  53819. var CandlestickSeries = SeriesModel.extend({
  53820. type: 'series.candlestick',
  53821. dependencies: ['xAxis', 'yAxis', 'grid'],
  53822. /**
  53823. * @readOnly
  53824. */
  53825. defaultValueDimensions: [
  53826. {name: 'open', defaultTooltip: true},
  53827. {name: 'close', defaultTooltip: true},
  53828. {name: 'lowest', defaultTooltip: true},
  53829. {name: 'highest', defaultTooltip: true}
  53830. ],
  53831. /**
  53832. * @type {Array.<string>}
  53833. * @readOnly
  53834. */
  53835. dimensions: null,
  53836. /**
  53837. * @override
  53838. */
  53839. defaultOption: {
  53840. zlevel: 0,
  53841. z: 2,
  53842. coordinateSystem: 'cartesian2d',
  53843. legendHoverLink: true,
  53844. hoverAnimation: true,
  53845. // xAxisIndex: 0,
  53846. // yAxisIndex: 0,
  53847. layout: null, // 'horizontal' or 'vertical'
  53848. itemStyle: {
  53849. color: '#c23531', // 阳线 positive
  53850. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  53851. borderWidth: 1,
  53852. // FIXME
  53853. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  53854. borderColor: '#c23531',
  53855. borderColor0: '#314656'
  53856. },
  53857. emphasis: {
  53858. itemStyle: {
  53859. borderWidth: 2
  53860. }
  53861. },
  53862. barMaxWidth: null,
  53863. barMinWidth: null,
  53864. barWidth: null,
  53865. large: true,
  53866. largeThreshold: 600,
  53867. progressive: 3e3,
  53868. progressiveThreshold: 1e4,
  53869. progressiveChunkMode: 'mod',
  53870. animationUpdate: false,
  53871. animationEasing: 'linear',
  53872. animationDuration: 300
  53873. },
  53874. /**
  53875. * Get dimension for shadow in dataZoom
  53876. * @return {string} dimension name
  53877. */
  53878. getShadowDim: function () {
  53879. return 'open';
  53880. },
  53881. brushSelector: function (dataIndex, data, selectors) {
  53882. var itemLayout = data.getItemLayout(dataIndex);
  53883. return itemLayout && selectors.rect(itemLayout.brushRect);
  53884. }
  53885. });
  53886. mixin(CandlestickSeries, seriesModelMixin, true);
  53887. /*
  53888. * Licensed to the Apache Software Foundation (ASF) under one
  53889. * or more contributor license agreements. See the NOTICE file
  53890. * distributed with this work for additional information
  53891. * regarding copyright ownership. The ASF licenses this file
  53892. * to you under the Apache License, Version 2.0 (the
  53893. * "License"); you may not use this file except in compliance
  53894. * with the License. You may obtain a copy of the License at
  53895. *
  53896. * http://www.apache.org/licenses/LICENSE-2.0
  53897. *
  53898. * Unless required by applicable law or agreed to in writing,
  53899. * software distributed under the License is distributed on an
  53900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53901. * KIND, either express or implied. See the License for the
  53902. * specific language governing permissions and limitations
  53903. * under the License.
  53904. */
  53905. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  53906. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  53907. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  53908. var CandlestickView = Chart.extend({
  53909. type: 'candlestick',
  53910. render: function (seriesModel, ecModel, api) {
  53911. this._updateDrawMode(seriesModel);
  53912. this._isLargeDraw
  53913. ? this._renderLarge(seriesModel)
  53914. : this._renderNormal(seriesModel);
  53915. },
  53916. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53917. this._clear();
  53918. this._updateDrawMode(seriesModel);
  53919. },
  53920. incrementalRender: function (params, seriesModel, ecModel, api) {
  53921. this._isLargeDraw
  53922. ? this._incrementalRenderLarge(params, seriesModel)
  53923. : this._incrementalRenderNormal(params, seriesModel);
  53924. },
  53925. _updateDrawMode: function (seriesModel) {
  53926. var isLargeDraw = seriesModel.pipelineContext.large;
  53927. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  53928. this._isLargeDraw = isLargeDraw;
  53929. this._clear();
  53930. }
  53931. },
  53932. _renderNormal: function (seriesModel) {
  53933. var data = seriesModel.getData();
  53934. var oldData = this._data;
  53935. var group = this.group;
  53936. var isSimpleBox = data.getLayout('isSimpleBox');
  53937. // There is no old data only when first rendering or switching from
  53938. // stream mode to normal mode, where previous elements should be removed.
  53939. if (!this._data) {
  53940. group.removeAll();
  53941. }
  53942. data.diff(oldData)
  53943. .add(function (newIdx) {
  53944. if (data.hasValue(newIdx)) {
  53945. var el;
  53946. var itemLayout = data.getItemLayout(newIdx);
  53947. el = createNormalBox$1(itemLayout, newIdx, true);
  53948. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53949. setBoxCommon(el, data, newIdx, isSimpleBox);
  53950. group.add(el);
  53951. data.setItemGraphicEl(newIdx, el);
  53952. }
  53953. })
  53954. .update(function (newIdx, oldIdx) {
  53955. var el = oldData.getItemGraphicEl(oldIdx);
  53956. // Empty data
  53957. if (!data.hasValue(newIdx)) {
  53958. group.remove(el);
  53959. return;
  53960. }
  53961. var itemLayout = data.getItemLayout(newIdx);
  53962. if (!el) {
  53963. el = createNormalBox$1(itemLayout, newIdx);
  53964. }
  53965. else {
  53966. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53967. }
  53968. setBoxCommon(el, data, newIdx, isSimpleBox);
  53969. group.add(el);
  53970. data.setItemGraphicEl(newIdx, el);
  53971. })
  53972. .remove(function (oldIdx) {
  53973. var el = oldData.getItemGraphicEl(oldIdx);
  53974. el && group.remove(el);
  53975. })
  53976. .execute();
  53977. this._data = data;
  53978. },
  53979. _renderLarge: function (seriesModel) {
  53980. this._clear();
  53981. createLarge$1(seriesModel, this.group);
  53982. },
  53983. _incrementalRenderNormal: function (params, seriesModel) {
  53984. var data = seriesModel.getData();
  53985. var isSimpleBox = data.getLayout('isSimpleBox');
  53986. var dataIndex;
  53987. while ((dataIndex = params.next()) != null) {
  53988. var el;
  53989. var itemLayout = data.getItemLayout(dataIndex);
  53990. el = createNormalBox$1(itemLayout, dataIndex);
  53991. setBoxCommon(el, data, dataIndex, isSimpleBox);
  53992. el.incremental = true;
  53993. this.group.add(el);
  53994. }
  53995. },
  53996. _incrementalRenderLarge: function (params, seriesModel) {
  53997. createLarge$1(seriesModel, this.group, true);
  53998. },
  53999. remove: function (ecModel) {
  54000. this._clear();
  54001. },
  54002. _clear: function () {
  54003. this.group.removeAll();
  54004. this._data = null;
  54005. },
  54006. dispose: noop
  54007. });
  54008. var NormalBoxPath = Path.extend({
  54009. type: 'normalCandlestickBox',
  54010. shape: {},
  54011. buildPath: function (ctx, shape) {
  54012. var ends = shape.points;
  54013. if (this.__simpleBox) {
  54014. ctx.moveTo(ends[4][0], ends[4][1]);
  54015. ctx.lineTo(ends[6][0], ends[6][1]);
  54016. }
  54017. else {
  54018. ctx.moveTo(ends[0][0], ends[0][1]);
  54019. ctx.lineTo(ends[1][0], ends[1][1]);
  54020. ctx.lineTo(ends[2][0], ends[2][1]);
  54021. ctx.lineTo(ends[3][0], ends[3][1]);
  54022. ctx.closePath();
  54023. ctx.moveTo(ends[4][0], ends[4][1]);
  54024. ctx.lineTo(ends[5][0], ends[5][1]);
  54025. ctx.moveTo(ends[6][0], ends[6][1]);
  54026. ctx.lineTo(ends[7][0], ends[7][1]);
  54027. }
  54028. }
  54029. });
  54030. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  54031. var ends = itemLayout.ends;
  54032. return new NormalBoxPath({
  54033. shape: {
  54034. points: isInit
  54035. ? transInit$1(ends, itemLayout)
  54036. : ends
  54037. },
  54038. z2: 100
  54039. });
  54040. }
  54041. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  54042. var itemModel = data.getItemModel(dataIndex);
  54043. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  54044. var color = data.getItemVisual(dataIndex, 'color');
  54045. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  54046. // Color must be excluded.
  54047. // Because symbol provide setColor individually to set fill and stroke
  54048. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  54049. el.useStyle(itemStyle);
  54050. el.style.strokeNoScale = true;
  54051. el.style.fill = color;
  54052. el.style.stroke = borderColor;
  54053. el.__simpleBox = isSimpleBox;
  54054. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  54055. setHoverStyle(el, hoverStyle);
  54056. }
  54057. function transInit$1(points, itemLayout) {
  54058. return map(points, function (point) {
  54059. point = point.slice();
  54060. point[1] = itemLayout.initBaseline;
  54061. return point;
  54062. });
  54063. }
  54064. var LargeBoxPath = Path.extend({
  54065. type: 'largeCandlestickBox',
  54066. shape: {},
  54067. buildPath: function (ctx, shape) {
  54068. // Drawing lines is more efficient than drawing
  54069. // a whole line or drawing rects.
  54070. var points = shape.points;
  54071. for (var i = 0; i < points.length;) {
  54072. if (this.__sign === points[i++]) {
  54073. var x = points[i++];
  54074. ctx.moveTo(x, points[i++]);
  54075. ctx.lineTo(x, points[i++]);
  54076. }
  54077. else {
  54078. i += 3;
  54079. }
  54080. }
  54081. }
  54082. });
  54083. function createLarge$1(seriesModel, group, incremental) {
  54084. var data = seriesModel.getData();
  54085. var largePoints = data.getLayout('largePoints');
  54086. var elP = new LargeBoxPath({
  54087. shape: {points: largePoints},
  54088. __sign: 1
  54089. });
  54090. group.add(elP);
  54091. var elN = new LargeBoxPath({
  54092. shape: {points: largePoints},
  54093. __sign: -1
  54094. });
  54095. group.add(elN);
  54096. setLargeStyle$1(1, elP, seriesModel, data);
  54097. setLargeStyle$1(-1, elN, seriesModel, data);
  54098. if (incremental) {
  54099. elP.incremental = true;
  54100. elN.incremental = true;
  54101. }
  54102. }
  54103. function setLargeStyle$1(sign, el, seriesModel, data) {
  54104. var suffix = sign > 0 ? 'P' : 'N';
  54105. var borderColor = data.getVisual('borderColor' + suffix)
  54106. || data.getVisual('color' + suffix);
  54107. // Color must be excluded.
  54108. // Because symbol provide setColor individually to set fill and stroke
  54109. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  54110. el.useStyle(itemStyle);
  54111. el.style.fill = null;
  54112. el.style.stroke = borderColor;
  54113. // No different
  54114. // el.style.lineWidth = .5;
  54115. }
  54116. /*
  54117. * Licensed to the Apache Software Foundation (ASF) under one
  54118. * or more contributor license agreements. See the NOTICE file
  54119. * distributed with this work for additional information
  54120. * regarding copyright ownership. The ASF licenses this file
  54121. * to you under the Apache License, Version 2.0 (the
  54122. * "License"); you may not use this file except in compliance
  54123. * with the License. You may obtain a copy of the License at
  54124. *
  54125. * http://www.apache.org/licenses/LICENSE-2.0
  54126. *
  54127. * Unless required by applicable law or agreed to in writing,
  54128. * software distributed under the License is distributed on an
  54129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54130. * KIND, either express or implied. See the License for the
  54131. * specific language governing permissions and limitations
  54132. * under the License.
  54133. */
  54134. var preprocessor = function (option) {
  54135. if (!option || !isArray(option.series)) {
  54136. return;
  54137. }
  54138. // Translate 'k' to 'candlestick'.
  54139. each$1(option.series, function (seriesItem) {
  54140. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  54141. seriesItem.type = 'candlestick';
  54142. }
  54143. });
  54144. };
  54145. /*
  54146. * Licensed to the Apache Software Foundation (ASF) under one
  54147. * or more contributor license agreements. See the NOTICE file
  54148. * distributed with this work for additional information
  54149. * regarding copyright ownership. The ASF licenses this file
  54150. * to you under the Apache License, Version 2.0 (the
  54151. * "License"); you may not use this file except in compliance
  54152. * with the License. You may obtain a copy of the License at
  54153. *
  54154. * http://www.apache.org/licenses/LICENSE-2.0
  54155. *
  54156. * Unless required by applicable law or agreed to in writing,
  54157. * software distributed under the License is distributed on an
  54158. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54159. * KIND, either express or implied. See the License for the
  54160. * specific language governing permissions and limitations
  54161. * under the License.
  54162. */
  54163. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  54164. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  54165. var positiveColorQuery = ['itemStyle', 'color'];
  54166. var negativeColorQuery = ['itemStyle', 'color0'];
  54167. var candlestickVisual = {
  54168. seriesType: 'candlestick',
  54169. plan: createRenderPlanner(),
  54170. // For legend.
  54171. performRawSeries: true,
  54172. reset: function (seriesModel, ecModel) {
  54173. var data = seriesModel.getData();
  54174. var isLargeRender = seriesModel.pipelineContext.large;
  54175. data.setVisual({
  54176. legendSymbol: 'roundRect',
  54177. colorP: getColor(1, seriesModel),
  54178. colorN: getColor(-1, seriesModel),
  54179. borderColorP: getBorderColor(1, seriesModel),
  54180. borderColorN: getBorderColor(-1, seriesModel)
  54181. });
  54182. // Only visible series has each data be visual encoded
  54183. if (ecModel.isSeriesFiltered(seriesModel)) {
  54184. return;
  54185. }
  54186. return !isLargeRender && {progress: progress};
  54187. function progress(params, data) {
  54188. var dataIndex;
  54189. while ((dataIndex = params.next()) != null) {
  54190. var itemModel = data.getItemModel(dataIndex);
  54191. var sign = data.getItemLayout(dataIndex).sign;
  54192. data.setItemVisual(
  54193. dataIndex,
  54194. {
  54195. color: getColor(sign, itemModel),
  54196. borderColor: getBorderColor(sign, itemModel)
  54197. }
  54198. );
  54199. }
  54200. }
  54201. function getColor(sign, model) {
  54202. return model.get(
  54203. sign > 0 ? positiveColorQuery : negativeColorQuery
  54204. );
  54205. }
  54206. function getBorderColor(sign, model) {
  54207. return model.get(
  54208. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  54209. );
  54210. }
  54211. }
  54212. };
  54213. /*
  54214. * Licensed to the Apache Software Foundation (ASF) under one
  54215. * or more contributor license agreements. See the NOTICE file
  54216. * distributed with this work for additional information
  54217. * regarding copyright ownership. The ASF licenses this file
  54218. * to you under the Apache License, Version 2.0 (the
  54219. * "License"); you may not use this file except in compliance
  54220. * with the License. You may obtain a copy of the License at
  54221. *
  54222. * http://www.apache.org/licenses/LICENSE-2.0
  54223. *
  54224. * Unless required by applicable law or agreed to in writing,
  54225. * software distributed under the License is distributed on an
  54226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54227. * KIND, either express or implied. See the License for the
  54228. * specific language governing permissions and limitations
  54229. * under the License.
  54230. */
  54231. /* global Float32Array */
  54232. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  54233. var candlestickLayout = {
  54234. seriesType: 'candlestick',
  54235. plan: createRenderPlanner(),
  54236. reset: function (seriesModel) {
  54237. var coordSys = seriesModel.coordinateSystem;
  54238. var data = seriesModel.getData();
  54239. var candleWidth = calculateCandleWidth(seriesModel, data);
  54240. var cDimIdx = 0;
  54241. var vDimIdx = 1;
  54242. var coordDims = ['x', 'y'];
  54243. var cDim = data.mapDimension(coordDims[cDimIdx]);
  54244. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  54245. var openDim = vDims[0];
  54246. var closeDim = vDims[1];
  54247. var lowestDim = vDims[2];
  54248. var highestDim = vDims[3];
  54249. data.setLayout({
  54250. candleWidth: candleWidth,
  54251. // The value is experimented visually.
  54252. isSimpleBox: candleWidth <= 1.3
  54253. });
  54254. if (cDim == null || vDims.length < 4) {
  54255. return;
  54256. }
  54257. return {
  54258. progress: seriesModel.pipelineContext.large
  54259. ? largeProgress : normalProgress
  54260. };
  54261. function normalProgress(params, data) {
  54262. var dataIndex;
  54263. while ((dataIndex = params.next()) != null) {
  54264. var axisDimVal = data.get(cDim, dataIndex);
  54265. var openVal = data.get(openDim, dataIndex);
  54266. var closeVal = data.get(closeDim, dataIndex);
  54267. var lowestVal = data.get(lowestDim, dataIndex);
  54268. var highestVal = data.get(highestDim, dataIndex);
  54269. var ocLow = Math.min(openVal, closeVal);
  54270. var ocHigh = Math.max(openVal, closeVal);
  54271. var ocLowPoint = getPoint(ocLow, axisDimVal);
  54272. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  54273. var lowestPoint = getPoint(lowestVal, axisDimVal);
  54274. var highestPoint = getPoint(highestVal, axisDimVal);
  54275. var ends = [];
  54276. addBodyEnd(ends, ocHighPoint, 0);
  54277. addBodyEnd(ends, ocLowPoint, 1);
  54278. ends.push(
  54279. subPixelOptimizePoint(highestPoint),
  54280. subPixelOptimizePoint(ocHighPoint),
  54281. subPixelOptimizePoint(lowestPoint),
  54282. subPixelOptimizePoint(ocLowPoint)
  54283. );
  54284. data.setItemLayout(dataIndex, {
  54285. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  54286. initBaseline: openVal > closeVal
  54287. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  54288. ends: ends,
  54289. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  54290. });
  54291. }
  54292. function getPoint(val, axisDimVal) {
  54293. var p = [];
  54294. p[cDimIdx] = axisDimVal;
  54295. p[vDimIdx] = val;
  54296. return (isNaN(axisDimVal) || isNaN(val))
  54297. ? [NaN, NaN]
  54298. : coordSys.dataToPoint(p);
  54299. }
  54300. function addBodyEnd(ends, point, start) {
  54301. var point1 = point.slice();
  54302. var point2 = point.slice();
  54303. point1[cDimIdx] = subPixelOptimize(
  54304. point1[cDimIdx] + candleWidth / 2, 1, false
  54305. );
  54306. point2[cDimIdx] = subPixelOptimize(
  54307. point2[cDimIdx] - candleWidth / 2, 1, true
  54308. );
  54309. start
  54310. ? ends.push(point1, point2)
  54311. : ends.push(point2, point1);
  54312. }
  54313. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  54314. var pmin = getPoint(lowestVal, axisDimVal);
  54315. var pmax = getPoint(highestVal, axisDimVal);
  54316. pmin[cDimIdx] -= candleWidth / 2;
  54317. pmax[cDimIdx] -= candleWidth / 2;
  54318. return {
  54319. x: pmin[0],
  54320. y: pmin[1],
  54321. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  54322. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  54323. };
  54324. }
  54325. function subPixelOptimizePoint(point) {
  54326. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  54327. return point;
  54328. }
  54329. }
  54330. function largeProgress(params, data) {
  54331. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  54332. var points = new LargeArr$1(params.count * 5);
  54333. var offset = 0;
  54334. var point;
  54335. var tmpIn = [];
  54336. var tmpOut = [];
  54337. var dataIndex;
  54338. while ((dataIndex = params.next()) != null) {
  54339. var axisDimVal = data.get(cDim, dataIndex);
  54340. var openVal = data.get(openDim, dataIndex);
  54341. var closeVal = data.get(closeDim, dataIndex);
  54342. var lowestVal = data.get(lowestDim, dataIndex);
  54343. var highestVal = data.get(highestDim, dataIndex);
  54344. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  54345. points[offset++] = NaN;
  54346. offset += 4;
  54347. continue;
  54348. }
  54349. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  54350. tmpIn[cDimIdx] = axisDimVal;
  54351. tmpIn[vDimIdx] = lowestVal;
  54352. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  54353. points[offset++] = point ? point[0] : NaN;
  54354. points[offset++] = point ? point[1] : NaN;
  54355. tmpIn[vDimIdx] = highestVal;
  54356. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  54357. points[offset++] = point ? point[1] : NaN;
  54358. }
  54359. data.setLayout('largePoints', points);
  54360. }
  54361. }
  54362. };
  54363. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  54364. var sign;
  54365. if (openVal > closeVal) {
  54366. sign = -1;
  54367. }
  54368. else if (openVal < closeVal) {
  54369. sign = 1;
  54370. }
  54371. else {
  54372. sign = dataIndex > 0
  54373. // If close === open, compare with close of last record
  54374. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  54375. // No record of previous, set to be positive
  54376. : 1;
  54377. }
  54378. return sign;
  54379. }
  54380. function calculateCandleWidth(seriesModel, data) {
  54381. var baseAxis = seriesModel.getBaseAxis();
  54382. var extent;
  54383. var bandWidth = baseAxis.type === 'category'
  54384. ? baseAxis.getBandWidth()
  54385. : (
  54386. extent = baseAxis.getExtent(),
  54387. Math.abs(extent[1] - extent[0]) / data.count()
  54388. );
  54389. var barMaxWidth = parsePercent$1(
  54390. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  54391. bandWidth
  54392. );
  54393. var barMinWidth = parsePercent$1(
  54394. retrieve2(seriesModel.get('barMinWidth'), 1),
  54395. bandWidth
  54396. );
  54397. var barWidth = seriesModel.get('barWidth');
  54398. return barWidth != null
  54399. ? parsePercent$1(barWidth, bandWidth)
  54400. // Put max outer to ensure bar visible in spite of overlap.
  54401. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  54402. }
  54403. /*
  54404. * Licensed to the Apache Software Foundation (ASF) under one
  54405. * or more contributor license agreements. See the NOTICE file
  54406. * distributed with this work for additional information
  54407. * regarding copyright ownership. The ASF licenses this file
  54408. * to you under the Apache License, Version 2.0 (the
  54409. * "License"); you may not use this file except in compliance
  54410. * with the License. You may obtain a copy of the License at
  54411. *
  54412. * http://www.apache.org/licenses/LICENSE-2.0
  54413. *
  54414. * Unless required by applicable law or agreed to in writing,
  54415. * software distributed under the License is distributed on an
  54416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54417. * KIND, either express or implied. See the License for the
  54418. * specific language governing permissions and limitations
  54419. * under the License.
  54420. */
  54421. registerPreprocessor(preprocessor);
  54422. registerVisual(candlestickVisual);
  54423. registerLayout(candlestickLayout);
  54424. /*
  54425. * Licensed to the Apache Software Foundation (ASF) under one
  54426. * or more contributor license agreements. See the NOTICE file
  54427. * distributed with this work for additional information
  54428. * regarding copyright ownership. The ASF licenses this file
  54429. * to you under the Apache License, Version 2.0 (the
  54430. * "License"); you may not use this file except in compliance
  54431. * with the License. You may obtain a copy of the License at
  54432. *
  54433. * http://www.apache.org/licenses/LICENSE-2.0
  54434. *
  54435. * Unless required by applicable law or agreed to in writing,
  54436. * software distributed under the License is distributed on an
  54437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54438. * KIND, either express or implied. See the License for the
  54439. * specific language governing permissions and limitations
  54440. * under the License.
  54441. */
  54442. SeriesModel.extend({
  54443. type: 'series.effectScatter',
  54444. dependencies: ['grid', 'polar'],
  54445. getInitialData: function (option, ecModel) {
  54446. return createListFromArray(this.getSource(), this);
  54447. },
  54448. brushSelector: 'point',
  54449. defaultOption: {
  54450. coordinateSystem: 'cartesian2d',
  54451. zlevel: 0,
  54452. z: 2,
  54453. legendHoverLink: true,
  54454. effectType: 'ripple',
  54455. progressive: 0,
  54456. // When to show the effect, option: 'render'|'emphasis'
  54457. showEffectOn: 'render',
  54458. // Ripple effect config
  54459. rippleEffect: {
  54460. period: 4,
  54461. // Scale of ripple
  54462. scale: 2.5,
  54463. // Brush type can be fill or stroke
  54464. brushType: 'fill'
  54465. },
  54466. // Cartesian coordinate system
  54467. // xAxisIndex: 0,
  54468. // yAxisIndex: 0,
  54469. // Polar coordinate system
  54470. // polarIndex: 0,
  54471. // Geo coordinate system
  54472. // geoIndex: 0,
  54473. // symbol: null, // 图形类型
  54474. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  54475. // symbolRotate: null, // 图形旋转控制
  54476. // large: false,
  54477. // Available when large is true
  54478. // largeThreshold: 2000,
  54479. // itemStyle: {
  54480. // opacity: 1
  54481. // }
  54482. }
  54483. });
  54484. /*
  54485. * Licensed to the Apache Software Foundation (ASF) under one
  54486. * or more contributor license agreements. See the NOTICE file
  54487. * distributed with this work for additional information
  54488. * regarding copyright ownership. The ASF licenses this file
  54489. * to you under the Apache License, Version 2.0 (the
  54490. * "License"); you may not use this file except in compliance
  54491. * with the License. You may obtain a copy of the License at
  54492. *
  54493. * http://www.apache.org/licenses/LICENSE-2.0
  54494. *
  54495. * Unless required by applicable law or agreed to in writing,
  54496. * software distributed under the License is distributed on an
  54497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54498. * KIND, either express or implied. See the License for the
  54499. * specific language governing permissions and limitations
  54500. * under the License.
  54501. */
  54502. /**
  54503. * Symbol with ripple effect
  54504. * @module echarts/chart/helper/EffectSymbol
  54505. */
  54506. var EFFECT_RIPPLE_NUMBER = 3;
  54507. function normalizeSymbolSize$1(symbolSize) {
  54508. if (!isArray(symbolSize)) {
  54509. symbolSize = [+symbolSize, +symbolSize];
  54510. }
  54511. return symbolSize;
  54512. }
  54513. function updateRipplePath(rippleGroup, effectCfg) {
  54514. rippleGroup.eachChild(function (ripplePath) {
  54515. ripplePath.attr({
  54516. z: effectCfg.z,
  54517. zlevel: effectCfg.zlevel,
  54518. style: {
  54519. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  54520. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  54521. }
  54522. });
  54523. });
  54524. }
  54525. /**
  54526. * @constructor
  54527. * @param {module:echarts/data/List} data
  54528. * @param {number} idx
  54529. * @extends {module:zrender/graphic/Group}
  54530. */
  54531. function EffectSymbol(data, idx) {
  54532. Group.call(this);
  54533. var symbol = new SymbolClz$1(data, idx);
  54534. var rippleGroup = new Group();
  54535. this.add(symbol);
  54536. this.add(rippleGroup);
  54537. rippleGroup.beforeUpdate = function () {
  54538. this.attr(symbol.getScale());
  54539. };
  54540. this.updateData(data, idx);
  54541. }
  54542. var effectSymbolProto = EffectSymbol.prototype;
  54543. effectSymbolProto.stopEffectAnimation = function () {
  54544. this.childAt(1).removeAll();
  54545. };
  54546. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  54547. var symbolType = effectCfg.symbolType;
  54548. var color = effectCfg.color;
  54549. var rippleGroup = this.childAt(1);
  54550. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  54551. // var ripplePath = createSymbol(
  54552. // symbolType, -0.5, -0.5, 1, 1, color
  54553. // );
  54554. // If width/height are set too small (e.g., set to 1) on ios10
  54555. // and macOS Sierra, a circle stroke become a rect, no matter what
  54556. // the scale is set. So we set width/height as 2. See #4136.
  54557. var ripplePath = createSymbol(
  54558. symbolType, -1, -1, 2, 2, color
  54559. );
  54560. ripplePath.attr({
  54561. style: {
  54562. strokeNoScale: true
  54563. },
  54564. z2: 99,
  54565. silent: true,
  54566. scale: [0.5, 0.5]
  54567. });
  54568. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  54569. // TODO Configurable effectCfg.period
  54570. ripplePath.animate('', true)
  54571. .when(effectCfg.period, {
  54572. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  54573. })
  54574. .delay(delay)
  54575. .start();
  54576. ripplePath.animateStyle(true)
  54577. .when(effectCfg.period, {
  54578. opacity: 0
  54579. })
  54580. .delay(delay)
  54581. .start();
  54582. rippleGroup.add(ripplePath);
  54583. }
  54584. updateRipplePath(rippleGroup, effectCfg);
  54585. };
  54586. /**
  54587. * Update effect symbol
  54588. */
  54589. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  54590. var oldEffectCfg = this._effectCfg;
  54591. var rippleGroup = this.childAt(1);
  54592. // Must reinitialize effect if following configuration changed
  54593. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  54594. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  54595. var propName = DIFFICULT_PROPS[i];
  54596. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  54597. this.stopEffectAnimation();
  54598. this.startEffectAnimation(effectCfg);
  54599. return;
  54600. }
  54601. }
  54602. updateRipplePath(rippleGroup, effectCfg);
  54603. };
  54604. /**
  54605. * Highlight symbol
  54606. */
  54607. effectSymbolProto.highlight = function () {
  54608. this.trigger('emphasis');
  54609. };
  54610. /**
  54611. * Downplay symbol
  54612. */
  54613. effectSymbolProto.downplay = function () {
  54614. this.trigger('normal');
  54615. };
  54616. /**
  54617. * Update symbol properties
  54618. * @param {module:echarts/data/List} data
  54619. * @param {number} idx
  54620. */
  54621. effectSymbolProto.updateData = function (data, idx) {
  54622. var seriesModel = data.hostModel;
  54623. this.childAt(0).updateData(data, idx);
  54624. var rippleGroup = this.childAt(1);
  54625. var itemModel = data.getItemModel(idx);
  54626. var symbolType = data.getItemVisual(idx, 'symbol');
  54627. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  54628. var color = data.getItemVisual(idx, 'color');
  54629. rippleGroup.attr('scale', symbolSize);
  54630. rippleGroup.traverse(function (ripplePath) {
  54631. ripplePath.attr({
  54632. fill: color
  54633. });
  54634. });
  54635. var symbolOffset = itemModel.getShallow('symbolOffset');
  54636. if (symbolOffset) {
  54637. var pos = rippleGroup.position;
  54638. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  54639. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  54640. }
  54641. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  54642. var effectCfg = {};
  54643. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  54644. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  54645. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  54646. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  54647. effectCfg.effectOffset = idx / data.count();
  54648. effectCfg.z = itemModel.getShallow('z') || 0;
  54649. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  54650. effectCfg.symbolType = symbolType;
  54651. effectCfg.color = color;
  54652. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54653. if (effectCfg.showEffectOn === 'render') {
  54654. this._effectCfg
  54655. ? this.updateEffectAnimation(effectCfg)
  54656. : this.startEffectAnimation(effectCfg);
  54657. this._effectCfg = effectCfg;
  54658. }
  54659. else {
  54660. // Not keep old effect config
  54661. this._effectCfg = null;
  54662. this.stopEffectAnimation();
  54663. var symbol = this.childAt(0);
  54664. var onEmphasis = function () {
  54665. symbol.highlight();
  54666. if (effectCfg.showEffectOn !== 'render') {
  54667. this.startEffectAnimation(effectCfg);
  54668. }
  54669. };
  54670. var onNormal = function () {
  54671. symbol.downplay();
  54672. if (effectCfg.showEffectOn !== 'render') {
  54673. this.stopEffectAnimation();
  54674. }
  54675. };
  54676. this.on('mouseover', onEmphasis, this)
  54677. .on('mouseout', onNormal, this)
  54678. .on('emphasis', onEmphasis, this)
  54679. .on('normal', onNormal, this);
  54680. }
  54681. this._effectCfg = effectCfg;
  54682. };
  54683. effectSymbolProto.fadeOut = function (cb) {
  54684. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54685. cb && cb();
  54686. };
  54687. inherits(EffectSymbol, Group);
  54688. /*
  54689. * Licensed to the Apache Software Foundation (ASF) under one
  54690. * or more contributor license agreements. See the NOTICE file
  54691. * distributed with this work for additional information
  54692. * regarding copyright ownership. The ASF licenses this file
  54693. * to you under the Apache License, Version 2.0 (the
  54694. * "License"); you may not use this file except in compliance
  54695. * with the License. You may obtain a copy of the License at
  54696. *
  54697. * http://www.apache.org/licenses/LICENSE-2.0
  54698. *
  54699. * Unless required by applicable law or agreed to in writing,
  54700. * software distributed under the License is distributed on an
  54701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54702. * KIND, either express or implied. See the License for the
  54703. * specific language governing permissions and limitations
  54704. * under the License.
  54705. */
  54706. extendChartView({
  54707. type: 'effectScatter',
  54708. init: function () {
  54709. this._symbolDraw = new SymbolDraw(EffectSymbol);
  54710. },
  54711. render: function (seriesModel, ecModel, api) {
  54712. var data = seriesModel.getData();
  54713. var effectSymbolDraw = this._symbolDraw;
  54714. effectSymbolDraw.updateData(data);
  54715. this.group.add(effectSymbolDraw.group);
  54716. },
  54717. updateTransform: function (seriesModel, ecModel, api) {
  54718. var data = seriesModel.getData();
  54719. this.group.dirty();
  54720. var res = pointsLayout().reset(seriesModel);
  54721. if (res.progress) {
  54722. res.progress({ start: 0, end: data.count() }, data);
  54723. }
  54724. this._symbolDraw.updateLayout(data);
  54725. },
  54726. _updateGroupTransform: function (seriesModel) {
  54727. var coordSys = seriesModel.coordinateSystem;
  54728. if (coordSys && coordSys.getRoamTransform) {
  54729. this.group.transform = clone$2(coordSys.getRoamTransform());
  54730. this.group.decomposeTransform();
  54731. }
  54732. },
  54733. remove: function (ecModel, api) {
  54734. this._symbolDraw && this._symbolDraw.remove(api);
  54735. },
  54736. dispose: function () {}
  54737. });
  54738. /*
  54739. * Licensed to the Apache Software Foundation (ASF) under one
  54740. * or more contributor license agreements. See the NOTICE file
  54741. * distributed with this work for additional information
  54742. * regarding copyright ownership. The ASF licenses this file
  54743. * to you under the Apache License, Version 2.0 (the
  54744. * "License"); you may not use this file except in compliance
  54745. * with the License. You may obtain a copy of the License at
  54746. *
  54747. * http://www.apache.org/licenses/LICENSE-2.0
  54748. *
  54749. * Unless required by applicable law or agreed to in writing,
  54750. * software distributed under the License is distributed on an
  54751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54752. * KIND, either express or implied. See the License for the
  54753. * specific language governing permissions and limitations
  54754. * under the License.
  54755. */
  54756. registerVisual(visualSymbol('effectScatter', 'circle'));
  54757. registerLayout(pointsLayout('effectScatter'));
  54758. /*
  54759. * Licensed to the Apache Software Foundation (ASF) under one
  54760. * or more contributor license agreements. See the NOTICE file
  54761. * distributed with this work for additional information
  54762. * regarding copyright ownership. The ASF licenses this file
  54763. * to you under the Apache License, Version 2.0 (the
  54764. * "License"); you may not use this file except in compliance
  54765. * with the License. You may obtain a copy of the License at
  54766. *
  54767. * http://www.apache.org/licenses/LICENSE-2.0
  54768. *
  54769. * Unless required by applicable law or agreed to in writing,
  54770. * software distributed under the License is distributed on an
  54771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54772. * KIND, either express or implied. See the License for the
  54773. * specific language governing permissions and limitations
  54774. * under the License.
  54775. */
  54776. /* global Uint32Array, Float64Array, Float32Array */
  54777. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  54778. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  54779. function compatEc2(seriesOpt) {
  54780. var data = seriesOpt.data;
  54781. if (data && data[0] && data[0][0] && data[0][0].coord) {
  54782. if (__DEV__) {
  54783. console.warn('Lines data configuration has been changed to'
  54784. + ' { coords:[[1,2],[2,3]] }');
  54785. }
  54786. seriesOpt.data = map(data, function (itemOpt) {
  54787. var coords = [
  54788. itemOpt[0].coord, itemOpt[1].coord
  54789. ];
  54790. var target = {
  54791. coords: coords
  54792. };
  54793. if (itemOpt[0].name) {
  54794. target.fromName = itemOpt[0].name;
  54795. }
  54796. if (itemOpt[1].name) {
  54797. target.toName = itemOpt[1].name;
  54798. }
  54799. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  54800. });
  54801. }
  54802. }
  54803. var LinesSeries = SeriesModel.extend({
  54804. type: 'series.lines',
  54805. dependencies: ['grid', 'polar'],
  54806. visualColorAccessPath: 'lineStyle.color',
  54807. init: function (option) {
  54808. // The input data may be null/undefined.
  54809. option.data = option.data || [];
  54810. // Not using preprocessor because mergeOption may not have series.type
  54811. compatEc2(option);
  54812. var result = this._processFlatCoordsArray(option.data);
  54813. this._flatCoords = result.flatCoords;
  54814. this._flatCoordsOffset = result.flatCoordsOffset;
  54815. if (result.flatCoords) {
  54816. option.data = new Float32Array(result.count);
  54817. }
  54818. LinesSeries.superApply(this, 'init', arguments);
  54819. },
  54820. mergeOption: function (option) {
  54821. // The input data may be null/undefined.
  54822. option.data = option.data || [];
  54823. compatEc2(option);
  54824. if (option.data) {
  54825. // Only update when have option data to merge.
  54826. var result = this._processFlatCoordsArray(option.data);
  54827. this._flatCoords = result.flatCoords;
  54828. this._flatCoordsOffset = result.flatCoordsOffset;
  54829. if (result.flatCoords) {
  54830. option.data = new Float32Array(result.count);
  54831. }
  54832. }
  54833. LinesSeries.superApply(this, 'mergeOption', arguments);
  54834. },
  54835. appendData: function (params) {
  54836. var result = this._processFlatCoordsArray(params.data);
  54837. if (result.flatCoords) {
  54838. if (!this._flatCoords) {
  54839. this._flatCoords = result.flatCoords;
  54840. this._flatCoordsOffset = result.flatCoordsOffset;
  54841. }
  54842. else {
  54843. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  54844. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  54845. }
  54846. params.data = new Float32Array(result.count);
  54847. }
  54848. this.getRawData().appendData(params.data);
  54849. },
  54850. _getCoordsFromItemModel: function (idx) {
  54851. var itemModel = this.getData().getItemModel(idx);
  54852. var coords = (itemModel.option instanceof Array)
  54853. ? itemModel.option : itemModel.getShallow('coords');
  54854. if (__DEV__) {
  54855. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  54856. throw new Error(
  54857. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  54858. );
  54859. }
  54860. }
  54861. return coords;
  54862. },
  54863. getLineCoordsCount: function (idx) {
  54864. if (this._flatCoordsOffset) {
  54865. return this._flatCoordsOffset[idx * 2 + 1];
  54866. }
  54867. else {
  54868. return this._getCoordsFromItemModel(idx).length;
  54869. }
  54870. },
  54871. getLineCoords: function (idx, out) {
  54872. if (this._flatCoordsOffset) {
  54873. var offset = this._flatCoordsOffset[idx * 2];
  54874. var len = this._flatCoordsOffset[idx * 2 + 1];
  54875. for (var i = 0; i < len; i++) {
  54876. out[i] = out[i] || [];
  54877. out[i][0] = this._flatCoords[offset + i * 2];
  54878. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  54879. }
  54880. return len;
  54881. }
  54882. else {
  54883. var coords = this._getCoordsFromItemModel(idx);
  54884. for (var i = 0; i < coords.length; i++) {
  54885. out[i] = out[i] || [];
  54886. out[i][0] = coords[i][0];
  54887. out[i][1] = coords[i][1];
  54888. }
  54889. return coords.length;
  54890. }
  54891. },
  54892. _processFlatCoordsArray: function (data) {
  54893. var startOffset = 0;
  54894. if (this._flatCoords) {
  54895. startOffset = this._flatCoords.length;
  54896. }
  54897. // Stored as a typed array. In format
  54898. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  54899. if (typeof data[0] === 'number') {
  54900. var len = data.length;
  54901. // Store offset and len of each segment
  54902. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  54903. var coordsStorage = new Float64Arr(len);
  54904. var coordsCursor = 0;
  54905. var offsetCursor = 0;
  54906. var dataCount = 0;
  54907. for (var i = 0; i < len;) {
  54908. dataCount++;
  54909. var count = data[i++];
  54910. // Offset
  54911. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  54912. // Len
  54913. coordsOffsetAndLenStorage[offsetCursor++] = count;
  54914. for (var k = 0; k < count; k++) {
  54915. var x = data[i++];
  54916. var y = data[i++];
  54917. coordsStorage[coordsCursor++] = x;
  54918. coordsStorage[coordsCursor++] = y;
  54919. if (i > len) {
  54920. if (__DEV__) {
  54921. throw new Error('Invalid data format.');
  54922. }
  54923. }
  54924. }
  54925. }
  54926. return {
  54927. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  54928. flatCoords: coordsStorage,
  54929. count: dataCount
  54930. };
  54931. }
  54932. return {
  54933. flatCoordsOffset: null,
  54934. flatCoords: null,
  54935. count: data.length
  54936. };
  54937. },
  54938. getInitialData: function (option, ecModel) {
  54939. if (__DEV__) {
  54940. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  54941. if (!CoordSys) {
  54942. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  54943. }
  54944. }
  54945. var lineData = new List(['value'], this);
  54946. lineData.hasItemOption = false;
  54947. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  54948. // dataItem is simply coords
  54949. if (dataItem instanceof Array) {
  54950. return NaN;
  54951. }
  54952. else {
  54953. lineData.hasItemOption = true;
  54954. var value = dataItem.value;
  54955. if (value != null) {
  54956. return value instanceof Array ? value[dimIndex] : value;
  54957. }
  54958. }
  54959. });
  54960. return lineData;
  54961. },
  54962. formatTooltip: function (dataIndex) {
  54963. var data = this.getData();
  54964. var itemModel = data.getItemModel(dataIndex);
  54965. var name = itemModel.get('name');
  54966. if (name) {
  54967. return name;
  54968. }
  54969. var fromName = itemModel.get('fromName');
  54970. var toName = itemModel.get('toName');
  54971. var html = [];
  54972. fromName != null && html.push(fromName);
  54973. toName != null && html.push(toName);
  54974. return encodeHTML(html.join(' > '));
  54975. },
  54976. preventIncremental: function () {
  54977. return !!this.get('effect.show');
  54978. },
  54979. getProgressive: function () {
  54980. var progressive = this.option.progressive;
  54981. if (progressive == null) {
  54982. return this.option.large ? 1e4 : this.get('progressive');
  54983. }
  54984. return progressive;
  54985. },
  54986. getProgressiveThreshold: function () {
  54987. var progressiveThreshold = this.option.progressiveThreshold;
  54988. if (progressiveThreshold == null) {
  54989. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  54990. }
  54991. return progressiveThreshold;
  54992. },
  54993. defaultOption: {
  54994. coordinateSystem: 'geo',
  54995. zlevel: 0,
  54996. z: 2,
  54997. legendHoverLink: true,
  54998. hoverAnimation: true,
  54999. // Cartesian coordinate system
  55000. xAxisIndex: 0,
  55001. yAxisIndex: 0,
  55002. symbol: ['none', 'none'],
  55003. symbolSize: [10, 10],
  55004. // Geo coordinate system
  55005. geoIndex: 0,
  55006. effect: {
  55007. show: false,
  55008. period: 4,
  55009. // Animation delay. support callback
  55010. // delay: 0,
  55011. // If move with constant speed px/sec
  55012. // period will be ignored if this property is > 0,
  55013. constantSpeed: 0,
  55014. symbol: 'circle',
  55015. symbolSize: 3,
  55016. loop: true,
  55017. // Length of trail, 0 - 1
  55018. trailLength: 0.2
  55019. // Same with lineStyle.color
  55020. // color
  55021. },
  55022. large: false,
  55023. // Available when large is true
  55024. largeThreshold: 2000,
  55025. // If lines are polyline
  55026. // polyline not support curveness, label, animation
  55027. polyline: false,
  55028. label: {
  55029. show: false,
  55030. position: 'end'
  55031. // distance: 5,
  55032. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  55033. },
  55034. lineStyle: {
  55035. opacity: 0.5
  55036. }
  55037. }
  55038. });
  55039. /*
  55040. * Licensed to the Apache Software Foundation (ASF) under one
  55041. * or more contributor license agreements. See the NOTICE file
  55042. * distributed with this work for additional information
  55043. * regarding copyright ownership. The ASF licenses this file
  55044. * to you under the Apache License, Version 2.0 (the
  55045. * "License"); you may not use this file except in compliance
  55046. * with the License. You may obtain a copy of the License at
  55047. *
  55048. * http://www.apache.org/licenses/LICENSE-2.0
  55049. *
  55050. * Unless required by applicable law or agreed to in writing,
  55051. * software distributed under the License is distributed on an
  55052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55053. * KIND, either express or implied. See the License for the
  55054. * specific language governing permissions and limitations
  55055. * under the License.
  55056. */
  55057. /**
  55058. * Provide effect for line
  55059. * @module echarts/chart/helper/EffectLine
  55060. */
  55061. /**
  55062. * @constructor
  55063. * @extends {module:zrender/graphic/Group}
  55064. * @alias {module:echarts/chart/helper/Line}
  55065. */
  55066. function EffectLine(lineData, idx, seriesScope) {
  55067. Group.call(this);
  55068. this.add(this.createLine(lineData, idx, seriesScope));
  55069. this._updateEffectSymbol(lineData, idx);
  55070. }
  55071. var effectLineProto = EffectLine.prototype;
  55072. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  55073. return new Line$1(lineData, idx, seriesScope);
  55074. };
  55075. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  55076. var itemModel = lineData.getItemModel(idx);
  55077. var effectModel = itemModel.getModel('effect');
  55078. var size = effectModel.get('symbolSize');
  55079. var symbolType = effectModel.get('symbol');
  55080. if (!isArray(size)) {
  55081. size = [size, size];
  55082. }
  55083. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  55084. var symbol = this.childAt(1);
  55085. if (this._symbolType !== symbolType) {
  55086. // Remove previous
  55087. this.remove(symbol);
  55088. symbol = createSymbol(
  55089. symbolType, -0.5, -0.5, 1, 1, color
  55090. );
  55091. symbol.z2 = 100;
  55092. symbol.culling = true;
  55093. this.add(symbol);
  55094. }
  55095. // Symbol may be removed if loop is false
  55096. if (!symbol) {
  55097. return;
  55098. }
  55099. // Shadow color is same with color in default
  55100. symbol.setStyle('shadowColor', color);
  55101. symbol.setStyle(effectModel.getItemStyle(['color']));
  55102. symbol.attr('scale', size);
  55103. symbol.setColor(color);
  55104. symbol.attr('scale', size);
  55105. this._symbolType = symbolType;
  55106. this._updateEffectAnimation(lineData, effectModel, idx);
  55107. };
  55108. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  55109. var symbol = this.childAt(1);
  55110. if (!symbol) {
  55111. return;
  55112. }
  55113. var self = this;
  55114. var points = lineData.getItemLayout(idx);
  55115. var period = effectModel.get('period') * 1000;
  55116. var loop = effectModel.get('loop');
  55117. var constantSpeed = effectModel.get('constantSpeed');
  55118. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  55119. return idx / lineData.count() * period / 3;
  55120. });
  55121. var isDelayFunc = typeof delayExpr === 'function';
  55122. // Ignore when updating
  55123. symbol.ignore = true;
  55124. this.updateAnimationPoints(symbol, points);
  55125. if (constantSpeed > 0) {
  55126. period = this.getLineLength(symbol) / constantSpeed * 1000;
  55127. }
  55128. if (period !== this._period || loop !== this._loop) {
  55129. symbol.stopAnimation();
  55130. var delay = delayExpr;
  55131. if (isDelayFunc) {
  55132. delay = delayExpr(idx);
  55133. }
  55134. if (symbol.__t > 0) {
  55135. delay = -period * symbol.__t;
  55136. }
  55137. symbol.__t = 0;
  55138. var animator = symbol.animate('', loop)
  55139. .when(period, {
  55140. __t: 1
  55141. })
  55142. .delay(delay)
  55143. .during(function () {
  55144. self.updateSymbolPosition(symbol);
  55145. });
  55146. if (!loop) {
  55147. animator.done(function () {
  55148. self.remove(symbol);
  55149. });
  55150. }
  55151. animator.start();
  55152. }
  55153. this._period = period;
  55154. this._loop = loop;
  55155. };
  55156. effectLineProto.getLineLength = function (symbol) {
  55157. // Not so accurate
  55158. return (dist(symbol.__p1, symbol.__cp1)
  55159. + dist(symbol.__cp1, symbol.__p2));
  55160. };
  55161. effectLineProto.updateAnimationPoints = function (symbol, points) {
  55162. symbol.__p1 = points[0];
  55163. symbol.__p2 = points[1];
  55164. symbol.__cp1 = points[2] || [
  55165. (points[0][0] + points[1][0]) / 2,
  55166. (points[0][1] + points[1][1]) / 2
  55167. ];
  55168. };
  55169. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  55170. this.childAt(0).updateData(lineData, idx, seriesScope);
  55171. this._updateEffectSymbol(lineData, idx);
  55172. };
  55173. effectLineProto.updateSymbolPosition = function (symbol) {
  55174. var p1 = symbol.__p1;
  55175. var p2 = symbol.__p2;
  55176. var cp1 = symbol.__cp1;
  55177. var t = symbol.__t;
  55178. var pos = symbol.position;
  55179. var quadraticAt$$1 = quadraticAt;
  55180. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  55181. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  55182. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  55183. // Tangent
  55184. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  55185. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  55186. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  55187. symbol.ignore = false;
  55188. };
  55189. effectLineProto.updateLayout = function (lineData, idx) {
  55190. this.childAt(0).updateLayout(lineData, idx);
  55191. var effectModel = lineData.getItemModel(idx).getModel('effect');
  55192. this._updateEffectAnimation(lineData, effectModel, idx);
  55193. };
  55194. inherits(EffectLine, Group);
  55195. /*
  55196. * Licensed to the Apache Software Foundation (ASF) under one
  55197. * or more contributor license agreements. See the NOTICE file
  55198. * distributed with this work for additional information
  55199. * regarding copyright ownership. The ASF licenses this file
  55200. * to you under the Apache License, Version 2.0 (the
  55201. * "License"); you may not use this file except in compliance
  55202. * with the License. You may obtain a copy of the License at
  55203. *
  55204. * http://www.apache.org/licenses/LICENSE-2.0
  55205. *
  55206. * Unless required by applicable law or agreed to in writing,
  55207. * software distributed under the License is distributed on an
  55208. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55209. * KIND, either express or implied. See the License for the
  55210. * specific language governing permissions and limitations
  55211. * under the License.
  55212. */
  55213. /**
  55214. * @module echarts/chart/helper/Line
  55215. */
  55216. /**
  55217. * @constructor
  55218. * @extends {module:zrender/graphic/Group}
  55219. * @alias {module:echarts/chart/helper/Polyline}
  55220. */
  55221. function Polyline$2(lineData, idx, seriesScope) {
  55222. Group.call(this);
  55223. this._createPolyline(lineData, idx, seriesScope);
  55224. }
  55225. var polylineProto = Polyline$2.prototype;
  55226. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  55227. // var seriesModel = lineData.hostModel;
  55228. var points = lineData.getItemLayout(idx);
  55229. var line = new Polyline({
  55230. shape: {
  55231. points: points
  55232. }
  55233. });
  55234. this.add(line);
  55235. this._updateCommonStl(lineData, idx, seriesScope);
  55236. };
  55237. polylineProto.updateData = function (lineData, idx, seriesScope) {
  55238. var seriesModel = lineData.hostModel;
  55239. var line = this.childAt(0);
  55240. var target = {
  55241. shape: {
  55242. points: lineData.getItemLayout(idx)
  55243. }
  55244. };
  55245. updateProps(line, target, seriesModel, idx);
  55246. this._updateCommonStl(lineData, idx, seriesScope);
  55247. };
  55248. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  55249. var line = this.childAt(0);
  55250. var itemModel = lineData.getItemModel(idx);
  55251. var visualColor = lineData.getItemVisual(idx, 'color');
  55252. var lineStyle = seriesScope && seriesScope.lineStyle;
  55253. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  55254. if (!seriesScope || lineData.hasItemOption) {
  55255. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  55256. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  55257. }
  55258. line.useStyle(defaults(
  55259. {
  55260. strokeNoScale: true,
  55261. fill: 'none',
  55262. stroke: visualColor
  55263. },
  55264. lineStyle
  55265. ));
  55266. line.hoverStyle = hoverLineStyle;
  55267. setHoverStyle(this);
  55268. };
  55269. polylineProto.updateLayout = function (lineData, idx) {
  55270. var polyline = this.childAt(0);
  55271. polyline.setShape('points', lineData.getItemLayout(idx));
  55272. };
  55273. inherits(Polyline$2, Group);
  55274. /*
  55275. * Licensed to the Apache Software Foundation (ASF) under one
  55276. * or more contributor license agreements. See the NOTICE file
  55277. * distributed with this work for additional information
  55278. * regarding copyright ownership. The ASF licenses this file
  55279. * to you under the Apache License, Version 2.0 (the
  55280. * "License"); you may not use this file except in compliance
  55281. * with the License. You may obtain a copy of the License at
  55282. *
  55283. * http://www.apache.org/licenses/LICENSE-2.0
  55284. *
  55285. * Unless required by applicable law or agreed to in writing,
  55286. * software distributed under the License is distributed on an
  55287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55288. * KIND, either express or implied. See the License for the
  55289. * specific language governing permissions and limitations
  55290. * under the License.
  55291. */
  55292. /**
  55293. * Provide effect for line
  55294. * @module echarts/chart/helper/EffectLine
  55295. */
  55296. /**
  55297. * @constructor
  55298. * @extends {module:echarts/chart/helper/EffectLine}
  55299. * @alias {module:echarts/chart/helper/Polyline}
  55300. */
  55301. function EffectPolyline(lineData, idx, seriesScope) {
  55302. EffectLine.call(this, lineData, idx, seriesScope);
  55303. this._lastFrame = 0;
  55304. this._lastFramePercent = 0;
  55305. }
  55306. var effectPolylineProto = EffectPolyline.prototype;
  55307. // Overwrite
  55308. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  55309. return new Polyline$2(lineData, idx, seriesScope);
  55310. };
  55311. // Overwrite
  55312. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  55313. this._points = points;
  55314. var accLenArr = [0];
  55315. var len$$1 = 0;
  55316. for (var i = 1; i < points.length; i++) {
  55317. var p1 = points[i - 1];
  55318. var p2 = points[i];
  55319. len$$1 += dist(p1, p2);
  55320. accLenArr.push(len$$1);
  55321. }
  55322. if (len$$1 === 0) {
  55323. return;
  55324. }
  55325. for (var i = 0; i < accLenArr.length; i++) {
  55326. accLenArr[i] /= len$$1;
  55327. }
  55328. this._offsets = accLenArr;
  55329. this._length = len$$1;
  55330. };
  55331. // Overwrite
  55332. effectPolylineProto.getLineLength = function (symbol) {
  55333. return this._length;
  55334. };
  55335. // Overwrite
  55336. effectPolylineProto.updateSymbolPosition = function (symbol) {
  55337. var t = symbol.__t;
  55338. var points = this._points;
  55339. var offsets = this._offsets;
  55340. var len$$1 = points.length;
  55341. if (!offsets) {
  55342. // Has length 0
  55343. return;
  55344. }
  55345. var lastFrame = this._lastFrame;
  55346. var frame;
  55347. if (t < this._lastFramePercent) {
  55348. // Start from the next frame
  55349. // PENDING start from lastFrame ?
  55350. var start = Math.min(lastFrame + 1, len$$1 - 1);
  55351. for (frame = start; frame >= 0; frame--) {
  55352. if (offsets[frame] <= t) {
  55353. break;
  55354. }
  55355. }
  55356. // PENDING really need to do this ?
  55357. frame = Math.min(frame, len$$1 - 2);
  55358. }
  55359. else {
  55360. for (var frame = lastFrame; frame < len$$1; frame++) {
  55361. if (offsets[frame] > t) {
  55362. break;
  55363. }
  55364. }
  55365. frame = Math.min(frame - 1, len$$1 - 2);
  55366. }
  55367. lerp(
  55368. symbol.position, points[frame], points[frame + 1],
  55369. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  55370. );
  55371. var tx = points[frame + 1][0] - points[frame][0];
  55372. var ty = points[frame + 1][1] - points[frame][1];
  55373. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  55374. this._lastFrame = frame;
  55375. this._lastFramePercent = t;
  55376. symbol.ignore = false;
  55377. };
  55378. inherits(EffectPolyline, EffectLine);
  55379. /*
  55380. * Licensed to the Apache Software Foundation (ASF) under one
  55381. * or more contributor license agreements. See the NOTICE file
  55382. * distributed with this work for additional information
  55383. * regarding copyright ownership. The ASF licenses this file
  55384. * to you under the Apache License, Version 2.0 (the
  55385. * "License"); you may not use this file except in compliance
  55386. * with the License. You may obtain a copy of the License at
  55387. *
  55388. * http://www.apache.org/licenses/LICENSE-2.0
  55389. *
  55390. * Unless required by applicable law or agreed to in writing,
  55391. * software distributed under the License is distributed on an
  55392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55393. * KIND, either express or implied. See the License for the
  55394. * specific language governing permissions and limitations
  55395. * under the License.
  55396. */
  55397. // TODO Batch by color
  55398. var LargeLineShape = extendShape({
  55399. shape: {
  55400. polyline: false,
  55401. curveness: 0,
  55402. segs: []
  55403. },
  55404. buildPath: function (path, shape) {
  55405. var segs = shape.segs;
  55406. var curveness = shape.curveness;
  55407. if (shape.polyline) {
  55408. for (var i = 0; i < segs.length;) {
  55409. var count = segs[i++];
  55410. if (count > 0) {
  55411. path.moveTo(segs[i++], segs[i++]);
  55412. for (var k = 1; k < count; k++) {
  55413. path.lineTo(segs[i++], segs[i++]);
  55414. }
  55415. }
  55416. }
  55417. }
  55418. else {
  55419. for (var i = 0; i < segs.length;) {
  55420. var x0 = segs[i++];
  55421. var y0 = segs[i++];
  55422. var x1 = segs[i++];
  55423. var y1 = segs[i++];
  55424. path.moveTo(x0, y0);
  55425. if (curveness > 0) {
  55426. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  55427. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  55428. path.quadraticCurveTo(x2, y2, x1, y1);
  55429. }
  55430. else {
  55431. path.lineTo(x1, y1);
  55432. }
  55433. }
  55434. }
  55435. },
  55436. findDataIndex: function (x, y) {
  55437. var shape = this.shape;
  55438. var segs = shape.segs;
  55439. var curveness = shape.curveness;
  55440. if (shape.polyline) {
  55441. var dataIndex = 0;
  55442. for (var i = 0; i < segs.length;) {
  55443. var count = segs[i++];
  55444. if (count > 0) {
  55445. var x0 = segs[i++];
  55446. var y0 = segs[i++];
  55447. for (var k = 1; k < count; k++) {
  55448. var x1 = segs[i++];
  55449. var y1 = segs[i++];
  55450. if (containStroke$1(x0, y0, x1, y1)) {
  55451. return dataIndex;
  55452. }
  55453. }
  55454. }
  55455. dataIndex++;
  55456. }
  55457. }
  55458. else {
  55459. var dataIndex = 0;
  55460. for (var i = 0; i < segs.length;) {
  55461. var x0 = segs[i++];
  55462. var y0 = segs[i++];
  55463. var x1 = segs[i++];
  55464. var y1 = segs[i++];
  55465. if (curveness > 0) {
  55466. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  55467. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  55468. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  55469. return dataIndex;
  55470. }
  55471. }
  55472. else {
  55473. if (containStroke$1(x0, y0, x1, y1)) {
  55474. return dataIndex;
  55475. }
  55476. }
  55477. dataIndex++;
  55478. }
  55479. }
  55480. return -1;
  55481. }
  55482. });
  55483. function LargeLineDraw() {
  55484. this.group = new Group();
  55485. }
  55486. var largeLineProto = LargeLineDraw.prototype;
  55487. largeLineProto.isPersistent = function () {
  55488. return !this._incremental;
  55489. };
  55490. /**
  55491. * Update symbols draw by new data
  55492. * @param {module:echarts/data/List} data
  55493. */
  55494. largeLineProto.updateData = function (data) {
  55495. this.group.removeAll();
  55496. var lineEl = new LargeLineShape({
  55497. rectHover: true,
  55498. cursor: 'default'
  55499. });
  55500. lineEl.setShape({
  55501. segs: data.getLayout('linesPoints')
  55502. });
  55503. this._setCommon(lineEl, data);
  55504. // Add back
  55505. this.group.add(lineEl);
  55506. this._incremental = null;
  55507. };
  55508. /**
  55509. * @override
  55510. */
  55511. largeLineProto.incrementalPrepareUpdate = function (data) {
  55512. this.group.removeAll();
  55513. this._clearIncremental();
  55514. if (data.count() > 5e5) {
  55515. if (!this._incremental) {
  55516. this._incremental = new IncrementalDisplayble({
  55517. silent: true
  55518. });
  55519. }
  55520. this.group.add(this._incremental);
  55521. }
  55522. else {
  55523. this._incremental = null;
  55524. }
  55525. };
  55526. /**
  55527. * @override
  55528. */
  55529. largeLineProto.incrementalUpdate = function (taskParams, data) {
  55530. var lineEl = new LargeLineShape();
  55531. lineEl.setShape({
  55532. segs: data.getLayout('linesPoints')
  55533. });
  55534. this._setCommon(lineEl, data, !!this._incremental);
  55535. if (!this._incremental) {
  55536. lineEl.rectHover = true;
  55537. lineEl.cursor = 'default';
  55538. lineEl.__startIndex = taskParams.start;
  55539. this.group.add(lineEl);
  55540. }
  55541. else {
  55542. this._incremental.addDisplayable(lineEl, true);
  55543. }
  55544. };
  55545. /**
  55546. * @override
  55547. */
  55548. largeLineProto.remove = function () {
  55549. this._clearIncremental();
  55550. this._incremental = null;
  55551. this.group.removeAll();
  55552. };
  55553. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  55554. var hostModel = data.hostModel;
  55555. lineEl.setShape({
  55556. polyline: hostModel.get('polyline'),
  55557. curveness: hostModel.get('lineStyle.curveness')
  55558. });
  55559. lineEl.useStyle(
  55560. hostModel.getModel('lineStyle').getLineStyle()
  55561. );
  55562. lineEl.style.strokeNoScale = true;
  55563. var visualColor = data.getVisual('color');
  55564. if (visualColor) {
  55565. lineEl.setStyle('stroke', visualColor);
  55566. }
  55567. lineEl.setStyle('fill');
  55568. if (!isIncremental) {
  55569. // Enable tooltip
  55570. // PENDING May have performance issue when path is extremely large
  55571. lineEl.seriesIndex = hostModel.seriesIndex;
  55572. lineEl.on('mousemove', function (e) {
  55573. lineEl.dataIndex = null;
  55574. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  55575. if (dataIndex > 0) {
  55576. // Provide dataIndex for tooltip
  55577. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  55578. }
  55579. });
  55580. }
  55581. };
  55582. largeLineProto._clearIncremental = function () {
  55583. var incremental = this._incremental;
  55584. if (incremental) {
  55585. incremental.clearDisplaybles();
  55586. }
  55587. };
  55588. /*
  55589. * Licensed to the Apache Software Foundation (ASF) under one
  55590. * or more contributor license agreements. See the NOTICE file
  55591. * distributed with this work for additional information
  55592. * regarding copyright ownership. The ASF licenses this file
  55593. * to you under the Apache License, Version 2.0 (the
  55594. * "License"); you may not use this file except in compliance
  55595. * with the License. You may obtain a copy of the License at
  55596. *
  55597. * http://www.apache.org/licenses/LICENSE-2.0
  55598. *
  55599. * Unless required by applicable law or agreed to in writing,
  55600. * software distributed under the License is distributed on an
  55601. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55602. * KIND, either express or implied. See the License for the
  55603. * specific language governing permissions and limitations
  55604. * under the License.
  55605. */
  55606. /* global Float32Array */
  55607. var linesLayout = {
  55608. seriesType: 'lines',
  55609. plan: createRenderPlanner(),
  55610. reset: function (seriesModel) {
  55611. var coordSys = seriesModel.coordinateSystem;
  55612. var isPolyline = seriesModel.get('polyline');
  55613. var isLarge = seriesModel.pipelineContext.large;
  55614. function progress(params, lineData) {
  55615. var lineCoords = [];
  55616. if (isLarge) {
  55617. var points;
  55618. var segCount = params.end - params.start;
  55619. if (isPolyline) {
  55620. var totalCoordsCount = 0;
  55621. for (var i = params.start; i < params.end; i++) {
  55622. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  55623. }
  55624. points = new Float32Array(segCount + totalCoordsCount * 2);
  55625. }
  55626. else {
  55627. points = new Float32Array(segCount * 4);
  55628. }
  55629. var offset = 0;
  55630. var pt = [];
  55631. for (var i = params.start; i < params.end; i++) {
  55632. var len = seriesModel.getLineCoords(i, lineCoords);
  55633. if (isPolyline) {
  55634. points[offset++] = len;
  55635. }
  55636. for (var k = 0; k < len; k++) {
  55637. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  55638. points[offset++] = pt[0];
  55639. points[offset++] = pt[1];
  55640. }
  55641. }
  55642. lineData.setLayout('linesPoints', points);
  55643. }
  55644. else {
  55645. for (var i = params.start; i < params.end; i++) {
  55646. var itemModel = lineData.getItemModel(i);
  55647. var len = seriesModel.getLineCoords(i, lineCoords);
  55648. var pts = [];
  55649. if (isPolyline) {
  55650. for (var j = 0; j < len; j++) {
  55651. pts.push(coordSys.dataToPoint(lineCoords[j]));
  55652. }
  55653. }
  55654. else {
  55655. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  55656. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  55657. var curveness = itemModel.get('lineStyle.curveness');
  55658. if (+curveness) {
  55659. pts[2] = [
  55660. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  55661. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  55662. ];
  55663. }
  55664. }
  55665. lineData.setItemLayout(i, pts);
  55666. }
  55667. }
  55668. }
  55669. return { progress: progress };
  55670. }
  55671. };
  55672. /*
  55673. * Licensed to the Apache Software Foundation (ASF) under one
  55674. * or more contributor license agreements. See the NOTICE file
  55675. * distributed with this work for additional information
  55676. * regarding copyright ownership. The ASF licenses this file
  55677. * to you under the Apache License, Version 2.0 (the
  55678. * "License"); you may not use this file except in compliance
  55679. * with the License. You may obtain a copy of the License at
  55680. *
  55681. * http://www.apache.org/licenses/LICENSE-2.0
  55682. *
  55683. * Unless required by applicable law or agreed to in writing,
  55684. * software distributed under the License is distributed on an
  55685. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55686. * KIND, either express or implied. See the License for the
  55687. * specific language governing permissions and limitations
  55688. * under the License.
  55689. */
  55690. extendChartView({
  55691. type: 'lines',
  55692. init: function () {},
  55693. render: function (seriesModel, ecModel, api) {
  55694. var data = seriesModel.getData();
  55695. var lineDraw = this._updateLineDraw(data, seriesModel);
  55696. var zlevel = seriesModel.get('zlevel');
  55697. var trailLength = seriesModel.get('effect.trailLength');
  55698. var zr = api.getZr();
  55699. // Avoid the drag cause ghost shadow
  55700. // FIXME Better way ?
  55701. // SVG doesn't support
  55702. var isSvg = zr.painter.getType() === 'svg';
  55703. if (!isSvg) {
  55704. zr.painter.getLayer(zlevel).clear(true);
  55705. }
  55706. // Config layer with motion blur
  55707. if (this._lastZlevel != null && !isSvg) {
  55708. zr.configLayer(this._lastZlevel, {
  55709. motionBlur: false
  55710. });
  55711. }
  55712. if (this._showEffect(seriesModel) && trailLength) {
  55713. if (__DEV__) {
  55714. var notInIndividual = false;
  55715. ecModel.eachSeries(function (otherSeriesModel) {
  55716. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  55717. notInIndividual = true;
  55718. }
  55719. });
  55720. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  55721. }
  55722. if (!isSvg) {
  55723. zr.configLayer(zlevel, {
  55724. motionBlur: true,
  55725. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  55726. });
  55727. }
  55728. }
  55729. lineDraw.updateData(data);
  55730. this._lastZlevel = zlevel;
  55731. this._finished = true;
  55732. },
  55733. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  55734. var data = seriesModel.getData();
  55735. var lineDraw = this._updateLineDraw(data, seriesModel);
  55736. lineDraw.incrementalPrepareUpdate(data);
  55737. this._clearLayer(api);
  55738. this._finished = false;
  55739. },
  55740. incrementalRender: function (taskParams, seriesModel, ecModel) {
  55741. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  55742. this._finished = taskParams.end === seriesModel.getData().count();
  55743. },
  55744. updateTransform: function (seriesModel, ecModel, api) {
  55745. var data = seriesModel.getData();
  55746. var pipelineContext = seriesModel.pipelineContext;
  55747. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  55748. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  55749. return {
  55750. update: true
  55751. };
  55752. }
  55753. else {
  55754. // TODO Use same logic with ScatterView.
  55755. // Manually update layout
  55756. var res = linesLayout.reset(seriesModel);
  55757. if (res.progress) {
  55758. res.progress({ start: 0, end: data.count() }, data);
  55759. }
  55760. this._lineDraw.updateLayout();
  55761. this._clearLayer(api);
  55762. }
  55763. },
  55764. _updateLineDraw: function (data, seriesModel) {
  55765. var lineDraw = this._lineDraw;
  55766. var hasEffect = this._showEffect(seriesModel);
  55767. var isPolyline = !!seriesModel.get('polyline');
  55768. var pipelineContext = seriesModel.pipelineContext;
  55769. var isLargeDraw = pipelineContext.large;
  55770. if (__DEV__) {
  55771. if (hasEffect && isLargeDraw) {
  55772. console.warn('Large lines not support effect');
  55773. }
  55774. }
  55775. if (!lineDraw
  55776. || hasEffect !== this._hasEffet
  55777. || isPolyline !== this._isPolyline
  55778. || isLargeDraw !== this._isLargeDraw
  55779. ) {
  55780. if (lineDraw) {
  55781. lineDraw.remove();
  55782. }
  55783. lineDraw = this._lineDraw = isLargeDraw
  55784. ? new LargeLineDraw()
  55785. : new LineDraw(
  55786. isPolyline
  55787. ? (hasEffect ? EffectPolyline : Polyline$2)
  55788. : (hasEffect ? EffectLine : Line$1)
  55789. );
  55790. this._hasEffet = hasEffect;
  55791. this._isPolyline = isPolyline;
  55792. this._isLargeDraw = isLargeDraw;
  55793. this.group.removeAll();
  55794. }
  55795. this.group.add(lineDraw.group);
  55796. return lineDraw;
  55797. },
  55798. _showEffect: function (seriesModel) {
  55799. return !!seriesModel.get('effect.show');
  55800. },
  55801. _clearLayer: function (api) {
  55802. // Not use motion when dragging or zooming
  55803. var zr = api.getZr();
  55804. var isSvg = zr.painter.getType() === 'svg';
  55805. if (!isSvg && this._lastZlevel != null) {
  55806. zr.painter.getLayer(this._lastZlevel).clear(true);
  55807. }
  55808. },
  55809. remove: function (ecModel, api) {
  55810. this._lineDraw && this._lineDraw.remove();
  55811. this._lineDraw = null;
  55812. // Clear motion when lineDraw is removed
  55813. this._clearLayer(api);
  55814. },
  55815. dispose: function () {}
  55816. });
  55817. /*
  55818. * Licensed to the Apache Software Foundation (ASF) under one
  55819. * or more contributor license agreements. See the NOTICE file
  55820. * distributed with this work for additional information
  55821. * regarding copyright ownership. The ASF licenses this file
  55822. * to you under the Apache License, Version 2.0 (the
  55823. * "License"); you may not use this file except in compliance
  55824. * with the License. You may obtain a copy of the License at
  55825. *
  55826. * http://www.apache.org/licenses/LICENSE-2.0
  55827. *
  55828. * Unless required by applicable law or agreed to in writing,
  55829. * software distributed under the License is distributed on an
  55830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55831. * KIND, either express or implied. See the License for the
  55832. * specific language governing permissions and limitations
  55833. * under the License.
  55834. */
  55835. function normalize$2(a) {
  55836. if (!(a instanceof Array)) {
  55837. a = [a, a];
  55838. }
  55839. return a;
  55840. }
  55841. var opacityQuery = 'lineStyle.opacity'.split('.');
  55842. var linesVisual = {
  55843. seriesType: 'lines',
  55844. reset: function (seriesModel, ecModel, api) {
  55845. var symbolType = normalize$2(seriesModel.get('symbol'));
  55846. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  55847. var data = seriesModel.getData();
  55848. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  55849. data.setVisual('toSymbol', symbolType && symbolType[1]);
  55850. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  55851. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  55852. data.setVisual('opacity', seriesModel.get(opacityQuery));
  55853. function dataEach(data, idx) {
  55854. var itemModel = data.getItemModel(idx);
  55855. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  55856. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  55857. var opacity = itemModel.get(opacityQuery);
  55858. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  55859. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  55860. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  55861. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  55862. data.setItemVisual(idx, 'opacity', opacity);
  55863. }
  55864. return {dataEach: data.hasItemOption ? dataEach : null};
  55865. }
  55866. };
  55867. /*
  55868. * Licensed to the Apache Software Foundation (ASF) under one
  55869. * or more contributor license agreements. See the NOTICE file
  55870. * distributed with this work for additional information
  55871. * regarding copyright ownership. The ASF licenses this file
  55872. * to you under the Apache License, Version 2.0 (the
  55873. * "License"); you may not use this file except in compliance
  55874. * with the License. You may obtain a copy of the License at
  55875. *
  55876. * http://www.apache.org/licenses/LICENSE-2.0
  55877. *
  55878. * Unless required by applicable law or agreed to in writing,
  55879. * software distributed under the License is distributed on an
  55880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55881. * KIND, either express or implied. See the License for the
  55882. * specific language governing permissions and limitations
  55883. * under the License.
  55884. */
  55885. registerLayout(linesLayout);
  55886. registerVisual(linesVisual);
  55887. /*
  55888. * Licensed to the Apache Software Foundation (ASF) under one
  55889. * or more contributor license agreements. See the NOTICE file
  55890. * distributed with this work for additional information
  55891. * regarding copyright ownership. The ASF licenses this file
  55892. * to you under the Apache License, Version 2.0 (the
  55893. * "License"); you may not use this file except in compliance
  55894. * with the License. You may obtain a copy of the License at
  55895. *
  55896. * http://www.apache.org/licenses/LICENSE-2.0
  55897. *
  55898. * Unless required by applicable law or agreed to in writing,
  55899. * software distributed under the License is distributed on an
  55900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55901. * KIND, either express or implied. See the License for the
  55902. * specific language governing permissions and limitations
  55903. * under the License.
  55904. */
  55905. SeriesModel.extend({
  55906. type: 'series.heatmap',
  55907. getInitialData: function (option, ecModel) {
  55908. return createListFromArray(this.getSource(), this, {
  55909. generateCoord: 'value'
  55910. });
  55911. },
  55912. preventIncremental: function () {
  55913. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  55914. if (coordSysCreator && coordSysCreator.dimensions) {
  55915. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  55916. }
  55917. },
  55918. defaultOption: {
  55919. // Cartesian2D or geo
  55920. coordinateSystem: 'cartesian2d',
  55921. zlevel: 0,
  55922. z: 2,
  55923. // Cartesian coordinate system
  55924. // xAxisIndex: 0,
  55925. // yAxisIndex: 0,
  55926. // Geo coordinate system
  55927. geoIndex: 0,
  55928. blurSize: 30,
  55929. pointSize: 20,
  55930. maxOpacity: 1,
  55931. minOpacity: 0
  55932. }
  55933. });
  55934. /*
  55935. * Licensed to the Apache Software Foundation (ASF) under one
  55936. * or more contributor license agreements. See the NOTICE file
  55937. * distributed with this work for additional information
  55938. * regarding copyright ownership. The ASF licenses this file
  55939. * to you under the Apache License, Version 2.0 (the
  55940. * "License"); you may not use this file except in compliance
  55941. * with the License. You may obtain a copy of the License at
  55942. *
  55943. * http://www.apache.org/licenses/LICENSE-2.0
  55944. *
  55945. * Unless required by applicable law or agreed to in writing,
  55946. * software distributed under the License is distributed on an
  55947. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55948. * KIND, either express or implied. See the License for the
  55949. * specific language governing permissions and limitations
  55950. * under the License.
  55951. */
  55952. /* global Uint8ClampedArray */
  55953. /**
  55954. * @file defines echarts Heatmap Chart
  55955. * @author Ovilia (me@zhangwenli.com)
  55956. * Inspired by https://github.com/mourner/simpleheat
  55957. *
  55958. * @module
  55959. */
  55960. var GRADIENT_LEVELS = 256;
  55961. /**
  55962. * Heatmap Chart
  55963. *
  55964. * @class
  55965. */
  55966. function Heatmap() {
  55967. var canvas = createCanvas();
  55968. this.canvas = canvas;
  55969. this.blurSize = 30;
  55970. this.pointSize = 20;
  55971. this.maxOpacity = 1;
  55972. this.minOpacity = 0;
  55973. this._gradientPixels = {};
  55974. }
  55975. Heatmap.prototype = {
  55976. /**
  55977. * Renders Heatmap and returns the rendered canvas
  55978. * @param {Array} data array of data, each has x, y, value
  55979. * @param {number} width canvas width
  55980. * @param {number} height canvas height
  55981. */
  55982. update: function (data, width, height, normalize, colorFunc, isInRange) {
  55983. var brush = this._getBrush();
  55984. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  55985. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  55986. var r = this.pointSize + this.blurSize;
  55987. var canvas = this.canvas;
  55988. var ctx = canvas.getContext('2d');
  55989. var len = data.length;
  55990. canvas.width = width;
  55991. canvas.height = height;
  55992. for (var i = 0; i < len; ++i) {
  55993. var p = data[i];
  55994. var x = p[0];
  55995. var y = p[1];
  55996. var value = p[2];
  55997. // calculate alpha using value
  55998. var alpha = normalize(value);
  55999. // draw with the circle brush with alpha
  56000. ctx.globalAlpha = alpha;
  56001. ctx.drawImage(brush, x - r, y - r);
  56002. }
  56003. if (!canvas.width || !canvas.height) {
  56004. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  56005. // 'CanvasRenderingContext2D': The source height is 0."
  56006. return canvas;
  56007. }
  56008. // colorize the canvas using alpha value and set with gradient
  56009. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  56010. var pixels = imageData.data;
  56011. var offset = 0;
  56012. var pixelLen = pixels.length;
  56013. var minOpacity = this.minOpacity;
  56014. var maxOpacity = this.maxOpacity;
  56015. var diffOpacity = maxOpacity - minOpacity;
  56016. while (offset < pixelLen) {
  56017. var alpha = pixels[offset + 3] / 256;
  56018. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  56019. // Simple optimize to ignore the empty data
  56020. if (alpha > 0) {
  56021. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  56022. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  56023. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  56024. pixels[offset++] = gradient[gradientOffset];
  56025. pixels[offset++] = gradient[gradientOffset + 1];
  56026. pixels[offset++] = gradient[gradientOffset + 2];
  56027. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  56028. }
  56029. else {
  56030. offset += 4;
  56031. }
  56032. }
  56033. ctx.putImageData(imageData, 0, 0);
  56034. return canvas;
  56035. },
  56036. /**
  56037. * get canvas of a black circle brush used for canvas to draw later
  56038. * @private
  56039. * @returns {Object} circle brush canvas
  56040. */
  56041. _getBrush: function () {
  56042. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  56043. // set brush size
  56044. var r = this.pointSize + this.blurSize;
  56045. var d = r * 2;
  56046. brushCanvas.width = d;
  56047. brushCanvas.height = d;
  56048. var ctx = brushCanvas.getContext('2d');
  56049. ctx.clearRect(0, 0, d, d);
  56050. // in order to render shadow without the distinct circle,
  56051. // draw the distinct circle in an invisible place,
  56052. // and use shadowOffset to draw shadow in the center of the canvas
  56053. ctx.shadowOffsetX = d;
  56054. ctx.shadowBlur = this.blurSize;
  56055. // draw the shadow in black, and use alpha and shadow blur to generate
  56056. // color in color map
  56057. ctx.shadowColor = '#000';
  56058. // draw circle in the left to the canvas
  56059. ctx.beginPath();
  56060. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  56061. ctx.closePath();
  56062. ctx.fill();
  56063. return brushCanvas;
  56064. },
  56065. /**
  56066. * get gradient color map
  56067. * @private
  56068. */
  56069. _getGradient: function (data, colorFunc, state) {
  56070. var gradientPixels = this._gradientPixels;
  56071. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  56072. var color = [0, 0, 0, 0];
  56073. var off = 0;
  56074. for (var i = 0; i < 256; i++) {
  56075. colorFunc[state](i / 255, true, color);
  56076. pixelsSingleState[off++] = color[0];
  56077. pixelsSingleState[off++] = color[1];
  56078. pixelsSingleState[off++] = color[2];
  56079. pixelsSingleState[off++] = color[3];
  56080. }
  56081. return pixelsSingleState;
  56082. }
  56083. };
  56084. /*
  56085. * Licensed to the Apache Software Foundation (ASF) under one
  56086. * or more contributor license agreements. See the NOTICE file
  56087. * distributed with this work for additional information
  56088. * regarding copyright ownership. The ASF licenses this file
  56089. * to you under the Apache License, Version 2.0 (the
  56090. * "License"); you may not use this file except in compliance
  56091. * with the License. You may obtain a copy of the License at
  56092. *
  56093. * http://www.apache.org/licenses/LICENSE-2.0
  56094. *
  56095. * Unless required by applicable law or agreed to in writing,
  56096. * software distributed under the License is distributed on an
  56097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56098. * KIND, either express or implied. See the License for the
  56099. * specific language governing permissions and limitations
  56100. * under the License.
  56101. */
  56102. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  56103. var dataSpan = dataExtent[1] - dataExtent[0];
  56104. pieceList = map(pieceList, function (piece) {
  56105. return {
  56106. interval: [
  56107. (piece.interval[0] - dataExtent[0]) / dataSpan,
  56108. (piece.interval[1] - dataExtent[0]) / dataSpan
  56109. ]
  56110. };
  56111. });
  56112. var len = pieceList.length;
  56113. var lastIndex = 0;
  56114. return function (val) {
  56115. // Try to find in the location of the last found
  56116. for (var i = lastIndex; i < len; i++) {
  56117. var interval = pieceList[i].interval;
  56118. if (interval[0] <= val && val <= interval[1]) {
  56119. lastIndex = i;
  56120. break;
  56121. }
  56122. }
  56123. if (i === len) { // Not found, back interation
  56124. for (var i = lastIndex - 1; i >= 0; i--) {
  56125. var interval = pieceList[i].interval;
  56126. if (interval[0] <= val && val <= interval[1]) {
  56127. lastIndex = i;
  56128. break;
  56129. }
  56130. }
  56131. }
  56132. return i >= 0 && i < len && selected[i];
  56133. };
  56134. }
  56135. function getIsInContinuousRange(dataExtent, range) {
  56136. var dataSpan = dataExtent[1] - dataExtent[0];
  56137. range = [
  56138. (range[0] - dataExtent[0]) / dataSpan,
  56139. (range[1] - dataExtent[0]) / dataSpan
  56140. ];
  56141. return function (val) {
  56142. return val >= range[0] && val <= range[1];
  56143. };
  56144. }
  56145. function isGeoCoordSys(coordSys) {
  56146. var dimensions = coordSys.dimensions;
  56147. // Not use coorSys.type === 'geo' because coordSys maybe extended
  56148. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  56149. }
  56150. extendChartView({
  56151. type: 'heatmap',
  56152. render: function (seriesModel, ecModel, api) {
  56153. var visualMapOfThisSeries;
  56154. ecModel.eachComponent('visualMap', function (visualMap) {
  56155. visualMap.eachTargetSeries(function (targetSeries) {
  56156. if (targetSeries === seriesModel) {
  56157. visualMapOfThisSeries = visualMap;
  56158. }
  56159. });
  56160. });
  56161. if (__DEV__) {
  56162. if (!visualMapOfThisSeries) {
  56163. throw new Error('Heatmap must use with visualMap');
  56164. }
  56165. }
  56166. this.group.removeAll();
  56167. this._incrementalDisplayable = null;
  56168. var coordSys = seriesModel.coordinateSystem;
  56169. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  56170. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  56171. }
  56172. else if (isGeoCoordSys(coordSys)) {
  56173. this._renderOnGeo(
  56174. coordSys, seriesModel, visualMapOfThisSeries, api
  56175. );
  56176. }
  56177. },
  56178. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  56179. this.group.removeAll();
  56180. },
  56181. incrementalRender: function (params, seriesModel, ecModel, api) {
  56182. var coordSys = seriesModel.coordinateSystem;
  56183. if (coordSys) {
  56184. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  56185. }
  56186. },
  56187. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  56188. var coordSys = seriesModel.coordinateSystem;
  56189. var width;
  56190. var height;
  56191. if (coordSys.type === 'cartesian2d') {
  56192. var xAxis = coordSys.getAxis('x');
  56193. var yAxis = coordSys.getAxis('y');
  56194. if (__DEV__) {
  56195. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  56196. throw new Error('Heatmap on cartesian must have two category axes');
  56197. }
  56198. if (!(xAxis.onBand && yAxis.onBand)) {
  56199. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  56200. }
  56201. }
  56202. width = xAxis.getBandWidth();
  56203. height = yAxis.getBandWidth();
  56204. }
  56205. var group = this.group;
  56206. var data = seriesModel.getData();
  56207. var itemStyleQuery = 'itemStyle';
  56208. var hoverItemStyleQuery = 'emphasis.itemStyle';
  56209. var labelQuery = 'label';
  56210. var hoverLabelQuery = 'emphasis.label';
  56211. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  56212. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  56213. var labelModel = seriesModel.getModel(labelQuery);
  56214. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  56215. var coordSysType = coordSys.type;
  56216. var dataDims = coordSysType === 'cartesian2d'
  56217. ? [
  56218. data.mapDimension('x'),
  56219. data.mapDimension('y'),
  56220. data.mapDimension('value')
  56221. ]
  56222. : [
  56223. data.mapDimension('time'),
  56224. data.mapDimension('value')
  56225. ];
  56226. for (var idx = start; idx < end; idx++) {
  56227. var rect;
  56228. if (coordSysType === 'cartesian2d') {
  56229. // Ignore empty data
  56230. if (isNaN(data.get(dataDims[2], idx))) {
  56231. continue;
  56232. }
  56233. var point = coordSys.dataToPoint([
  56234. data.get(dataDims[0], idx),
  56235. data.get(dataDims[1], idx)
  56236. ]);
  56237. rect = new Rect({
  56238. shape: {
  56239. x: point[0] - width / 2,
  56240. y: point[1] - height / 2,
  56241. width: width,
  56242. height: height
  56243. },
  56244. style: {
  56245. fill: data.getItemVisual(idx, 'color'),
  56246. opacity: data.getItemVisual(idx, 'opacity')
  56247. }
  56248. });
  56249. }
  56250. else {
  56251. // Ignore empty data
  56252. if (isNaN(data.get(dataDims[1], idx))) {
  56253. continue;
  56254. }
  56255. rect = new Rect({
  56256. z2: 1,
  56257. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  56258. style: {
  56259. fill: data.getItemVisual(idx, 'color'),
  56260. opacity: data.getItemVisual(idx, 'opacity')
  56261. }
  56262. });
  56263. }
  56264. var itemModel = data.getItemModel(idx);
  56265. // Optimization for large datset
  56266. if (data.hasItemOption) {
  56267. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  56268. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  56269. labelModel = itemModel.getModel(labelQuery);
  56270. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  56271. }
  56272. var rawValue = seriesModel.getRawValue(idx);
  56273. var defaultText = '-';
  56274. if (rawValue && rawValue[2] != null) {
  56275. defaultText = rawValue[2];
  56276. }
  56277. setLabelStyle(
  56278. style, hoverStl, labelModel, hoverLabelModel,
  56279. {
  56280. labelFetcher: seriesModel,
  56281. labelDataIndex: idx,
  56282. defaultText: defaultText,
  56283. isRectText: true
  56284. }
  56285. );
  56286. rect.setStyle(style);
  56287. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  56288. rect.incremental = incremental;
  56289. // PENDING
  56290. if (incremental) {
  56291. // Rect must use hover layer if it's incremental.
  56292. rect.useHoverLayer = true;
  56293. }
  56294. group.add(rect);
  56295. data.setItemGraphicEl(idx, rect);
  56296. }
  56297. },
  56298. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  56299. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  56300. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  56301. // if (!visualMapping) {
  56302. // throw new Error('Data range must have color visuals');
  56303. // }
  56304. var data = seriesModel.getData();
  56305. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  56306. hmLayer.blurSize = seriesModel.get('blurSize');
  56307. hmLayer.pointSize = seriesModel.get('pointSize');
  56308. hmLayer.minOpacity = seriesModel.get('minOpacity');
  56309. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  56310. var rect = geo.getViewRect().clone();
  56311. var roamTransform = geo.getRoamTransform();
  56312. rect.applyTransform(roamTransform);
  56313. // Clamp on viewport
  56314. var x = Math.max(rect.x, 0);
  56315. var y = Math.max(rect.y, 0);
  56316. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  56317. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  56318. var width = x2 - x;
  56319. var height = y2 - y;
  56320. var dims = [
  56321. data.mapDimension('lng'),
  56322. data.mapDimension('lat'),
  56323. data.mapDimension('value')
  56324. ];
  56325. var points = data.mapArray(dims, function (lng, lat, value) {
  56326. var pt = geo.dataToPoint([lng, lat]);
  56327. pt[0] -= x;
  56328. pt[1] -= y;
  56329. pt.push(value);
  56330. return pt;
  56331. });
  56332. var dataExtent = visualMapModel.getExtent();
  56333. var isInRange = visualMapModel.type === 'visualMap.continuous'
  56334. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  56335. : getIsInPiecewiseRange(
  56336. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  56337. );
  56338. hmLayer.update(
  56339. points, width, height,
  56340. inRangeVisuals.color.getNormalizer(),
  56341. {
  56342. inRange: inRangeVisuals.color.getColorMapper(),
  56343. outOfRange: outOfRangeVisuals.color.getColorMapper()
  56344. },
  56345. isInRange
  56346. );
  56347. var img = new ZImage({
  56348. style: {
  56349. width: width,
  56350. height: height,
  56351. x: x,
  56352. y: y,
  56353. image: hmLayer.canvas
  56354. },
  56355. silent: true
  56356. });
  56357. this.group.add(img);
  56358. },
  56359. dispose: function () {}
  56360. });
  56361. /*
  56362. * Licensed to the Apache Software Foundation (ASF) under one
  56363. * or more contributor license agreements. See the NOTICE file
  56364. * distributed with this work for additional information
  56365. * regarding copyright ownership. The ASF licenses this file
  56366. * to you under the Apache License, Version 2.0 (the
  56367. * "License"); you may not use this file except in compliance
  56368. * with the License. You may obtain a copy of the License at
  56369. *
  56370. * http://www.apache.org/licenses/LICENSE-2.0
  56371. *
  56372. * Unless required by applicable law or agreed to in writing,
  56373. * software distributed under the License is distributed on an
  56374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56375. * KIND, either express or implied. See the License for the
  56376. * specific language governing permissions and limitations
  56377. * under the License.
  56378. */
  56379. /*
  56380. * Licensed to the Apache Software Foundation (ASF) under one
  56381. * or more contributor license agreements. See the NOTICE file
  56382. * distributed with this work for additional information
  56383. * regarding copyright ownership. The ASF licenses this file
  56384. * to you under the Apache License, Version 2.0 (the
  56385. * "License"); you may not use this file except in compliance
  56386. * with the License. You may obtain a copy of the License at
  56387. *
  56388. * http://www.apache.org/licenses/LICENSE-2.0
  56389. *
  56390. * Unless required by applicable law or agreed to in writing,
  56391. * software distributed under the License is distributed on an
  56392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56393. * KIND, either express or implied. See the License for the
  56394. * specific language governing permissions and limitations
  56395. * under the License.
  56396. */
  56397. var PictorialBarSeries = BaseBarSeries.extend({
  56398. type: 'series.pictorialBar',
  56399. dependencies: ['grid'],
  56400. defaultOption: {
  56401. symbol: 'circle', // Customized bar shape
  56402. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  56403. symbolRotate: null,
  56404. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  56405. symbolOffset: null,
  56406. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  56407. // Auto margin by defualt.
  56408. symbolRepeat: false, // false/null/undefined, means no repeat.
  56409. // Can be true, means auto calculate repeat times and cut by data.
  56410. // Can be a number, specifies repeat times, and do not cut by data.
  56411. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  56412. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  56413. symbolClip: false,
  56414. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  56415. symbolPatternSize: 400, // 400 * 400 px
  56416. barGap: '-100%', // In most case, overlap is needed.
  56417. // z can be set in data item, which is z2 actually.
  56418. // Disable progressive
  56419. progressive: 0,
  56420. hoverAnimation: false // Open only when needed.
  56421. },
  56422. getInitialData: function (option) {
  56423. // Disable stack.
  56424. option.stack = null;
  56425. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  56426. }
  56427. });
  56428. /*
  56429. * Licensed to the Apache Software Foundation (ASF) under one
  56430. * or more contributor license agreements. See the NOTICE file
  56431. * distributed with this work for additional information
  56432. * regarding copyright ownership. The ASF licenses this file
  56433. * to you under the Apache License, Version 2.0 (the
  56434. * "License"); you may not use this file except in compliance
  56435. * with the License. You may obtain a copy of the License at
  56436. *
  56437. * http://www.apache.org/licenses/LICENSE-2.0
  56438. *
  56439. * Unless required by applicable law or agreed to in writing,
  56440. * software distributed under the License is distributed on an
  56441. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56442. * KIND, either express or implied. See the License for the
  56443. * specific language governing permissions and limitations
  56444. * under the License.
  56445. */
  56446. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  56447. // index: +isHorizontal
  56448. var LAYOUT_ATTRS = [
  56449. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  56450. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  56451. ];
  56452. var pathForLineWidth = new Circle();
  56453. var BarView$1 = extendChartView({
  56454. type: 'pictorialBar',
  56455. render: function (seriesModel, ecModel, api) {
  56456. var group = this.group;
  56457. var data = seriesModel.getData();
  56458. var oldData = this._data;
  56459. var cartesian = seriesModel.coordinateSystem;
  56460. var baseAxis = cartesian.getBaseAxis();
  56461. var isHorizontal = !!baseAxis.isHorizontal();
  56462. var coordSysRect = cartesian.grid.getRect();
  56463. var opt = {
  56464. ecSize: {width: api.getWidth(), height: api.getHeight()},
  56465. seriesModel: seriesModel,
  56466. coordSys: cartesian,
  56467. coordSysExtent: [
  56468. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  56469. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  56470. ],
  56471. isHorizontal: isHorizontal,
  56472. valueDim: LAYOUT_ATTRS[+isHorizontal],
  56473. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  56474. };
  56475. data.diff(oldData)
  56476. .add(function (dataIndex) {
  56477. if (!data.hasValue(dataIndex)) {
  56478. return;
  56479. }
  56480. var itemModel = getItemModel(data, dataIndex);
  56481. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  56482. var bar = createBar(data, opt, symbolMeta);
  56483. data.setItemGraphicEl(dataIndex, bar);
  56484. group.add(bar);
  56485. updateCommon$1(bar, opt, symbolMeta);
  56486. })
  56487. .update(function (newIndex, oldIndex) {
  56488. var bar = oldData.getItemGraphicEl(oldIndex);
  56489. if (!data.hasValue(newIndex)) {
  56490. group.remove(bar);
  56491. return;
  56492. }
  56493. var itemModel = getItemModel(data, newIndex);
  56494. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  56495. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  56496. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  56497. group.remove(bar);
  56498. data.setItemGraphicEl(newIndex, null);
  56499. bar = null;
  56500. }
  56501. if (bar) {
  56502. updateBar(bar, opt, symbolMeta);
  56503. }
  56504. else {
  56505. bar = createBar(data, opt, symbolMeta, true);
  56506. }
  56507. data.setItemGraphicEl(newIndex, bar);
  56508. bar.__pictorialSymbolMeta = symbolMeta;
  56509. // Add back
  56510. group.add(bar);
  56511. updateCommon$1(bar, opt, symbolMeta);
  56512. })
  56513. .remove(function (dataIndex) {
  56514. var bar = oldData.getItemGraphicEl(dataIndex);
  56515. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  56516. })
  56517. .execute();
  56518. this._data = data;
  56519. return this.group;
  56520. },
  56521. dispose: noop,
  56522. remove: function (ecModel, api) {
  56523. var group = this.group;
  56524. var data = this._data;
  56525. if (ecModel.get('animation')) {
  56526. if (data) {
  56527. data.eachItemGraphicEl(function (bar) {
  56528. removeBar(data, bar.dataIndex, ecModel, bar);
  56529. });
  56530. }
  56531. }
  56532. else {
  56533. group.removeAll();
  56534. }
  56535. }
  56536. });
  56537. // Set or calculate default value about symbol, and calculate layout info.
  56538. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  56539. var layout = data.getItemLayout(dataIndex);
  56540. var symbolRepeat = itemModel.get('symbolRepeat');
  56541. var symbolClip = itemModel.get('symbolClip');
  56542. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  56543. var symbolRotate = itemModel.get('symbolRotate');
  56544. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  56545. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  56546. var isAnimationEnabled = itemModel.isAnimationEnabled();
  56547. var symbolMeta = {
  56548. dataIndex: dataIndex,
  56549. layout: layout,
  56550. itemModel: itemModel,
  56551. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  56552. color: data.getItemVisual(dataIndex, 'color'),
  56553. symbolClip: symbolClip,
  56554. symbolRepeat: symbolRepeat,
  56555. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  56556. symbolPatternSize: symbolPatternSize,
  56557. rotation: rotation,
  56558. animationModel: isAnimationEnabled ? itemModel : null,
  56559. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  56560. z2: itemModel.getShallow('z', true) || 0
  56561. };
  56562. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  56563. prepareSymbolSize(
  56564. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  56565. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  56566. );
  56567. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  56568. var symbolSize = symbolMeta.symbolSize;
  56569. var symbolOffset = itemModel.get('symbolOffset');
  56570. if (isArray(symbolOffset)) {
  56571. symbolOffset = [
  56572. parsePercent$1(symbolOffset[0], symbolSize[0]),
  56573. parsePercent$1(symbolOffset[1], symbolSize[1])
  56574. ];
  56575. }
  56576. prepareLayoutInfo(
  56577. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56578. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  56579. opt, symbolMeta
  56580. );
  56581. return symbolMeta;
  56582. }
  56583. // bar length can be negative.
  56584. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  56585. var valueDim = opt.valueDim;
  56586. var symbolBoundingData = itemModel.get('symbolBoundingData');
  56587. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  56588. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  56589. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  56590. var boundingLength;
  56591. if (isArray(symbolBoundingData)) {
  56592. var symbolBoundingExtent = [
  56593. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  56594. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  56595. ];
  56596. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  56597. boundingLength = symbolBoundingExtent[pxSignIdx];
  56598. }
  56599. else if (symbolBoundingData != null) {
  56600. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  56601. }
  56602. else if (symbolRepeat) {
  56603. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  56604. }
  56605. else {
  56606. boundingLength = layout[valueDim.wh];
  56607. }
  56608. output.boundingLength = boundingLength;
  56609. if (symbolRepeat) {
  56610. output.repeatCutLength = layout[valueDim.wh];
  56611. }
  56612. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  56613. }
  56614. function convertToCoordOnAxis(axis, value) {
  56615. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  56616. }
  56617. // Support ['100%', '100%']
  56618. function prepareSymbolSize(
  56619. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  56620. pxSign, symbolPatternSize, opt, output
  56621. ) {
  56622. var valueDim = opt.valueDim;
  56623. var categoryDim = opt.categoryDim;
  56624. var categorySize = Math.abs(layout[categoryDim.wh]);
  56625. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  56626. if (isArray(symbolSize)) {
  56627. symbolSize = symbolSize.slice();
  56628. }
  56629. else {
  56630. if (symbolSize == null) {
  56631. symbolSize = '100%';
  56632. }
  56633. symbolSize = [symbolSize, symbolSize];
  56634. }
  56635. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  56636. // to complicated to calculate real percent value if considering scaled lineWidth.
  56637. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  56638. // which can be tolerated in pictorial chart.
  56639. symbolSize[categoryDim.index] = parsePercent$1(
  56640. symbolSize[categoryDim.index],
  56641. categorySize
  56642. );
  56643. symbolSize[valueDim.index] = parsePercent$1(
  56644. symbolSize[valueDim.index],
  56645. symbolRepeat ? categorySize : Math.abs(boundingLength)
  56646. );
  56647. output.symbolSize = symbolSize;
  56648. // If x or y is less than zero, show reversed shape.
  56649. var symbolScale = output.symbolScale = [
  56650. symbolSize[0] / symbolPatternSize,
  56651. symbolSize[1] / symbolPatternSize
  56652. ];
  56653. // Follow convention, 'right' and 'top' is the normal scale.
  56654. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  56655. }
  56656. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  56657. // In symbols are drawn with scale, so do not need to care about the case that width
  56658. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  56659. // be calculated.
  56660. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  56661. if (valueLineWidth) {
  56662. pathForLineWidth.attr({
  56663. scale: symbolScale.slice(),
  56664. rotation: rotation
  56665. });
  56666. pathForLineWidth.updateTransform();
  56667. valueLineWidth /= pathForLineWidth.getLineScale();
  56668. valueLineWidth *= symbolScale[opt.valueDim.index];
  56669. }
  56670. output.valueLineWidth = valueLineWidth;
  56671. }
  56672. function prepareLayoutInfo(
  56673. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56674. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  56675. ) {
  56676. var categoryDim = opt.categoryDim;
  56677. var valueDim = opt.valueDim;
  56678. var pxSign = output.pxSign;
  56679. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  56680. var pathLen = unitLength;
  56681. // Note: rotation will not effect the layout of symbols, because user may
  56682. // want symbols to rotate on its center, which should not be translated
  56683. // when rotating.
  56684. if (symbolRepeat) {
  56685. var absBoundingLength = Math.abs(boundingLength);
  56686. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  56687. var hasEndGap = false;
  56688. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  56689. hasEndGap = true;
  56690. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  56691. }
  56692. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  56693. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  56694. // When symbol margin is less than 0, margin at both ends will be subtracted
  56695. // to ensure that all of the symbols will not be overflow the given area.
  56696. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  56697. // Both final repeatTimes and final symbolMargin area calculated based on
  56698. // boundingLength.
  56699. var repeatSpecified = isNumeric(symbolRepeat);
  56700. var repeatTimes = repeatSpecified
  56701. ? symbolRepeat
  56702. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  56703. // Adjust calculate margin, to ensure each symbol is displayed
  56704. // entirely in the given layout area.
  56705. var mDiff = absBoundingLength - repeatTimes * unitLength;
  56706. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  56707. uLenWithMargin = unitLength + symbolMargin * 2;
  56708. endFix = hasEndGap ? 0 : symbolMargin * 2;
  56709. // Update repeatTimes when not all symbol will be shown.
  56710. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  56711. repeatTimes = repeatCutLength
  56712. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  56713. : 0;
  56714. }
  56715. pathLen = repeatTimes * uLenWithMargin - endFix;
  56716. output.repeatTimes = repeatTimes;
  56717. output.symbolMargin = symbolMargin;
  56718. }
  56719. var sizeFix = pxSign * (pathLen / 2);
  56720. var pathPosition = output.pathPosition = [];
  56721. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  56722. pathPosition[valueDim.index] = symbolPosition === 'start'
  56723. ? sizeFix
  56724. : symbolPosition === 'end'
  56725. ? boundingLength - sizeFix
  56726. : boundingLength / 2; // 'center'
  56727. if (symbolOffset) {
  56728. pathPosition[0] += symbolOffset[0];
  56729. pathPosition[1] += symbolOffset[1];
  56730. }
  56731. var bundlePosition = output.bundlePosition = [];
  56732. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  56733. bundlePosition[valueDim.index] = layout[valueDim.xy];
  56734. var barRectShape = output.barRectShape = extend({}, layout);
  56735. barRectShape[valueDim.wh] = pxSign * Math.max(
  56736. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  56737. );
  56738. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  56739. var clipShape = output.clipShape = {};
  56740. // Consider that symbol may be overflow layout rect.
  56741. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  56742. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  56743. clipShape[valueDim.xy] = 0;
  56744. clipShape[valueDim.wh] = layout[valueDim.wh];
  56745. }
  56746. function createPath(symbolMeta) {
  56747. var symbolPatternSize = symbolMeta.symbolPatternSize;
  56748. var path = createSymbol(
  56749. // Consider texture img, make a big size.
  56750. symbolMeta.symbolType,
  56751. -symbolPatternSize / 2,
  56752. -symbolPatternSize / 2,
  56753. symbolPatternSize,
  56754. symbolPatternSize,
  56755. symbolMeta.color
  56756. );
  56757. path.attr({
  56758. culling: true
  56759. });
  56760. path.type !== 'image' && path.setStyle({
  56761. strokeNoScale: true
  56762. });
  56763. return path;
  56764. }
  56765. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  56766. var bundle = bar.__pictorialBundle;
  56767. var symbolSize = symbolMeta.symbolSize;
  56768. var valueLineWidth = symbolMeta.valueLineWidth;
  56769. var pathPosition = symbolMeta.pathPosition;
  56770. var valueDim = opt.valueDim;
  56771. var repeatTimes = symbolMeta.repeatTimes || 0;
  56772. var index = 0;
  56773. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  56774. eachPath(bar, function (path) {
  56775. path.__pictorialAnimationIndex = index;
  56776. path.__pictorialRepeatTimes = repeatTimes;
  56777. if (index < repeatTimes) {
  56778. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  56779. }
  56780. else {
  56781. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  56782. bundle.remove(path);
  56783. });
  56784. }
  56785. updateHoverAnimation(path, symbolMeta);
  56786. index++;
  56787. });
  56788. for (; index < repeatTimes; index++) {
  56789. var path = createPath(symbolMeta);
  56790. path.__pictorialAnimationIndex = index;
  56791. path.__pictorialRepeatTimes = repeatTimes;
  56792. bundle.add(path);
  56793. var target = makeTarget(index);
  56794. updateAttr(
  56795. path,
  56796. {
  56797. position: target.position,
  56798. scale: [0, 0]
  56799. },
  56800. {
  56801. scale: target.scale,
  56802. rotation: target.rotation
  56803. },
  56804. symbolMeta,
  56805. isUpdate
  56806. );
  56807. // FIXME
  56808. // If all emphasis/normal through action.
  56809. path
  56810. .on('mouseover', onMouseOver)
  56811. .on('mouseout', onMouseOut);
  56812. updateHoverAnimation(path, symbolMeta);
  56813. }
  56814. function makeTarget(index) {
  56815. var position = pathPosition.slice();
  56816. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  56817. // Otherwise: i = index;
  56818. var pxSign = symbolMeta.pxSign;
  56819. var i = index;
  56820. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  56821. i = repeatTimes - 1 - index;
  56822. }
  56823. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  56824. return {
  56825. position: position,
  56826. scale: symbolMeta.symbolScale.slice(),
  56827. rotation: symbolMeta.rotation
  56828. };
  56829. }
  56830. function onMouseOver() {
  56831. eachPath(bar, function (path) {
  56832. path.trigger('emphasis');
  56833. });
  56834. }
  56835. function onMouseOut() {
  56836. eachPath(bar, function (path) {
  56837. path.trigger('normal');
  56838. });
  56839. }
  56840. }
  56841. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  56842. var bundle = bar.__pictorialBundle;
  56843. var mainPath = bar.__pictorialMainPath;
  56844. if (!mainPath) {
  56845. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  56846. bundle.add(mainPath);
  56847. updateAttr(
  56848. mainPath,
  56849. {
  56850. position: symbolMeta.pathPosition.slice(),
  56851. scale: [0, 0],
  56852. rotation: symbolMeta.rotation
  56853. },
  56854. {
  56855. scale: symbolMeta.symbolScale.slice()
  56856. },
  56857. symbolMeta,
  56858. isUpdate
  56859. );
  56860. mainPath
  56861. .on('mouseover', onMouseOver)
  56862. .on('mouseout', onMouseOut);
  56863. }
  56864. else {
  56865. updateAttr(
  56866. mainPath,
  56867. null,
  56868. {
  56869. position: symbolMeta.pathPosition.slice(),
  56870. scale: symbolMeta.symbolScale.slice(),
  56871. rotation: symbolMeta.rotation
  56872. },
  56873. symbolMeta,
  56874. isUpdate
  56875. );
  56876. }
  56877. updateHoverAnimation(mainPath, symbolMeta);
  56878. function onMouseOver() {
  56879. this.trigger('emphasis');
  56880. }
  56881. function onMouseOut() {
  56882. this.trigger('normal');
  56883. }
  56884. }
  56885. // bar rect is used for label.
  56886. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  56887. var rectShape = extend({}, symbolMeta.barRectShape);
  56888. var barRect = bar.__pictorialBarRect;
  56889. if (!barRect) {
  56890. barRect = bar.__pictorialBarRect = new Rect({
  56891. z2: 2,
  56892. shape: rectShape,
  56893. silent: true,
  56894. style: {
  56895. stroke: 'transparent',
  56896. fill: 'transparent',
  56897. lineWidth: 0
  56898. }
  56899. });
  56900. bar.add(barRect);
  56901. }
  56902. else {
  56903. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  56904. }
  56905. }
  56906. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  56907. // If not clip, symbol will be remove and rebuilt.
  56908. if (symbolMeta.symbolClip) {
  56909. var clipPath = bar.__pictorialClipPath;
  56910. var clipShape = extend({}, symbolMeta.clipShape);
  56911. var valueDim = opt.valueDim;
  56912. var animationModel = symbolMeta.animationModel;
  56913. var dataIndex = symbolMeta.dataIndex;
  56914. if (clipPath) {
  56915. updateProps(
  56916. clipPath, {shape: clipShape}, animationModel, dataIndex
  56917. );
  56918. }
  56919. else {
  56920. clipShape[valueDim.wh] = 0;
  56921. clipPath = new Rect({shape: clipShape});
  56922. bar.__pictorialBundle.setClipPath(clipPath);
  56923. bar.__pictorialClipPath = clipPath;
  56924. var target = {};
  56925. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  56926. graphic[isUpdate ? 'updateProps' : 'initProps'](
  56927. clipPath, {shape: target}, animationModel, dataIndex
  56928. );
  56929. }
  56930. }
  56931. }
  56932. function getItemModel(data, dataIndex) {
  56933. var itemModel = data.getItemModel(dataIndex);
  56934. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  56935. itemModel.isAnimationEnabled = isAnimationEnabled;
  56936. return itemModel;
  56937. }
  56938. function getAnimationDelayParams(path) {
  56939. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  56940. return {
  56941. index: path.__pictorialAnimationIndex,
  56942. count: path.__pictorialRepeatTimes
  56943. };
  56944. }
  56945. function isAnimationEnabled() {
  56946. // `animation` prop can be set on itemModel in pictorial bar chart.
  56947. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  56948. }
  56949. function updateHoverAnimation(path, symbolMeta) {
  56950. path.off('emphasis').off('normal');
  56951. var scale = symbolMeta.symbolScale.slice();
  56952. symbolMeta.hoverAnimation && path
  56953. .on('emphasis', function () {
  56954. this.animateTo({
  56955. scale: [scale[0] * 1.1, scale[1] * 1.1]
  56956. }, 400, 'elasticOut');
  56957. })
  56958. .on('normal', function () {
  56959. this.animateTo({
  56960. scale: scale.slice()
  56961. }, 400, 'elasticOut');
  56962. });
  56963. }
  56964. function createBar(data, opt, symbolMeta, isUpdate) {
  56965. // bar is the main element for each data.
  56966. var bar = new Group();
  56967. // bundle is used for location and clip.
  56968. var bundle = new Group();
  56969. bar.add(bundle);
  56970. bar.__pictorialBundle = bundle;
  56971. bundle.attr('position', symbolMeta.bundlePosition.slice());
  56972. if (symbolMeta.symbolRepeat) {
  56973. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  56974. }
  56975. else {
  56976. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  56977. }
  56978. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  56979. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  56980. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  56981. bar.__pictorialSymbolMeta = symbolMeta;
  56982. return bar;
  56983. }
  56984. function updateBar(bar, opt, symbolMeta) {
  56985. var animationModel = symbolMeta.animationModel;
  56986. var dataIndex = symbolMeta.dataIndex;
  56987. var bundle = bar.__pictorialBundle;
  56988. updateProps(
  56989. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  56990. );
  56991. if (symbolMeta.symbolRepeat) {
  56992. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  56993. }
  56994. else {
  56995. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  56996. }
  56997. createOrUpdateBarRect(bar, symbolMeta, true);
  56998. createOrUpdateClip(bar, opt, symbolMeta, true);
  56999. }
  57000. function removeBar(data, dataIndex, animationModel, bar) {
  57001. // Not show text when animating
  57002. var labelRect = bar.__pictorialBarRect;
  57003. labelRect && (labelRect.style.text = null);
  57004. var pathes = [];
  57005. eachPath(bar, function (path) {
  57006. pathes.push(path);
  57007. });
  57008. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  57009. // I do not find proper remove animation for clip yet.
  57010. bar.__pictorialClipPath && (animationModel = null);
  57011. each$1(pathes, function (path) {
  57012. updateProps(
  57013. path, {scale: [0, 0]}, animationModel, dataIndex,
  57014. function () {
  57015. bar.parent && bar.parent.remove(bar);
  57016. }
  57017. );
  57018. });
  57019. data.setItemGraphicEl(dataIndex, null);
  57020. }
  57021. function getShapeStr(data, symbolMeta) {
  57022. return [
  57023. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  57024. !!symbolMeta.symbolRepeat,
  57025. !!symbolMeta.symbolClip
  57026. ].join(':');
  57027. }
  57028. function eachPath(bar, cb, context) {
  57029. // Do not use Group#eachChild, because it do not support remove.
  57030. each$1(bar.__pictorialBundle.children(), function (el) {
  57031. el !== bar.__pictorialBarRect && cb.call(context, el);
  57032. });
  57033. }
  57034. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  57035. immediateAttrs && el.attr(immediateAttrs);
  57036. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  57037. if (symbolMeta.symbolClip && !isUpdate) {
  57038. animationAttrs && el.attr(animationAttrs);
  57039. }
  57040. else {
  57041. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  57042. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  57043. );
  57044. }
  57045. }
  57046. function updateCommon$1(bar, opt, symbolMeta) {
  57047. var color = symbolMeta.color;
  57048. var dataIndex = symbolMeta.dataIndex;
  57049. var itemModel = symbolMeta.itemModel;
  57050. // Color must be excluded.
  57051. // Because symbol provide setColor individually to set fill and stroke
  57052. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  57053. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  57054. var cursorStyle = itemModel.getShallow('cursor');
  57055. eachPath(bar, function (path) {
  57056. // PENDING setColor should be before setStyle!!!
  57057. path.setColor(color);
  57058. path.setStyle(defaults(
  57059. {
  57060. fill: color,
  57061. opacity: symbolMeta.opacity
  57062. },
  57063. normalStyle
  57064. ));
  57065. setHoverStyle(path, hoverStyle);
  57066. cursorStyle && (path.cursor = cursorStyle);
  57067. path.z2 = symbolMeta.z2;
  57068. });
  57069. var barRectHoverStyle = {};
  57070. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  57071. var barRect = bar.__pictorialBarRect;
  57072. setLabel(
  57073. barRect.style, barRectHoverStyle, itemModel,
  57074. color, opt.seriesModel, dataIndex, barPositionOutside
  57075. );
  57076. setHoverStyle(barRect, barRectHoverStyle);
  57077. }
  57078. function toIntTimes(times) {
  57079. var roundedTimes = Math.round(times);
  57080. // Escapse accurate error
  57081. return Math.abs(times - roundedTimes) < 1e-4
  57082. ? roundedTimes
  57083. : Math.ceil(times);
  57084. }
  57085. /*
  57086. * Licensed to the Apache Software Foundation (ASF) under one
  57087. * or more contributor license agreements. See the NOTICE file
  57088. * distributed with this work for additional information
  57089. * regarding copyright ownership. The ASF licenses this file
  57090. * to you under the Apache License, Version 2.0 (the
  57091. * "License"); you may not use this file except in compliance
  57092. * with the License. You may obtain a copy of the License at
  57093. *
  57094. * http://www.apache.org/licenses/LICENSE-2.0
  57095. *
  57096. * Unless required by applicable law or agreed to in writing,
  57097. * software distributed under the License is distributed on an
  57098. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57099. * KIND, either express or implied. See the License for the
  57100. * specific language governing permissions and limitations
  57101. * under the License.
  57102. */
  57103. // In case developer forget to include grid component
  57104. registerLayout(curry(
  57105. layout, 'pictorialBar'
  57106. ));
  57107. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  57108. /*
  57109. * Licensed to the Apache Software Foundation (ASF) under one
  57110. * or more contributor license agreements. See the NOTICE file
  57111. * distributed with this work for additional information
  57112. * regarding copyright ownership. The ASF licenses this file
  57113. * to you under the Apache License, Version 2.0 (the
  57114. * "License"); you may not use this file except in compliance
  57115. * with the License. You may obtain a copy of the License at
  57116. *
  57117. * http://www.apache.org/licenses/LICENSE-2.0
  57118. *
  57119. * Unless required by applicable law or agreed to in writing,
  57120. * software distributed under the License is distributed on an
  57121. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57122. * KIND, either express or implied. See the License for the
  57123. * specific language governing permissions and limitations
  57124. * under the License.
  57125. */
  57126. /**
  57127. * @constructor module:echarts/coord/single/SingleAxis
  57128. * @extends {module:echarts/coord/Axis}
  57129. * @param {string} dim
  57130. * @param {*} scale
  57131. * @param {Array.<number>} coordExtent
  57132. * @param {string} axisType
  57133. * @param {string} position
  57134. */
  57135. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  57136. Axis.call(this, dim, scale, coordExtent);
  57137. /**
  57138. * Axis type
  57139. * - 'category'
  57140. * - 'value'
  57141. * - 'time'
  57142. * - 'log'
  57143. * @type {string}
  57144. */
  57145. this.type = axisType || 'value';
  57146. /**
  57147. * Axis position
  57148. * - 'top'
  57149. * - 'bottom'
  57150. * - 'left'
  57151. * - 'right'
  57152. * @type {string}
  57153. */
  57154. this.position = position || 'bottom';
  57155. /**
  57156. * Axis orient
  57157. * - 'horizontal'
  57158. * - 'vertical'
  57159. * @type {[type]}
  57160. */
  57161. this.orient = null;
  57162. };
  57163. SingleAxis.prototype = {
  57164. constructor: SingleAxis,
  57165. /**
  57166. * Axis model
  57167. * @type {module:echarts/coord/single/AxisModel}
  57168. */
  57169. model: null,
  57170. /**
  57171. * Judge the orient of the axis.
  57172. * @return {boolean}
  57173. */
  57174. isHorizontal: function () {
  57175. var position = this.position;
  57176. return position === 'top' || position === 'bottom';
  57177. },
  57178. /**
  57179. * @override
  57180. */
  57181. pointToData: function (point, clamp) {
  57182. return this.coordinateSystem.pointToData(point, clamp)[0];
  57183. },
  57184. /**
  57185. * Convert the local coord(processed by dataToCoord())
  57186. * to global coord(concrete pixel coord).
  57187. * designated by module:echarts/coord/single/Single.
  57188. * @type {Function}
  57189. */
  57190. toGlobalCoord: null,
  57191. /**
  57192. * Convert the global coord to local coord.
  57193. * designated by module:echarts/coord/single/Single.
  57194. * @type {Function}
  57195. */
  57196. toLocalCoord: null
  57197. };
  57198. inherits(SingleAxis, Axis);
  57199. /*
  57200. * Licensed to the Apache Software Foundation (ASF) under one
  57201. * or more contributor license agreements. See the NOTICE file
  57202. * distributed with this work for additional information
  57203. * regarding copyright ownership. The ASF licenses this file
  57204. * to you under the Apache License, Version 2.0 (the
  57205. * "License"); you may not use this file except in compliance
  57206. * with the License. You may obtain a copy of the License at
  57207. *
  57208. * http://www.apache.org/licenses/LICENSE-2.0
  57209. *
  57210. * Unless required by applicable law or agreed to in writing,
  57211. * software distributed under the License is distributed on an
  57212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57213. * KIND, either express or implied. See the License for the
  57214. * specific language governing permissions and limitations
  57215. * under the License.
  57216. */
  57217. /**
  57218. * Single coordinates system.
  57219. */
  57220. /**
  57221. * Create a single coordinates system.
  57222. *
  57223. * @param {module:echarts/coord/single/AxisModel} axisModel
  57224. * @param {module:echarts/model/Global} ecModel
  57225. * @param {module:echarts/ExtensionAPI} api
  57226. */
  57227. function Single(axisModel, ecModel, api) {
  57228. /**
  57229. * @type {string}
  57230. * @readOnly
  57231. */
  57232. this.dimension = 'single';
  57233. /**
  57234. * Add it just for draw tooltip.
  57235. *
  57236. * @type {Array.<string>}
  57237. * @readOnly
  57238. */
  57239. this.dimensions = ['single'];
  57240. /**
  57241. * @private
  57242. * @type {module:echarts/coord/single/SingleAxis}.
  57243. */
  57244. this._axis = null;
  57245. /**
  57246. * @private
  57247. * @type {module:zrender/core/BoundingRect}
  57248. */
  57249. this._rect;
  57250. this._init(axisModel, ecModel, api);
  57251. /**
  57252. * @type {module:echarts/coord/single/AxisModel}
  57253. */
  57254. this.model = axisModel;
  57255. }
  57256. Single.prototype = {
  57257. type: 'singleAxis',
  57258. axisPointerEnabled: true,
  57259. constructor: Single,
  57260. /**
  57261. * Initialize single coordinate system.
  57262. *
  57263. * @param {module:echarts/coord/single/AxisModel} axisModel
  57264. * @param {module:echarts/model/Global} ecModel
  57265. * @param {module:echarts/ExtensionAPI} api
  57266. * @private
  57267. */
  57268. _init: function (axisModel, ecModel, api) {
  57269. var dim = this.dimension;
  57270. var axis = new SingleAxis(
  57271. dim,
  57272. createScaleByModel(axisModel),
  57273. [0, 0],
  57274. axisModel.get('type'),
  57275. axisModel.get('position')
  57276. );
  57277. var isCategory = axis.type === 'category';
  57278. axis.onBand = isCategory && axisModel.get('boundaryGap');
  57279. axis.inverse = axisModel.get('inverse');
  57280. axis.orient = axisModel.get('orient');
  57281. axisModel.axis = axis;
  57282. axis.model = axisModel;
  57283. axis.coordinateSystem = this;
  57284. this._axis = axis;
  57285. },
  57286. /**
  57287. * Update axis scale after data processed
  57288. * @param {module:echarts/model/Global} ecModel
  57289. * @param {module:echarts/ExtensionAPI} api
  57290. */
  57291. update: function (ecModel, api) {
  57292. ecModel.eachSeries(function (seriesModel) {
  57293. if (seriesModel.coordinateSystem === this) {
  57294. var data = seriesModel.getData();
  57295. each$1(data.mapDimension(this.dimension, true), function (dim) {
  57296. this._axis.scale.unionExtentFromData(data, dim);
  57297. }, this);
  57298. niceScaleExtent(this._axis.scale, this._axis.model);
  57299. }
  57300. }, this);
  57301. },
  57302. /**
  57303. * Resize the single coordinate system.
  57304. *
  57305. * @param {module:echarts/coord/single/AxisModel} axisModel
  57306. * @param {module:echarts/ExtensionAPI} api
  57307. */
  57308. resize: function (axisModel, api) {
  57309. this._rect = getLayoutRect(
  57310. {
  57311. left: axisModel.get('left'),
  57312. top: axisModel.get('top'),
  57313. right: axisModel.get('right'),
  57314. bottom: axisModel.get('bottom'),
  57315. width: axisModel.get('width'),
  57316. height: axisModel.get('height')
  57317. },
  57318. {
  57319. width: api.getWidth(),
  57320. height: api.getHeight()
  57321. }
  57322. );
  57323. this._adjustAxis();
  57324. },
  57325. /**
  57326. * @return {module:zrender/core/BoundingRect}
  57327. */
  57328. getRect: function () {
  57329. return this._rect;
  57330. },
  57331. /**
  57332. * @private
  57333. */
  57334. _adjustAxis: function () {
  57335. var rect = this._rect;
  57336. var axis = this._axis;
  57337. var isHorizontal = axis.isHorizontal();
  57338. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  57339. var idx = axis.reverse ? 1 : 0;
  57340. axis.setExtent(extent[idx], extent[1 - idx]);
  57341. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  57342. },
  57343. /**
  57344. * @param {module:echarts/coord/single/SingleAxis} axis
  57345. * @param {number} coordBase
  57346. */
  57347. _updateAxisTransform: function (axis, coordBase) {
  57348. var axisExtent = axis.getExtent();
  57349. var extentSum = axisExtent[0] + axisExtent[1];
  57350. var isHorizontal = axis.isHorizontal();
  57351. axis.toGlobalCoord = isHorizontal
  57352. ? function (coord) {
  57353. return coord + coordBase;
  57354. }
  57355. : function (coord) {
  57356. return extentSum - coord + coordBase;
  57357. };
  57358. axis.toLocalCoord = isHorizontal
  57359. ? function (coord) {
  57360. return coord - coordBase;
  57361. }
  57362. : function (coord) {
  57363. return extentSum - coord + coordBase;
  57364. };
  57365. },
  57366. /**
  57367. * Get axis.
  57368. *
  57369. * @return {module:echarts/coord/single/SingleAxis}
  57370. */
  57371. getAxis: function () {
  57372. return this._axis;
  57373. },
  57374. /**
  57375. * Get axis, add it just for draw tooltip.
  57376. *
  57377. * @return {[type]} [description]
  57378. */
  57379. getBaseAxis: function () {
  57380. return this._axis;
  57381. },
  57382. /**
  57383. * @return {Array.<module:echarts/coord/Axis>}
  57384. */
  57385. getAxes: function () {
  57386. return [this._axis];
  57387. },
  57388. /**
  57389. * @return {Object} {baseAxes: [], otherAxes: []}
  57390. */
  57391. getTooltipAxes: function () {
  57392. return {baseAxes: [this.getAxis()]};
  57393. },
  57394. /**
  57395. * If contain point.
  57396. *
  57397. * @param {Array.<number>} point
  57398. * @return {boolean}
  57399. */
  57400. containPoint: function (point) {
  57401. var rect = this.getRect();
  57402. var axis = this.getAxis();
  57403. var orient = axis.orient;
  57404. if (orient === 'horizontal') {
  57405. return axis.contain(axis.toLocalCoord(point[0]))
  57406. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  57407. }
  57408. else {
  57409. return axis.contain(axis.toLocalCoord(point[1]))
  57410. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  57411. }
  57412. },
  57413. /**
  57414. * @param {Array.<number>} point
  57415. * @return {Array.<number>}
  57416. */
  57417. pointToData: function (point) {
  57418. var axis = this.getAxis();
  57419. return [axis.coordToData(axis.toLocalCoord(
  57420. point[axis.orient === 'horizontal' ? 0 : 1]
  57421. ))];
  57422. },
  57423. /**
  57424. * Convert the series data to concrete point.
  57425. *
  57426. * @param {number|Array.<number>} val
  57427. * @return {Array.<number>}
  57428. */
  57429. dataToPoint: function (val) {
  57430. var axis = this.getAxis();
  57431. var rect = this.getRect();
  57432. var pt = [];
  57433. var idx = axis.orient === 'horizontal' ? 0 : 1;
  57434. if (val instanceof Array) {
  57435. val = val[0];
  57436. }
  57437. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  57438. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  57439. return pt;
  57440. }
  57441. };
  57442. /*
  57443. * Licensed to the Apache Software Foundation (ASF) under one
  57444. * or more contributor license agreements. See the NOTICE file
  57445. * distributed with this work for additional information
  57446. * regarding copyright ownership. The ASF licenses this file
  57447. * to you under the Apache License, Version 2.0 (the
  57448. * "License"); you may not use this file except in compliance
  57449. * with the License. You may obtain a copy of the License at
  57450. *
  57451. * http://www.apache.org/licenses/LICENSE-2.0
  57452. *
  57453. * Unless required by applicable law or agreed to in writing,
  57454. * software distributed under the License is distributed on an
  57455. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57456. * KIND, either express or implied. See the License for the
  57457. * specific language governing permissions and limitations
  57458. * under the License.
  57459. */
  57460. /**
  57461. * Single coordinate system creator.
  57462. */
  57463. /**
  57464. * Create single coordinate system and inject it into seriesModel.
  57465. *
  57466. * @param {module:echarts/model/Global} ecModel
  57467. * @param {module:echarts/ExtensionAPI} api
  57468. * @return {Array.<module:echarts/coord/single/Single>}
  57469. */
  57470. function create$3(ecModel, api) {
  57471. var singles = [];
  57472. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  57473. var single = new Single(axisModel, ecModel, api);
  57474. single.name = 'single_' + idx;
  57475. single.resize(axisModel, api);
  57476. axisModel.coordinateSystem = single;
  57477. singles.push(single);
  57478. });
  57479. ecModel.eachSeries(function (seriesModel) {
  57480. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  57481. var singleAxisModel = ecModel.queryComponents({
  57482. mainType: 'singleAxis',
  57483. index: seriesModel.get('singleAxisIndex'),
  57484. id: seriesModel.get('singleAxisId')
  57485. })[0];
  57486. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  57487. }
  57488. });
  57489. return singles;
  57490. }
  57491. CoordinateSystemManager.register('single', {
  57492. create: create$3,
  57493. dimensions: Single.prototype.dimensions
  57494. });
  57495. /*
  57496. * Licensed to the Apache Software Foundation (ASF) under one
  57497. * or more contributor license agreements. See the NOTICE file
  57498. * distributed with this work for additional information
  57499. * regarding copyright ownership. The ASF licenses this file
  57500. * to you under the Apache License, Version 2.0 (the
  57501. * "License"); you may not use this file except in compliance
  57502. * with the License. You may obtain a copy of the License at
  57503. *
  57504. * http://www.apache.org/licenses/LICENSE-2.0
  57505. *
  57506. * Unless required by applicable law or agreed to in writing,
  57507. * software distributed under the License is distributed on an
  57508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57509. * KIND, either express or implied. See the License for the
  57510. * specific language governing permissions and limitations
  57511. * under the License.
  57512. */
  57513. /**
  57514. * @param {Object} opt {labelInside}
  57515. * @return {Object} {
  57516. * position, rotation, labelDirection, labelOffset,
  57517. * tickDirection, labelRotate, z2
  57518. * }
  57519. */
  57520. function layout$2(axisModel, opt) {
  57521. opt = opt || {};
  57522. var single = axisModel.coordinateSystem;
  57523. var axis = axisModel.axis;
  57524. var layout = {};
  57525. var axisPosition = axis.position;
  57526. var orient = axis.orient;
  57527. var rect = single.getRect();
  57528. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  57529. var positionMap = {
  57530. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  57531. vertical: {left: rectBound[0], right: rectBound[1]}
  57532. };
  57533. layout.position = [
  57534. orient === 'vertical'
  57535. ? positionMap.vertical[axisPosition]
  57536. : rectBound[0],
  57537. orient === 'horizontal'
  57538. ? positionMap.horizontal[axisPosition]
  57539. : rectBound[3]
  57540. ];
  57541. var r = {horizontal: 0, vertical: 1};
  57542. layout.rotation = Math.PI / 2 * r[orient];
  57543. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  57544. layout.labelDirection = layout.tickDirection
  57545. = layout.nameDirection
  57546. = directionMap[axisPosition];
  57547. if (axisModel.get('axisTick.inside')) {
  57548. layout.tickDirection = -layout.tickDirection;
  57549. }
  57550. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  57551. layout.labelDirection = -layout.labelDirection;
  57552. }
  57553. var labelRotation = opt.rotate;
  57554. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  57555. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  57556. layout.z2 = 1;
  57557. return layout;
  57558. }
  57559. /*
  57560. * Licensed to the Apache Software Foundation (ASF) under one
  57561. * or more contributor license agreements. See the NOTICE file
  57562. * distributed with this work for additional information
  57563. * regarding copyright ownership. The ASF licenses this file
  57564. * to you under the Apache License, Version 2.0 (the
  57565. * "License"); you may not use this file except in compliance
  57566. * with the License. You may obtain a copy of the License at
  57567. *
  57568. * http://www.apache.org/licenses/LICENSE-2.0
  57569. *
  57570. * Unless required by applicable law or agreed to in writing,
  57571. * software distributed under the License is distributed on an
  57572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57573. * KIND, either express or implied. See the License for the
  57574. * specific language governing permissions and limitations
  57575. * under the License.
  57576. */
  57577. var axisBuilderAttrs$2 = [
  57578. 'axisLine', 'axisTickLabel', 'axisName'
  57579. ];
  57580. var selfBuilderAttr = 'splitLine';
  57581. var SingleAxisView = AxisView.extend({
  57582. type: 'singleAxis',
  57583. axisPointerClass: 'SingleAxisPointer',
  57584. render: function (axisModel, ecModel, api, payload) {
  57585. var group = this.group;
  57586. group.removeAll();
  57587. var layout = layout$2(axisModel);
  57588. var axisBuilder = new AxisBuilder(axisModel, layout);
  57589. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  57590. group.add(axisBuilder.getGroup());
  57591. if (axisModel.get(selfBuilderAttr + '.show')) {
  57592. this['_' + selfBuilderAttr](axisModel);
  57593. }
  57594. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  57595. },
  57596. _splitLine: function (axisModel) {
  57597. var axis = axisModel.axis;
  57598. if (axis.scale.isBlank()) {
  57599. return;
  57600. }
  57601. var splitLineModel = axisModel.getModel('splitLine');
  57602. var lineStyleModel = splitLineModel.getModel('lineStyle');
  57603. var lineWidth = lineStyleModel.get('width');
  57604. var lineColors = lineStyleModel.get('color');
  57605. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  57606. var gridRect = axisModel.coordinateSystem.getRect();
  57607. var isHorizontal = axis.isHorizontal();
  57608. var splitLines = [];
  57609. var lineCount = 0;
  57610. var ticksCoords = axis.getTicksCoords({
  57611. tickModel: splitLineModel
  57612. });
  57613. var p1 = [];
  57614. var p2 = [];
  57615. for (var i = 0; i < ticksCoords.length; ++i) {
  57616. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  57617. if (isHorizontal) {
  57618. p1[0] = tickCoord;
  57619. p1[1] = gridRect.y;
  57620. p2[0] = tickCoord;
  57621. p2[1] = gridRect.y + gridRect.height;
  57622. }
  57623. else {
  57624. p1[0] = gridRect.x;
  57625. p1[1] = tickCoord;
  57626. p2[0] = gridRect.x + gridRect.width;
  57627. p2[1] = tickCoord;
  57628. }
  57629. var colorIndex = (lineCount++) % lineColors.length;
  57630. splitLines[colorIndex] = splitLines[colorIndex] || [];
  57631. splitLines[colorIndex].push(new Line(
  57632. subPixelOptimizeLine({
  57633. shape: {
  57634. x1: p1[0],
  57635. y1: p1[1],
  57636. x2: p2[0],
  57637. y2: p2[1]
  57638. },
  57639. style: {
  57640. lineWidth: lineWidth
  57641. },
  57642. silent: true
  57643. })));
  57644. }
  57645. for (var i = 0; i < splitLines.length; ++i) {
  57646. this.group.add(mergePath(splitLines[i], {
  57647. style: {
  57648. stroke: lineColors[i % lineColors.length],
  57649. lineDash: lineStyleModel.getLineDash(lineWidth),
  57650. lineWidth: lineWidth
  57651. },
  57652. silent: true
  57653. }));
  57654. }
  57655. }
  57656. });
  57657. /*
  57658. * Licensed to the Apache Software Foundation (ASF) under one
  57659. * or more contributor license agreements. See the NOTICE file
  57660. * distributed with this work for additional information
  57661. * regarding copyright ownership. The ASF licenses this file
  57662. * to you under the Apache License, Version 2.0 (the
  57663. * "License"); you may not use this file except in compliance
  57664. * with the License. You may obtain a copy of the License at
  57665. *
  57666. * http://www.apache.org/licenses/LICENSE-2.0
  57667. *
  57668. * Unless required by applicable law or agreed to in writing,
  57669. * software distributed under the License is distributed on an
  57670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57671. * KIND, either express or implied. See the License for the
  57672. * specific language governing permissions and limitations
  57673. * under the License.
  57674. */
  57675. var AxisModel$4 = ComponentModel.extend({
  57676. type: 'singleAxis',
  57677. layoutMode: 'box',
  57678. /**
  57679. * @type {module:echarts/coord/single/SingleAxis}
  57680. */
  57681. axis: null,
  57682. /**
  57683. * @type {module:echarts/coord/single/Single}
  57684. */
  57685. coordinateSystem: null,
  57686. /**
  57687. * @override
  57688. */
  57689. getCoordSysModel: function () {
  57690. return this;
  57691. }
  57692. });
  57693. var defaultOption$2 = {
  57694. left: '5%',
  57695. top: '5%',
  57696. right: '5%',
  57697. bottom: '5%',
  57698. type: 'value',
  57699. position: 'bottom',
  57700. orient: 'horizontal',
  57701. axisLine: {
  57702. show: true,
  57703. lineStyle: {
  57704. width: 2,
  57705. type: 'solid'
  57706. }
  57707. },
  57708. // Single coordinate system and single axis is the,
  57709. // which is used as the parent tooltip model.
  57710. // same model, so we set default tooltip show as true.
  57711. tooltip: {
  57712. show: true
  57713. },
  57714. axisTick: {
  57715. show: true,
  57716. length: 6,
  57717. lineStyle: {
  57718. width: 2
  57719. }
  57720. },
  57721. axisLabel: {
  57722. show: true,
  57723. interval: 'auto'
  57724. },
  57725. splitLine: {
  57726. show: true,
  57727. lineStyle: {
  57728. type: 'dashed',
  57729. opacity: 0.2
  57730. }
  57731. }
  57732. };
  57733. function getAxisType$2(axisName, option) {
  57734. return option.type || (option.data ? 'category' : 'value');
  57735. }
  57736. merge(AxisModel$4.prototype, axisModelCommonMixin);
  57737. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  57738. /*
  57739. * Licensed to the Apache Software Foundation (ASF) under one
  57740. * or more contributor license agreements. See the NOTICE file
  57741. * distributed with this work for additional information
  57742. * regarding copyright ownership. The ASF licenses this file
  57743. * to you under the Apache License, Version 2.0 (the
  57744. * "License"); you may not use this file except in compliance
  57745. * with the License. You may obtain a copy of the License at
  57746. *
  57747. * http://www.apache.org/licenses/LICENSE-2.0
  57748. *
  57749. * Unless required by applicable law or agreed to in writing,
  57750. * software distributed under the License is distributed on an
  57751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57752. * KIND, either express or implied. See the License for the
  57753. * specific language governing permissions and limitations
  57754. * under the License.
  57755. */
  57756. /**
  57757. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  57758. * @param {module:echarts/model/Global} ecModel
  57759. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  57760. */
  57761. var findPointFromSeries = function (finder, ecModel) {
  57762. var point = [];
  57763. var seriesIndex = finder.seriesIndex;
  57764. var seriesModel;
  57765. if (seriesIndex == null || !(
  57766. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  57767. )) {
  57768. return {point: []};
  57769. }
  57770. var data = seriesModel.getData();
  57771. var dataIndex = queryDataIndex(data, finder);
  57772. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  57773. return {point: []};
  57774. }
  57775. var el = data.getItemGraphicEl(dataIndex);
  57776. var coordSys = seriesModel.coordinateSystem;
  57777. if (seriesModel.getTooltipPosition) {
  57778. point = seriesModel.getTooltipPosition(dataIndex) || [];
  57779. }
  57780. else if (coordSys && coordSys.dataToPoint) {
  57781. point = coordSys.dataToPoint(
  57782. data.getValues(
  57783. map(coordSys.dimensions, function (dim) {
  57784. return data.mapDimension(dim);
  57785. }), dataIndex, true
  57786. )
  57787. ) || [];
  57788. }
  57789. else if (el) {
  57790. // Use graphic bounding rect
  57791. var rect = el.getBoundingRect().clone();
  57792. rect.applyTransform(el.transform);
  57793. point = [
  57794. rect.x + rect.width / 2,
  57795. rect.y + rect.height / 2
  57796. ];
  57797. }
  57798. return {point: point, el: el};
  57799. };
  57800. /*
  57801. * Licensed to the Apache Software Foundation (ASF) under one
  57802. * or more contributor license agreements. See the NOTICE file
  57803. * distributed with this work for additional information
  57804. * regarding copyright ownership. The ASF licenses this file
  57805. * to you under the Apache License, Version 2.0 (the
  57806. * "License"); you may not use this file except in compliance
  57807. * with the License. You may obtain a copy of the License at
  57808. *
  57809. * http://www.apache.org/licenses/LICENSE-2.0
  57810. *
  57811. * Unless required by applicable law or agreed to in writing,
  57812. * software distributed under the License is distributed on an
  57813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57814. * KIND, either express or implied. See the License for the
  57815. * specific language governing permissions and limitations
  57816. * under the License.
  57817. */
  57818. var each$14 = each$1;
  57819. var curry$3 = curry;
  57820. var inner$9 = makeInner();
  57821. /**
  57822. * Basic logic: check all axis, if they do not demand show/highlight,
  57823. * then hide/downplay them.
  57824. *
  57825. * @param {Object} coordSysAxesInfo
  57826. * @param {Object} payload
  57827. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  57828. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  57829. * trigger axisPointer and tooltip.
  57830. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  57831. * trigger axisPointer and tooltip.
  57832. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  57833. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  57834. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  57835. * [{
  57836. * axisDim: 'x'|'y'|'angle'|...,
  57837. * axisIndex: ...,
  57838. * value: ...
  57839. * }, ...]
  57840. * @param {Function} [payload.dispatchAction]
  57841. * @param {Object} [payload.tooltipOption]
  57842. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  57843. * which can be specified in dispatchAction
  57844. * @param {module:echarts/model/Global} ecModel
  57845. * @param {module:echarts/ExtensionAPI} api
  57846. * @return {Object} content of event obj for echarts.connect.
  57847. */
  57848. var axisTrigger = function (payload, ecModel, api) {
  57849. var currTrigger = payload.currTrigger;
  57850. var point = [payload.x, payload.y];
  57851. var finder = payload;
  57852. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  57853. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  57854. // Pending
  57855. // See #6121. But we are not able to reproduce it yet.
  57856. if (!coordSysAxesInfo) {
  57857. return;
  57858. }
  57859. if (illegalPoint(point)) {
  57860. // Used in the default behavior of `connection`: use the sample seriesIndex
  57861. // and dataIndex. And also used in the tooltipView trigger.
  57862. point = findPointFromSeries({
  57863. seriesIndex: finder.seriesIndex,
  57864. // Do not use dataIndexInside from other ec instance.
  57865. // FIXME: auto detect it?
  57866. dataIndex: finder.dataIndex
  57867. }, ecModel).point;
  57868. }
  57869. var isIllegalPoint = illegalPoint(point);
  57870. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  57871. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  57872. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  57873. // and dataIndex.
  57874. var inputAxesInfo = finder.axesInfo;
  57875. var axesInfo = coordSysAxesInfo.axesInfo;
  57876. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  57877. var outputFinder = {};
  57878. var showValueMap = {};
  57879. var dataByCoordSys = {list: [], map: {}};
  57880. var updaters = {
  57881. showPointer: curry$3(showPointer, showValueMap),
  57882. showTooltip: curry$3(showTooltip, dataByCoordSys)
  57883. };
  57884. // Process for triggered axes.
  57885. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  57886. // If a point given, it must be contained by the coordinate system.
  57887. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  57888. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  57889. var axis = axisInfo.axis;
  57890. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  57891. // If no inputAxesInfo, no axis is restricted.
  57892. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  57893. var val = inputAxisInfo && inputAxisInfo.value;
  57894. if (val == null && !isIllegalPoint) {
  57895. val = axis.pointToData(point);
  57896. }
  57897. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  57898. }
  57899. });
  57900. });
  57901. // Process for linked axes.
  57902. var linkTriggers = {};
  57903. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  57904. var linkGroup = tarAxisInfo.linkGroup;
  57905. // If axis has been triggered in the previous stage, it should not be triggered by link.
  57906. if (linkGroup && !showValueMap[tarKey]) {
  57907. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  57908. var srcValItem = showValueMap[srcKey];
  57909. // If srcValItem exist, source axis is triggered, so link to target axis.
  57910. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  57911. var val = srcValItem.value;
  57912. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  57913. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  57914. )));
  57915. linkTriggers[tarAxisInfo.key] = val;
  57916. }
  57917. });
  57918. }
  57919. });
  57920. each$14(linkTriggers, function (val, tarKey) {
  57921. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  57922. });
  57923. updateModelActually(showValueMap, axesInfo, outputFinder);
  57924. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  57925. dispatchHighDownActually(axesInfo, dispatchAction, api);
  57926. return outputFinder;
  57927. };
  57928. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  57929. var axis = axisInfo.axis;
  57930. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  57931. return;
  57932. }
  57933. if (!axisInfo.involveSeries) {
  57934. updaters.showPointer(axisInfo, newValue);
  57935. return;
  57936. }
  57937. // Heavy calculation. So put it after axis.containData checking.
  57938. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  57939. var payloadBatch = payloadInfo.payloadBatch;
  57940. var snapToValue = payloadInfo.snapToValue;
  57941. // Fill content of event obj for echarts.connect.
  57942. // By defualt use the first involved series data as a sample to connect.
  57943. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  57944. extend(outputFinder, payloadBatch[0]);
  57945. }
  57946. // If no linkSource input, this process is for collecting link
  57947. // target, where snap should not be accepted.
  57948. if (!dontSnap && axisInfo.snap) {
  57949. if (axis.containData(snapToValue) && snapToValue != null) {
  57950. newValue = snapToValue;
  57951. }
  57952. }
  57953. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  57954. // Tooltip should always be snapToValue, otherwise there will be
  57955. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  57956. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  57957. }
  57958. function buildPayloadsBySeries(value, axisInfo) {
  57959. var axis = axisInfo.axis;
  57960. var dim = axis.dim;
  57961. var snapToValue = value;
  57962. var payloadBatch = [];
  57963. var minDist = Number.MAX_VALUE;
  57964. var minDiff = -1;
  57965. each$14(axisInfo.seriesModels, function (series, idx) {
  57966. var dataDim = series.getData().mapDimension(dim, true);
  57967. var seriesNestestValue;
  57968. var dataIndices;
  57969. if (series.getAxisTooltipData) {
  57970. var result = series.getAxisTooltipData(dataDim, value, axis);
  57971. dataIndices = result.dataIndices;
  57972. seriesNestestValue = result.nestestValue;
  57973. }
  57974. else {
  57975. dataIndices = series.getData().indicesOfNearest(
  57976. dataDim[0],
  57977. value,
  57978. // Add a threshold to avoid find the wrong dataIndex
  57979. // when data length is not same.
  57980. // false,
  57981. axis.type === 'category' ? 0.5 : null
  57982. );
  57983. if (!dataIndices.length) {
  57984. return;
  57985. }
  57986. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  57987. }
  57988. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  57989. return;
  57990. }
  57991. var diff = value - seriesNestestValue;
  57992. var dist = Math.abs(diff);
  57993. // Consider category case
  57994. if (dist <= minDist) {
  57995. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  57996. minDist = dist;
  57997. minDiff = diff;
  57998. snapToValue = seriesNestestValue;
  57999. payloadBatch.length = 0;
  58000. }
  58001. each$14(dataIndices, function (dataIndex) {
  58002. payloadBatch.push({
  58003. seriesIndex: series.seriesIndex,
  58004. dataIndexInside: dataIndex,
  58005. dataIndex: series.getData().getRawIndex(dataIndex)
  58006. });
  58007. });
  58008. }
  58009. });
  58010. return {
  58011. payloadBatch: payloadBatch,
  58012. snapToValue: snapToValue
  58013. };
  58014. }
  58015. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  58016. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  58017. }
  58018. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  58019. var payloadBatch = payloadInfo.payloadBatch;
  58020. var axis = axisInfo.axis;
  58021. var axisModel = axis.model;
  58022. var axisPointerModel = axisInfo.axisPointerModel;
  58023. // If no data, do not create anything in dataByCoordSys,
  58024. // whose length will be used to judge whether dispatch action.
  58025. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  58026. return;
  58027. }
  58028. var coordSysModel = axisInfo.coordSys.model;
  58029. var coordSysKey = makeKey(coordSysModel);
  58030. var coordSysItem = dataByCoordSys.map[coordSysKey];
  58031. if (!coordSysItem) {
  58032. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  58033. coordSysId: coordSysModel.id,
  58034. coordSysIndex: coordSysModel.componentIndex,
  58035. coordSysType: coordSysModel.type,
  58036. coordSysMainType: coordSysModel.mainType,
  58037. dataByAxis: []
  58038. };
  58039. dataByCoordSys.list.push(coordSysItem);
  58040. }
  58041. coordSysItem.dataByAxis.push({
  58042. axisDim: axis.dim,
  58043. axisIndex: axisModel.componentIndex,
  58044. axisType: axisModel.type,
  58045. axisId: axisModel.id,
  58046. value: value,
  58047. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  58048. // depends that all models have been updated. So it should not be performed
  58049. // here. Considering axisPointerModel used here is volatile, which is hard
  58050. // to be retrieve in TooltipView, we prepare parameters here.
  58051. valueLabelOpt: {
  58052. precision: axisPointerModel.get('label.precision'),
  58053. formatter: axisPointerModel.get('label.formatter')
  58054. },
  58055. seriesDataIndices: payloadBatch.slice()
  58056. });
  58057. }
  58058. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  58059. var outputAxesInfo = outputFinder.axesInfo = [];
  58060. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  58061. each$14(axesInfo, function (axisInfo, key) {
  58062. var option = axisInfo.axisPointerModel.option;
  58063. var valItem = showValueMap[key];
  58064. if (valItem) {
  58065. !axisInfo.useHandle && (option.status = 'show');
  58066. option.value = valItem.value;
  58067. // For label formatter param and highlight.
  58068. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  58069. }
  58070. // When always show (e.g., handle used), remain
  58071. // original value and status.
  58072. else {
  58073. // If hide, value still need to be set, consider
  58074. // click legend to toggle axis blank.
  58075. !axisInfo.useHandle && (option.status = 'hide');
  58076. }
  58077. // If status is 'hide', should be no info in payload.
  58078. option.status === 'show' && outputAxesInfo.push({
  58079. axisDim: axisInfo.axis.dim,
  58080. axisIndex: axisInfo.axis.model.componentIndex,
  58081. value: option.value
  58082. });
  58083. });
  58084. }
  58085. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  58086. // Basic logic: If no showTip required, hideTip will be dispatched.
  58087. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  58088. dispatchAction({type: 'hideTip'});
  58089. return;
  58090. }
  58091. // In most case only one axis (or event one series is used). It is
  58092. // convinient to fetch payload.seriesIndex and payload.dataIndex
  58093. // dirtectly. So put the first seriesIndex and dataIndex of the first
  58094. // axis on the payload.
  58095. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  58096. dispatchAction({
  58097. type: 'showTip',
  58098. escapeConnect: true,
  58099. x: point[0],
  58100. y: point[1],
  58101. tooltipOption: payload.tooltipOption,
  58102. position: payload.position,
  58103. dataIndexInside: sampleItem.dataIndexInside,
  58104. dataIndex: sampleItem.dataIndex,
  58105. seriesIndex: sampleItem.seriesIndex,
  58106. dataByCoordSys: dataByCoordSys.list
  58107. });
  58108. }
  58109. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  58110. // FIXME
  58111. // highlight status modification shoule be a stage of main process?
  58112. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  58113. var zr = api.getZr();
  58114. var highDownKey = 'axisPointerLastHighlights';
  58115. var lastHighlights = inner$9(zr)[highDownKey] || {};
  58116. var newHighlights = inner$9(zr)[highDownKey] = {};
  58117. // Update highlight/downplay status according to axisPointer model.
  58118. // Build hash map and remove duplicate incidentally.
  58119. each$14(axesInfo, function (axisInfo, key) {
  58120. var option = axisInfo.axisPointerModel.option;
  58121. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  58122. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  58123. newHighlights[key] = batchItem;
  58124. });
  58125. });
  58126. // Diff.
  58127. var toHighlight = [];
  58128. var toDownplay = [];
  58129. each$1(lastHighlights, function (batchItem, key) {
  58130. !newHighlights[key] && toDownplay.push(batchItem);
  58131. });
  58132. each$1(newHighlights, function (batchItem, key) {
  58133. !lastHighlights[key] && toHighlight.push(batchItem);
  58134. });
  58135. toDownplay.length && api.dispatchAction({
  58136. type: 'downplay', escapeConnect: true, batch: toDownplay
  58137. });
  58138. toHighlight.length && api.dispatchAction({
  58139. type: 'highlight', escapeConnect: true, batch: toHighlight
  58140. });
  58141. }
  58142. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  58143. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  58144. var inputAxisInfo = inputAxesInfo[i];
  58145. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  58146. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  58147. ) {
  58148. return inputAxisInfo;
  58149. }
  58150. }
  58151. }
  58152. function makeMapperParam(axisInfo) {
  58153. var axisModel = axisInfo.axis.model;
  58154. var item = {};
  58155. var dim = item.axisDim = axisInfo.axis.dim;
  58156. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  58157. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  58158. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  58159. return item;
  58160. }
  58161. function illegalPoint(point) {
  58162. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  58163. }
  58164. /*
  58165. * Licensed to the Apache Software Foundation (ASF) under one
  58166. * or more contributor license agreements. See the NOTICE file
  58167. * distributed with this work for additional information
  58168. * regarding copyright ownership. The ASF licenses this file
  58169. * to you under the Apache License, Version 2.0 (the
  58170. * "License"); you may not use this file except in compliance
  58171. * with the License. You may obtain a copy of the License at
  58172. *
  58173. * http://www.apache.org/licenses/LICENSE-2.0
  58174. *
  58175. * Unless required by applicable law or agreed to in writing,
  58176. * software distributed under the License is distributed on an
  58177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58178. * KIND, either express or implied. See the License for the
  58179. * specific language governing permissions and limitations
  58180. * under the License.
  58181. */
  58182. var AxisPointerModel = extendComponentModel({
  58183. type: 'axisPointer',
  58184. coordSysAxesInfo: null,
  58185. defaultOption: {
  58186. // 'auto' means that show when triggered by tooltip or handle.
  58187. show: 'auto',
  58188. // 'click' | 'mousemove' | 'none'
  58189. triggerOn: null, // set default in AxisPonterView.js
  58190. zlevel: 0,
  58191. z: 50,
  58192. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  58193. // axispointer triggered by tootip determine snap automatically,
  58194. // see `modelHelper`.
  58195. snap: false,
  58196. triggerTooltip: true,
  58197. value: null,
  58198. status: null, // Init value depends on whether handle is used.
  58199. // [group0, group1, ...]
  58200. // Each group can be: {
  58201. // mapper: function () {},
  58202. // singleTooltip: 'multiple', // 'multiple' or 'single'
  58203. // xAxisId: ...,
  58204. // yAxisName: ...,
  58205. // angleAxisIndex: ...
  58206. // }
  58207. // mapper: can be ignored.
  58208. // input: {axisInfo, value}
  58209. // output: {axisInfo, value}
  58210. link: [],
  58211. // Do not set 'auto' here, otherwise global animation: false
  58212. // will not effect at this axispointer.
  58213. animation: null,
  58214. animationDurationUpdate: 200,
  58215. lineStyle: {
  58216. color: '#aaa',
  58217. width: 1,
  58218. type: 'solid'
  58219. },
  58220. shadowStyle: {
  58221. color: 'rgba(150,150,150,0.3)'
  58222. },
  58223. label: {
  58224. show: true,
  58225. formatter: null, // string | Function
  58226. precision: 'auto', // Or a number like 0, 1, 2 ...
  58227. margin: 3,
  58228. color: '#fff',
  58229. padding: [5, 7, 5, 7],
  58230. backgroundColor: 'auto', // default: axis line color
  58231. borderColor: null,
  58232. borderWidth: 0,
  58233. shadowBlur: 3,
  58234. shadowColor: '#aaa'
  58235. // Considering applicability, common style should
  58236. // better not have shadowOffset.
  58237. // shadowOffsetX: 0,
  58238. // shadowOffsetY: 2
  58239. },
  58240. handle: {
  58241. show: false,
  58242. /* eslint-disable */
  58243. 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
  58244. /* eslint-enable */
  58245. size: 45,
  58246. // handle margin is from symbol center to axis, which is stable when circular move.
  58247. margin: 50,
  58248. // color: '#1b8bbd'
  58249. // color: '#2f4554'
  58250. color: '#333',
  58251. shadowBlur: 3,
  58252. shadowColor: '#aaa',
  58253. shadowOffsetX: 0,
  58254. shadowOffsetY: 2,
  58255. // For mobile performance
  58256. throttle: 40
  58257. }
  58258. }
  58259. });
  58260. /*
  58261. * Licensed to the Apache Software Foundation (ASF) under one
  58262. * or more contributor license agreements. See the NOTICE file
  58263. * distributed with this work for additional information
  58264. * regarding copyright ownership. The ASF licenses this file
  58265. * to you under the Apache License, Version 2.0 (the
  58266. * "License"); you may not use this file except in compliance
  58267. * with the License. You may obtain a copy of the License at
  58268. *
  58269. * http://www.apache.org/licenses/LICENSE-2.0
  58270. *
  58271. * Unless required by applicable law or agreed to in writing,
  58272. * software distributed under the License is distributed on an
  58273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58274. * KIND, either express or implied. See the License for the
  58275. * specific language governing permissions and limitations
  58276. * under the License.
  58277. */
  58278. var inner$10 = makeInner();
  58279. var each$15 = each$1;
  58280. /**
  58281. * @param {string} key
  58282. * @param {module:echarts/ExtensionAPI} api
  58283. * @param {Function} handler
  58284. * param: {string} currTrigger
  58285. * param: {Array.<number>} point
  58286. */
  58287. function register(key, api, handler) {
  58288. if (env$1.node) {
  58289. return;
  58290. }
  58291. var zr = api.getZr();
  58292. inner$10(zr).records || (inner$10(zr).records = {});
  58293. initGlobalListeners(zr, api);
  58294. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  58295. record.handler = handler;
  58296. }
  58297. function initGlobalListeners(zr, api) {
  58298. if (inner$10(zr).initialized) {
  58299. return;
  58300. }
  58301. inner$10(zr).initialized = true;
  58302. useHandler('click', curry(doEnter, 'click'));
  58303. useHandler('mousemove', curry(doEnter, 'mousemove'));
  58304. // useHandler('mouseout', onLeave);
  58305. useHandler('globalout', onLeave);
  58306. function useHandler(eventType, cb) {
  58307. zr.on(eventType, function (e) {
  58308. var dis = makeDispatchAction(api);
  58309. each$15(inner$10(zr).records, function (record) {
  58310. record && cb(record, e, dis.dispatchAction);
  58311. });
  58312. dispatchTooltipFinally(dis.pendings, api);
  58313. });
  58314. }
  58315. }
  58316. function dispatchTooltipFinally(pendings, api) {
  58317. var showLen = pendings.showTip.length;
  58318. var hideLen = pendings.hideTip.length;
  58319. var actuallyPayload;
  58320. if (showLen) {
  58321. actuallyPayload = pendings.showTip[showLen - 1];
  58322. }
  58323. else if (hideLen) {
  58324. actuallyPayload = pendings.hideTip[hideLen - 1];
  58325. }
  58326. if (actuallyPayload) {
  58327. actuallyPayload.dispatchAction = null;
  58328. api.dispatchAction(actuallyPayload);
  58329. }
  58330. }
  58331. function onLeave(record, e, dispatchAction) {
  58332. record.handler('leave', null, dispatchAction);
  58333. }
  58334. function doEnter(currTrigger, record, e, dispatchAction) {
  58335. record.handler(currTrigger, e, dispatchAction);
  58336. }
  58337. function makeDispatchAction(api) {
  58338. var pendings = {
  58339. showTip: [],
  58340. hideTip: []
  58341. };
  58342. // FIXME
  58343. // better approach?
  58344. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  58345. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  58346. // So we have to add "final stage" to merge those dispatched actions.
  58347. var dispatchAction = function (payload) {
  58348. var pendingList = pendings[payload.type];
  58349. if (pendingList) {
  58350. pendingList.push(payload);
  58351. }
  58352. else {
  58353. payload.dispatchAction = dispatchAction;
  58354. api.dispatchAction(payload);
  58355. }
  58356. };
  58357. return {
  58358. dispatchAction: dispatchAction,
  58359. pendings: pendings
  58360. };
  58361. }
  58362. /**
  58363. * @param {string} key
  58364. * @param {module:echarts/ExtensionAPI} api
  58365. */
  58366. function unregister(key, api) {
  58367. if (env$1.node) {
  58368. return;
  58369. }
  58370. var zr = api.getZr();
  58371. var record = (inner$10(zr).records || {})[key];
  58372. if (record) {
  58373. inner$10(zr).records[key] = null;
  58374. }
  58375. }
  58376. /*
  58377. * Licensed to the Apache Software Foundation (ASF) under one
  58378. * or more contributor license agreements. See the NOTICE file
  58379. * distributed with this work for additional information
  58380. * regarding copyright ownership. The ASF licenses this file
  58381. * to you under the Apache License, Version 2.0 (the
  58382. * "License"); you may not use this file except in compliance
  58383. * with the License. You may obtain a copy of the License at
  58384. *
  58385. * http://www.apache.org/licenses/LICENSE-2.0
  58386. *
  58387. * Unless required by applicable law or agreed to in writing,
  58388. * software distributed under the License is distributed on an
  58389. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58390. * KIND, either express or implied. See the License for the
  58391. * specific language governing permissions and limitations
  58392. * under the License.
  58393. */
  58394. var AxisPointerView = extendComponentView({
  58395. type: 'axisPointer',
  58396. render: function (globalAxisPointerModel, ecModel, api) {
  58397. var globalTooltipModel = ecModel.getComponent('tooltip');
  58398. var triggerOn = globalAxisPointerModel.get('triggerOn')
  58399. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  58400. // Register global listener in AxisPointerView to enable
  58401. // AxisPointerView to be independent to Tooltip.
  58402. register(
  58403. 'axisPointer',
  58404. api,
  58405. function (currTrigger, e, dispatchAction) {
  58406. // If 'none', it is not controlled by mouse totally.
  58407. if (triggerOn !== 'none'
  58408. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  58409. ) {
  58410. dispatchAction({
  58411. type: 'updateAxisPointer',
  58412. currTrigger: currTrigger,
  58413. x: e && e.offsetX,
  58414. y: e && e.offsetY
  58415. });
  58416. }
  58417. }
  58418. );
  58419. },
  58420. /**
  58421. * @override
  58422. */
  58423. remove: function (ecModel, api) {
  58424. unregister(api.getZr(), 'axisPointer');
  58425. AxisPointerView.superApply(this._model, 'remove', arguments);
  58426. },
  58427. /**
  58428. * @override
  58429. */
  58430. dispose: function (ecModel, api) {
  58431. unregister('axisPointer', api);
  58432. AxisPointerView.superApply(this._model, 'dispose', arguments);
  58433. }
  58434. });
  58435. /*
  58436. * Licensed to the Apache Software Foundation (ASF) under one
  58437. * or more contributor license agreements. See the NOTICE file
  58438. * distributed with this work for additional information
  58439. * regarding copyright ownership. The ASF licenses this file
  58440. * to you under the Apache License, Version 2.0 (the
  58441. * "License"); you may not use this file except in compliance
  58442. * with the License. You may obtain a copy of the License at
  58443. *
  58444. * http://www.apache.org/licenses/LICENSE-2.0
  58445. *
  58446. * Unless required by applicable law or agreed to in writing,
  58447. * software distributed under the License is distributed on an
  58448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58449. * KIND, either express or implied. See the License for the
  58450. * specific language governing permissions and limitations
  58451. * under the License.
  58452. */
  58453. var inner$11 = makeInner();
  58454. var clone$4 = clone;
  58455. var bind$2 = bind;
  58456. /**
  58457. * Base axis pointer class in 2D.
  58458. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  58459. */
  58460. function BaseAxisPointer() {
  58461. }
  58462. BaseAxisPointer.prototype = {
  58463. /**
  58464. * @private
  58465. */
  58466. _group: null,
  58467. /**
  58468. * @private
  58469. */
  58470. _lastGraphicKey: null,
  58471. /**
  58472. * @private
  58473. */
  58474. _handle: null,
  58475. /**
  58476. * @private
  58477. */
  58478. _dragging: false,
  58479. /**
  58480. * @private
  58481. */
  58482. _lastValue: null,
  58483. /**
  58484. * @private
  58485. */
  58486. _lastStatus: null,
  58487. /**
  58488. * @private
  58489. */
  58490. _payloadInfo: null,
  58491. /**
  58492. * In px, arbitrary value. Do not set too small,
  58493. * no animation is ok for most cases.
  58494. * @protected
  58495. */
  58496. animationThreshold: 15,
  58497. /**
  58498. * @implement
  58499. */
  58500. render: function (axisModel, axisPointerModel, api, forceRender) {
  58501. var value = axisPointerModel.get('value');
  58502. var status = axisPointerModel.get('status');
  58503. // Bind them to `this`, not in closure, otherwise they will not
  58504. // be replaced when user calling setOption in not merge mode.
  58505. this._axisModel = axisModel;
  58506. this._axisPointerModel = axisPointerModel;
  58507. this._api = api;
  58508. // Optimize: `render` will be called repeatly during mouse move.
  58509. // So it is power consuming if performing `render` each time,
  58510. // especially on mobile device.
  58511. if (!forceRender
  58512. && this._lastValue === value
  58513. && this._lastStatus === status
  58514. ) {
  58515. return;
  58516. }
  58517. this._lastValue = value;
  58518. this._lastStatus = status;
  58519. var group = this._group;
  58520. var handle = this._handle;
  58521. if (!status || status === 'hide') {
  58522. // Do not clear here, for animation better.
  58523. group && group.hide();
  58524. handle && handle.hide();
  58525. return;
  58526. }
  58527. group && group.show();
  58528. handle && handle.show();
  58529. // Otherwise status is 'show'
  58530. var elOption = {};
  58531. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  58532. // Enable change axis pointer type.
  58533. var graphicKey = elOption.graphicKey;
  58534. if (graphicKey !== this._lastGraphicKey) {
  58535. this.clear(api);
  58536. }
  58537. this._lastGraphicKey = graphicKey;
  58538. var moveAnimation = this._moveAnimation
  58539. = this.determineAnimation(axisModel, axisPointerModel);
  58540. if (!group) {
  58541. group = this._group = new Group();
  58542. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  58543. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  58544. api.getZr().add(group);
  58545. }
  58546. else {
  58547. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  58548. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  58549. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  58550. }
  58551. updateMandatoryProps(group, axisPointerModel, true);
  58552. this._renderHandle(value);
  58553. },
  58554. /**
  58555. * @implement
  58556. */
  58557. remove: function (api) {
  58558. this.clear(api);
  58559. },
  58560. /**
  58561. * @implement
  58562. */
  58563. dispose: function (api) {
  58564. this.clear(api);
  58565. },
  58566. /**
  58567. * @protected
  58568. */
  58569. determineAnimation: function (axisModel, axisPointerModel) {
  58570. var animation = axisPointerModel.get('animation');
  58571. var axis = axisModel.axis;
  58572. var isCategoryAxis = axis.type === 'category';
  58573. var useSnap = axisPointerModel.get('snap');
  58574. // Value axis without snap always do not snap.
  58575. if (!useSnap && !isCategoryAxis) {
  58576. return false;
  58577. }
  58578. if (animation === 'auto' || animation == null) {
  58579. var animationThreshold = this.animationThreshold;
  58580. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  58581. return true;
  58582. }
  58583. // It is important to auto animation when snap used. Consider if there is
  58584. // a dataZoom, animation will be disabled when too many points exist, while
  58585. // it will be enabled for better visual effect when little points exist.
  58586. if (useSnap) {
  58587. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  58588. var axisExtent = axis.getExtent();
  58589. // Approximate band width
  58590. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  58591. }
  58592. return false;
  58593. }
  58594. return animation === true;
  58595. },
  58596. /**
  58597. * add {pointer, label, graphicKey} to elOption
  58598. * @protected
  58599. */
  58600. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  58601. // Shoule be implemenented by sub-class.
  58602. },
  58603. /**
  58604. * @protected
  58605. */
  58606. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  58607. var pointerOption = elOption.pointer;
  58608. if (pointerOption) {
  58609. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  58610. clone$4(elOption.pointer)
  58611. );
  58612. group.add(pointerEl);
  58613. }
  58614. },
  58615. /**
  58616. * @protected
  58617. */
  58618. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  58619. if (elOption.label) {
  58620. var labelEl = inner$11(group).labelEl = new Rect(
  58621. clone$4(elOption.label)
  58622. );
  58623. group.add(labelEl);
  58624. updateLabelShowHide(labelEl, axisPointerModel);
  58625. }
  58626. },
  58627. /**
  58628. * @protected
  58629. */
  58630. updatePointerEl: function (group, elOption, updateProps$$1) {
  58631. var pointerEl = inner$11(group).pointerEl;
  58632. if (pointerEl) {
  58633. pointerEl.setStyle(elOption.pointer.style);
  58634. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  58635. }
  58636. },
  58637. /**
  58638. * @protected
  58639. */
  58640. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  58641. var labelEl = inner$11(group).labelEl;
  58642. if (labelEl) {
  58643. labelEl.setStyle(elOption.label.style);
  58644. updateProps$$1(labelEl, {
  58645. // Consider text length change in vertical axis, animation should
  58646. // be used on shape, otherwise the effect will be weird.
  58647. shape: elOption.label.shape,
  58648. position: elOption.label.position
  58649. });
  58650. updateLabelShowHide(labelEl, axisPointerModel);
  58651. }
  58652. },
  58653. /**
  58654. * @private
  58655. */
  58656. _renderHandle: function (value) {
  58657. if (this._dragging || !this.updateHandleTransform) {
  58658. return;
  58659. }
  58660. var axisPointerModel = this._axisPointerModel;
  58661. var zr = this._api.getZr();
  58662. var handle = this._handle;
  58663. var handleModel = axisPointerModel.getModel('handle');
  58664. var status = axisPointerModel.get('status');
  58665. if (!handleModel.get('show') || !status || status === 'hide') {
  58666. handle && zr.remove(handle);
  58667. this._handle = null;
  58668. return;
  58669. }
  58670. var isInit;
  58671. if (!this._handle) {
  58672. isInit = true;
  58673. handle = this._handle = createIcon(
  58674. handleModel.get('icon'),
  58675. {
  58676. cursor: 'move',
  58677. draggable: true,
  58678. onmousemove: function (e) {
  58679. // Fot mobile devicem, prevent screen slider on the button.
  58680. stop(e.event);
  58681. },
  58682. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  58683. drift: bind$2(this._onHandleDragMove, this),
  58684. ondragend: bind$2(this._onHandleDragEnd, this)
  58685. }
  58686. );
  58687. zr.add(handle);
  58688. }
  58689. updateMandatoryProps(handle, axisPointerModel, false);
  58690. // update style
  58691. var includeStyles = [
  58692. 'color', 'borderColor', 'borderWidth', 'opacity',
  58693. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  58694. ];
  58695. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  58696. // update position
  58697. var handleSize = handleModel.get('size');
  58698. if (!isArray(handleSize)) {
  58699. handleSize = [handleSize, handleSize];
  58700. }
  58701. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  58702. createOrUpdate(
  58703. this,
  58704. '_doDispatchAxisPointer',
  58705. handleModel.get('throttle') || 0,
  58706. 'fixRate'
  58707. );
  58708. this._moveHandleToValue(value, isInit);
  58709. },
  58710. /**
  58711. * @private
  58712. */
  58713. _moveHandleToValue: function (value, isInit) {
  58714. updateProps$1(
  58715. this._axisPointerModel,
  58716. !isInit && this._moveAnimation,
  58717. this._handle,
  58718. getHandleTransProps(this.getHandleTransform(
  58719. value, this._axisModel, this._axisPointerModel
  58720. ))
  58721. );
  58722. },
  58723. /**
  58724. * @private
  58725. */
  58726. _onHandleDragMove: function (dx, dy) {
  58727. var handle = this._handle;
  58728. if (!handle) {
  58729. return;
  58730. }
  58731. this._dragging = true;
  58732. // Persistent for throttle.
  58733. var trans = this.updateHandleTransform(
  58734. getHandleTransProps(handle),
  58735. [dx, dy],
  58736. this._axisModel,
  58737. this._axisPointerModel
  58738. );
  58739. this._payloadInfo = trans;
  58740. handle.stopAnimation();
  58741. handle.attr(getHandleTransProps(trans));
  58742. inner$11(handle).lastProp = null;
  58743. this._doDispatchAxisPointer();
  58744. },
  58745. /**
  58746. * Throttled method.
  58747. * @private
  58748. */
  58749. _doDispatchAxisPointer: function () {
  58750. var handle = this._handle;
  58751. if (!handle) {
  58752. return;
  58753. }
  58754. var payloadInfo = this._payloadInfo;
  58755. var axisModel = this._axisModel;
  58756. this._api.dispatchAction({
  58757. type: 'updateAxisPointer',
  58758. x: payloadInfo.cursorPoint[0],
  58759. y: payloadInfo.cursorPoint[1],
  58760. tooltipOption: payloadInfo.tooltipOption,
  58761. axesInfo: [{
  58762. axisDim: axisModel.axis.dim,
  58763. axisIndex: axisModel.componentIndex
  58764. }]
  58765. });
  58766. },
  58767. /**
  58768. * @private
  58769. */
  58770. _onHandleDragEnd: function (moveAnimation) {
  58771. this._dragging = false;
  58772. var handle = this._handle;
  58773. if (!handle) {
  58774. return;
  58775. }
  58776. var value = this._axisPointerModel.get('value');
  58777. // Consider snap or categroy axis, handle may be not consistent with
  58778. // axisPointer. So move handle to align the exact value position when
  58779. // drag ended.
  58780. this._moveHandleToValue(value);
  58781. // For the effect: tooltip will be shown when finger holding on handle
  58782. // button, and will be hidden after finger left handle button.
  58783. this._api.dispatchAction({
  58784. type: 'hideTip'
  58785. });
  58786. },
  58787. /**
  58788. * Should be implemenented by sub-class if support `handle`.
  58789. * @protected
  58790. * @param {number} value
  58791. * @param {module:echarts/model/Model} axisModel
  58792. * @param {module:echarts/model/Model} axisPointerModel
  58793. * @return {Object} {position: [x, y], rotation: 0}
  58794. */
  58795. getHandleTransform: null,
  58796. /**
  58797. * * Should be implemenented by sub-class if support `handle`.
  58798. * @protected
  58799. * @param {Object} transform {position, rotation}
  58800. * @param {Array.<number>} delta [dx, dy]
  58801. * @param {module:echarts/model/Model} axisModel
  58802. * @param {module:echarts/model/Model} axisPointerModel
  58803. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  58804. */
  58805. updateHandleTransform: null,
  58806. /**
  58807. * @private
  58808. */
  58809. clear: function (api) {
  58810. this._lastValue = null;
  58811. this._lastStatus = null;
  58812. var zr = api.getZr();
  58813. var group = this._group;
  58814. var handle = this._handle;
  58815. if (zr && group) {
  58816. this._lastGraphicKey = null;
  58817. group && zr.remove(group);
  58818. handle && zr.remove(handle);
  58819. this._group = null;
  58820. this._handle = null;
  58821. this._payloadInfo = null;
  58822. }
  58823. },
  58824. /**
  58825. * @protected
  58826. */
  58827. doClear: function () {
  58828. // Implemented by sub-class if necessary.
  58829. },
  58830. /**
  58831. * @protected
  58832. * @param {Array.<number>} xy
  58833. * @param {Array.<number>} wh
  58834. * @param {number} [xDimIndex=0] or 1
  58835. */
  58836. buildLabel: function (xy, wh, xDimIndex) {
  58837. xDimIndex = xDimIndex || 0;
  58838. return {
  58839. x: xy[xDimIndex],
  58840. y: xy[1 - xDimIndex],
  58841. width: wh[xDimIndex],
  58842. height: wh[1 - xDimIndex]
  58843. };
  58844. }
  58845. };
  58846. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  58847. function updateProps$1(animationModel, moveAnimation, el, props) {
  58848. // Animation optimize.
  58849. if (!propsEqual(inner$11(el).lastProp, props)) {
  58850. inner$11(el).lastProp = props;
  58851. moveAnimation
  58852. ? updateProps(el, props, animationModel)
  58853. : (el.stopAnimation(), el.attr(props));
  58854. }
  58855. }
  58856. function propsEqual(lastProps, newProps) {
  58857. if (isObject$1(lastProps) && isObject$1(newProps)) {
  58858. var equals = true;
  58859. each$1(newProps, function (item, key) {
  58860. equals = equals && propsEqual(lastProps[key], item);
  58861. });
  58862. return !!equals;
  58863. }
  58864. else {
  58865. return lastProps === newProps;
  58866. }
  58867. }
  58868. function updateLabelShowHide(labelEl, axisPointerModel) {
  58869. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  58870. }
  58871. function getHandleTransProps(trans) {
  58872. return {
  58873. position: trans.position.slice(),
  58874. rotation: trans.rotation || 0
  58875. };
  58876. }
  58877. function updateMandatoryProps(group, axisPointerModel, silent) {
  58878. var z = axisPointerModel.get('z');
  58879. var zlevel = axisPointerModel.get('zlevel');
  58880. group && group.traverse(function (el) {
  58881. if (el.type !== 'group') {
  58882. z != null && (el.z = z);
  58883. zlevel != null && (el.zlevel = zlevel);
  58884. el.silent = silent;
  58885. }
  58886. });
  58887. }
  58888. enableClassExtend(BaseAxisPointer);
  58889. /*
  58890. * Licensed to the Apache Software Foundation (ASF) under one
  58891. * or more contributor license agreements. See the NOTICE file
  58892. * distributed with this work for additional information
  58893. * regarding copyright ownership. The ASF licenses this file
  58894. * to you under the Apache License, Version 2.0 (the
  58895. * "License"); you may not use this file except in compliance
  58896. * with the License. You may obtain a copy of the License at
  58897. *
  58898. * http://www.apache.org/licenses/LICENSE-2.0
  58899. *
  58900. * Unless required by applicable law or agreed to in writing,
  58901. * software distributed under the License is distributed on an
  58902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58903. * KIND, either express or implied. See the License for the
  58904. * specific language governing permissions and limitations
  58905. * under the License.
  58906. */
  58907. /**
  58908. * @param {module:echarts/model/Model} axisPointerModel
  58909. */
  58910. function buildElStyle(axisPointerModel) {
  58911. var axisPointerType = axisPointerModel.get('type');
  58912. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  58913. var style;
  58914. if (axisPointerType === 'line') {
  58915. style = styleModel.getLineStyle();
  58916. style.fill = null;
  58917. }
  58918. else if (axisPointerType === 'shadow') {
  58919. style = styleModel.getAreaStyle();
  58920. style.stroke = null;
  58921. }
  58922. return style;
  58923. }
  58924. /**
  58925. * @param {Function} labelPos {align, verticalAlign, position}
  58926. */
  58927. function buildLabelElOption(
  58928. elOption, axisModel, axisPointerModel, api, labelPos
  58929. ) {
  58930. var value = axisPointerModel.get('value');
  58931. var text = getValueLabel(
  58932. value, axisModel.axis, axisModel.ecModel,
  58933. axisPointerModel.get('seriesDataIndices'),
  58934. {
  58935. precision: axisPointerModel.get('label.precision'),
  58936. formatter: axisPointerModel.get('label.formatter')
  58937. }
  58938. );
  58939. var labelModel = axisPointerModel.getModel('label');
  58940. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  58941. var font = labelModel.getFont();
  58942. var textRect = getBoundingRect(text, font);
  58943. var position = labelPos.position;
  58944. var width = textRect.width + paddings[1] + paddings[3];
  58945. var height = textRect.height + paddings[0] + paddings[2];
  58946. // Adjust by align.
  58947. var align = labelPos.align;
  58948. align === 'right' && (position[0] -= width);
  58949. align === 'center' && (position[0] -= width / 2);
  58950. var verticalAlign = labelPos.verticalAlign;
  58951. verticalAlign === 'bottom' && (position[1] -= height);
  58952. verticalAlign === 'middle' && (position[1] -= height / 2);
  58953. // Not overflow ec container
  58954. confineInContainer(position, width, height, api);
  58955. var bgColor = labelModel.get('backgroundColor');
  58956. if (!bgColor || bgColor === 'auto') {
  58957. bgColor = axisModel.get('axisLine.lineStyle.color');
  58958. }
  58959. elOption.label = {
  58960. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  58961. position: position.slice(),
  58962. // TODO: rich
  58963. style: {
  58964. text: text,
  58965. textFont: font,
  58966. textFill: labelModel.getTextColor(),
  58967. textPosition: 'inside',
  58968. fill: bgColor,
  58969. stroke: labelModel.get('borderColor') || 'transparent',
  58970. lineWidth: labelModel.get('borderWidth') || 0,
  58971. shadowBlur: labelModel.get('shadowBlur'),
  58972. shadowColor: labelModel.get('shadowColor'),
  58973. shadowOffsetX: labelModel.get('shadowOffsetX'),
  58974. shadowOffsetY: labelModel.get('shadowOffsetY')
  58975. },
  58976. // Lable should be over axisPointer.
  58977. z2: 10
  58978. };
  58979. }
  58980. // Do not overflow ec container
  58981. function confineInContainer(position, width, height, api) {
  58982. var viewWidth = api.getWidth();
  58983. var viewHeight = api.getHeight();
  58984. position[0] = Math.min(position[0] + width, viewWidth) - width;
  58985. position[1] = Math.min(position[1] + height, viewHeight) - height;
  58986. position[0] = Math.max(position[0], 0);
  58987. position[1] = Math.max(position[1], 0);
  58988. }
  58989. /**
  58990. * @param {number} value
  58991. * @param {module:echarts/coord/Axis} axis
  58992. * @param {module:echarts/model/Global} ecModel
  58993. * @param {Object} opt
  58994. * @param {Array.<Object>} seriesDataIndices
  58995. * @param {number|string} opt.precision 'auto' or a number
  58996. * @param {string|Function} opt.formatter label formatter
  58997. */
  58998. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  58999. value = axis.scale.parse(value);
  59000. var text = axis.scale.getLabel(
  59001. // If `precision` is set, width can be fixed (like '12.00500'), which
  59002. // helps to debounce when when moving label.
  59003. value, {precision: opt.precision}
  59004. );
  59005. var formatter = opt.formatter;
  59006. if (formatter) {
  59007. var params = {
  59008. value: getAxisRawValue(axis, value),
  59009. seriesData: []
  59010. };
  59011. each$1(seriesDataIndices, function (idxItem) {
  59012. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  59013. var dataIndex = idxItem.dataIndexInside;
  59014. var dataParams = series && series.getDataParams(dataIndex);
  59015. dataParams && params.seriesData.push(dataParams);
  59016. });
  59017. if (isString(formatter)) {
  59018. text = formatter.replace('{value}', text);
  59019. }
  59020. else if (isFunction$1(formatter)) {
  59021. text = formatter(params);
  59022. }
  59023. }
  59024. return text;
  59025. }
  59026. /**
  59027. * @param {module:echarts/coord/Axis} axis
  59028. * @param {number} value
  59029. * @param {Object} layoutInfo {
  59030. * rotation, position, labelOffset, labelDirection, labelMargin
  59031. * }
  59032. */
  59033. function getTransformedPosition(axis, value, layoutInfo) {
  59034. var transform = create$1();
  59035. rotate(transform, transform, layoutInfo.rotation);
  59036. translate(transform, transform, layoutInfo.position);
  59037. return applyTransform$1([
  59038. axis.dataToCoord(value),
  59039. (layoutInfo.labelOffset || 0)
  59040. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  59041. ], transform);
  59042. }
  59043. function buildCartesianSingleLabelElOption(
  59044. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  59045. ) {
  59046. var textLayout = AxisBuilder.innerTextLayout(
  59047. layoutInfo.rotation, 0, layoutInfo.labelDirection
  59048. );
  59049. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  59050. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  59051. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  59052. align: textLayout.textAlign,
  59053. verticalAlign: textLayout.textVerticalAlign
  59054. });
  59055. }
  59056. /**
  59057. * @param {Array.<number>} p1
  59058. * @param {Array.<number>} p2
  59059. * @param {number} [xDimIndex=0] or 1
  59060. */
  59061. function makeLineShape(p1, p2, xDimIndex) {
  59062. xDimIndex = xDimIndex || 0;
  59063. return {
  59064. x1: p1[xDimIndex],
  59065. y1: p1[1 - xDimIndex],
  59066. x2: p2[xDimIndex],
  59067. y2: p2[1 - xDimIndex]
  59068. };
  59069. }
  59070. /**
  59071. * @param {Array.<number>} xy
  59072. * @param {Array.<number>} wh
  59073. * @param {number} [xDimIndex=0] or 1
  59074. */
  59075. function makeRectShape(xy, wh, xDimIndex) {
  59076. xDimIndex = xDimIndex || 0;
  59077. return {
  59078. x: xy[xDimIndex],
  59079. y: xy[1 - xDimIndex],
  59080. width: wh[xDimIndex],
  59081. height: wh[1 - xDimIndex]
  59082. };
  59083. }
  59084. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  59085. return {
  59086. cx: cx,
  59087. cy: cy,
  59088. r0: r0,
  59089. r: r,
  59090. startAngle: startAngle,
  59091. endAngle: endAngle,
  59092. clockwise: true
  59093. };
  59094. }
  59095. /*
  59096. * Licensed to the Apache Software Foundation (ASF) under one
  59097. * or more contributor license agreements. See the NOTICE file
  59098. * distributed with this work for additional information
  59099. * regarding copyright ownership. The ASF licenses this file
  59100. * to you under the Apache License, Version 2.0 (the
  59101. * "License"); you may not use this file except in compliance
  59102. * with the License. You may obtain a copy of the License at
  59103. *
  59104. * http://www.apache.org/licenses/LICENSE-2.0
  59105. *
  59106. * Unless required by applicable law or agreed to in writing,
  59107. * software distributed under the License is distributed on an
  59108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59109. * KIND, either express or implied. See the License for the
  59110. * specific language governing permissions and limitations
  59111. * under the License.
  59112. */
  59113. var CartesianAxisPointer = BaseAxisPointer.extend({
  59114. /**
  59115. * @override
  59116. */
  59117. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  59118. var axis = axisModel.axis;
  59119. var grid = axis.grid;
  59120. var axisPointerType = axisPointerModel.get('type');
  59121. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  59122. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  59123. if (axisPointerType && axisPointerType !== 'none') {
  59124. var elStyle = buildElStyle(axisPointerModel);
  59125. var pointerOption = pointerShapeBuilder[axisPointerType](
  59126. axis, pixelValue, otherExtent, elStyle
  59127. );
  59128. pointerOption.style = elStyle;
  59129. elOption.graphicKey = pointerOption.type;
  59130. elOption.pointer = pointerOption;
  59131. }
  59132. var layoutInfo = layout$1(grid.model, axisModel);
  59133. buildCartesianSingleLabelElOption(
  59134. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  59135. );
  59136. },
  59137. /**
  59138. * @override
  59139. */
  59140. getHandleTransform: function (value, axisModel, axisPointerModel) {
  59141. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  59142. labelInside: false
  59143. });
  59144. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  59145. return {
  59146. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  59147. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  59148. };
  59149. },
  59150. /**
  59151. * @override
  59152. */
  59153. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  59154. var axis = axisModel.axis;
  59155. var grid = axis.grid;
  59156. var axisExtent = axis.getGlobalExtent(true);
  59157. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  59158. var dimIndex = axis.dim === 'x' ? 0 : 1;
  59159. var currPosition = transform.position;
  59160. currPosition[dimIndex] += delta[dimIndex];
  59161. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  59162. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  59163. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  59164. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  59165. cursorPoint[dimIndex] = currPosition[dimIndex];
  59166. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  59167. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  59168. return {
  59169. position: currPosition,
  59170. rotation: transform.rotation,
  59171. cursorPoint: cursorPoint,
  59172. tooltipOption: tooltipOptions[dimIndex]
  59173. };
  59174. }
  59175. });
  59176. function getCartesian(grid, axis) {
  59177. var opt = {};
  59178. opt[axis.dim + 'AxisIndex'] = axis.index;
  59179. return grid.getCartesian(opt);
  59180. }
  59181. var pointerShapeBuilder = {
  59182. line: function (axis, pixelValue, otherExtent, elStyle) {
  59183. var targetShape = makeLineShape(
  59184. [pixelValue, otherExtent[0]],
  59185. [pixelValue, otherExtent[1]],
  59186. getAxisDimIndex(axis)
  59187. );
  59188. subPixelOptimizeLine({
  59189. shape: targetShape,
  59190. style: elStyle
  59191. });
  59192. return {
  59193. type: 'Line',
  59194. shape: targetShape
  59195. };
  59196. },
  59197. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  59198. var bandWidth = Math.max(1, axis.getBandWidth());
  59199. var span = otherExtent[1] - otherExtent[0];
  59200. return {
  59201. type: 'Rect',
  59202. shape: makeRectShape(
  59203. [pixelValue - bandWidth / 2, otherExtent[0]],
  59204. [bandWidth, span],
  59205. getAxisDimIndex(axis)
  59206. )
  59207. };
  59208. }
  59209. };
  59210. function getAxisDimIndex(axis) {
  59211. return axis.dim === 'x' ? 0 : 1;
  59212. }
  59213. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  59214. /*
  59215. * Licensed to the Apache Software Foundation (ASF) under one
  59216. * or more contributor license agreements. See the NOTICE file
  59217. * distributed with this work for additional information
  59218. * regarding copyright ownership. The ASF licenses this file
  59219. * to you under the Apache License, Version 2.0 (the
  59220. * "License"); you may not use this file except in compliance
  59221. * with the License. You may obtain a copy of the License at
  59222. *
  59223. * http://www.apache.org/licenses/LICENSE-2.0
  59224. *
  59225. * Unless required by applicable law or agreed to in writing,
  59226. * software distributed under the License is distributed on an
  59227. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59228. * KIND, either express or implied. See the License for the
  59229. * specific language governing permissions and limitations
  59230. * under the License.
  59231. */
  59232. // CartesianAxisPointer is not supposed to be required here. But consider
  59233. // echarts.simple.js and online build tooltip, which only require gridSimple,
  59234. // CartesianAxisPointer should be able to required somewhere.
  59235. registerPreprocessor(function (option) {
  59236. // Always has a global axisPointerModel for default setting.
  59237. if (option) {
  59238. (!option.axisPointer || option.axisPointer.length === 0)
  59239. && (option.axisPointer = {});
  59240. var link = option.axisPointer.link;
  59241. // Normalize to array to avoid object mergin. But if link
  59242. // is not set, remain null/undefined, otherwise it will
  59243. // override existent link setting.
  59244. if (link && !isArray(link)) {
  59245. option.axisPointer.link = [link];
  59246. }
  59247. }
  59248. });
  59249. // This process should proformed after coordinate systems created
  59250. // and series data processed. So put it on statistic processing stage.
  59251. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  59252. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  59253. // allAxesInfo should be updated when setOption performed.
  59254. ecModel.getComponent('axisPointer').coordSysAxesInfo
  59255. = collect(ecModel, api);
  59256. });
  59257. // Broadcast to all views.
  59258. registerAction({
  59259. type: 'updateAxisPointer',
  59260. event: 'updateAxisPointer',
  59261. update: ':updateAxisPointer'
  59262. }, axisTrigger);
  59263. /*
  59264. * Licensed to the Apache Software Foundation (ASF) under one
  59265. * or more contributor license agreements. See the NOTICE file
  59266. * distributed with this work for additional information
  59267. * regarding copyright ownership. The ASF licenses this file
  59268. * to you under the Apache License, Version 2.0 (the
  59269. * "License"); you may not use this file except in compliance
  59270. * with the License. You may obtain a copy of the License at
  59271. *
  59272. * http://www.apache.org/licenses/LICENSE-2.0
  59273. *
  59274. * Unless required by applicable law or agreed to in writing,
  59275. * software distributed under the License is distributed on an
  59276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59277. * KIND, either express or implied. See the License for the
  59278. * specific language governing permissions and limitations
  59279. * under the License.
  59280. */
  59281. var XY = ['x', 'y'];
  59282. var WH = ['width', 'height'];
  59283. var SingleAxisPointer = BaseAxisPointer.extend({
  59284. /**
  59285. * @override
  59286. */
  59287. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  59288. var axis = axisModel.axis;
  59289. var coordSys = axis.coordinateSystem;
  59290. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  59291. var pixelValue = coordSys.dataToPoint(value)[0];
  59292. var axisPointerType = axisPointerModel.get('type');
  59293. if (axisPointerType && axisPointerType !== 'none') {
  59294. var elStyle = buildElStyle(axisPointerModel);
  59295. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  59296. axis, pixelValue, otherExtent, elStyle
  59297. );
  59298. pointerOption.style = elStyle;
  59299. elOption.graphicKey = pointerOption.type;
  59300. elOption.pointer = pointerOption;
  59301. }
  59302. var layoutInfo = layout$2(axisModel);
  59303. buildCartesianSingleLabelElOption(
  59304. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  59305. );
  59306. },
  59307. /**
  59308. * @override
  59309. */
  59310. getHandleTransform: function (value, axisModel, axisPointerModel) {
  59311. var layoutInfo = layout$2(axisModel, {labelInside: false});
  59312. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  59313. return {
  59314. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  59315. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  59316. };
  59317. },
  59318. /**
  59319. * @override
  59320. */
  59321. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  59322. var axis = axisModel.axis;
  59323. var coordSys = axis.coordinateSystem;
  59324. var dimIndex = getPointDimIndex(axis);
  59325. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  59326. var currPosition = transform.position;
  59327. currPosition[dimIndex] += delta[dimIndex];
  59328. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  59329. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  59330. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  59331. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  59332. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  59333. cursorPoint[dimIndex] = currPosition[dimIndex];
  59334. return {
  59335. position: currPosition,
  59336. rotation: transform.rotation,
  59337. cursorPoint: cursorPoint,
  59338. tooltipOption: {
  59339. verticalAlign: 'middle'
  59340. }
  59341. };
  59342. }
  59343. });
  59344. var pointerShapeBuilder$1 = {
  59345. line: function (axis, pixelValue, otherExtent, elStyle) {
  59346. var targetShape = makeLineShape(
  59347. [pixelValue, otherExtent[0]],
  59348. [pixelValue, otherExtent[1]],
  59349. getPointDimIndex(axis)
  59350. );
  59351. subPixelOptimizeLine({
  59352. shape: targetShape,
  59353. style: elStyle
  59354. });
  59355. return {
  59356. type: 'Line',
  59357. shape: targetShape
  59358. };
  59359. },
  59360. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  59361. var bandWidth = axis.getBandWidth();
  59362. var span = otherExtent[1] - otherExtent[0];
  59363. return {
  59364. type: 'Rect',
  59365. shape: makeRectShape(
  59366. [pixelValue - bandWidth / 2, otherExtent[0]],
  59367. [bandWidth, span],
  59368. getPointDimIndex(axis)
  59369. )
  59370. };
  59371. }
  59372. };
  59373. function getPointDimIndex(axis) {
  59374. return axis.isHorizontal() ? 0 : 1;
  59375. }
  59376. function getGlobalExtent(coordSys, dimIndex) {
  59377. var rect = coordSys.getRect();
  59378. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  59379. }
  59380. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  59381. /*
  59382. * Licensed to the Apache Software Foundation (ASF) under one
  59383. * or more contributor license agreements. See the NOTICE file
  59384. * distributed with this work for additional information
  59385. * regarding copyright ownership. The ASF licenses this file
  59386. * to you under the Apache License, Version 2.0 (the
  59387. * "License"); you may not use this file except in compliance
  59388. * with the License. You may obtain a copy of the License at
  59389. *
  59390. * http://www.apache.org/licenses/LICENSE-2.0
  59391. *
  59392. * Unless required by applicable law or agreed to in writing,
  59393. * software distributed under the License is distributed on an
  59394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59395. * KIND, either express or implied. See the License for the
  59396. * specific language governing permissions and limitations
  59397. * under the License.
  59398. */
  59399. extendComponentView({
  59400. type: 'single'
  59401. });
  59402. /*
  59403. * Licensed to the Apache Software Foundation (ASF) under one
  59404. * or more contributor license agreements. See the NOTICE file
  59405. * distributed with this work for additional information
  59406. * regarding copyright ownership. The ASF licenses this file
  59407. * to you under the Apache License, Version 2.0 (the
  59408. * "License"); you may not use this file except in compliance
  59409. * with the License. You may obtain a copy of the License at
  59410. *
  59411. * http://www.apache.org/licenses/LICENSE-2.0
  59412. *
  59413. * Unless required by applicable law or agreed to in writing,
  59414. * software distributed under the License is distributed on an
  59415. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59416. * KIND, either express or implied. See the License for the
  59417. * specific language governing permissions and limitations
  59418. * under the License.
  59419. */
  59420. /**
  59421. * @file Define the themeRiver view's series model
  59422. * @author Deqing Li(annong035@gmail.com)
  59423. */
  59424. var DATA_NAME_INDEX = 2;
  59425. var ThemeRiverSeries = SeriesModel.extend({
  59426. type: 'series.themeRiver',
  59427. dependencies: ['singleAxis'],
  59428. /**
  59429. * @readOnly
  59430. * @type {module:zrender/core/util#HashMap}
  59431. */
  59432. nameMap: null,
  59433. /**
  59434. * @override
  59435. */
  59436. init: function (option) {
  59437. // eslint-disable-next-line
  59438. ThemeRiverSeries.superApply(this, 'init', arguments);
  59439. // Put this function here is for the sake of consistency of code style.
  59440. // Enable legend selection for each data item
  59441. // Use a function instead of direct access because data reference may changed
  59442. this.legendDataProvider = function () {
  59443. return this.getRawData();
  59444. };
  59445. },
  59446. /**
  59447. * If there is no value of a certain point in the time for some event,set it value to 0.
  59448. *
  59449. * @param {Array} data initial data in the option
  59450. * @return {Array}
  59451. */
  59452. fixData: function (data) {
  59453. var rawDataLength = data.length;
  59454. // grouped data by name
  59455. var dataByName = nest()
  59456. .key(function (dataItem) {
  59457. return dataItem[2];
  59458. })
  59459. .entries(data);
  59460. // data group in each layer
  59461. var layData = map(dataByName, function (d) {
  59462. return {
  59463. name: d.key,
  59464. dataList: d.values
  59465. };
  59466. });
  59467. var layerNum = layData.length;
  59468. var largestLayer = -1;
  59469. var index = -1;
  59470. for (var i = 0; i < layerNum; ++i) {
  59471. var len = layData[i].dataList.length;
  59472. if (len > largestLayer) {
  59473. largestLayer = len;
  59474. index = i;
  59475. }
  59476. }
  59477. for (var k = 0; k < layerNum; ++k) {
  59478. if (k === index) {
  59479. continue;
  59480. }
  59481. var name = layData[k].name;
  59482. for (var j = 0; j < largestLayer; ++j) {
  59483. var timeValue = layData[index].dataList[j][0];
  59484. var length = layData[k].dataList.length;
  59485. var keyIndex = -1;
  59486. for (var l = 0; l < length; ++l) {
  59487. var value = layData[k].dataList[l][0];
  59488. if (value === timeValue) {
  59489. keyIndex = l;
  59490. break;
  59491. }
  59492. }
  59493. if (keyIndex === -1) {
  59494. data[rawDataLength] = [];
  59495. data[rawDataLength][0] = timeValue;
  59496. data[rawDataLength][1] = 0;
  59497. data[rawDataLength][2] = name;
  59498. rawDataLength++;
  59499. }
  59500. }
  59501. }
  59502. return data;
  59503. },
  59504. /**
  59505. * @override
  59506. * @param {Object} option the initial option that user gived
  59507. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  59508. * @return {module:echarts/data/List}
  59509. */
  59510. getInitialData: function (option, ecModel) {
  59511. var singleAxisModel = ecModel.queryComponents({
  59512. mainType: 'singleAxis',
  59513. index: this.get('singleAxisIndex'),
  59514. id: this.get('singleAxisId')
  59515. })[0];
  59516. var axisType = singleAxisModel.get('type');
  59517. // filter the data item with the value of label is undefined
  59518. var filterData = filter(option.data, function (dataItem) {
  59519. return dataItem[2] !== undefined;
  59520. });
  59521. // ??? TODO design a stage to transfer data for themeRiver and lines?
  59522. var data = this.fixData(filterData || []);
  59523. var nameList = [];
  59524. var nameMap = this.nameMap = createHashMap();
  59525. var count = 0;
  59526. for (var i = 0; i < data.length; ++i) {
  59527. nameList.push(data[i][DATA_NAME_INDEX]);
  59528. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  59529. nameMap.set(data[i][DATA_NAME_INDEX], count);
  59530. count++;
  59531. }
  59532. }
  59533. var dimensionsInfo = createDimensions(data, {
  59534. coordDimensions: ['single'],
  59535. dimensionsDefine: [
  59536. {
  59537. name: 'time',
  59538. type: getDimensionTypeByAxis(axisType)
  59539. },
  59540. {
  59541. name: 'value',
  59542. type: 'float'
  59543. },
  59544. {
  59545. name: 'name',
  59546. type: 'ordinal'
  59547. }
  59548. ],
  59549. encodeDefine: {
  59550. single: 0,
  59551. value: 1,
  59552. itemName: 2
  59553. }
  59554. });
  59555. var list = new List(dimensionsInfo, this);
  59556. list.initData(data);
  59557. return list;
  59558. },
  59559. /**
  59560. * The raw data is divided into multiple layers and each layer
  59561. * has same name.
  59562. *
  59563. * @return {Array.<Array.<number>>}
  59564. */
  59565. getLayerSeries: function () {
  59566. var data = this.getData();
  59567. var lenCount = data.count();
  59568. var indexArr = [];
  59569. for (var i = 0; i < lenCount; ++i) {
  59570. indexArr[i] = i;
  59571. }
  59572. // data group by name
  59573. var dataByName = nest()
  59574. .key(function (index) {
  59575. return data.get('name', index);
  59576. })
  59577. .entries(indexArr);
  59578. var layerSeries = map(dataByName, function (d) {
  59579. return {
  59580. name: d.key,
  59581. indices: d.values
  59582. };
  59583. });
  59584. var timeDim = data.mapDimension('single');
  59585. for (var j = 0; j < layerSeries.length; ++j) {
  59586. layerSeries[j].indices.sort(comparer);
  59587. }
  59588. function comparer(index1, index2) {
  59589. return data.get(timeDim, index1) - data.get(timeDim, index2);
  59590. }
  59591. return layerSeries;
  59592. },
  59593. /**
  59594. * Get data indices for show tooltip content
  59595. *
  59596. * @param {Array.<string>|string} dim single coordinate dimension
  59597. * @param {number} value axis value
  59598. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  59599. * the themeRiver.
  59600. * @return {Object} {dataIndices, nestestValue}
  59601. */
  59602. getAxisTooltipData: function (dim, value, baseAxis) {
  59603. if (!isArray(dim)) {
  59604. dim = dim ? [dim] : [];
  59605. }
  59606. var data = this.getData();
  59607. var layerSeries = this.getLayerSeries();
  59608. var indices = [];
  59609. var layerNum = layerSeries.length;
  59610. var nestestValue;
  59611. for (var i = 0; i < layerNum; ++i) {
  59612. var minDist = Number.MAX_VALUE;
  59613. var nearestIdx = -1;
  59614. var pointNum = layerSeries[i].indices.length;
  59615. for (var j = 0; j < pointNum; ++j) {
  59616. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  59617. var dist = Math.abs(theValue - value);
  59618. if (dist <= minDist) {
  59619. nestestValue = theValue;
  59620. minDist = dist;
  59621. nearestIdx = layerSeries[i].indices[j];
  59622. }
  59623. }
  59624. indices.push(nearestIdx);
  59625. }
  59626. return {dataIndices: indices, nestestValue: nestestValue};
  59627. },
  59628. /**
  59629. * @override
  59630. * @param {number} dataIndex index of data
  59631. */
  59632. formatTooltip: function (dataIndex) {
  59633. var data = this.getData();
  59634. var htmlName = data.getName(dataIndex);
  59635. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  59636. if (isNaN(htmlValue) || htmlValue == null) {
  59637. htmlValue = '-';
  59638. }
  59639. return encodeHTML(htmlName + ' : ' + htmlValue);
  59640. },
  59641. defaultOption: {
  59642. zlevel: 0,
  59643. z: 2,
  59644. coordinateSystem: 'singleAxis',
  59645. // gap in axis's orthogonal orientation
  59646. boundaryGap: ['10%', '10%'],
  59647. // legendHoverLink: true,
  59648. singleAxisIndex: 0,
  59649. animationEasing: 'linear',
  59650. label: {
  59651. margin: 4,
  59652. show: true,
  59653. position: 'left',
  59654. color: '#000',
  59655. fontSize: 11
  59656. },
  59657. emphasis: {
  59658. label: {
  59659. show: true
  59660. }
  59661. }
  59662. }
  59663. });
  59664. /*
  59665. * Licensed to the Apache Software Foundation (ASF) under one
  59666. * or more contributor license agreements. See the NOTICE file
  59667. * distributed with this work for additional information
  59668. * regarding copyright ownership. The ASF licenses this file
  59669. * to you under the Apache License, Version 2.0 (the
  59670. * "License"); you may not use this file except in compliance
  59671. * with the License. You may obtain a copy of the License at
  59672. *
  59673. * http://www.apache.org/licenses/LICENSE-2.0
  59674. *
  59675. * Unless required by applicable law or agreed to in writing,
  59676. * software distributed under the License is distributed on an
  59677. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59678. * KIND, either express or implied. See the License for the
  59679. * specific language governing permissions and limitations
  59680. * under the License.
  59681. */
  59682. /**
  59683. * @file The file used to draw themeRiver view
  59684. * @author Deqing Li(annong035@gmail.com)
  59685. */
  59686. extendChartView({
  59687. type: 'themeRiver',
  59688. init: function () {
  59689. this._layers = [];
  59690. },
  59691. render: function (seriesModel, ecModel, api) {
  59692. var data = seriesModel.getData();
  59693. var group = this.group;
  59694. var layerSeries = seriesModel.getLayerSeries();
  59695. var layoutInfo = data.getLayout('layoutInfo');
  59696. var rect = layoutInfo.rect;
  59697. var boundaryGap = layoutInfo.boundaryGap;
  59698. group.attr('position', [0, rect.y + boundaryGap[0]]);
  59699. function keyGetter(item) {
  59700. return item.name;
  59701. }
  59702. var dataDiffer = new DataDiffer(
  59703. this._layersSeries || [], layerSeries,
  59704. keyGetter, keyGetter
  59705. );
  59706. var newLayersGroups = {};
  59707. dataDiffer
  59708. .add(bind(process, this, 'add'))
  59709. .update(bind(process, this, 'update'))
  59710. .remove(bind(process, this, 'remove'))
  59711. .execute();
  59712. function process(status, idx, oldIdx) {
  59713. var oldLayersGroups = this._layers;
  59714. if (status === 'remove') {
  59715. group.remove(oldLayersGroups[idx]);
  59716. return;
  59717. }
  59718. var points0 = [];
  59719. var points1 = [];
  59720. var color;
  59721. var indices = layerSeries[idx].indices;
  59722. for (var j = 0; j < indices.length; j++) {
  59723. var layout = data.getItemLayout(indices[j]);
  59724. var x = layout.x;
  59725. var y0 = layout.y0;
  59726. var y = layout.y;
  59727. points0.push([x, y0]);
  59728. points1.push([x, y0 + y]);
  59729. color = data.getItemVisual(indices[j], 'color');
  59730. }
  59731. var polygon;
  59732. var text;
  59733. var textLayout = data.getItemLayout(indices[0]);
  59734. var itemModel = data.getItemModel(indices[j - 1]);
  59735. var labelModel = itemModel.getModel('label');
  59736. var margin = labelModel.get('margin');
  59737. if (status === 'add') {
  59738. var layerGroup = newLayersGroups[idx] = new Group();
  59739. polygon = new Polygon$1({
  59740. shape: {
  59741. points: points0,
  59742. stackedOnPoints: points1,
  59743. smooth: 0.4,
  59744. stackedOnSmooth: 0.4,
  59745. smoothConstraint: false
  59746. },
  59747. z2: 0
  59748. });
  59749. text = new Text({
  59750. style: {
  59751. x: textLayout.x - margin,
  59752. y: textLayout.y0 + textLayout.y / 2
  59753. }
  59754. });
  59755. layerGroup.add(polygon);
  59756. layerGroup.add(text);
  59757. group.add(layerGroup);
  59758. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  59759. polygon.removeClipPath();
  59760. }));
  59761. }
  59762. else {
  59763. var layerGroup = oldLayersGroups[oldIdx];
  59764. polygon = layerGroup.childAt(0);
  59765. text = layerGroup.childAt(1);
  59766. group.add(layerGroup);
  59767. newLayersGroups[idx] = layerGroup;
  59768. updateProps(polygon, {
  59769. shape: {
  59770. points: points0,
  59771. stackedOnPoints: points1
  59772. }
  59773. }, seriesModel);
  59774. updateProps(text, {
  59775. style: {
  59776. x: textLayout.x - margin,
  59777. y: textLayout.y0 + textLayout.y / 2
  59778. }
  59779. }, seriesModel);
  59780. }
  59781. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  59782. var itemStyleModel = itemModel.getModel('itemStyle');
  59783. setTextStyle(text.style, labelModel, {
  59784. text: labelModel.get('show')
  59785. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  59786. || data.getName(indices[j - 1])
  59787. : null,
  59788. textVerticalAlign: 'middle'
  59789. });
  59790. polygon.setStyle(extend({
  59791. fill: color
  59792. }, itemStyleModel.getItemStyle(['color'])));
  59793. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  59794. }
  59795. this._layersSeries = layerSeries;
  59796. this._layers = newLayersGroups;
  59797. },
  59798. dispose: function () {}
  59799. });
  59800. // add animation to the view
  59801. function createGridClipShape$3(rect, seriesModel, cb) {
  59802. var rectEl = new Rect({
  59803. shape: {
  59804. x: rect.x - 10,
  59805. y: rect.y - 10,
  59806. width: 0,
  59807. height: rect.height + 20
  59808. }
  59809. });
  59810. initProps(rectEl, {
  59811. shape: {
  59812. width: rect.width + 20,
  59813. height: rect.height + 20
  59814. }
  59815. }, seriesModel, cb);
  59816. return rectEl;
  59817. }
  59818. /*
  59819. * Licensed to the Apache Software Foundation (ASF) under one
  59820. * or more contributor license agreements. See the NOTICE file
  59821. * distributed with this work for additional information
  59822. * regarding copyright ownership. The ASF licenses this file
  59823. * to you under the Apache License, Version 2.0 (the
  59824. * "License"); you may not use this file except in compliance
  59825. * with the License. You may obtain a copy of the License at
  59826. *
  59827. * http://www.apache.org/licenses/LICENSE-2.0
  59828. *
  59829. * Unless required by applicable law or agreed to in writing,
  59830. * software distributed under the License is distributed on an
  59831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59832. * KIND, either express or implied. See the License for the
  59833. * specific language governing permissions and limitations
  59834. * under the License.
  59835. */
  59836. /**
  59837. * @file Using layout algorithm transform the raw data to layout information.
  59838. * @author Deqing Li(annong035@gmail.com)
  59839. */
  59840. var themeRiverLayout = function (ecModel, api) {
  59841. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59842. var data = seriesModel.getData();
  59843. var single = seriesModel.coordinateSystem;
  59844. var layoutInfo = {};
  59845. // use the axis boundingRect for view
  59846. var rect = single.getRect();
  59847. layoutInfo.rect = rect;
  59848. var boundaryGap = seriesModel.get('boundaryGap');
  59849. var axis = single.getAxis();
  59850. layoutInfo.boundaryGap = boundaryGap;
  59851. if (axis.orient === 'horizontal') {
  59852. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  59853. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  59854. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  59855. themeRiverLayout$1(data, seriesModel, height);
  59856. }
  59857. else {
  59858. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  59859. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  59860. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  59861. themeRiverLayout$1(data, seriesModel, width);
  59862. }
  59863. data.setLayout('layoutInfo', layoutInfo);
  59864. });
  59865. };
  59866. /**
  59867. * The layout information about themeriver
  59868. *
  59869. * @param {module:echarts/data/List} data data in the series
  59870. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  59871. * @param {number} height value used to compute every series height
  59872. */
  59873. function themeRiverLayout$1(data, seriesModel, height) {
  59874. if (!data.count()) {
  59875. return;
  59876. }
  59877. var coordSys = seriesModel.coordinateSystem;
  59878. // the data in each layer are organized into a series.
  59879. var layerSeries = seriesModel.getLayerSeries();
  59880. // the points in each layer.
  59881. var timeDim = data.mapDimension('single');
  59882. var valueDim = data.mapDimension('value');
  59883. var layerPoints = map(layerSeries, function (singleLayer) {
  59884. return map(singleLayer.indices, function (idx) {
  59885. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  59886. pt[1] = data.get(valueDim, idx);
  59887. return pt;
  59888. });
  59889. });
  59890. var base = computeBaseline(layerPoints);
  59891. var baseLine = base.y0;
  59892. var ky = height / base.max;
  59893. // set layout information for each item.
  59894. var n = layerSeries.length;
  59895. var m = layerSeries[0].indices.length;
  59896. var baseY0;
  59897. for (var j = 0; j < m; ++j) {
  59898. baseY0 = baseLine[j] * ky;
  59899. data.setItemLayout(layerSeries[0].indices[j], {
  59900. layerIndex: 0,
  59901. x: layerPoints[0][j][0],
  59902. y0: baseY0,
  59903. y: layerPoints[0][j][1] * ky
  59904. });
  59905. for (var i = 1; i < n; ++i) {
  59906. baseY0 += layerPoints[i - 1][j][1] * ky;
  59907. data.setItemLayout(layerSeries[i].indices[j], {
  59908. layerIndex: i,
  59909. x: layerPoints[i][j][0],
  59910. y0: baseY0,
  59911. y: layerPoints[i][j][1] * ky
  59912. });
  59913. }
  59914. }
  59915. }
  59916. /**
  59917. * Compute the baseLine of the rawdata
  59918. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  59919. *
  59920. * @param {Array.<Array>} data the points in each layer
  59921. * @return {Object}
  59922. */
  59923. function computeBaseline(data) {
  59924. var layerNum = data.length;
  59925. var pointNum = data[0].length;
  59926. var sums = [];
  59927. var y0 = [];
  59928. var max = 0;
  59929. var temp;
  59930. var base = {};
  59931. for (var i = 0; i < pointNum; ++i) {
  59932. for (var j = 0, temp = 0; j < layerNum; ++j) {
  59933. temp += data[j][i][1];
  59934. }
  59935. if (temp > max) {
  59936. max = temp;
  59937. }
  59938. sums.push(temp);
  59939. }
  59940. for (var k = 0; k < pointNum; ++k) {
  59941. y0[k] = (max - sums[k]) / 2;
  59942. }
  59943. max = 0;
  59944. for (var l = 0; l < pointNum; ++l) {
  59945. var sum = sums[l] + y0[l];
  59946. if (sum > max) {
  59947. max = sum;
  59948. }
  59949. }
  59950. base.y0 = y0;
  59951. base.max = max;
  59952. return base;
  59953. }
  59954. /*
  59955. * Licensed to the Apache Software Foundation (ASF) under one
  59956. * or more contributor license agreements. See the NOTICE file
  59957. * distributed with this work for additional information
  59958. * regarding copyright ownership. The ASF licenses this file
  59959. * to you under the Apache License, Version 2.0 (the
  59960. * "License"); you may not use this file except in compliance
  59961. * with the License. You may obtain a copy of the License at
  59962. *
  59963. * http://www.apache.org/licenses/LICENSE-2.0
  59964. *
  59965. * Unless required by applicable law or agreed to in writing,
  59966. * software distributed under the License is distributed on an
  59967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59968. * KIND, either express or implied. See the License for the
  59969. * specific language governing permissions and limitations
  59970. * under the License.
  59971. */
  59972. /**
  59973. * @file Visual encoding for themeRiver view
  59974. * @author Deqing Li(annong035@gmail.com)
  59975. */
  59976. var themeRiverVisual = function (ecModel) {
  59977. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59978. var data = seriesModel.getData();
  59979. var rawData = seriesModel.getRawData();
  59980. var colorList = seriesModel.get('color');
  59981. var idxMap = createHashMap();
  59982. data.each(function (idx) {
  59983. idxMap.set(data.getRawIndex(idx), idx);
  59984. });
  59985. rawData.each(function (rawIndex) {
  59986. var name = rawData.getName(rawIndex);
  59987. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  59988. rawData.setItemVisual(rawIndex, 'color', color);
  59989. var idx = idxMap.get(rawIndex);
  59990. if (idx != null) {
  59991. data.setItemVisual(idx, 'color', color);
  59992. }
  59993. });
  59994. });
  59995. };
  59996. /*
  59997. * Licensed to the Apache Software Foundation (ASF) under one
  59998. * or more contributor license agreements. See the NOTICE file
  59999. * distributed with this work for additional information
  60000. * regarding copyright ownership. The ASF licenses this file
  60001. * to you under the Apache License, Version 2.0 (the
  60002. * "License"); you may not use this file except in compliance
  60003. * with the License. You may obtain a copy of the License at
  60004. *
  60005. * http://www.apache.org/licenses/LICENSE-2.0
  60006. *
  60007. * Unless required by applicable law or agreed to in writing,
  60008. * software distributed under the License is distributed on an
  60009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60010. * KIND, either express or implied. See the License for the
  60011. * specific language governing permissions and limitations
  60012. * under the License.
  60013. */
  60014. registerLayout(themeRiverLayout);
  60015. registerVisual(themeRiverVisual);
  60016. registerProcessor(dataFilter('themeRiver'));
  60017. /*
  60018. * Licensed to the Apache Software Foundation (ASF) under one
  60019. * or more contributor license agreements. See the NOTICE file
  60020. * distributed with this work for additional information
  60021. * regarding copyright ownership. The ASF licenses this file
  60022. * to you under the Apache License, Version 2.0 (the
  60023. * "License"); you may not use this file except in compliance
  60024. * with the License. You may obtain a copy of the License at
  60025. *
  60026. * http://www.apache.org/licenses/LICENSE-2.0
  60027. *
  60028. * Unless required by applicable law or agreed to in writing,
  60029. * software distributed under the License is distributed on an
  60030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60031. * KIND, either express or implied. See the License for the
  60032. * specific language governing permissions and limitations
  60033. * under the License.
  60034. */
  60035. SeriesModel.extend({
  60036. type: 'series.sunburst',
  60037. /**
  60038. * @type {module:echarts/data/Tree~Node}
  60039. */
  60040. _viewRoot: null,
  60041. getInitialData: function (option, ecModel) {
  60042. // Create a virtual root.
  60043. var root = { name: option.name, children: option.data };
  60044. completeTreeValue$1(root);
  60045. var levels = option.levels || [];
  60046. // levels = option.levels = setDefault(levels, ecModel);
  60047. var treeOption = {};
  60048. treeOption.levels = levels;
  60049. // Make sure always a new tree is created when setOption,
  60050. // in TreemapView, we check whether oldTree === newTree
  60051. // to choose mappings approach among old shapes and new shapes.
  60052. return Tree.createTree(root, this, treeOption).data;
  60053. },
  60054. optionUpdated: function () {
  60055. this.resetViewRoot();
  60056. },
  60057. /*
  60058. * @override
  60059. */
  60060. getDataParams: function (dataIndex) {
  60061. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  60062. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  60063. params.treePathInfo = wrapTreePathInfo(node, this);
  60064. return params;
  60065. },
  60066. defaultOption: {
  60067. zlevel: 0,
  60068. z: 2,
  60069. // 默认全局居中
  60070. center: ['50%', '50%'],
  60071. radius: [0, '75%'],
  60072. // 默认顺时针
  60073. clockwise: true,
  60074. startAngle: 90,
  60075. // 最小角度改为0
  60076. minAngle: 0,
  60077. percentPrecision: 2,
  60078. // If still show when all data zero.
  60079. stillShowZeroSum: true,
  60080. // Policy of highlighting pieces when hover on one
  60081. // Valid values: 'none' (for not downplay others), 'descendant',
  60082. // 'ancestor', 'self'
  60083. highlightPolicy: 'descendant',
  60084. // 'rootToNode', 'link', or false
  60085. nodeClick: 'rootToNode',
  60086. renderLabelForZeroData: false,
  60087. label: {
  60088. // could be: 'radial', 'tangential', or 'none'
  60089. rotate: 'radial',
  60090. show: true,
  60091. opacity: 1,
  60092. // 'left' is for inner side of inside, and 'right' is for outter
  60093. // side for inside
  60094. align: 'center',
  60095. position: 'inside',
  60096. distance: 5,
  60097. silent: true,
  60098. emphasis: {}
  60099. },
  60100. itemStyle: {
  60101. borderWidth: 1,
  60102. borderColor: 'white',
  60103. borderType: 'solid',
  60104. shadowBlur: 0,
  60105. shadowColor: 'rgba(0, 0, 0, 0.2)',
  60106. shadowOffsetX: 0,
  60107. shadowOffsetY: 0,
  60108. opacity: 1,
  60109. emphasis: {},
  60110. highlight: {
  60111. opacity: 1
  60112. },
  60113. downplay: {
  60114. opacity: 0.9
  60115. }
  60116. },
  60117. // Animation type canbe expansion, scale
  60118. animationType: 'expansion',
  60119. animationDuration: 1000,
  60120. animationDurationUpdate: 500,
  60121. animationEasing: 'cubicOut',
  60122. data: [],
  60123. levels: [],
  60124. /**
  60125. * Sort order.
  60126. *
  60127. * Valid values: 'desc', 'asc', null, or callback function.
  60128. * 'desc' and 'asc' for descend and ascendant order;
  60129. * null for not sorting;
  60130. * example of callback function:
  60131. * function(nodeA, nodeB) {
  60132. * return nodeA.getValue() - nodeB.getValue();
  60133. * }
  60134. */
  60135. sort: 'desc'
  60136. },
  60137. getViewRoot: function () {
  60138. return this._viewRoot;
  60139. },
  60140. /**
  60141. * @param {module:echarts/data/Tree~Node} [viewRoot]
  60142. */
  60143. resetViewRoot: function (viewRoot) {
  60144. viewRoot
  60145. ? (this._viewRoot = viewRoot)
  60146. : (viewRoot = this._viewRoot);
  60147. var root = this.getRawData().tree.root;
  60148. if (!viewRoot
  60149. || (viewRoot !== root && !root.contains(viewRoot))
  60150. ) {
  60151. this._viewRoot = root;
  60152. }
  60153. }
  60154. });
  60155. /**
  60156. * @param {Object} dataNode
  60157. */
  60158. function completeTreeValue$1(dataNode) {
  60159. // Postorder travel tree.
  60160. // If value of none-leaf node is not set,
  60161. // calculate it by suming up the value of all children.
  60162. var sum = 0;
  60163. each$1(dataNode.children, function (child) {
  60164. completeTreeValue$1(child);
  60165. var childValue = child.value;
  60166. isArray(childValue) && (childValue = childValue[0]);
  60167. sum += childValue;
  60168. });
  60169. var thisValue = dataNode.value;
  60170. if (isArray(thisValue)) {
  60171. thisValue = thisValue[0];
  60172. }
  60173. if (thisValue == null || isNaN(thisValue)) {
  60174. thisValue = sum;
  60175. }
  60176. // Value should not less than 0.
  60177. if (thisValue < 0) {
  60178. thisValue = 0;
  60179. }
  60180. isArray(dataNode.value)
  60181. ? (dataNode.value[0] = thisValue)
  60182. : (dataNode.value = thisValue);
  60183. }
  60184. /*
  60185. * Licensed to the Apache Software Foundation (ASF) under one
  60186. * or more contributor license agreements. See the NOTICE file
  60187. * distributed with this work for additional information
  60188. * regarding copyright ownership. The ASF licenses this file
  60189. * to you under the Apache License, Version 2.0 (the
  60190. * "License"); you may not use this file except in compliance
  60191. * with the License. You may obtain a copy of the License at
  60192. *
  60193. * http://www.apache.org/licenses/LICENSE-2.0
  60194. *
  60195. * Unless required by applicable law or agreed to in writing,
  60196. * software distributed under the License is distributed on an
  60197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60198. * KIND, either express or implied. See the License for the
  60199. * specific language governing permissions and limitations
  60200. * under the License.
  60201. */
  60202. var NodeHighlightPolicy = {
  60203. NONE: 'none', // not downplay others
  60204. DESCENDANT: 'descendant',
  60205. ANCESTOR: 'ancestor',
  60206. SELF: 'self'
  60207. };
  60208. var DEFAULT_SECTOR_Z = 2;
  60209. var DEFAULT_TEXT_Z = 4;
  60210. /**
  60211. * Sunburstce of Sunburst including Sector, Label, LabelLine
  60212. * @constructor
  60213. * @extends {module:zrender/graphic/Group}
  60214. */
  60215. function SunburstPiece(node, seriesModel, ecModel) {
  60216. Group.call(this);
  60217. var sector = new Sector({
  60218. z2: DEFAULT_SECTOR_Z
  60219. });
  60220. sector.seriesIndex = seriesModel.seriesIndex;
  60221. var text = new Text({
  60222. z2: DEFAULT_TEXT_Z,
  60223. silent: node.getModel('label').get('silent')
  60224. });
  60225. this.add(sector);
  60226. this.add(text);
  60227. this.updateData(true, node, 'normal', seriesModel, ecModel);
  60228. // Hover to change label and labelLine
  60229. function onEmphasis() {
  60230. text.ignore = text.hoverIgnore;
  60231. }
  60232. function onNormal() {
  60233. text.ignore = text.normalIgnore;
  60234. }
  60235. this.on('emphasis', onEmphasis)
  60236. .on('normal', onNormal)
  60237. .on('mouseover', onEmphasis)
  60238. .on('mouseout', onNormal);
  60239. }
  60240. var SunburstPieceProto = SunburstPiece.prototype;
  60241. SunburstPieceProto.updateData = function (
  60242. firstCreate,
  60243. node,
  60244. state,
  60245. seriesModel,
  60246. ecModel
  60247. ) {
  60248. this.node = node;
  60249. node.piece = this;
  60250. seriesModel = seriesModel || this._seriesModel;
  60251. ecModel = ecModel || this._ecModel;
  60252. var sector = this.childAt(0);
  60253. sector.dataIndex = node.dataIndex;
  60254. var itemModel = node.getModel();
  60255. var layout = node.getLayout();
  60256. // if (!layout) {
  60257. // console.log(node.getLayout());
  60258. // }
  60259. var sectorShape = extend({}, layout);
  60260. sectorShape.label = null;
  60261. var visualColor = getNodeColor(node, seriesModel, ecModel);
  60262. fillDefaultColor(node, seriesModel, visualColor);
  60263. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  60264. var style;
  60265. if (state === 'normal') {
  60266. style = normalStyle;
  60267. }
  60268. else {
  60269. var stateStyle = itemModel.getModel(state + '.itemStyle')
  60270. .getItemStyle();
  60271. style = merge(stateStyle, normalStyle);
  60272. }
  60273. style = defaults(
  60274. {
  60275. lineJoin: 'bevel',
  60276. fill: style.fill || visualColor
  60277. },
  60278. style
  60279. );
  60280. if (firstCreate) {
  60281. sector.setShape(sectorShape);
  60282. sector.shape.r = layout.r0;
  60283. updateProps(
  60284. sector,
  60285. {
  60286. shape: {
  60287. r: layout.r
  60288. }
  60289. },
  60290. seriesModel,
  60291. node.dataIndex
  60292. );
  60293. sector.useStyle(style);
  60294. }
  60295. else if (typeof style.fill === 'object' && style.fill.type
  60296. || typeof sector.style.fill === 'object' && sector.style.fill.type
  60297. ) {
  60298. // Disable animation for gradient since no interpolation method
  60299. // is supported for gradient
  60300. updateProps(sector, {
  60301. shape: sectorShape
  60302. }, seriesModel);
  60303. sector.useStyle(style);
  60304. }
  60305. else {
  60306. updateProps(sector, {
  60307. shape: sectorShape,
  60308. style: style
  60309. }, seriesModel);
  60310. }
  60311. this._updateLabel(seriesModel, visualColor, state);
  60312. var cursorStyle = itemModel.getShallow('cursor');
  60313. cursorStyle && sector.attr('cursor', cursorStyle);
  60314. if (firstCreate) {
  60315. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  60316. this._initEvents(sector, node, seriesModel, highlightPolicy);
  60317. }
  60318. this._seriesModel = seriesModel || this._seriesModel;
  60319. this._ecModel = ecModel || this._ecModel;
  60320. };
  60321. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  60322. var that = this;
  60323. this.node.hostTree.root.eachNode(function (n) {
  60324. if (n.piece) {
  60325. if (that.node === n) {
  60326. n.piece.updateData(false, n, 'emphasis');
  60327. }
  60328. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  60329. n.piece.childAt(0).trigger('highlight');
  60330. }
  60331. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  60332. n.piece.childAt(0).trigger('downplay');
  60333. }
  60334. }
  60335. });
  60336. };
  60337. SunburstPieceProto.onNormal = function () {
  60338. this.node.hostTree.root.eachNode(function (n) {
  60339. if (n.piece) {
  60340. n.piece.updateData(false, n, 'normal');
  60341. }
  60342. });
  60343. };
  60344. SunburstPieceProto.onHighlight = function () {
  60345. this.updateData(false, this.node, 'highlight');
  60346. };
  60347. SunburstPieceProto.onDownplay = function () {
  60348. this.updateData(false, this.node, 'downplay');
  60349. };
  60350. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  60351. var itemModel = this.node.getModel();
  60352. var normalModel = itemModel.getModel('label');
  60353. var labelModel = state === 'normal' || state === 'emphasis'
  60354. ? normalModel
  60355. : itemModel.getModel(state + '.label');
  60356. var labelHoverModel = itemModel.getModel('emphasis.label');
  60357. var text = retrieve(
  60358. seriesModel.getFormattedLabel(
  60359. this.node.dataIndex, 'normal', null, null, 'label'
  60360. ),
  60361. this.node.name
  60362. );
  60363. if (getLabelAttr('show') === false) {
  60364. text = '';
  60365. }
  60366. var layout = this.node.getLayout();
  60367. var labelMinAngle = labelModel.get('minAngle');
  60368. if (labelMinAngle == null) {
  60369. labelMinAngle = normalModel.get('minAngle');
  60370. }
  60371. labelMinAngle = labelMinAngle / 180 * Math.PI;
  60372. var angle = layout.endAngle - layout.startAngle;
  60373. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  60374. // Not displaying text when angle is too small
  60375. text = '';
  60376. }
  60377. var label = this.childAt(1);
  60378. setLabelStyle(
  60379. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  60380. {
  60381. defaultText: labelModel.getShallow('show') ? text : null,
  60382. autoColor: visualColor,
  60383. useInsideStyle: true
  60384. }
  60385. );
  60386. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  60387. var dx = Math.cos(midAngle);
  60388. var dy = Math.sin(midAngle);
  60389. var r;
  60390. var labelPosition = getLabelAttr('position');
  60391. var labelPadding = getLabelAttr('distance') || 0;
  60392. var textAlign = getLabelAttr('align');
  60393. if (labelPosition === 'outside') {
  60394. r = layout.r + labelPadding;
  60395. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  60396. }
  60397. else {
  60398. if (!textAlign || textAlign === 'center') {
  60399. r = (layout.r + layout.r0) / 2;
  60400. textAlign = 'center';
  60401. }
  60402. else if (textAlign === 'left') {
  60403. r = layout.r0 + labelPadding;
  60404. if (midAngle > Math.PI / 2) {
  60405. textAlign = 'right';
  60406. }
  60407. }
  60408. else if (textAlign === 'right') {
  60409. r = layout.r - labelPadding;
  60410. if (midAngle > Math.PI / 2) {
  60411. textAlign = 'left';
  60412. }
  60413. }
  60414. }
  60415. label.attr('style', {
  60416. text: text,
  60417. textAlign: textAlign,
  60418. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  60419. opacity: getLabelAttr('opacity')
  60420. });
  60421. var textX = r * dx + layout.cx;
  60422. var textY = r * dy + layout.cy;
  60423. label.attr('position', [textX, textY]);
  60424. var rotateType = getLabelAttr('rotate');
  60425. var rotate = 0;
  60426. if (rotateType === 'radial') {
  60427. rotate = -midAngle;
  60428. if (rotate < -Math.PI / 2) {
  60429. rotate += Math.PI;
  60430. }
  60431. }
  60432. else if (rotateType === 'tangential') {
  60433. rotate = Math.PI / 2 - midAngle;
  60434. if (rotate > Math.PI / 2) {
  60435. rotate -= Math.PI;
  60436. }
  60437. else if (rotate < -Math.PI / 2) {
  60438. rotate += Math.PI;
  60439. }
  60440. } else if (typeof rotateType === 'number') {
  60441. rotate = rotateType * Math.PI / 180;
  60442. }
  60443. label.attr('rotation', rotate);
  60444. function getLabelAttr(name) {
  60445. var stateAttr = labelModel.get(name);
  60446. if (stateAttr == null) {
  60447. return normalModel.get(name);
  60448. }
  60449. else {
  60450. return stateAttr;
  60451. }
  60452. }
  60453. };
  60454. SunburstPieceProto._initEvents = function (
  60455. sector,
  60456. node,
  60457. seriesModel,
  60458. highlightPolicy
  60459. ) {
  60460. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  60461. var that = this;
  60462. var onEmphasis = function () {
  60463. that.onEmphasis(highlightPolicy);
  60464. };
  60465. var onNormal = function () {
  60466. that.onNormal();
  60467. };
  60468. var onDownplay = function () {
  60469. that.onDownplay();
  60470. };
  60471. var onHighlight = function () {
  60472. that.onHighlight();
  60473. };
  60474. if (seriesModel.isAnimationEnabled()) {
  60475. sector
  60476. .on('mouseover', onEmphasis)
  60477. .on('mouseout', onNormal)
  60478. .on('emphasis', onEmphasis)
  60479. .on('normal', onNormal)
  60480. .on('downplay', onDownplay)
  60481. .on('highlight', onHighlight);
  60482. }
  60483. };
  60484. inherits(SunburstPiece, Group);
  60485. /**
  60486. * Get node color
  60487. *
  60488. * @param {TreeNode} node the node to get color
  60489. * @param {module:echarts/model/Series} seriesModel series
  60490. * @param {module:echarts/model/Global} ecModel echarts defaults
  60491. */
  60492. function getNodeColor(node, seriesModel, ecModel) {
  60493. // Color from visualMap
  60494. var visualColor = node.getVisual('color');
  60495. var visualMetaList = node.getVisual('visualMeta');
  60496. if (!visualMetaList || visualMetaList.length === 0) {
  60497. // Use first-generation color if has no visualMap
  60498. visualColor = null;
  60499. }
  60500. // Self color or level color
  60501. var color = node.getModel('itemStyle').get('color');
  60502. if (color) {
  60503. return color;
  60504. }
  60505. else if (visualColor) {
  60506. // Color mapping
  60507. return visualColor;
  60508. }
  60509. else if (node.depth === 0) {
  60510. // Virtual root node
  60511. return ecModel.option.color[0];
  60512. }
  60513. else {
  60514. // First-generation color
  60515. var length = ecModel.option.color.length;
  60516. color = ecModel.option.color[getRootId(node) % length];
  60517. }
  60518. return color;
  60519. }
  60520. /**
  60521. * Get index of root in sorted order
  60522. *
  60523. * @param {TreeNode} node current node
  60524. * @return {number} index in root
  60525. */
  60526. function getRootId(node) {
  60527. var ancestor = node;
  60528. while (ancestor.depth > 1) {
  60529. ancestor = ancestor.parentNode;
  60530. }
  60531. var virtualRoot = node.getAncestors()[0];
  60532. return indexOf(virtualRoot.children, ancestor);
  60533. }
  60534. function isNodeHighlighted(node, activeNode, policy) {
  60535. if (policy === NodeHighlightPolicy.NONE) {
  60536. return false;
  60537. }
  60538. else if (policy === NodeHighlightPolicy.SELF) {
  60539. return node === activeNode;
  60540. }
  60541. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  60542. return node === activeNode || node.isAncestorOf(activeNode);
  60543. }
  60544. else {
  60545. return node === activeNode || node.isDescendantOf(activeNode);
  60546. }
  60547. }
  60548. // Fix tooltip callback function params.color incorrect when pick a default color
  60549. function fillDefaultColor(node, seriesModel, color) {
  60550. var data = seriesModel.getData();
  60551. data.setItemVisual(node.dataIndex, 'color', color);
  60552. }
  60553. /*
  60554. * Licensed to the Apache Software Foundation (ASF) under one
  60555. * or more contributor license agreements. See the NOTICE file
  60556. * distributed with this work for additional information
  60557. * regarding copyright ownership. The ASF licenses this file
  60558. * to you under the Apache License, Version 2.0 (the
  60559. * "License"); you may not use this file except in compliance
  60560. * with the License. You may obtain a copy of the License at
  60561. *
  60562. * http://www.apache.org/licenses/LICENSE-2.0
  60563. *
  60564. * Unless required by applicable law or agreed to in writing,
  60565. * software distributed under the License is distributed on an
  60566. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60567. * KIND, either express or implied. See the License for the
  60568. * specific language governing permissions and limitations
  60569. * under the License.
  60570. */
  60571. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  60572. var SunburstView = Chart.extend({
  60573. type: 'sunburst',
  60574. init: function () {
  60575. },
  60576. render: function (seriesModel, ecModel, api, payload) {
  60577. var that = this;
  60578. this.seriesModel = seriesModel;
  60579. this.api = api;
  60580. this.ecModel = ecModel;
  60581. var data = seriesModel.getData();
  60582. var virtualRoot = data.tree.root;
  60583. var newRoot = seriesModel.getViewRoot();
  60584. var group = this.group;
  60585. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  60586. var newChildren = [];
  60587. newRoot.eachNode(function (node) {
  60588. newChildren.push(node);
  60589. });
  60590. var oldChildren = this._oldChildren || [];
  60591. dualTravel(newChildren, oldChildren);
  60592. renderRollUp(virtualRoot, newRoot);
  60593. if (payload && payload.highlight && payload.highlight.piece) {
  60594. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  60595. payload.highlight.piece.onEmphasis(highlightPolicy);
  60596. }
  60597. else if (payload && payload.unhighlight) {
  60598. var piece = this.virtualPiece;
  60599. if (!piece && virtualRoot.children.length) {
  60600. piece = virtualRoot.children[0].piece;
  60601. }
  60602. if (piece) {
  60603. piece.onNormal();
  60604. }
  60605. }
  60606. this._initEvents();
  60607. this._oldChildren = newChildren;
  60608. function dualTravel(newChildren, oldChildren) {
  60609. if (newChildren.length === 0 && oldChildren.length === 0) {
  60610. return;
  60611. }
  60612. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  60613. .add(processNode)
  60614. .update(processNode)
  60615. .remove(curry(processNode, null))
  60616. .execute();
  60617. function getKey(node) {
  60618. return node.getId();
  60619. }
  60620. function processNode(newId, oldId) {
  60621. var newNode = newId == null ? null : newChildren[newId];
  60622. var oldNode = oldId == null ? null : oldChildren[oldId];
  60623. doRenderNode(newNode, oldNode);
  60624. }
  60625. }
  60626. function doRenderNode(newNode, oldNode) {
  60627. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  60628. // Not render data with value 0
  60629. newNode = null;
  60630. }
  60631. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  60632. if (oldNode && oldNode.piece) {
  60633. if (newNode) {
  60634. // Update
  60635. oldNode.piece.updateData(
  60636. false, newNode, 'normal', seriesModel, ecModel);
  60637. // For tooltip
  60638. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  60639. }
  60640. else {
  60641. // Remove
  60642. removeNode(oldNode);
  60643. }
  60644. }
  60645. else if (newNode) {
  60646. // Add
  60647. var piece = new SunburstPiece(
  60648. newNode,
  60649. seriesModel,
  60650. ecModel
  60651. );
  60652. group.add(piece);
  60653. // For tooltip
  60654. data.setItemGraphicEl(newNode.dataIndex, piece);
  60655. }
  60656. }
  60657. }
  60658. function removeNode(node) {
  60659. if (!node) {
  60660. return;
  60661. }
  60662. if (node.piece) {
  60663. group.remove(node.piece);
  60664. node.piece = null;
  60665. }
  60666. }
  60667. function renderRollUp(virtualRoot, viewRoot) {
  60668. if (viewRoot.depth > 0) {
  60669. // Render
  60670. if (that.virtualPiece) {
  60671. // Update
  60672. that.virtualPiece.updateData(
  60673. false, virtualRoot, 'normal', seriesModel, ecModel);
  60674. }
  60675. else {
  60676. // Add
  60677. that.virtualPiece = new SunburstPiece(
  60678. virtualRoot,
  60679. seriesModel,
  60680. ecModel
  60681. );
  60682. group.add(that.virtualPiece);
  60683. }
  60684. if (viewRoot.piece._onclickEvent) {
  60685. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  60686. }
  60687. var event = function (e) {
  60688. that._rootToNode(viewRoot.parentNode);
  60689. };
  60690. viewRoot.piece._onclickEvent = event;
  60691. that.virtualPiece.on('click', event);
  60692. }
  60693. else if (that.virtualPiece) {
  60694. // Remove
  60695. group.remove(that.virtualPiece);
  60696. that.virtualPiece = null;
  60697. }
  60698. }
  60699. },
  60700. dispose: function () {
  60701. },
  60702. /**
  60703. * @private
  60704. */
  60705. _initEvents: function () {
  60706. var that = this;
  60707. var event = function (e) {
  60708. var targetFound = false;
  60709. var viewRoot = that.seriesModel.getViewRoot();
  60710. viewRoot.eachNode(function (node) {
  60711. if (!targetFound
  60712. && node.piece && node.piece.childAt(0) === e.target
  60713. ) {
  60714. var nodeClick = node.getModel().get('nodeClick');
  60715. if (nodeClick === 'rootToNode') {
  60716. that._rootToNode(node);
  60717. }
  60718. else if (nodeClick === 'link') {
  60719. var itemModel = node.getModel();
  60720. var link = itemModel.get('link');
  60721. if (link) {
  60722. var linkTarget = itemModel.get('target', true)
  60723. || '_blank';
  60724. window.open(link, linkTarget);
  60725. }
  60726. }
  60727. targetFound = true;
  60728. }
  60729. });
  60730. };
  60731. if (this.group._onclickEvent) {
  60732. this.group.off('click', this.group._onclickEvent);
  60733. }
  60734. this.group.on('click', event);
  60735. this.group._onclickEvent = event;
  60736. },
  60737. /**
  60738. * @private
  60739. */
  60740. _rootToNode: function (node) {
  60741. if (node !== this.seriesModel.getViewRoot()) {
  60742. this.api.dispatchAction({
  60743. type: ROOT_TO_NODE_ACTION,
  60744. from: this.uid,
  60745. seriesId: this.seriesModel.id,
  60746. targetNode: node
  60747. });
  60748. }
  60749. },
  60750. /**
  60751. * @implement
  60752. */
  60753. containPoint: function (point, seriesModel) {
  60754. var treeRoot = seriesModel.getData();
  60755. var itemLayout = treeRoot.getItemLayout(0);
  60756. if (itemLayout) {
  60757. var dx = point[0] - itemLayout.cx;
  60758. var dy = point[1] - itemLayout.cy;
  60759. var radius = Math.sqrt(dx * dx + dy * dy);
  60760. return radius <= itemLayout.r && radius >= itemLayout.r0;
  60761. }
  60762. }
  60763. });
  60764. /*
  60765. * Licensed to the Apache Software Foundation (ASF) under one
  60766. * or more contributor license agreements. See the NOTICE file
  60767. * distributed with this work for additional information
  60768. * regarding copyright ownership. The ASF licenses this file
  60769. * to you under the Apache License, Version 2.0 (the
  60770. * "License"); you may not use this file except in compliance
  60771. * with the License. You may obtain a copy of the License at
  60772. *
  60773. * http://www.apache.org/licenses/LICENSE-2.0
  60774. *
  60775. * Unless required by applicable law or agreed to in writing,
  60776. * software distributed under the License is distributed on an
  60777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60778. * KIND, either express or implied. See the License for the
  60779. * specific language governing permissions and limitations
  60780. * under the License.
  60781. */
  60782. /**
  60783. * @file Sunburst action
  60784. */
  60785. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  60786. registerAction(
  60787. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  60788. function (payload, ecModel) {
  60789. ecModel.eachComponent(
  60790. {mainType: 'series', subType: 'sunburst', query: payload},
  60791. handleRootToNode
  60792. );
  60793. function handleRootToNode(model, index) {
  60794. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  60795. if (targetInfo) {
  60796. var originViewRoot = model.getViewRoot();
  60797. if (originViewRoot) {
  60798. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  60799. ? 'rollUp' : 'drillDown';
  60800. }
  60801. model.resetViewRoot(targetInfo.node);
  60802. }
  60803. }
  60804. }
  60805. );
  60806. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  60807. registerAction(
  60808. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  60809. function (payload, ecModel) {
  60810. ecModel.eachComponent(
  60811. {mainType: 'series', subType: 'sunburst', query: payload},
  60812. handleHighlight
  60813. );
  60814. function handleHighlight(model, index) {
  60815. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  60816. if (targetInfo) {
  60817. payload.highlight = targetInfo.node;
  60818. }
  60819. }
  60820. }
  60821. );
  60822. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  60823. registerAction(
  60824. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  60825. function (payload, ecModel) {
  60826. ecModel.eachComponent(
  60827. {mainType: 'series', subType: 'sunburst', query: payload},
  60828. handleUnhighlight
  60829. );
  60830. function handleUnhighlight(model, index) {
  60831. payload.unhighlight = true;
  60832. }
  60833. }
  60834. );
  60835. /*
  60836. * Licensed to the Apache Software Foundation (ASF) under one
  60837. * or more contributor license agreements. See the NOTICE file
  60838. * distributed with this work for additional information
  60839. * regarding copyright ownership. The ASF licenses this file
  60840. * to you under the Apache License, Version 2.0 (the
  60841. * "License"); you may not use this file except in compliance
  60842. * with the License. You may obtain a copy of the License at
  60843. *
  60844. * http://www.apache.org/licenses/LICENSE-2.0
  60845. *
  60846. * Unless required by applicable law or agreed to in writing,
  60847. * software distributed under the License is distributed on an
  60848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60849. * KIND, either express or implied. See the License for the
  60850. * specific language governing permissions and limitations
  60851. * under the License.
  60852. */
  60853. var RADIAN$1 = Math.PI / 180;
  60854. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  60855. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  60856. var center = seriesModel.get('center');
  60857. var radius = seriesModel.get('radius');
  60858. if (!isArray(radius)) {
  60859. radius = [0, radius];
  60860. }
  60861. if (!isArray(center)) {
  60862. center = [center, center];
  60863. }
  60864. var width = api.getWidth();
  60865. var height = api.getHeight();
  60866. var size = Math.min(width, height);
  60867. var cx = parsePercent$1(center[0], width);
  60868. var cy = parsePercent$1(center[1], height);
  60869. var r0 = parsePercent$1(radius[0], size / 2);
  60870. var r = parsePercent$1(radius[1], size / 2);
  60871. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  60872. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  60873. var virtualRoot = seriesModel.getData().tree.root;
  60874. var treeRoot = seriesModel.getViewRoot();
  60875. var rootDepth = treeRoot.depth;
  60876. var sort = seriesModel.get('sort');
  60877. if (sort != null) {
  60878. initChildren$1(treeRoot, sort);
  60879. }
  60880. var validDataCount = 0;
  60881. each$1(treeRoot.children, function (child) {
  60882. !isNaN(child.getValue()) && validDataCount++;
  60883. });
  60884. var sum = treeRoot.getValue();
  60885. // Sum may be 0
  60886. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  60887. var renderRollupNode = treeRoot.depth > 0;
  60888. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  60889. var rPerLevel = (r - r0) / (levels || 1);
  60890. var clockwise = seriesModel.get('clockwise');
  60891. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  60892. // In the case some sector angle is smaller than minAngle
  60893. var dir = clockwise ? 1 : -1;
  60894. /**
  60895. * Render a tree
  60896. * @return increased angle
  60897. */
  60898. var renderNode = function (node, startAngle) {
  60899. if (!node) {
  60900. return;
  60901. }
  60902. var endAngle = startAngle;
  60903. // Render self
  60904. if (node !== virtualRoot) {
  60905. // Tree node is virtual, so it doesn't need to be drawn
  60906. var value = node.getValue();
  60907. var angle = (sum === 0 && stillShowZeroSum)
  60908. ? unitRadian : (value * unitRadian);
  60909. if (angle < minAngle) {
  60910. angle = minAngle;
  60911. }
  60912. else {
  60913. }
  60914. endAngle = startAngle + dir * angle;
  60915. var depth = node.depth - rootDepth
  60916. - (renderRollupNode ? -1 : 1);
  60917. var rStart = r0 + rPerLevel * depth;
  60918. var rEnd = r0 + rPerLevel * (depth + 1);
  60919. var itemModel = node.getModel();
  60920. if (itemModel.get('r0') != null) {
  60921. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  60922. }
  60923. if (itemModel.get('r') != null) {
  60924. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  60925. }
  60926. node.setLayout({
  60927. angle: angle,
  60928. startAngle: startAngle,
  60929. endAngle: endAngle,
  60930. clockwise: clockwise,
  60931. cx: cx,
  60932. cy: cy,
  60933. r0: rStart,
  60934. r: rEnd
  60935. });
  60936. }
  60937. // Render children
  60938. if (node.children && node.children.length) {
  60939. // currentAngle = startAngle;
  60940. var siblingAngle = 0;
  60941. each$1(node.children, function (node) {
  60942. siblingAngle += renderNode(node, startAngle + siblingAngle);
  60943. });
  60944. }
  60945. return endAngle - startAngle;
  60946. };
  60947. // Virtual root node for roll up
  60948. if (renderRollupNode) {
  60949. var rStart = r0;
  60950. var rEnd = r0 + rPerLevel;
  60951. var angle = Math.PI * 2;
  60952. virtualRoot.setLayout({
  60953. angle: angle,
  60954. startAngle: startAngle,
  60955. endAngle: startAngle + angle,
  60956. clockwise: clockwise,
  60957. cx: cx,
  60958. cy: cy,
  60959. r0: rStart,
  60960. r: rEnd
  60961. });
  60962. }
  60963. renderNode(treeRoot, startAngle);
  60964. });
  60965. };
  60966. /**
  60967. * Init node children by order and update visual
  60968. *
  60969. * @param {TreeNode} node root node
  60970. * @param {boolean} isAsc if is in ascendant order
  60971. */
  60972. function initChildren$1(node, isAsc) {
  60973. var children = node.children || [];
  60974. node.children = sort$2(children, isAsc);
  60975. // Init children recursively
  60976. if (children.length) {
  60977. each$1(node.children, function (child) {
  60978. initChildren$1(child, isAsc);
  60979. });
  60980. }
  60981. }
  60982. /**
  60983. * Sort children nodes
  60984. *
  60985. * @param {TreeNode[]} children children of node to be sorted
  60986. * @param {string | function | null} sort sort method
  60987. * See SunburstSeries.js for details.
  60988. */
  60989. function sort$2(children, sortOrder) {
  60990. if (typeof sortOrder === 'function') {
  60991. return children.sort(sortOrder);
  60992. }
  60993. else {
  60994. var isAsc = sortOrder === 'asc';
  60995. return children.sort(function (a, b) {
  60996. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  60997. return diff === 0
  60998. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  60999. : diff;
  61000. });
  61001. }
  61002. }
  61003. /*
  61004. * Licensed to the Apache Software Foundation (ASF) under one
  61005. * or more contributor license agreements. See the NOTICE file
  61006. * distributed with this work for additional information
  61007. * regarding copyright ownership. The ASF licenses this file
  61008. * to you under the Apache License, Version 2.0 (the
  61009. * "License"); you may not use this file except in compliance
  61010. * with the License. You may obtain a copy of the License at
  61011. *
  61012. * http://www.apache.org/licenses/LICENSE-2.0
  61013. *
  61014. * Unless required by applicable law or agreed to in writing,
  61015. * software distributed under the License is distributed on an
  61016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61017. * KIND, either express or implied. See the License for the
  61018. * specific language governing permissions and limitations
  61019. * under the License.
  61020. */
  61021. registerVisual(curry(dataColor, 'sunburst'));
  61022. registerLayout(curry(sunburstLayout, 'sunburst'));
  61023. registerProcessor(curry(dataFilter, 'sunburst'));
  61024. /*
  61025. * Licensed to the Apache Software Foundation (ASF) under one
  61026. * or more contributor license agreements. See the NOTICE file
  61027. * distributed with this work for additional information
  61028. * regarding copyright ownership. The ASF licenses this file
  61029. * to you under the Apache License, Version 2.0 (the
  61030. * "License"); you may not use this file except in compliance
  61031. * with the License. You may obtain a copy of the License at
  61032. *
  61033. * http://www.apache.org/licenses/LICENSE-2.0
  61034. *
  61035. * Unless required by applicable law or agreed to in writing,
  61036. * software distributed under the License is distributed on an
  61037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61038. * KIND, either express or implied. See the License for the
  61039. * specific language governing permissions and limitations
  61040. * under the License.
  61041. */
  61042. function dataToCoordSize(dataSize, dataItem) {
  61043. // dataItem is necessary in log axis.
  61044. dataItem = dataItem || [0, 0];
  61045. return map(['x', 'y'], function (dim, dimIdx) {
  61046. var axis = this.getAxis(dim);
  61047. var val = dataItem[dimIdx];
  61048. var halfSize = dataSize[dimIdx] / 2;
  61049. return axis.type === 'category'
  61050. ? axis.getBandWidth()
  61051. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61052. }, this);
  61053. }
  61054. var prepareCartesian2d = function (coordSys) {
  61055. var rect = coordSys.grid.getRect();
  61056. return {
  61057. coordSys: {
  61058. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  61059. type: 'cartesian2d',
  61060. x: rect.x,
  61061. y: rect.y,
  61062. width: rect.width,
  61063. height: rect.height
  61064. },
  61065. api: {
  61066. coord: function (data) {
  61067. // do not provide "out" param
  61068. return coordSys.dataToPoint(data);
  61069. },
  61070. size: bind(dataToCoordSize, coordSys)
  61071. }
  61072. };
  61073. };
  61074. /*
  61075. * Licensed to the Apache Software Foundation (ASF) under one
  61076. * or more contributor license agreements. See the NOTICE file
  61077. * distributed with this work for additional information
  61078. * regarding copyright ownership. The ASF licenses this file
  61079. * to you under the Apache License, Version 2.0 (the
  61080. * "License"); you may not use this file except in compliance
  61081. * with the License. You may obtain a copy of the License at
  61082. *
  61083. * http://www.apache.org/licenses/LICENSE-2.0
  61084. *
  61085. * Unless required by applicable law or agreed to in writing,
  61086. * software distributed under the License is distributed on an
  61087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61088. * KIND, either express or implied. See the License for the
  61089. * specific language governing permissions and limitations
  61090. * under the License.
  61091. */
  61092. function dataToCoordSize$1(dataSize, dataItem) {
  61093. dataItem = dataItem || [0, 0];
  61094. return map([0, 1], function (dimIdx) {
  61095. var val = dataItem[dimIdx];
  61096. var halfSize = dataSize[dimIdx] / 2;
  61097. var p1 = [];
  61098. var p2 = [];
  61099. p1[dimIdx] = val - halfSize;
  61100. p2[dimIdx] = val + halfSize;
  61101. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  61102. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  61103. }, this);
  61104. }
  61105. var prepareGeo = function (coordSys) {
  61106. var rect = coordSys.getBoundingRect();
  61107. return {
  61108. coordSys: {
  61109. type: 'geo',
  61110. x: rect.x,
  61111. y: rect.y,
  61112. width: rect.width,
  61113. height: rect.height,
  61114. zoom: coordSys.getZoom()
  61115. },
  61116. api: {
  61117. coord: function (data) {
  61118. // do not provide "out" and noRoam param,
  61119. // Compatible with this usage:
  61120. // echarts.util.map(item.points, api.coord)
  61121. return coordSys.dataToPoint(data);
  61122. },
  61123. size: bind(dataToCoordSize$1, coordSys)
  61124. }
  61125. };
  61126. };
  61127. /*
  61128. * Licensed to the Apache Software Foundation (ASF) under one
  61129. * or more contributor license agreements. See the NOTICE file
  61130. * distributed with this work for additional information
  61131. * regarding copyright ownership. The ASF licenses this file
  61132. * to you under the Apache License, Version 2.0 (the
  61133. * "License"); you may not use this file except in compliance
  61134. * with the License. You may obtain a copy of the License at
  61135. *
  61136. * http://www.apache.org/licenses/LICENSE-2.0
  61137. *
  61138. * Unless required by applicable law or agreed to in writing,
  61139. * software distributed under the License is distributed on an
  61140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61141. * KIND, either express or implied. See the License for the
  61142. * specific language governing permissions and limitations
  61143. * under the License.
  61144. */
  61145. function dataToCoordSize$2(dataSize, dataItem) {
  61146. // dataItem is necessary in log axis.
  61147. var axis = this.getAxis();
  61148. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  61149. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  61150. return axis.type === 'category'
  61151. ? axis.getBandWidth()
  61152. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61153. }
  61154. var prepareSingleAxis = function (coordSys) {
  61155. var rect = coordSys.getRect();
  61156. return {
  61157. coordSys: {
  61158. type: 'singleAxis',
  61159. x: rect.x,
  61160. y: rect.y,
  61161. width: rect.width,
  61162. height: rect.height
  61163. },
  61164. api: {
  61165. coord: function (val) {
  61166. // do not provide "out" param
  61167. return coordSys.dataToPoint(val);
  61168. },
  61169. size: bind(dataToCoordSize$2, coordSys)
  61170. }
  61171. };
  61172. };
  61173. /*
  61174. * Licensed to the Apache Software Foundation (ASF) under one
  61175. * or more contributor license agreements. See the NOTICE file
  61176. * distributed with this work for additional information
  61177. * regarding copyright ownership. The ASF licenses this file
  61178. * to you under the Apache License, Version 2.0 (the
  61179. * "License"); you may not use this file except in compliance
  61180. * with the License. You may obtain a copy of the License at
  61181. *
  61182. * http://www.apache.org/licenses/LICENSE-2.0
  61183. *
  61184. * Unless required by applicable law or agreed to in writing,
  61185. * software distributed under the License is distributed on an
  61186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61187. * KIND, either express or implied. See the License for the
  61188. * specific language governing permissions and limitations
  61189. * under the License.
  61190. */
  61191. function dataToCoordSize$3(dataSize, dataItem) {
  61192. // dataItem is necessary in log axis.
  61193. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  61194. var axis = this['get' + dim + 'Axis']();
  61195. var val = dataItem[dimIdx];
  61196. var halfSize = dataSize[dimIdx] / 2;
  61197. var method = 'dataTo' + dim;
  61198. var result = axis.type === 'category'
  61199. ? axis.getBandWidth()
  61200. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  61201. if (dim === 'Angle') {
  61202. result = result * Math.PI / 180;
  61203. }
  61204. return result;
  61205. }, this);
  61206. }
  61207. var preparePolar = function (coordSys) {
  61208. var radiusAxis = coordSys.getRadiusAxis();
  61209. var angleAxis = coordSys.getAngleAxis();
  61210. var radius = radiusAxis.getExtent();
  61211. radius[0] > radius[1] && radius.reverse();
  61212. return {
  61213. coordSys: {
  61214. type: 'polar',
  61215. cx: coordSys.cx,
  61216. cy: coordSys.cy,
  61217. r: radius[1],
  61218. r0: radius[0]
  61219. },
  61220. api: {
  61221. coord: bind(function (data) {
  61222. var radius = radiusAxis.dataToRadius(data[0]);
  61223. var angle = angleAxis.dataToAngle(data[1]);
  61224. var coord = coordSys.coordToPoint([radius, angle]);
  61225. coord.push(radius, angle * Math.PI / 180);
  61226. return coord;
  61227. }),
  61228. size: bind(dataToCoordSize$3, coordSys)
  61229. }
  61230. };
  61231. };
  61232. /*
  61233. * Licensed to the Apache Software Foundation (ASF) under one
  61234. * or more contributor license agreements. See the NOTICE file
  61235. * distributed with this work for additional information
  61236. * regarding copyright ownership. The ASF licenses this file
  61237. * to you under the Apache License, Version 2.0 (the
  61238. * "License"); you may not use this file except in compliance
  61239. * with the License. You may obtain a copy of the License at
  61240. *
  61241. * http://www.apache.org/licenses/LICENSE-2.0
  61242. *
  61243. * Unless required by applicable law or agreed to in writing,
  61244. * software distributed under the License is distributed on an
  61245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61246. * KIND, either express or implied. See the License for the
  61247. * specific language governing permissions and limitations
  61248. * under the License.
  61249. */
  61250. var prepareCalendar = function (coordSys) {
  61251. var rect = coordSys.getRect();
  61252. var rangeInfo = coordSys.getRangeInfo();
  61253. return {
  61254. coordSys: {
  61255. type: 'calendar',
  61256. x: rect.x,
  61257. y: rect.y,
  61258. width: rect.width,
  61259. height: rect.height,
  61260. cellWidth: coordSys.getCellWidth(),
  61261. cellHeight: coordSys.getCellHeight(),
  61262. rangeInfo: {
  61263. start: rangeInfo.start,
  61264. end: rangeInfo.end,
  61265. weeks: rangeInfo.weeks,
  61266. dayCount: rangeInfo.allDay
  61267. }
  61268. },
  61269. api: {
  61270. coord: function (data, clamp) {
  61271. return coordSys.dataToPoint(data, clamp);
  61272. }
  61273. }
  61274. };
  61275. };
  61276. /*
  61277. * Licensed to the Apache Software Foundation (ASF) under one
  61278. * or more contributor license agreements. See the NOTICE file
  61279. * distributed with this work for additional information
  61280. * regarding copyright ownership. The ASF licenses this file
  61281. * to you under the Apache License, Version 2.0 (the
  61282. * "License"); you may not use this file except in compliance
  61283. * with the License. You may obtain a copy of the License at
  61284. *
  61285. * http://www.apache.org/licenses/LICENSE-2.0
  61286. *
  61287. * Unless required by applicable law or agreed to in writing,
  61288. * software distributed under the License is distributed on an
  61289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61290. * KIND, either express or implied. See the License for the
  61291. * specific language governing permissions and limitations
  61292. * under the License.
  61293. */
  61294. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  61295. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  61296. var LABEL_NORMAL = ['label'];
  61297. var LABEL_EMPHASIS = ['emphasis', 'label'];
  61298. // Use prefix to avoid index to be the same as el.name,
  61299. // which will cause weird udpate animation.
  61300. var GROUP_DIFF_PREFIX = 'e\0\0';
  61301. /**
  61302. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  61303. * of each coordinate systems are not required by each coordinate systems directly, but
  61304. * required by the module `custom`.
  61305. *
  61306. * prepareInfoForCustomSeries {Function}: optional
  61307. * @return {Object} {coordSys: {...}, api: {
  61308. * coord: function (data, clamp) {}, // return point in global.
  61309. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  61310. * }}
  61311. */
  61312. var prepareCustoms = {
  61313. cartesian2d: prepareCartesian2d,
  61314. geo: prepareGeo,
  61315. singleAxis: prepareSingleAxis,
  61316. polar: preparePolar,
  61317. calendar: prepareCalendar
  61318. };
  61319. // ------
  61320. // Model
  61321. // ------
  61322. SeriesModel.extend({
  61323. type: 'series.custom',
  61324. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  61325. defaultOption: {
  61326. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  61327. zlevel: 0,
  61328. z: 2,
  61329. legendHoverLink: true,
  61330. useTransform: true
  61331. // Cartesian coordinate system
  61332. // xAxisIndex: 0,
  61333. // yAxisIndex: 0,
  61334. // Polar coordinate system
  61335. // polarIndex: 0,
  61336. // Geo coordinate system
  61337. // geoIndex: 0,
  61338. // label: {}
  61339. // itemStyle: {}
  61340. },
  61341. /**
  61342. * @override
  61343. */
  61344. getInitialData: function (option, ecModel) {
  61345. return createListFromArray(this.getSource(), this);
  61346. },
  61347. /**
  61348. * @override
  61349. */
  61350. getDataParams: function (dataIndex, dataType, el) {
  61351. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  61352. el && (params.info = el.info);
  61353. return params;
  61354. }
  61355. });
  61356. // -----
  61357. // View
  61358. // -----
  61359. Chart.extend({
  61360. type: 'custom',
  61361. /**
  61362. * @private
  61363. * @type {module:echarts/data/List}
  61364. */
  61365. _data: null,
  61366. /**
  61367. * @override
  61368. */
  61369. render: function (customSeries, ecModel, api, payload) {
  61370. var oldData = this._data;
  61371. var data = customSeries.getData();
  61372. var group = this.group;
  61373. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  61374. // By default, merge mode is applied. In most cases, custom series is
  61375. // used in the scenario that data amount is not large but graphic elements
  61376. // is complicated, where merge mode is probably necessary for optimization.
  61377. // For example, reuse graphic elements and only update the transform when
  61378. // roam or data zoom according to `actionType`.
  61379. data.diff(oldData)
  61380. .add(function (newIdx) {
  61381. createOrUpdate$1(
  61382. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  61383. );
  61384. })
  61385. .update(function (newIdx, oldIdx) {
  61386. var el = oldData.getItemGraphicEl(oldIdx);
  61387. createOrUpdate$1(
  61388. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  61389. );
  61390. })
  61391. .remove(function (oldIdx) {
  61392. var el = oldData.getItemGraphicEl(oldIdx);
  61393. el && group.remove(el);
  61394. })
  61395. .execute();
  61396. this._data = data;
  61397. },
  61398. incrementalPrepareRender: function (customSeries, ecModel, api) {
  61399. this.group.removeAll();
  61400. this._data = null;
  61401. },
  61402. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  61403. var data = customSeries.getData();
  61404. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  61405. function setIncrementalAndHoverLayer(el) {
  61406. if (!el.isGroup) {
  61407. el.incremental = true;
  61408. el.useHoverLayer = true;
  61409. }
  61410. }
  61411. for (var idx = params.start; idx < params.end; idx++) {
  61412. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  61413. el.traverse(setIncrementalAndHoverLayer);
  61414. }
  61415. },
  61416. /**
  61417. * @override
  61418. */
  61419. dispose: noop,
  61420. /**
  61421. * @override
  61422. */
  61423. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  61424. var elementName = query.element;
  61425. if (elementName == null || targetEl.name === elementName) {
  61426. return true;
  61427. }
  61428. // Enable to give a name on a group made by `renderItem`, and listen
  61429. // events that triggerd by its descendents.
  61430. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  61431. if (targetEl.name === elementName) {
  61432. return true;
  61433. }
  61434. }
  61435. return false;
  61436. }
  61437. });
  61438. function createEl(elOption) {
  61439. var graphicType = elOption.type;
  61440. var el;
  61441. if (graphicType === 'path') {
  61442. var shape = elOption.shape;
  61443. // Using pathRect brings convenience to users sacle svg path.
  61444. var pathRect = (shape.width != null && shape.height != null)
  61445. ? {
  61446. x: shape.x || 0,
  61447. y: shape.y || 0,
  61448. width: shape.width,
  61449. height: shape.height
  61450. }
  61451. : null;
  61452. var pathData = getPathData(shape);
  61453. // Path is also used for icon, so layout 'center' by default.
  61454. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  61455. el.__customPathData = pathData;
  61456. }
  61457. else if (graphicType === 'image') {
  61458. el = new ZImage({});
  61459. el.__customImagePath = elOption.style.image;
  61460. }
  61461. else if (graphicType === 'text') {
  61462. el = new Text({});
  61463. el.__customText = elOption.style.text;
  61464. }
  61465. else {
  61466. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  61467. if (__DEV__) {
  61468. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  61469. }
  61470. el = new Clz();
  61471. }
  61472. el.__customGraphicType = graphicType;
  61473. el.name = elOption.name;
  61474. return el;
  61475. }
  61476. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  61477. var transitionProps = {};
  61478. var elOptionStyle = elOption.style || {};
  61479. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  61480. elOption.position && (transitionProps.position = elOption.position.slice());
  61481. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  61482. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  61483. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  61484. if (el.type === 'image' && elOption.style) {
  61485. var targetStyle = transitionProps.style = {};
  61486. each$1(['x', 'y', 'width', 'height'], function (prop) {
  61487. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61488. });
  61489. }
  61490. if (el.type === 'text' && elOption.style) {
  61491. var targetStyle = transitionProps.style = {};
  61492. each$1(['x', 'y'], function (prop) {
  61493. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61494. });
  61495. // Compatible with previous: both support
  61496. // textFill and fill, textStroke and stroke in 'text' element.
  61497. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  61498. elOptionStyle.textFill = elOptionStyle.fill
  61499. );
  61500. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  61501. elOptionStyle.textStroke = elOptionStyle.stroke
  61502. );
  61503. }
  61504. if (el.type !== 'group') {
  61505. el.useStyle(elOptionStyle);
  61506. // Init animation.
  61507. if (isInit) {
  61508. el.style.opacity = 0;
  61509. var targetOpacity = elOptionStyle.opacity;
  61510. targetOpacity == null && (targetOpacity = 1);
  61511. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  61512. }
  61513. }
  61514. if (isInit) {
  61515. el.attr(transitionProps);
  61516. }
  61517. else {
  61518. updateProps(el, transitionProps, animatableModel, dataIndex);
  61519. }
  61520. // Merge by default.
  61521. // z2 must not be null/undefined, otherwise sort error may occur.
  61522. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  61523. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  61524. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  61525. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  61526. // `elOption.info` enables user to mount some info on
  61527. // elements and use them in event handlers.
  61528. // Update them only when user specified, otherwise, remain.
  61529. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  61530. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  61531. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  61532. var styleEmphasis = elOption.styleEmphasis;
  61533. var disableStyleEmphasis = styleEmphasis === false;
  61534. if (!(
  61535. // Try to escapse setting hover style for performance.
  61536. (el.__cusHasEmphStl && styleEmphasis == null)
  61537. || (!el.__cusHasEmphStl && disableStyleEmphasis)
  61538. )) {
  61539. // Should not use graphicUtil.setHoverStyle, since the styleEmphasis
  61540. // should not be share by group and its descendants.
  61541. setElementHoverStyle(el, styleEmphasis);
  61542. el.__cusHasEmphStl = !disableStyleEmphasis;
  61543. }
  61544. isRoot && setAsHoverStyleTrigger(el, !disableStyleEmphasis);
  61545. }
  61546. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  61547. if (elOptionStyle[prop] != null && !isInit) {
  61548. targetStyle[prop] = elOptionStyle[prop];
  61549. elOptionStyle[prop] = oldElStyle[prop];
  61550. }
  61551. }
  61552. function makeRenderItem(customSeries, data, ecModel, api) {
  61553. var renderItem = customSeries.get('renderItem');
  61554. var coordSys = customSeries.coordinateSystem;
  61555. var prepareResult = {};
  61556. if (coordSys) {
  61557. if (__DEV__) {
  61558. assert$1(renderItem, 'series.render is required.');
  61559. assert$1(
  61560. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  61561. 'This coordSys does not support custom series.'
  61562. );
  61563. }
  61564. prepareResult = coordSys.prepareCustoms
  61565. ? coordSys.prepareCustoms()
  61566. : prepareCustoms[coordSys.type](coordSys);
  61567. }
  61568. var userAPI = defaults({
  61569. getWidth: api.getWidth,
  61570. getHeight: api.getHeight,
  61571. getZr: api.getZr,
  61572. getDevicePixelRatio: api.getDevicePixelRatio,
  61573. value: value,
  61574. style: style,
  61575. styleEmphasis: styleEmphasis,
  61576. visual: visual,
  61577. barLayout: barLayout,
  61578. currentSeriesIndices: currentSeriesIndices,
  61579. font: font
  61580. }, prepareResult.api || {});
  61581. var userParams = {
  61582. // The life cycle of context: current round of rendering.
  61583. // The global life cycle is probably not necessary, because
  61584. // user can store global status by themselves.
  61585. context: {},
  61586. seriesId: customSeries.id,
  61587. seriesName: customSeries.name,
  61588. seriesIndex: customSeries.seriesIndex,
  61589. coordSys: prepareResult.coordSys,
  61590. dataInsideLength: data.count(),
  61591. encode: wrapEncodeDef(customSeries.getData())
  61592. };
  61593. // Do not support call `api` asynchronously without dataIndexInside input.
  61594. var currDataIndexInside;
  61595. var currDirty = true;
  61596. var currItemModel;
  61597. var currLabelNormalModel;
  61598. var currLabelEmphasisModel;
  61599. var currVisualColor;
  61600. return function (dataIndexInside, payload) {
  61601. currDataIndexInside = dataIndexInside;
  61602. currDirty = true;
  61603. return renderItem && renderItem(
  61604. defaults({
  61605. dataIndexInside: dataIndexInside,
  61606. dataIndex: data.getRawIndex(dataIndexInside),
  61607. // Can be used for optimization when zoom or roam.
  61608. actionType: payload ? payload.type : null
  61609. }, userParams),
  61610. userAPI
  61611. );
  61612. };
  61613. // Do not update cache until api called.
  61614. function updateCache(dataIndexInside) {
  61615. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61616. if (currDirty) {
  61617. currItemModel = data.getItemModel(dataIndexInside);
  61618. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  61619. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  61620. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  61621. currDirty = false;
  61622. }
  61623. }
  61624. /**
  61625. * @public
  61626. * @param {number|string} dim
  61627. * @param {number} [dataIndexInside=currDataIndexInside]
  61628. * @return {number|string} value
  61629. */
  61630. function value(dim, dataIndexInside) {
  61631. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61632. return data.get(data.getDimension(dim || 0), dataIndexInside);
  61633. }
  61634. /**
  61635. * By default, `visual` is applied to style (to support visualMap).
  61636. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  61637. * it can be implemented as:
  61638. * `api.style({stroke: api.visual('color'), fill: null})`;
  61639. * @public
  61640. * @param {Object} [extra]
  61641. * @param {number} [dataIndexInside=currDataIndexInside]
  61642. */
  61643. function style(extra, dataIndexInside) {
  61644. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61645. updateCache(dataIndexInside);
  61646. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  61647. currVisualColor != null && (itemStyle.fill = currVisualColor);
  61648. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  61649. opacity != null && (itemStyle.opacity = opacity);
  61650. setTextStyle(itemStyle, currLabelNormalModel, null, {
  61651. autoColor: currVisualColor,
  61652. isRectText: true
  61653. });
  61654. itemStyle.text = currLabelNormalModel.getShallow('show')
  61655. ? retrieve2(
  61656. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61657. getDefaultLabel(data, dataIndexInside)
  61658. )
  61659. : null;
  61660. extra && extend(itemStyle, extra);
  61661. return itemStyle;
  61662. }
  61663. /**
  61664. * @public
  61665. * @param {Object} [extra]
  61666. * @param {number} [dataIndexInside=currDataIndexInside]
  61667. */
  61668. function styleEmphasis(extra, dataIndexInside) {
  61669. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61670. updateCache(dataIndexInside);
  61671. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  61672. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  61673. isRectText: true
  61674. }, true);
  61675. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  61676. ? retrieve3(
  61677. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  61678. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61679. getDefaultLabel(data, dataIndexInside)
  61680. )
  61681. : null;
  61682. extra && extend(itemStyle, extra);
  61683. return itemStyle;
  61684. }
  61685. /**
  61686. * @public
  61687. * @param {string} visualType
  61688. * @param {number} [dataIndexInside=currDataIndexInside]
  61689. */
  61690. function visual(visualType, dataIndexInside) {
  61691. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61692. return data.getItemVisual(dataIndexInside, visualType);
  61693. }
  61694. /**
  61695. * @public
  61696. * @param {number} opt.count Positive interger.
  61697. * @param {number} [opt.barWidth]
  61698. * @param {number} [opt.barMaxWidth]
  61699. * @param {number} [opt.barGap]
  61700. * @param {number} [opt.barCategoryGap]
  61701. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  61702. */
  61703. function barLayout(opt) {
  61704. if (coordSys.getBaseAxis) {
  61705. var baseAxis = coordSys.getBaseAxis();
  61706. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  61707. }
  61708. }
  61709. /**
  61710. * @public
  61711. * @return {Array.<number>}
  61712. */
  61713. function currentSeriesIndices() {
  61714. return ecModel.getCurrentSeriesIndices();
  61715. }
  61716. /**
  61717. * @public
  61718. * @param {Object} opt
  61719. * @param {string} [opt.fontStyle]
  61720. * @param {number} [opt.fontWeight]
  61721. * @param {number} [opt.fontSize]
  61722. * @param {string} [opt.fontFamily]
  61723. * @return {string} font string
  61724. */
  61725. function font(opt) {
  61726. return getFont(opt, ecModel);
  61727. }
  61728. }
  61729. function wrapEncodeDef(data) {
  61730. var encodeDef = {};
  61731. each$1(data.dimensions, function (dimName, dataDimIndex) {
  61732. var dimInfo = data.getDimensionInfo(dimName);
  61733. if (!dimInfo.isExtraCoord) {
  61734. var coordDim = dimInfo.coordDim;
  61735. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  61736. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  61737. }
  61738. });
  61739. return encodeDef;
  61740. }
  61741. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  61742. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  61743. el && data.setItemGraphicEl(dataIndex, el);
  61744. return el;
  61745. }
  61746. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  61747. // [Rule]
  61748. // By default, follow merge mode.
  61749. // (It probably brings benifit for performance in some cases of large data, where
  61750. // user program can be optimized to that only updated props needed to be re-calculated,
  61751. // or according to `actionType` some calculation can be skipped.)
  61752. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  61753. // (It seems that violate the "merge" principle, but most of users probably intuitively
  61754. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  61755. // most cases.)
  61756. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  61757. elOption = elOption || {};
  61758. var elOptionType = elOption.type;
  61759. var elOptionShape = elOption.shape;
  61760. var elOptionStyle = elOption.style;
  61761. if (el && (
  61762. simplyRemove
  61763. // || elOption.$merge === false
  61764. // If `elOptionType` is `null`, follow the merge principle.
  61765. || (elOptionType != null
  61766. && elOptionType !== el.__customGraphicType
  61767. )
  61768. || (elOptionType === 'path'
  61769. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  61770. )
  61771. || (elOptionType === 'image'
  61772. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  61773. )
  61774. // FIXME test and remove this restriction?
  61775. || (elOptionType === 'text'
  61776. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  61777. )
  61778. )) {
  61779. group.remove(el);
  61780. el = null;
  61781. }
  61782. // `elOption.type` is undefined when `renderItem` returns nothing.
  61783. if (simplyRemove) {
  61784. return;
  61785. }
  61786. var isInit = !el;
  61787. !el && (el = createEl(elOption));
  61788. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  61789. if (elOptionType === 'group') {
  61790. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  61791. }
  61792. // Always add whatever already added to ensure sequence.
  61793. group.add(el);
  61794. return el;
  61795. }
  61796. // Usage:
  61797. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  61798. // the existing children will not be removed, and enables the feature that
  61799. // update some of the props of some of the children simply by construct
  61800. // the returned children of `renderItem` like:
  61801. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  61802. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  61803. // by child.name. But that might be lower performance.
  61804. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  61805. // replaced totally.
  61806. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  61807. //
  61808. // For implementation simpleness, do not provide a direct way to remove sinlge
  61809. // child (otherwise the total indicies of the children array have to be modified).
  61810. // User can remove a single child by set its `ignore` as `true` or replace
  61811. // it by another element, where its `$merge` can be set as `true` if necessary.
  61812. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  61813. var newChildren = elOption.children;
  61814. var newLen = newChildren ? newChildren.length : 0;
  61815. var mergeChildren = elOption.$mergeChildren;
  61816. // `diffChildrenByName` has been deprecated.
  61817. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  61818. var notMerge = mergeChildren === false;
  61819. // For better performance on roam update, only enter if necessary.
  61820. if (!newLen && !byName && !notMerge) {
  61821. return;
  61822. }
  61823. if (byName) {
  61824. diffGroupChildren({
  61825. oldChildren: el.children() || [],
  61826. newChildren: newChildren || [],
  61827. dataIndex: dataIndex,
  61828. animatableModel: animatableModel,
  61829. group: el,
  61830. data: data
  61831. });
  61832. return;
  61833. }
  61834. notMerge && el.removeAll();
  61835. // Mapping children of a group simply by index, which
  61836. // might be better performance.
  61837. var index = 0;
  61838. for (; index < newLen; index++) {
  61839. newChildren[index] && doCreateOrUpdate(
  61840. el.childAt(index),
  61841. dataIndex,
  61842. newChildren[index],
  61843. animatableModel,
  61844. el,
  61845. data
  61846. );
  61847. }
  61848. if (__DEV__) {
  61849. assert$1(
  61850. !notMerge || el.childCount() === index,
  61851. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  61852. );
  61853. }
  61854. }
  61855. function diffGroupChildren(context) {
  61856. (new DataDiffer(
  61857. context.oldChildren,
  61858. context.newChildren,
  61859. getKey,
  61860. getKey,
  61861. context
  61862. ))
  61863. .add(processAddUpdate)
  61864. .update(processAddUpdate)
  61865. .remove(processRemove)
  61866. .execute();
  61867. }
  61868. function getKey(item, idx) {
  61869. var name = item && item.name;
  61870. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  61871. }
  61872. function processAddUpdate(newIndex, oldIndex) {
  61873. var context = this.context;
  61874. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  61875. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  61876. doCreateOrUpdate(
  61877. child,
  61878. context.dataIndex,
  61879. childOption,
  61880. context.animatableModel,
  61881. context.group,
  61882. context.data
  61883. );
  61884. }
  61885. function processRemove(oldIndex) {
  61886. var context = this.context;
  61887. var child = context.oldChildren[oldIndex];
  61888. child && context.group.remove(child);
  61889. }
  61890. function getPathData(shape) {
  61891. // "d" follows the SVG convention.
  61892. return shape && (shape.pathData || shape.d);
  61893. }
  61894. function hasOwnPathData(shape) {
  61895. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  61896. }
  61897. function hasOwn(host, prop) {
  61898. return host && host.hasOwnProperty(prop);
  61899. }
  61900. /*
  61901. * Licensed to the Apache Software Foundation (ASF) under one
  61902. * or more contributor license agreements. See the NOTICE file
  61903. * distributed with this work for additional information
  61904. * regarding copyright ownership. The ASF licenses this file
  61905. * to you under the Apache License, Version 2.0 (the
  61906. * "License"); you may not use this file except in compliance
  61907. * with the License. You may obtain a copy of the License at
  61908. *
  61909. * http://www.apache.org/licenses/LICENSE-2.0
  61910. *
  61911. * Unless required by applicable law or agreed to in writing,
  61912. * software distributed under the License is distributed on an
  61913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61914. * KIND, either express or implied. See the License for the
  61915. * specific language governing permissions and limitations
  61916. * under the License.
  61917. */
  61918. // -------------
  61919. // Preprocessor
  61920. // -------------
  61921. registerPreprocessor(function (option) {
  61922. var graphicOption = option.graphic;
  61923. // Convert
  61924. // {graphic: [{left: 10, type: 'circle'}, ...]}
  61925. // or
  61926. // {graphic: {left: 10, type: 'circle'}}
  61927. // to
  61928. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  61929. if (isArray(graphicOption)) {
  61930. if (!graphicOption[0] || !graphicOption[0].elements) {
  61931. option.graphic = [{elements: graphicOption}];
  61932. }
  61933. else {
  61934. // Only one graphic instance can be instantiated. (We dont
  61935. // want that too many views are created in echarts._viewMap)
  61936. option.graphic = [option.graphic[0]];
  61937. }
  61938. }
  61939. else if (graphicOption && !graphicOption.elements) {
  61940. option.graphic = [{elements: [graphicOption]}];
  61941. }
  61942. });
  61943. // ------
  61944. // Model
  61945. // ------
  61946. var GraphicModel = extendComponentModel({
  61947. type: 'graphic',
  61948. defaultOption: {
  61949. // Extra properties for each elements:
  61950. //
  61951. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  61952. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  61953. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  61954. // This mechanism is useful when you want to position a group/element
  61955. // against the right side or the center of this container.
  61956. //
  61957. // width/height: (can only be pixel value, default 0)
  61958. // Only be used to specify contianer(group) size, if needed. And
  61959. // can not be percentage value (like '33%'). See the reason in the
  61960. // layout algorithm below.
  61961. //
  61962. // bounding: (enum: 'all' (default) | 'raw')
  61963. // Specify how to calculate boundingRect when locating.
  61964. // 'all': Get uioned and transformed boundingRect
  61965. // from both itself and its descendants.
  61966. // This mode simplies confining a group of elements in the bounding
  61967. // of their ancester container (e.g., using 'right: 0').
  61968. // 'raw': Only use the boundingRect of itself and before transformed.
  61969. // This mode is similar to css behavior, which is useful when you
  61970. // want an element to be able to overflow its container. (Consider
  61971. // a rotated circle needs to be located in a corner.)
  61972. // info: custom info. enables user to mount some info on elements and use them
  61973. // in event handlers. Update them only when user specified, otherwise, remain.
  61974. // Note: elements is always behind its ancestors in this elements array.
  61975. elements: [],
  61976. parentId: null
  61977. },
  61978. /**
  61979. * Save el options for the sake of the performance (only update modified graphics).
  61980. * The order is the same as those in option. (ancesters -> descendants)
  61981. *
  61982. * @private
  61983. * @type {Array.<Object>}
  61984. */
  61985. _elOptionsToUpdate: null,
  61986. /**
  61987. * @override
  61988. */
  61989. mergeOption: function (option) {
  61990. // Prevent default merge to elements
  61991. var elements = this.option.elements;
  61992. this.option.elements = null;
  61993. GraphicModel.superApply(this, 'mergeOption', arguments);
  61994. this.option.elements = elements;
  61995. },
  61996. /**
  61997. * @override
  61998. */
  61999. optionUpdated: function (newOption, isInit) {
  62000. var thisOption = this.option;
  62001. var newList = (isInit ? thisOption : newOption).elements;
  62002. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  62003. var flattenedList = [];
  62004. this._flatten(newList, flattenedList);
  62005. var mappingResult = mappingToExists(existList, flattenedList);
  62006. makeIdAndName(mappingResult);
  62007. // Clear elOptionsToUpdate
  62008. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  62009. each$1(mappingResult, function (resultItem, index) {
  62010. var newElOption = resultItem.option;
  62011. if (__DEV__) {
  62012. assert$1(
  62013. isObject$1(newElOption) || resultItem.exist,
  62014. 'Empty graphic option definition'
  62015. );
  62016. }
  62017. if (!newElOption) {
  62018. return;
  62019. }
  62020. elOptionsToUpdate.push(newElOption);
  62021. setKeyInfoToNewElOption(resultItem, newElOption);
  62022. mergeNewElOptionToExist(existList, index, newElOption);
  62023. setLayoutInfoToExist(existList[index], newElOption);
  62024. }, this);
  62025. // Clean
  62026. for (var i = existList.length - 1; i >= 0; i--) {
  62027. if (existList[i] == null) {
  62028. existList.splice(i, 1);
  62029. }
  62030. else {
  62031. // $action should be volatile, otherwise option gotten from
  62032. // `getOption` will contain unexpected $action.
  62033. delete existList[i].$action;
  62034. }
  62035. }
  62036. },
  62037. /**
  62038. * Convert
  62039. * [{
  62040. * type: 'group',
  62041. * id: 'xx',
  62042. * children: [{type: 'circle'}, {type: 'polygon'}]
  62043. * }]
  62044. * to
  62045. * [
  62046. * {type: 'group', id: 'xx'},
  62047. * {type: 'circle', parentId: 'xx'},
  62048. * {type: 'polygon', parentId: 'xx'}
  62049. * ]
  62050. *
  62051. * @private
  62052. * @param {Array.<Object>} optionList option list
  62053. * @param {Array.<Object>} result result of flatten
  62054. * @param {Object} parentOption parent option
  62055. */
  62056. _flatten: function (optionList, result, parentOption) {
  62057. each$1(optionList, function (option) {
  62058. if (!option) {
  62059. return;
  62060. }
  62061. if (parentOption) {
  62062. option.parentOption = parentOption;
  62063. }
  62064. result.push(option);
  62065. var children = option.children;
  62066. if (option.type === 'group' && children) {
  62067. this._flatten(children, result, option);
  62068. }
  62069. // Deleting for JSON output, and for not affecting group creation.
  62070. delete option.children;
  62071. }, this);
  62072. },
  62073. // FIXME
  62074. // Pass to view using payload? setOption has a payload?
  62075. useElOptionsToUpdate: function () {
  62076. var els = this._elOptionsToUpdate;
  62077. // Clear to avoid render duplicately when zooming.
  62078. this._elOptionsToUpdate = null;
  62079. return els;
  62080. }
  62081. });
  62082. // -----
  62083. // View
  62084. // -----
  62085. extendComponentView({
  62086. type: 'graphic',
  62087. /**
  62088. * @override
  62089. */
  62090. init: function (ecModel, api) {
  62091. /**
  62092. * @private
  62093. * @type {module:zrender/core/util.HashMap}
  62094. */
  62095. this._elMap = createHashMap();
  62096. /**
  62097. * @private
  62098. * @type {module:echarts/graphic/GraphicModel}
  62099. */
  62100. this._lastGraphicModel;
  62101. },
  62102. /**
  62103. * @override
  62104. */
  62105. render: function (graphicModel, ecModel, api) {
  62106. // Having leveraged between use cases and algorithm complexity, a very
  62107. // simple layout mechanism is used:
  62108. // The size(width/height) can be determined by itself or its parent (not
  62109. // implemented yet), but can not by its children. (Top-down travel)
  62110. // The location(x/y) can be determined by the bounding rect of itself
  62111. // (can including its descendants or not) and the size of its parent.
  62112. // (Bottom-up travel)
  62113. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  62114. // view will be reused.
  62115. if (graphicModel !== this._lastGraphicModel) {
  62116. this._clear();
  62117. }
  62118. this._lastGraphicModel = graphicModel;
  62119. this._updateElements(graphicModel);
  62120. this._relocate(graphicModel, api);
  62121. },
  62122. /**
  62123. * Update graphic elements.
  62124. *
  62125. * @private
  62126. * @param {Object} graphicModel graphic model
  62127. */
  62128. _updateElements: function (graphicModel) {
  62129. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  62130. if (!elOptionsToUpdate) {
  62131. return;
  62132. }
  62133. var elMap = this._elMap;
  62134. var rootGroup = this.group;
  62135. // Top-down tranverse to assign graphic settings to each elements.
  62136. each$1(elOptionsToUpdate, function (elOption) {
  62137. var $action = elOption.$action;
  62138. var id = elOption.id;
  62139. var existEl = elMap.get(id);
  62140. var parentId = elOption.parentId;
  62141. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  62142. var elOptionStyle = elOption.style;
  62143. if (elOption.type === 'text' && elOptionStyle) {
  62144. // In top/bottom mode, textVerticalAlign should not be used, which cause
  62145. // inaccurately locating.
  62146. if (elOption.hv && elOption.hv[1]) {
  62147. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  62148. }
  62149. // Compatible with previous setting: both support fill and textFill,
  62150. // stroke and textStroke.
  62151. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  62152. elOptionStyle.textFill = elOptionStyle.fill
  62153. );
  62154. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  62155. elOptionStyle.textStroke = elOptionStyle.stroke
  62156. );
  62157. }
  62158. // Remove unnecessary props to avoid potential problems.
  62159. var elOptionCleaned = getCleanedElOption(elOption);
  62160. // For simple, do not support parent change, otherwise reorder is needed.
  62161. if (__DEV__) {
  62162. existEl && assert$1(
  62163. targetElParent === existEl.parent,
  62164. 'Changing parent is not supported.'
  62165. );
  62166. }
  62167. if (!$action || $action === 'merge') {
  62168. existEl
  62169. ? existEl.attr(elOptionCleaned)
  62170. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  62171. }
  62172. else if ($action === 'replace') {
  62173. removeEl(existEl, elMap);
  62174. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  62175. }
  62176. else if ($action === 'remove') {
  62177. removeEl(existEl, elMap);
  62178. }
  62179. var el = elMap.get(id);
  62180. if (el) {
  62181. el.__ecGraphicWidth = elOption.width;
  62182. el.__ecGraphicHeight = elOption.height;
  62183. setEventData(el, graphicModel, elOption);
  62184. }
  62185. });
  62186. },
  62187. /**
  62188. * Locate graphic elements.
  62189. *
  62190. * @private
  62191. * @param {Object} graphicModel graphic model
  62192. * @param {module:echarts/ExtensionAPI} api extension API
  62193. */
  62194. _relocate: function (graphicModel, api) {
  62195. var elOptions = graphicModel.option.elements;
  62196. var rootGroup = this.group;
  62197. var elMap = this._elMap;
  62198. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  62199. for (var i = elOptions.length - 1; i >= 0; i--) {
  62200. var elOption = elOptions[i];
  62201. var el = elMap.get(elOption.id);
  62202. if (!el) {
  62203. continue;
  62204. }
  62205. var parentEl = el.parent;
  62206. var containerInfo = parentEl === rootGroup
  62207. ? {
  62208. width: api.getWidth(),
  62209. height: api.getHeight()
  62210. }
  62211. : { // Like 'position:absolut' in css, default 0.
  62212. width: parentEl.__ecGraphicWidth || 0,
  62213. height: parentEl.__ecGraphicHeight || 0
  62214. };
  62215. positionElement(
  62216. el, elOption, containerInfo, null,
  62217. {hv: elOption.hv, boundingMode: elOption.bounding}
  62218. );
  62219. }
  62220. },
  62221. /**
  62222. * Clear all elements.
  62223. *
  62224. * @private
  62225. */
  62226. _clear: function () {
  62227. var elMap = this._elMap;
  62228. elMap.each(function (el) {
  62229. removeEl(el, elMap);
  62230. });
  62231. this._elMap = createHashMap();
  62232. },
  62233. /**
  62234. * @override
  62235. */
  62236. dispose: function () {
  62237. this._clear();
  62238. }
  62239. });
  62240. function createEl$1(id, targetElParent, elOption, elMap) {
  62241. var graphicType = elOption.type;
  62242. if (__DEV__) {
  62243. assert$1(graphicType, 'graphic type MUST be set');
  62244. }
  62245. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  62246. if (__DEV__) {
  62247. assert$1(Clz, 'graphic type can not be found');
  62248. }
  62249. var el = new Clz(elOption);
  62250. targetElParent.add(el);
  62251. elMap.set(id, el);
  62252. el.__ecGraphicId = id;
  62253. }
  62254. function removeEl(existEl, elMap) {
  62255. var existElParent = existEl && existEl.parent;
  62256. if (existElParent) {
  62257. existEl.type === 'group' && existEl.traverse(function (el) {
  62258. removeEl(el, elMap);
  62259. });
  62260. elMap.removeKey(existEl.__ecGraphicId);
  62261. existElParent.remove(existEl);
  62262. }
  62263. }
  62264. // Remove unnecessary props to avoid potential problems.
  62265. function getCleanedElOption(elOption) {
  62266. elOption = extend({}, elOption);
  62267. each$1(
  62268. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  62269. function (name) {
  62270. delete elOption[name];
  62271. }
  62272. );
  62273. return elOption;
  62274. }
  62275. function isSetLoc(obj, props) {
  62276. var isSet;
  62277. each$1(props, function (prop) {
  62278. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  62279. });
  62280. return isSet;
  62281. }
  62282. function setKeyInfoToNewElOption(resultItem, newElOption) {
  62283. var existElOption = resultItem.exist;
  62284. // Set id and type after id assigned.
  62285. newElOption.id = resultItem.keyInfo.id;
  62286. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  62287. // Set parent id if not specified
  62288. if (newElOption.parentId == null) {
  62289. var newElParentOption = newElOption.parentOption;
  62290. if (newElParentOption) {
  62291. newElOption.parentId = newElParentOption.id;
  62292. }
  62293. else if (existElOption) {
  62294. newElOption.parentId = existElOption.parentId;
  62295. }
  62296. }
  62297. // Clear
  62298. newElOption.parentOption = null;
  62299. }
  62300. function mergeNewElOptionToExist(existList, index, newElOption) {
  62301. // Update existing options, for `getOption` feature.
  62302. var newElOptCopy = extend({}, newElOption);
  62303. var existElOption = existList[index];
  62304. var $action = newElOption.$action || 'merge';
  62305. if ($action === 'merge') {
  62306. if (existElOption) {
  62307. if (__DEV__) {
  62308. var newType = newElOption.type;
  62309. assert$1(
  62310. !newType || existElOption.type === newType,
  62311. 'Please set $action: "replace" to change `type`'
  62312. );
  62313. }
  62314. // We can ensure that newElOptCopy and existElOption are not
  62315. // the same object, so `merge` will not change newElOptCopy.
  62316. merge(existElOption, newElOptCopy, true);
  62317. // Rigid body, use ignoreSize.
  62318. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  62319. // Will be used in render.
  62320. copyLayoutParams(newElOption, existElOption);
  62321. }
  62322. else {
  62323. existList[index] = newElOptCopy;
  62324. }
  62325. }
  62326. else if ($action === 'replace') {
  62327. existList[index] = newElOptCopy;
  62328. }
  62329. else if ($action === 'remove') {
  62330. // null will be cleaned later.
  62331. existElOption && (existList[index] = null);
  62332. }
  62333. }
  62334. function setLayoutInfoToExist(existItem, newElOption) {
  62335. if (!existItem) {
  62336. return;
  62337. }
  62338. existItem.hv = newElOption.hv = [
  62339. // Rigid body, dont care `width`.
  62340. isSetLoc(newElOption, ['left', 'right']),
  62341. // Rigid body, dont care `height`.
  62342. isSetLoc(newElOption, ['top', 'bottom'])
  62343. ];
  62344. // Give default group size. Otherwise layout error may occur.
  62345. if (existItem.type === 'group') {
  62346. existItem.width == null && (existItem.width = newElOption.width = 0);
  62347. existItem.height == null && (existItem.height = newElOption.height = 0);
  62348. }
  62349. }
  62350. function setEventData(el, graphicModel, elOption) {
  62351. var eventData = el.eventData;
  62352. // Simple optimize for large amount of elements that no need event.
  62353. if (!el.silent && !el.ignore && !eventData) {
  62354. eventData = el.eventData = {
  62355. componentType: 'graphic',
  62356. componentIndex: graphicModel.componentIndex,
  62357. name: el.name
  62358. };
  62359. }
  62360. // `elOption.info` enables user to mount some info on
  62361. // elements and use them in event handlers.
  62362. if (eventData) {
  62363. eventData.info = el.info;
  62364. }
  62365. }
  62366. /*
  62367. * Licensed to the Apache Software Foundation (ASF) under one
  62368. * or more contributor license agreements. See the NOTICE file
  62369. * distributed with this work for additional information
  62370. * regarding copyright ownership. The ASF licenses this file
  62371. * to you under the Apache License, Version 2.0 (the
  62372. * "License"); you may not use this file except in compliance
  62373. * with the License. You may obtain a copy of the License at
  62374. *
  62375. * http://www.apache.org/licenses/LICENSE-2.0
  62376. *
  62377. * Unless required by applicable law or agreed to in writing,
  62378. * software distributed under the License is distributed on an
  62379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62380. * KIND, either express or implied. See the License for the
  62381. * specific language governing permissions and limitations
  62382. * under the License.
  62383. */
  62384. /*
  62385. * Licensed to the Apache Software Foundation (ASF) under one
  62386. * or more contributor license agreements. See the NOTICE file
  62387. * distributed with this work for additional information
  62388. * regarding copyright ownership. The ASF licenses this file
  62389. * to you under the Apache License, Version 2.0 (the
  62390. * "License"); you may not use this file except in compliance
  62391. * with the License. You may obtain a copy of the License at
  62392. *
  62393. * http://www.apache.org/licenses/LICENSE-2.0
  62394. *
  62395. * Unless required by applicable law or agreed to in writing,
  62396. * software distributed under the License is distributed on an
  62397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62398. * KIND, either express or implied. See the License for the
  62399. * specific language governing permissions and limitations
  62400. * under the License.
  62401. */
  62402. var LegendModel = extendComponentModel({
  62403. type: 'legend.plain',
  62404. dependencies: ['series'],
  62405. layoutMode: {
  62406. type: 'box',
  62407. // legend.width/height are maxWidth/maxHeight actually,
  62408. // whereas realy width/height is calculated by its content.
  62409. // (Setting {left: 10, right: 10} does not make sense).
  62410. // So consider the case:
  62411. // `setOption({legend: {left: 10});`
  62412. // then `setOption({legend: {right: 10});`
  62413. // The previous `left` should be cleared by setting `ignoreSize`.
  62414. ignoreSize: true
  62415. },
  62416. init: function (option, parentModel, ecModel) {
  62417. this.mergeDefaultAndTheme(option, ecModel);
  62418. option.selected = option.selected || {};
  62419. },
  62420. mergeOption: function (option) {
  62421. LegendModel.superCall(this, 'mergeOption', option);
  62422. },
  62423. optionUpdated: function () {
  62424. this._updateData(this.ecModel);
  62425. var legendData = this._data;
  62426. // If selectedMode is single, try to select one
  62427. if (legendData[0] && this.get('selectedMode') === 'single') {
  62428. var hasSelected = false;
  62429. // If has any selected in option.selected
  62430. for (var i = 0; i < legendData.length; i++) {
  62431. var name = legendData[i].get('name');
  62432. if (this.isSelected(name)) {
  62433. // Force to unselect others
  62434. this.select(name);
  62435. hasSelected = true;
  62436. break;
  62437. }
  62438. }
  62439. // Try select the first if selectedMode is single
  62440. !hasSelected && this.select(legendData[0].get('name'));
  62441. }
  62442. },
  62443. _updateData: function (ecModel) {
  62444. var potentialData = [];
  62445. var availableNames = [];
  62446. ecModel.eachRawSeries(function (seriesModel) {
  62447. var seriesName = seriesModel.name;
  62448. availableNames.push(seriesName);
  62449. var isPotential;
  62450. if (seriesModel.legendDataProvider) {
  62451. var data = seriesModel.legendDataProvider();
  62452. var names = data.mapArray(data.getName);
  62453. if (!ecModel.isSeriesFiltered(seriesModel)) {
  62454. availableNames = availableNames.concat(names);
  62455. }
  62456. if (names.length) {
  62457. potentialData = potentialData.concat(names);
  62458. }
  62459. else {
  62460. isPotential = true;
  62461. }
  62462. }
  62463. else {
  62464. isPotential = true;
  62465. }
  62466. if (isPotential && isNameSpecified(seriesModel)) {
  62467. potentialData.push(seriesModel.name);
  62468. }
  62469. });
  62470. /**
  62471. * @type {Array.<string>}
  62472. * @private
  62473. */
  62474. this._availableNames = availableNames;
  62475. // If legend.data not specified in option, use availableNames as data,
  62476. // which is convinient for user preparing option.
  62477. var rawData = this.get('data') || potentialData;
  62478. var legendData = map(rawData, function (dataItem) {
  62479. // Can be string or number
  62480. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  62481. dataItem = {
  62482. name: dataItem
  62483. };
  62484. }
  62485. return new Model(dataItem, this, this.ecModel);
  62486. }, this);
  62487. /**
  62488. * @type {Array.<module:echarts/model/Model>}
  62489. * @private
  62490. */
  62491. this._data = legendData;
  62492. },
  62493. /**
  62494. * @return {Array.<module:echarts/model/Model>}
  62495. */
  62496. getData: function () {
  62497. return this._data;
  62498. },
  62499. /**
  62500. * @param {string} name
  62501. */
  62502. select: function (name) {
  62503. var selected = this.option.selected;
  62504. var selectedMode = this.get('selectedMode');
  62505. if (selectedMode === 'single') {
  62506. var data = this._data;
  62507. each$1(data, function (dataItem) {
  62508. selected[dataItem.get('name')] = false;
  62509. });
  62510. }
  62511. selected[name] = true;
  62512. },
  62513. /**
  62514. * @param {string} name
  62515. */
  62516. unSelect: function (name) {
  62517. if (this.get('selectedMode') !== 'single') {
  62518. this.option.selected[name] = false;
  62519. }
  62520. },
  62521. /**
  62522. * @param {string} name
  62523. */
  62524. toggleSelected: function (name) {
  62525. var selected = this.option.selected;
  62526. // Default is true
  62527. if (!selected.hasOwnProperty(name)) {
  62528. selected[name] = true;
  62529. }
  62530. this[selected[name] ? 'unSelect' : 'select'](name);
  62531. },
  62532. /**
  62533. * @param {string} name
  62534. */
  62535. isSelected: function (name) {
  62536. var selected = this.option.selected;
  62537. return !(selected.hasOwnProperty(name) && !selected[name])
  62538. && indexOf(this._availableNames, name) >= 0;
  62539. },
  62540. defaultOption: {
  62541. // 一级层叠
  62542. zlevel: 0,
  62543. // 二级层叠
  62544. z: 4,
  62545. show: true,
  62546. // 布局方式,默认为水平布局,可选为:
  62547. // 'horizontal' | 'vertical'
  62548. orient: 'horizontal',
  62549. left: 'center',
  62550. // right: 'center',
  62551. top: 0,
  62552. // bottom: null,
  62553. // 水平对齐
  62554. // 'auto' | 'left' | 'right'
  62555. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  62556. align: 'auto',
  62557. backgroundColor: 'rgba(0,0,0,0)',
  62558. // 图例边框颜色
  62559. borderColor: '#ccc',
  62560. borderRadius: 0,
  62561. // 图例边框线宽,单位px,默认为0(无边框)
  62562. borderWidth: 0,
  62563. // 图例内边距,单位px,默认各方向内边距为5,
  62564. // 接受数组分别设定上右下左边距,同css
  62565. padding: 5,
  62566. // 各个item之间的间隔,单位px,默认为10,
  62567. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  62568. itemGap: 10,
  62569. // 图例图形宽度
  62570. itemWidth: 25,
  62571. // 图例图形高度
  62572. itemHeight: 14,
  62573. // 图例关闭时候的颜色
  62574. inactiveColor: '#ccc',
  62575. textStyle: {
  62576. // 图例文字颜色
  62577. color: '#333'
  62578. },
  62579. // formatter: '',
  62580. // 选择模式,默认开启图例开关
  62581. selectedMode: true,
  62582. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  62583. // selected: null,
  62584. // 图例内容(详见legend.data,数组中每一项代表一个item
  62585. // data: [],
  62586. // Tooltip 相关配置
  62587. tooltip: {
  62588. show: false
  62589. }
  62590. }
  62591. });
  62592. /*
  62593. * Licensed to the Apache Software Foundation (ASF) under one
  62594. * or more contributor license agreements. See the NOTICE file
  62595. * distributed with this work for additional information
  62596. * regarding copyright ownership. The ASF licenses this file
  62597. * to you under the Apache License, Version 2.0 (the
  62598. * "License"); you may not use this file except in compliance
  62599. * with the License. You may obtain a copy of the License at
  62600. *
  62601. * http://www.apache.org/licenses/LICENSE-2.0
  62602. *
  62603. * Unless required by applicable law or agreed to in writing,
  62604. * software distributed under the License is distributed on an
  62605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62606. * KIND, either express or implied. See the License for the
  62607. * specific language governing permissions and limitations
  62608. * under the License.
  62609. */
  62610. function legendSelectActionHandler(methodName, payload, ecModel) {
  62611. var selectedMap = {};
  62612. var isToggleSelect = methodName === 'toggleSelected';
  62613. var isSelected;
  62614. // Update all legend components
  62615. ecModel.eachComponent('legend', function (legendModel) {
  62616. if (isToggleSelect && isSelected != null) {
  62617. // Force other legend has same selected status
  62618. // Or the first is toggled to true and other are toggled to false
  62619. // In the case one legend has some item unSelected in option. And if other legend
  62620. // doesn't has the item, they will assume it is selected.
  62621. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  62622. }
  62623. else {
  62624. legendModel[methodName](payload.name);
  62625. isSelected = legendModel.isSelected(payload.name);
  62626. }
  62627. var legendData = legendModel.getData();
  62628. each$1(legendData, function (model) {
  62629. var name = model.get('name');
  62630. // Wrap element
  62631. if (name === '\n' || name === '') {
  62632. return;
  62633. }
  62634. var isItemSelected = legendModel.isSelected(name);
  62635. if (selectedMap.hasOwnProperty(name)) {
  62636. // Unselected if any legend is unselected
  62637. selectedMap[name] = selectedMap[name] && isItemSelected;
  62638. }
  62639. else {
  62640. selectedMap[name] = isItemSelected;
  62641. }
  62642. });
  62643. });
  62644. // Return the event explicitly
  62645. return {
  62646. name: payload.name,
  62647. selected: selectedMap
  62648. };
  62649. }
  62650. /**
  62651. * @event legendToggleSelect
  62652. * @type {Object}
  62653. * @property {string} type 'legendToggleSelect'
  62654. * @property {string} [from]
  62655. * @property {string} name Series name or data item name
  62656. */
  62657. registerAction(
  62658. 'legendToggleSelect', 'legendselectchanged',
  62659. curry(legendSelectActionHandler, 'toggleSelected')
  62660. );
  62661. /**
  62662. * @event legendSelect
  62663. * @type {Object}
  62664. * @property {string} type 'legendSelect'
  62665. * @property {string} name Series name or data item name
  62666. */
  62667. registerAction(
  62668. 'legendSelect', 'legendselected',
  62669. curry(legendSelectActionHandler, 'select')
  62670. );
  62671. /**
  62672. * @event legendUnSelect
  62673. * @type {Object}
  62674. * @property {string} type 'legendUnSelect'
  62675. * @property {string} name Series name or data item name
  62676. */
  62677. registerAction(
  62678. 'legendUnSelect', 'legendunselected',
  62679. curry(legendSelectActionHandler, 'unSelect')
  62680. );
  62681. /*
  62682. * Licensed to the Apache Software Foundation (ASF) under one
  62683. * or more contributor license agreements. See the NOTICE file
  62684. * distributed with this work for additional information
  62685. * regarding copyright ownership. The ASF licenses this file
  62686. * to you under the Apache License, Version 2.0 (the
  62687. * "License"); you may not use this file except in compliance
  62688. * with the License. You may obtain a copy of the License at
  62689. *
  62690. * http://www.apache.org/licenses/LICENSE-2.0
  62691. *
  62692. * Unless required by applicable law or agreed to in writing,
  62693. * software distributed under the License is distributed on an
  62694. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62695. * KIND, either express or implied. See the License for the
  62696. * specific language governing permissions and limitations
  62697. * under the License.
  62698. */
  62699. /**
  62700. * Layout list like component.
  62701. * It will box layout each items in group of component and then position the whole group in the viewport
  62702. * @param {module:zrender/group/Group} group
  62703. * @param {module:echarts/model/Component} componentModel
  62704. * @param {module:echarts/ExtensionAPI}
  62705. */
  62706. function layout$3(group, componentModel, api) {
  62707. var boxLayoutParams = componentModel.getBoxLayoutParams();
  62708. var padding = componentModel.get('padding');
  62709. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62710. var rect = getLayoutRect(
  62711. boxLayoutParams,
  62712. viewportSize,
  62713. padding
  62714. );
  62715. box(
  62716. componentModel.get('orient'),
  62717. group,
  62718. componentModel.get('itemGap'),
  62719. rect.width,
  62720. rect.height
  62721. );
  62722. positionElement(
  62723. group,
  62724. boxLayoutParams,
  62725. viewportSize,
  62726. padding
  62727. );
  62728. }
  62729. function makeBackground(rect, componentModel) {
  62730. var padding = normalizeCssArray$1(
  62731. componentModel.get('padding')
  62732. );
  62733. var style = componentModel.getItemStyle(['color', 'opacity']);
  62734. style.fill = componentModel.get('backgroundColor');
  62735. var rect = new Rect({
  62736. shape: {
  62737. x: rect.x - padding[3],
  62738. y: rect.y - padding[0],
  62739. width: rect.width + padding[1] + padding[3],
  62740. height: rect.height + padding[0] + padding[2],
  62741. r: componentModel.get('borderRadius')
  62742. },
  62743. style: style,
  62744. silent: true,
  62745. z2: -1
  62746. });
  62747. // FIXME
  62748. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  62749. // and background rect when setting like `left: 0`, `top: 0`.
  62750. // graphic.subPixelOptimizeRect(rect);
  62751. return rect;
  62752. }
  62753. /*
  62754. * Licensed to the Apache Software Foundation (ASF) under one
  62755. * or more contributor license agreements. See the NOTICE file
  62756. * distributed with this work for additional information
  62757. * regarding copyright ownership. The ASF licenses this file
  62758. * to you under the Apache License, Version 2.0 (the
  62759. * "License"); you may not use this file except in compliance
  62760. * with the License. You may obtain a copy of the License at
  62761. *
  62762. * http://www.apache.org/licenses/LICENSE-2.0
  62763. *
  62764. * Unless required by applicable law or agreed to in writing,
  62765. * software distributed under the License is distributed on an
  62766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62767. * KIND, either express or implied. See the License for the
  62768. * specific language governing permissions and limitations
  62769. * under the License.
  62770. */
  62771. var curry$4 = curry;
  62772. var each$16 = each$1;
  62773. var Group$3 = Group;
  62774. var LegendView = extendComponentView({
  62775. type: 'legend.plain',
  62776. newlineDisabled: false,
  62777. /**
  62778. * @override
  62779. */
  62780. init: function () {
  62781. /**
  62782. * @private
  62783. * @type {module:zrender/container/Group}
  62784. */
  62785. this.group.add(this._contentGroup = new Group$3());
  62786. /**
  62787. * @private
  62788. * @type {module:zrender/Element}
  62789. */
  62790. this._backgroundEl;
  62791. /**
  62792. * If first rendering, `contentGroup.position` is [0, 0], which
  62793. * does not make sense and may cause unexepcted animation if adopted.
  62794. * @private
  62795. * @type {boolean}
  62796. */
  62797. this._isFirstRender = true;
  62798. },
  62799. /**
  62800. * @protected
  62801. */
  62802. getContentGroup: function () {
  62803. return this._contentGroup;
  62804. },
  62805. /**
  62806. * @override
  62807. */
  62808. render: function (legendModel, ecModel, api) {
  62809. var isFirstRender = this._isFirstRender;
  62810. this._isFirstRender = false;
  62811. this.resetInner();
  62812. if (!legendModel.get('show', true)) {
  62813. return;
  62814. }
  62815. var itemAlign = legendModel.get('align');
  62816. if (!itemAlign || itemAlign === 'auto') {
  62817. itemAlign = (
  62818. legendModel.get('left') === 'right'
  62819. && legendModel.get('orient') === 'vertical'
  62820. ) ? 'right' : 'left';
  62821. }
  62822. this.renderInner(itemAlign, legendModel, ecModel, api);
  62823. // Perform layout.
  62824. var positionInfo = legendModel.getBoxLayoutParams();
  62825. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62826. var padding = legendModel.get('padding');
  62827. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  62828. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender);
  62829. // Place mainGroup, based on the calculated `mainRect`.
  62830. var layoutRect = getLayoutRect(
  62831. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  62832. viewportSize,
  62833. padding
  62834. );
  62835. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  62836. // Render background after group is layout.
  62837. this.group.add(
  62838. this._backgroundEl = makeBackground(mainRect, legendModel)
  62839. );
  62840. },
  62841. /**
  62842. * @protected
  62843. */
  62844. resetInner: function () {
  62845. this.getContentGroup().removeAll();
  62846. this._backgroundEl && this.group.remove(this._backgroundEl);
  62847. },
  62848. /**
  62849. * @protected
  62850. */
  62851. renderInner: function (itemAlign, legendModel, ecModel, api) {
  62852. var contentGroup = this.getContentGroup();
  62853. var legendDrawnMap = createHashMap();
  62854. var selectMode = legendModel.get('selectedMode');
  62855. var excludeSeriesId = [];
  62856. ecModel.eachRawSeries(function (seriesModel) {
  62857. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  62858. });
  62859. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  62860. var name = itemModel.get('name');
  62861. // Use empty string or \n as a newline string
  62862. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  62863. contentGroup.add(new Group$3({
  62864. newline: true
  62865. }));
  62866. return;
  62867. }
  62868. // Representitive series.
  62869. var seriesModel = ecModel.getSeriesByName(name)[0];
  62870. if (legendDrawnMap.get(name)) {
  62871. // Have been drawed
  62872. return;
  62873. }
  62874. // Series legend
  62875. if (seriesModel) {
  62876. var data = seriesModel.getData();
  62877. var color = data.getVisual('color');
  62878. // If color is a callback function
  62879. if (typeof color === 'function') {
  62880. // Use the first data
  62881. color = color(seriesModel.getDataParams(0));
  62882. }
  62883. // Using rect symbol defaultly
  62884. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  62885. var symbolType = data.getVisual('symbol');
  62886. var itemGroup = this._createItem(
  62887. name, dataIndex, itemModel, legendModel,
  62888. legendSymbolType, symbolType,
  62889. itemAlign, color,
  62890. selectMode
  62891. );
  62892. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62893. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  62894. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  62895. legendDrawnMap.set(name, true);
  62896. }
  62897. else {
  62898. // Data legend of pie, funnel
  62899. ecModel.eachRawSeries(function (seriesModel) {
  62900. // In case multiple series has same data name
  62901. if (legendDrawnMap.get(name)) {
  62902. return;
  62903. }
  62904. if (seriesModel.legendDataProvider) {
  62905. var data = seriesModel.legendDataProvider();
  62906. var idx = data.indexOfName(name);
  62907. if (idx < 0) {
  62908. return;
  62909. }
  62910. var color = data.getItemVisual(idx, 'color');
  62911. var legendSymbolType = 'roundRect';
  62912. var itemGroup = this._createItem(
  62913. name, dataIndex, itemModel, legendModel,
  62914. legendSymbolType, null,
  62915. itemAlign, color,
  62916. selectMode
  62917. );
  62918. // FIXME: consider different series has items with the same name.
  62919. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62920. // Should not specify the series name, consider legend controls
  62921. // more than one pie series.
  62922. .on('mouseover', curry$4(dispatchHighlightAction, null, name, api, excludeSeriesId))
  62923. .on('mouseout', curry$4(dispatchDownplayAction, null, name, api, excludeSeriesId));
  62924. legendDrawnMap.set(name, true);
  62925. }
  62926. }, this);
  62927. }
  62928. if (__DEV__) {
  62929. if (!legendDrawnMap.get(name)) {
  62930. console.warn(
  62931. name + ' series not exists. Legend data should be same with series name or data name.'
  62932. );
  62933. }
  62934. }
  62935. }, this);
  62936. },
  62937. _createItem: function (
  62938. name, dataIndex, itemModel, legendModel,
  62939. legendSymbolType, symbolType,
  62940. itemAlign, color, selectMode
  62941. ) {
  62942. var itemWidth = legendModel.get('itemWidth');
  62943. var itemHeight = legendModel.get('itemHeight');
  62944. var inactiveColor = legendModel.get('inactiveColor');
  62945. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  62946. var isSelected = legendModel.isSelected(name);
  62947. var itemGroup = new Group$3();
  62948. var textStyleModel = itemModel.getModel('textStyle');
  62949. var itemIcon = itemModel.get('icon');
  62950. var tooltipModel = itemModel.getModel('tooltip');
  62951. var legendGlobalTooltipModel = tooltipModel.parentModel;
  62952. // Use user given icon first
  62953. legendSymbolType = itemIcon || legendSymbolType;
  62954. itemGroup.add(createSymbol(
  62955. legendSymbolType,
  62956. 0,
  62957. 0,
  62958. itemWidth,
  62959. itemHeight,
  62960. isSelected ? color : inactiveColor,
  62961. // symbolKeepAspect default true for legend
  62962. symbolKeepAspect == null ? true : symbolKeepAspect
  62963. ));
  62964. // Compose symbols
  62965. // PENDING
  62966. if (!itemIcon && symbolType
  62967. // At least show one symbol, can't be all none
  62968. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  62969. ) {
  62970. var size = itemHeight * 0.8;
  62971. if (symbolType === 'none') {
  62972. symbolType = 'circle';
  62973. }
  62974. // Put symbol in the center
  62975. itemGroup.add(createSymbol(
  62976. symbolType,
  62977. (itemWidth - size) / 2,
  62978. (itemHeight - size) / 2,
  62979. size,
  62980. size,
  62981. isSelected ? color : inactiveColor,
  62982. // symbolKeepAspect default true for legend
  62983. symbolKeepAspect == null ? true : symbolKeepAspect
  62984. ));
  62985. }
  62986. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  62987. var textAlign = itemAlign;
  62988. var formatter = legendModel.get('formatter');
  62989. var content = name;
  62990. if (typeof formatter === 'string' && formatter) {
  62991. content = formatter.replace('{name}', name != null ? name : '');
  62992. }
  62993. else if (typeof formatter === 'function') {
  62994. content = formatter(name);
  62995. }
  62996. itemGroup.add(new Text({
  62997. style: setTextStyle({}, textStyleModel, {
  62998. text: content,
  62999. x: textX,
  63000. y: itemHeight / 2,
  63001. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  63002. textAlign: textAlign,
  63003. textVerticalAlign: 'middle'
  63004. })
  63005. }));
  63006. // Add a invisible rect to increase the area of mouse hover
  63007. var hitRect = new Rect({
  63008. shape: itemGroup.getBoundingRect(),
  63009. invisible: true,
  63010. tooltip: tooltipModel.get('show') ? extend({
  63011. content: name,
  63012. // Defaul formatter
  63013. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  63014. return name;
  63015. },
  63016. formatterParams: {
  63017. componentType: 'legend',
  63018. legendIndex: legendModel.componentIndex,
  63019. name: name,
  63020. $vars: ['name']
  63021. }
  63022. }, tooltipModel.option) : null
  63023. });
  63024. itemGroup.add(hitRect);
  63025. itemGroup.eachChild(function (child) {
  63026. child.silent = true;
  63027. });
  63028. hitRect.silent = !selectMode;
  63029. this.getContentGroup().add(itemGroup);
  63030. setHoverStyle(itemGroup);
  63031. itemGroup.__legendDataIndex = dataIndex;
  63032. return itemGroup;
  63033. },
  63034. /**
  63035. * @protected
  63036. */
  63037. layoutInner: function (legendModel, itemAlign, maxSize) {
  63038. var contentGroup = this.getContentGroup();
  63039. // Place items in contentGroup.
  63040. box(
  63041. legendModel.get('orient'),
  63042. contentGroup,
  63043. legendModel.get('itemGap'),
  63044. maxSize.width,
  63045. maxSize.height
  63046. );
  63047. var contentRect = contentGroup.getBoundingRect();
  63048. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  63049. return this.group.getBoundingRect();
  63050. },
  63051. /**
  63052. * @protected
  63053. */
  63054. remove: function () {
  63055. this.getContentGroup().removeAll();
  63056. this._isFirstRender = true;
  63057. }
  63058. });
  63059. function dispatchSelectAction(name, api) {
  63060. api.dispatchAction({
  63061. type: 'legendToggleSelect',
  63062. name: name
  63063. });
  63064. }
  63065. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  63066. // If element hover will move to a hoverLayer.
  63067. var el = api.getZr().storage.getDisplayList()[0];
  63068. if (!(el && el.useHoverLayer)) {
  63069. api.dispatchAction({
  63070. type: 'highlight',
  63071. seriesName: seriesName,
  63072. name: dataName,
  63073. excludeSeriesId: excludeSeriesId
  63074. });
  63075. }
  63076. }
  63077. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  63078. // If element hover will move to a hoverLayer.
  63079. var el = api.getZr().storage.getDisplayList()[0];
  63080. if (!(el && el.useHoverLayer)) {
  63081. api.dispatchAction({
  63082. type: 'downplay',
  63083. seriesName: seriesName,
  63084. name: dataName,
  63085. excludeSeriesId: excludeSeriesId
  63086. });
  63087. }
  63088. }
  63089. /*
  63090. * Licensed to the Apache Software Foundation (ASF) under one
  63091. * or more contributor license agreements. See the NOTICE file
  63092. * distributed with this work for additional information
  63093. * regarding copyright ownership. The ASF licenses this file
  63094. * to you under the Apache License, Version 2.0 (the
  63095. * "License"); you may not use this file except in compliance
  63096. * with the License. You may obtain a copy of the License at
  63097. *
  63098. * http://www.apache.org/licenses/LICENSE-2.0
  63099. *
  63100. * Unless required by applicable law or agreed to in writing,
  63101. * software distributed under the License is distributed on an
  63102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63103. * KIND, either express or implied. See the License for the
  63104. * specific language governing permissions and limitations
  63105. * under the License.
  63106. */
  63107. var legendFilter = function (ecModel) {
  63108. var legendModels = ecModel.findComponents({
  63109. mainType: 'legend'
  63110. });
  63111. if (legendModels && legendModels.length) {
  63112. ecModel.filterSeries(function (series) {
  63113. // If in any legend component the status is not selected.
  63114. // Because in legend series is assumed selected when it is not in the legend data.
  63115. for (var i = 0; i < legendModels.length; i++) {
  63116. if (!legendModels[i].isSelected(series.name)) {
  63117. return false;
  63118. }
  63119. }
  63120. return true;
  63121. });
  63122. }
  63123. };
  63124. /*
  63125. * Licensed to the Apache Software Foundation (ASF) under one
  63126. * or more contributor license agreements. See the NOTICE file
  63127. * distributed with this work for additional information
  63128. * regarding copyright ownership. The ASF licenses this file
  63129. * to you under the Apache License, Version 2.0 (the
  63130. * "License"); you may not use this file except in compliance
  63131. * with the License. You may obtain a copy of the License at
  63132. *
  63133. * http://www.apache.org/licenses/LICENSE-2.0
  63134. *
  63135. * Unless required by applicable law or agreed to in writing,
  63136. * software distributed under the License is distributed on an
  63137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63138. * KIND, either express or implied. See the License for the
  63139. * specific language governing permissions and limitations
  63140. * under the License.
  63141. */
  63142. // Do not contain scrollable legend, for sake of file size.
  63143. // Series Filter
  63144. registerProcessor(legendFilter);
  63145. ComponentModel.registerSubTypeDefaulter('legend', function () {
  63146. // Default 'plain' when no type specified.
  63147. return 'plain';
  63148. });
  63149. /*
  63150. * Licensed to the Apache Software Foundation (ASF) under one
  63151. * or more contributor license agreements. See the NOTICE file
  63152. * distributed with this work for additional information
  63153. * regarding copyright ownership. The ASF licenses this file
  63154. * to you under the Apache License, Version 2.0 (the
  63155. * "License"); you may not use this file except in compliance
  63156. * with the License. You may obtain a copy of the License at
  63157. *
  63158. * http://www.apache.org/licenses/LICENSE-2.0
  63159. *
  63160. * Unless required by applicable law or agreed to in writing,
  63161. * software distributed under the License is distributed on an
  63162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63163. * KIND, either express or implied. See the License for the
  63164. * specific language governing permissions and limitations
  63165. * under the License.
  63166. */
  63167. var ScrollableLegendModel = LegendModel.extend({
  63168. type: 'legend.scroll',
  63169. /**
  63170. * @param {number} scrollDataIndex
  63171. */
  63172. setScrollDataIndex: function (scrollDataIndex) {
  63173. this.option.scrollDataIndex = scrollDataIndex;
  63174. },
  63175. defaultOption: {
  63176. scrollDataIndex: 0,
  63177. pageButtonItemGap: 5,
  63178. pageButtonGap: null,
  63179. pageButtonPosition: 'end', // 'start' or 'end'
  63180. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  63181. pageIcons: {
  63182. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  63183. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  63184. },
  63185. pageIconColor: '#2f4554',
  63186. pageIconInactiveColor: '#aaa',
  63187. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  63188. pageTextStyle: {
  63189. color: '#333'
  63190. },
  63191. animationDurationUpdate: 800
  63192. },
  63193. /**
  63194. * @override
  63195. */
  63196. init: function (option, parentModel, ecModel, extraOpt) {
  63197. var inputPositionParams = getLayoutParams(option);
  63198. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  63199. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  63200. },
  63201. /**
  63202. * @override
  63203. */
  63204. mergeOption: function (option, extraOpt) {
  63205. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  63206. mergeAndNormalizeLayoutParams(this, this.option, option);
  63207. },
  63208. getOrient: function () {
  63209. return this.get('orient') === 'vertical'
  63210. ? {index: 1, name: 'vertical'}
  63211. : {index: 0, name: 'horizontal'};
  63212. }
  63213. });
  63214. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  63215. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  63216. var orient = legendModel.getOrient();
  63217. var ignoreSize = [1, 1];
  63218. ignoreSize[orient.index] = 0;
  63219. mergeLayoutParam(target, raw, {
  63220. type: 'box', ignoreSize: ignoreSize
  63221. });
  63222. }
  63223. /*
  63224. * Licensed to the Apache Software Foundation (ASF) under one
  63225. * or more contributor license agreements. See the NOTICE file
  63226. * distributed with this work for additional information
  63227. * regarding copyright ownership. The ASF licenses this file
  63228. * to you under the Apache License, Version 2.0 (the
  63229. * "License"); you may not use this file except in compliance
  63230. * with the License. You may obtain a copy of the License at
  63231. *
  63232. * http://www.apache.org/licenses/LICENSE-2.0
  63233. *
  63234. * Unless required by applicable law or agreed to in writing,
  63235. * software distributed under the License is distributed on an
  63236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63237. * KIND, either express or implied. See the License for the
  63238. * specific language governing permissions and limitations
  63239. * under the License.
  63240. */
  63241. /**
  63242. * Separate legend and scrollable legend to reduce package size.
  63243. */
  63244. var Group$4 = Group;
  63245. var WH$1 = ['width', 'height'];
  63246. var XY$1 = ['x', 'y'];
  63247. var ScrollableLegendView = LegendView.extend({
  63248. type: 'legend.scroll',
  63249. newlineDisabled: true,
  63250. init: function () {
  63251. ScrollableLegendView.superCall(this, 'init');
  63252. /**
  63253. * @private
  63254. * @type {number} For `scroll`.
  63255. */
  63256. this._currentIndex = 0;
  63257. /**
  63258. * @private
  63259. * @type {module:zrender/container/Group}
  63260. */
  63261. this.group.add(this._containerGroup = new Group$4());
  63262. this._containerGroup.add(this.getContentGroup());
  63263. /**
  63264. * @private
  63265. * @type {module:zrender/container/Group}
  63266. */
  63267. this.group.add(this._controllerGroup = new Group$4());
  63268. /**
  63269. *
  63270. * @private
  63271. */
  63272. this._showController;
  63273. },
  63274. /**
  63275. * @override
  63276. */
  63277. resetInner: function () {
  63278. ScrollableLegendView.superCall(this, 'resetInner');
  63279. this._controllerGroup.removeAll();
  63280. this._containerGroup.removeClipPath();
  63281. this._containerGroup.__rectSize = null;
  63282. },
  63283. /**
  63284. * @override
  63285. */
  63286. renderInner: function (itemAlign, legendModel, ecModel, api) {
  63287. var me = this;
  63288. // Render content items.
  63289. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  63290. var controllerGroup = this._controllerGroup;
  63291. // FIXME: support be 'auto' adapt to size number text length,
  63292. // e.g., '3/12345' should not overlap with the control arrow button.
  63293. var pageIconSize = legendModel.get('pageIconSize', true);
  63294. if (!isArray(pageIconSize)) {
  63295. pageIconSize = [pageIconSize, pageIconSize];
  63296. }
  63297. createPageButton('pagePrev', 0);
  63298. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  63299. controllerGroup.add(new Text({
  63300. name: 'pageText',
  63301. style: {
  63302. textFill: pageTextStyleModel.getTextColor(),
  63303. font: pageTextStyleModel.getFont(),
  63304. textVerticalAlign: 'middle',
  63305. textAlign: 'center'
  63306. },
  63307. silent: true
  63308. }));
  63309. createPageButton('pageNext', 1);
  63310. function createPageButton(name, iconIdx) {
  63311. var pageDataIndexName = name + 'DataIndex';
  63312. var icon = createIcon(
  63313. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  63314. {
  63315. // Buttons will be created in each render, so we do not need
  63316. // to worry about avoiding using legendModel kept in scope.
  63317. onclick: bind(
  63318. me._pageGo, me, pageDataIndexName, legendModel, api
  63319. )
  63320. },
  63321. {
  63322. x: -pageIconSize[0] / 2,
  63323. y: -pageIconSize[1] / 2,
  63324. width: pageIconSize[0],
  63325. height: pageIconSize[1]
  63326. }
  63327. );
  63328. icon.name = name;
  63329. controllerGroup.add(icon);
  63330. }
  63331. },
  63332. /**
  63333. * @override
  63334. */
  63335. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender) {
  63336. var contentGroup = this.getContentGroup();
  63337. var containerGroup = this._containerGroup;
  63338. var controllerGroup = this._controllerGroup;
  63339. var orientIdx = legendModel.getOrient().index;
  63340. var wh = WH$1[orientIdx];
  63341. var hw = WH$1[1 - orientIdx];
  63342. var yx = XY$1[1 - orientIdx];
  63343. // Place items in contentGroup.
  63344. box(
  63345. legendModel.get('orient'),
  63346. contentGroup,
  63347. legendModel.get('itemGap'),
  63348. !orientIdx ? null : maxSize.width,
  63349. orientIdx ? null : maxSize.height
  63350. );
  63351. box(
  63352. // Buttons in controller are layout always horizontally.
  63353. 'horizontal',
  63354. controllerGroup,
  63355. legendModel.get('pageButtonItemGap', true)
  63356. );
  63357. var contentRect = contentGroup.getBoundingRect();
  63358. var controllerRect = controllerGroup.getBoundingRect();
  63359. var showController = this._showController = contentRect[wh] > maxSize[wh];
  63360. var contentPos = [-contentRect.x, -contentRect.y];
  63361. // Remain contentPos when scroll animation perfroming.
  63362. // If first rendering, `contentGroup.position` is [0, 0], which
  63363. // does not make sense and may cause unexepcted animation if adopted.
  63364. if (!isFirstRender) {
  63365. contentPos[orientIdx] = contentGroup.position[orientIdx];
  63366. }
  63367. // Layout container group based on 0.
  63368. var containerPos = [0, 0];
  63369. var controllerPos = [-controllerRect.x, -controllerRect.y];
  63370. var pageButtonGap = retrieve2(
  63371. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  63372. );
  63373. // Place containerGroup and controllerGroup and contentGroup.
  63374. if (showController) {
  63375. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  63376. // controller is on the right / bottom.
  63377. if (pageButtonPosition === 'end') {
  63378. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  63379. }
  63380. // controller is on the left / top.
  63381. else {
  63382. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  63383. }
  63384. }
  63385. // Always align controller to content as 'middle'.
  63386. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  63387. contentGroup.attr('position', contentPos);
  63388. containerGroup.attr('position', containerPos);
  63389. controllerGroup.attr('position', controllerPos);
  63390. // Calculate `mainRect` and set `clipPath`.
  63391. // mainRect should not be calculated by `this.group.getBoundingRect()`
  63392. // for sake of the overflow.
  63393. var mainRect = this.group.getBoundingRect();
  63394. var mainRect = {x: 0, y: 0};
  63395. // Consider content may be overflow (should be clipped).
  63396. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  63397. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  63398. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  63399. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  63400. containerGroup.__rectSize = maxSize[wh];
  63401. if (showController) {
  63402. var clipShape = {x: 0, y: 0};
  63403. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  63404. clipShape[hw] = mainRect[hw];
  63405. containerGroup.setClipPath(new Rect({shape: clipShape}));
  63406. // Consider content may be larger than container, container rect
  63407. // can not be obtained from `containerGroup.getBoundingRect()`.
  63408. containerGroup.__rectSize = clipShape[wh];
  63409. }
  63410. else {
  63411. // Do not remove or ignore controller. Keep them set as place holders.
  63412. controllerGroup.eachChild(function (child) {
  63413. child.attr({invisible: true, silent: true});
  63414. });
  63415. }
  63416. // Content translate animation.
  63417. var pageInfo = this._getPageInfo(legendModel);
  63418. pageInfo.pageIndex != null && updateProps(
  63419. contentGroup,
  63420. {position: pageInfo.contentPosition},
  63421. // When switch from "show controller" to "not show controller", view should be
  63422. // updated immediately without animation, otherwise causes weird efffect.
  63423. showController ? legendModel : false
  63424. );
  63425. this._updatePageInfoView(legendModel, pageInfo);
  63426. return mainRect;
  63427. },
  63428. _pageGo: function (to, legendModel, api) {
  63429. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  63430. scrollDataIndex != null && api.dispatchAction({
  63431. type: 'legendScroll',
  63432. scrollDataIndex: scrollDataIndex,
  63433. legendId: legendModel.id
  63434. });
  63435. },
  63436. _updatePageInfoView: function (legendModel, pageInfo) {
  63437. var controllerGroup = this._controllerGroup;
  63438. each$1(['pagePrev', 'pageNext'], function (name) {
  63439. var canJump = pageInfo[name + 'DataIndex'] != null;
  63440. var icon = controllerGroup.childOfName(name);
  63441. if (icon) {
  63442. icon.setStyle(
  63443. 'fill',
  63444. canJump
  63445. ? legendModel.get('pageIconColor', true)
  63446. : legendModel.get('pageIconInactiveColor', true)
  63447. );
  63448. icon.cursor = canJump ? 'pointer' : 'default';
  63449. }
  63450. });
  63451. var pageText = controllerGroup.childOfName('pageText');
  63452. var pageFormatter = legendModel.get('pageFormatter');
  63453. var pageIndex = pageInfo.pageIndex;
  63454. var current = pageIndex != null ? pageIndex + 1 : 0;
  63455. var total = pageInfo.pageCount;
  63456. pageText && pageFormatter && pageText.setStyle(
  63457. 'text',
  63458. isString(pageFormatter)
  63459. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  63460. : pageFormatter({current: current, total: total})
  63461. );
  63462. },
  63463. /**
  63464. * @param {module:echarts/model/Model} legendModel
  63465. * @return {Object} {
  63466. * contentPosition: Array.<number>, null when data item not found.
  63467. * pageIndex: number, null when data item not found.
  63468. * pageCount: number, always be a number, can be 0.
  63469. * pagePrevDataIndex: number, null when no next page.
  63470. * pageNextDataIndex: number, null when no previous page.
  63471. * }
  63472. */
  63473. _getPageInfo: function (legendModel) {
  63474. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  63475. var contentGroup = this.getContentGroup();
  63476. var containerRectSize = this._containerGroup.__rectSize;
  63477. var orientIdx = legendModel.getOrient().index;
  63478. var wh = WH$1[orientIdx];
  63479. var xy = XY$1[orientIdx];
  63480. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  63481. var children = contentGroup.children();
  63482. var targetItem = children[targetItemIndex];
  63483. var itemCount = children.length;
  63484. var pCount = !itemCount ? 0 : 1;
  63485. var result = {
  63486. contentPosition: contentGroup.position.slice(),
  63487. pageCount: pCount,
  63488. pageIndex: pCount - 1,
  63489. pagePrevDataIndex: null,
  63490. pageNextDataIndex: null
  63491. };
  63492. if (!targetItem) {
  63493. return result;
  63494. }
  63495. var targetItemInfo = getItemInfo(targetItem);
  63496. result.contentPosition[orientIdx] = -targetItemInfo.s;
  63497. // Strategy:
  63498. // (1) Always align based on the left/top most item.
  63499. // (2) It is user-friendly that the last item shown in the
  63500. // current window is shown at the begining of next window.
  63501. // Otherwise if half of the last item is cut by the window,
  63502. // it will have no chance to display entirely.
  63503. // (3) Consider that item size probably be different, we
  63504. // have calculate pageIndex by size rather than item index,
  63505. // and we can not get page index directly by division.
  63506. // (4) The window is to narrow to contain more than
  63507. // one item, we should make sure that the page can be fliped.
  63508. for (var i = targetItemIndex + 1,
  63509. winStartItemInfo = targetItemInfo,
  63510. winEndItemInfo = targetItemInfo,
  63511. currItemInfo = null;
  63512. i <= itemCount;
  63513. ++i
  63514. ) {
  63515. currItemInfo = getItemInfo(children[i]);
  63516. if (
  63517. // Half of the last item is out of the window.
  63518. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  63519. // If the current item does not intersect with the window, the new page
  63520. // can be started at the current item or the last item.
  63521. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  63522. ) {
  63523. if (winEndItemInfo.i > winStartItemInfo.i) {
  63524. winStartItemInfo = winEndItemInfo;
  63525. }
  63526. else { // e.g., when page size is smaller than item size.
  63527. winStartItemInfo = currItemInfo;
  63528. }
  63529. if (winStartItemInfo) {
  63530. if (result.pageNextDataIndex == null) {
  63531. result.pageNextDataIndex = winStartItemInfo.i;
  63532. }
  63533. ++result.pageCount;
  63534. }
  63535. }
  63536. winEndItemInfo = currItemInfo;
  63537. }
  63538. for (var i = targetItemIndex - 1,
  63539. winStartItemInfo = targetItemInfo,
  63540. winEndItemInfo = targetItemInfo,
  63541. currItemInfo = null;
  63542. i >= -1;
  63543. --i
  63544. ) {
  63545. currItemInfo = getItemInfo(children[i]);
  63546. if (
  63547. // If the the end item does not intersect with the window started
  63548. // from the current item, a page can be settled.
  63549. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  63550. // e.g., when page size is smaller than item size.
  63551. && winStartItemInfo.i < winEndItemInfo.i
  63552. ) {
  63553. winEndItemInfo = winStartItemInfo;
  63554. if (result.pagePrevDataIndex == null) {
  63555. result.pagePrevDataIndex = winStartItemInfo.i;
  63556. }
  63557. ++result.pageCount;
  63558. ++result.pageIndex;
  63559. }
  63560. winStartItemInfo = currItemInfo;
  63561. }
  63562. return result;
  63563. function getItemInfo(el) {
  63564. if (el) {
  63565. var itemRect = el.getBoundingRect();
  63566. var start = itemRect[xy] + el.position[orientIdx];
  63567. return {
  63568. s: start,
  63569. e: start + itemRect[wh],
  63570. i: el.__legendDataIndex
  63571. };
  63572. }
  63573. }
  63574. function intersect(itemInfo, winStart) {
  63575. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  63576. }
  63577. },
  63578. _findTargetItemIndex: function (targetDataIndex) {
  63579. var index;
  63580. var contentGroup = this.getContentGroup();
  63581. if (this._showController) {
  63582. contentGroup.eachChild(function (child, idx) {
  63583. if (child.__legendDataIndex === targetDataIndex) {
  63584. index = idx;
  63585. }
  63586. });
  63587. }
  63588. else {
  63589. index = 0;
  63590. }
  63591. return index;
  63592. }
  63593. });
  63594. /*
  63595. * Licensed to the Apache Software Foundation (ASF) under one
  63596. * or more contributor license agreements. See the NOTICE file
  63597. * distributed with this work for additional information
  63598. * regarding copyright ownership. The ASF licenses this file
  63599. * to you under the Apache License, Version 2.0 (the
  63600. * "License"); you may not use this file except in compliance
  63601. * with the License. You may obtain a copy of the License at
  63602. *
  63603. * http://www.apache.org/licenses/LICENSE-2.0
  63604. *
  63605. * Unless required by applicable law or agreed to in writing,
  63606. * software distributed under the License is distributed on an
  63607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63608. * KIND, either express or implied. See the License for the
  63609. * specific language governing permissions and limitations
  63610. * under the License.
  63611. */
  63612. /**
  63613. * @event legendScroll
  63614. * @type {Object}
  63615. * @property {string} type 'legendScroll'
  63616. * @property {string} scrollDataIndex
  63617. */
  63618. registerAction(
  63619. 'legendScroll', 'legendscroll',
  63620. function (payload, ecModel) {
  63621. var scrollDataIndex = payload.scrollDataIndex;
  63622. scrollDataIndex != null && ecModel.eachComponent(
  63623. {mainType: 'legend', subType: 'scroll', query: payload},
  63624. function (legendModel) {
  63625. legendModel.setScrollDataIndex(scrollDataIndex);
  63626. }
  63627. );
  63628. }
  63629. );
  63630. /*
  63631. * Licensed to the Apache Software Foundation (ASF) under one
  63632. * or more contributor license agreements. See the NOTICE file
  63633. * distributed with this work for additional information
  63634. * regarding copyright ownership. The ASF licenses this file
  63635. * to you under the Apache License, Version 2.0 (the
  63636. * "License"); you may not use this file except in compliance
  63637. * with the License. You may obtain a copy of the License at
  63638. *
  63639. * http://www.apache.org/licenses/LICENSE-2.0
  63640. *
  63641. * Unless required by applicable law or agreed to in writing,
  63642. * software distributed under the License is distributed on an
  63643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63644. * KIND, either express or implied. See the License for the
  63645. * specific language governing permissions and limitations
  63646. * under the License.
  63647. */
  63648. /**
  63649. * Legend component entry file8
  63650. */
  63651. /*
  63652. * Licensed to the Apache Software Foundation (ASF) under one
  63653. * or more contributor license agreements. See the NOTICE file
  63654. * distributed with this work for additional information
  63655. * regarding copyright ownership. The ASF licenses this file
  63656. * to you under the Apache License, Version 2.0 (the
  63657. * "License"); you may not use this file except in compliance
  63658. * with the License. You may obtain a copy of the License at
  63659. *
  63660. * http://www.apache.org/licenses/LICENSE-2.0
  63661. *
  63662. * Unless required by applicable law or agreed to in writing,
  63663. * software distributed under the License is distributed on an
  63664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63665. * KIND, either express or implied. See the License for the
  63666. * specific language governing permissions and limitations
  63667. * under the License.
  63668. */
  63669. extendComponentModel({
  63670. type: 'tooltip',
  63671. dependencies: ['axisPointer'],
  63672. defaultOption: {
  63673. zlevel: 0,
  63674. z: 60,
  63675. show: true,
  63676. // tooltip主体内容
  63677. showContent: true,
  63678. // 'trigger' only works on coordinate system.
  63679. // 'item' | 'axis' | 'none'
  63680. trigger: 'item',
  63681. // 'click' | 'mousemove' | 'none'
  63682. triggerOn: 'mousemove|click',
  63683. alwaysShowContent: false,
  63684. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  63685. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  63686. // 'auto': use html by default, and use non-html if `document` is not defined
  63687. // 'html': use html for tooltip
  63688. // 'richText': use canvas, svg, and etc. for tooltip
  63689. // 位置 {Array} | {Function}
  63690. // position: null
  63691. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  63692. // align: null,
  63693. // verticalAlign: null,
  63694. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  63695. confine: false,
  63696. // 内容格式器:{string}(Template) ¦ {Function}
  63697. // formatter: null
  63698. showDelay: 0,
  63699. // 隐藏延迟,单位ms
  63700. hideDelay: 100,
  63701. // 动画变换时间,单位s
  63702. transitionDuration: 0.4,
  63703. enterable: false,
  63704. // 提示背景颜色,默认为透明度为0.7的黑色
  63705. backgroundColor: 'rgba(50,50,50,0.7)',
  63706. // 提示边框颜色
  63707. borderColor: '#333',
  63708. // 提示边框圆角,单位px,默认为4
  63709. borderRadius: 4,
  63710. // 提示边框线宽,单位px,默认为0(无边框)
  63711. borderWidth: 0,
  63712. // 提示内边距,单位px,默认各方向内边距为5,
  63713. // 接受数组分别设定上右下左边距,同css
  63714. padding: 5,
  63715. // Extra css text
  63716. extraCssText: '',
  63717. // 坐标轴指示器,坐标轴触发有效
  63718. axisPointer: {
  63719. // 默认为直线
  63720. // 可选为:'line' | 'shadow' | 'cross'
  63721. type: 'line',
  63722. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  63723. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  63724. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  63725. // 极坐标系会默认选择 angle 轴
  63726. axis: 'auto',
  63727. animation: 'auto',
  63728. animationDurationUpdate: 200,
  63729. animationEasingUpdate: 'exponentialOut',
  63730. crossStyle: {
  63731. color: '#999',
  63732. width: 1,
  63733. type: 'dashed',
  63734. // TODO formatter
  63735. textStyle: {}
  63736. }
  63737. // lineStyle and shadowStyle should not be specified here,
  63738. // otherwise it will always override those styles on option.axisPointer.
  63739. },
  63740. textStyle: {
  63741. color: '#fff',
  63742. fontSize: 14
  63743. }
  63744. }
  63745. });
  63746. /*
  63747. * Licensed to the Apache Software Foundation (ASF) under one
  63748. * or more contributor license agreements. See the NOTICE file
  63749. * distributed with this work for additional information
  63750. * regarding copyright ownership. The ASF licenses this file
  63751. * to you under the Apache License, Version 2.0 (the
  63752. * "License"); you may not use this file except in compliance
  63753. * with the License. You may obtain a copy of the License at
  63754. *
  63755. * http://www.apache.org/licenses/LICENSE-2.0
  63756. *
  63757. * Unless required by applicable law or agreed to in writing,
  63758. * software distributed under the License is distributed on an
  63759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63760. * KIND, either express or implied. See the License for the
  63761. * specific language governing permissions and limitations
  63762. * under the License.
  63763. */
  63764. var each$18 = each$1;
  63765. var toCamelCase$1 = toCamelCase;
  63766. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  63767. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  63768. /**
  63769. * @param {number} duration
  63770. * @return {string}
  63771. * @inner
  63772. */
  63773. function assembleTransition(duration) {
  63774. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  63775. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  63776. + 'top ' + duration + 's ' + transitionCurve;
  63777. return map(vendors, function (vendorPrefix) {
  63778. return vendorPrefix + 'transition:' + transitionText;
  63779. }).join(';');
  63780. }
  63781. /**
  63782. * @param {Object} textStyle
  63783. * @return {string}
  63784. * @inner
  63785. */
  63786. function assembleFont(textStyleModel) {
  63787. var cssText = [];
  63788. var fontSize = textStyleModel.get('fontSize');
  63789. var color = textStyleModel.getTextColor();
  63790. color && cssText.push('color:' + color);
  63791. cssText.push('font:' + textStyleModel.getFont());
  63792. fontSize
  63793. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  63794. each$18(['decoration', 'align'], function (name) {
  63795. var val = textStyleModel.get(name);
  63796. val && cssText.push('text-' + name + ':' + val);
  63797. });
  63798. return cssText.join(';');
  63799. }
  63800. /**
  63801. * @param {Object} tooltipModel
  63802. * @return {string}
  63803. * @inner
  63804. */
  63805. function assembleCssText(tooltipModel) {
  63806. var cssText = [];
  63807. var transitionDuration = tooltipModel.get('transitionDuration');
  63808. var backgroundColor = tooltipModel.get('backgroundColor');
  63809. var textStyleModel = tooltipModel.getModel('textStyle');
  63810. var padding = tooltipModel.get('padding');
  63811. // Animation transition. Do not animate when transitionDuration is 0.
  63812. transitionDuration
  63813. && cssText.push(assembleTransition(transitionDuration));
  63814. if (backgroundColor) {
  63815. if (env$1.canvasSupported) {
  63816. cssText.push('background-Color:' + backgroundColor);
  63817. }
  63818. else {
  63819. // for ie
  63820. cssText.push(
  63821. 'background-Color:#' + toHex(backgroundColor)
  63822. );
  63823. cssText.push('filter:alpha(opacity=70)');
  63824. }
  63825. }
  63826. // Border style
  63827. each$18(['width', 'color', 'radius'], function (name) {
  63828. var borderName = 'border-' + name;
  63829. var camelCase = toCamelCase$1(borderName);
  63830. var val = tooltipModel.get(camelCase);
  63831. val != null
  63832. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  63833. });
  63834. // Text style
  63835. cssText.push(assembleFont(textStyleModel));
  63836. // Padding
  63837. if (padding != null) {
  63838. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  63839. }
  63840. return cssText.join(';') + ';';
  63841. }
  63842. /**
  63843. * @alias module:echarts/component/tooltip/TooltipContent
  63844. * @constructor
  63845. */
  63846. function TooltipContent(container, api) {
  63847. if (env$1.wxa) {
  63848. return null;
  63849. }
  63850. var el = document.createElement('div');
  63851. var zr = this._zr = api.getZr();
  63852. this.el = el;
  63853. this._x = api.getWidth() / 2;
  63854. this._y = api.getHeight() / 2;
  63855. container.appendChild(el);
  63856. this._container = container;
  63857. this._show = false;
  63858. /**
  63859. * @private
  63860. */
  63861. this._hideTimeout;
  63862. var self = this;
  63863. el.onmouseenter = function () {
  63864. // clear the timeout in hideLater and keep showing tooltip
  63865. if (self._enterable) {
  63866. clearTimeout(self._hideTimeout);
  63867. self._show = true;
  63868. }
  63869. self._inContent = true;
  63870. };
  63871. el.onmousemove = function (e) {
  63872. e = e || window.event;
  63873. if (!self._enterable) {
  63874. // Try trigger zrender event to avoid mouse
  63875. // in and out shape too frequently
  63876. var handler = zr.handler;
  63877. normalizeEvent(container, e, true);
  63878. handler.dispatch('mousemove', e);
  63879. }
  63880. };
  63881. el.onmouseleave = function () {
  63882. if (self._enterable) {
  63883. if (self._show) {
  63884. self.hideLater(self._hideDelay);
  63885. }
  63886. }
  63887. self._inContent = false;
  63888. };
  63889. }
  63890. TooltipContent.prototype = {
  63891. constructor: TooltipContent,
  63892. /**
  63893. * @private
  63894. * @type {boolean}
  63895. */
  63896. _enterable: true,
  63897. /**
  63898. * Update when tooltip is rendered
  63899. */
  63900. update: function () {
  63901. // FIXME
  63902. // Move this logic to ec main?
  63903. var container = this._container;
  63904. var stl = container.currentStyle
  63905. || document.defaultView.getComputedStyle(container);
  63906. var domStyle = container.style;
  63907. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  63908. domStyle.position = 'relative';
  63909. }
  63910. // Hide the tooltip
  63911. // PENDING
  63912. // this.hide();
  63913. },
  63914. show: function (tooltipModel) {
  63915. clearTimeout(this._hideTimeout);
  63916. var el = this.el;
  63917. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  63918. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  63919. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  63920. + (tooltipModel.get('extraCssText') || '');
  63921. el.style.display = el.innerHTML ? 'block' : 'none';
  63922. // If mouse occsionally move over the tooltip, a mouseout event will be
  63923. // triggered by canvas, and cuase some unexpectable result like dragging
  63924. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  63925. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  63926. // scenario.
  63927. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  63928. this._show = true;
  63929. },
  63930. setContent: function (content) {
  63931. this.el.innerHTML = content == null ? '' : content;
  63932. },
  63933. setEnterable: function (enterable) {
  63934. this._enterable = enterable;
  63935. },
  63936. getSize: function () {
  63937. var el = this.el;
  63938. return [el.clientWidth, el.clientHeight];
  63939. },
  63940. moveTo: function (x, y) {
  63941. // xy should be based on canvas root. But tooltipContent is
  63942. // the sibling of canvas root. So padding of ec container
  63943. // should be considered here.
  63944. var zr = this._zr;
  63945. var viewportRootOffset;
  63946. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  63947. x += viewportRootOffset.offsetLeft;
  63948. y += viewportRootOffset.offsetTop;
  63949. }
  63950. var style = this.el.style;
  63951. style.left = x + 'px';
  63952. style.top = y + 'px';
  63953. this._x = x;
  63954. this._y = y;
  63955. },
  63956. hide: function () {
  63957. this.el.style.display = 'none';
  63958. this._show = false;
  63959. },
  63960. hideLater: function (time) {
  63961. if (this._show && !(this._inContent && this._enterable)) {
  63962. if (time) {
  63963. this._hideDelay = time;
  63964. // Set show false to avoid invoke hideLater mutiple times
  63965. this._show = false;
  63966. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  63967. }
  63968. else {
  63969. this.hide();
  63970. }
  63971. }
  63972. },
  63973. isShow: function () {
  63974. return this._show;
  63975. },
  63976. getOuterSize: function () {
  63977. var width = this.el.clientWidth;
  63978. var height = this.el.clientHeight;
  63979. // Consider browser compatibility.
  63980. // IE8 does not support getComputedStyle.
  63981. if (document.defaultView && document.defaultView.getComputedStyle) {
  63982. var stl = document.defaultView.getComputedStyle(this.el);
  63983. if (stl) {
  63984. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  63985. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  63986. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  63987. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  63988. }
  63989. }
  63990. return {width: width, height: height};
  63991. }
  63992. };
  63993. /*
  63994. * Licensed to the Apache Software Foundation (ASF) under one
  63995. * or more contributor license agreements. See the NOTICE file
  63996. * distributed with this work for additional information
  63997. * regarding copyright ownership. The ASF licenses this file
  63998. * to you under the Apache License, Version 2.0 (the
  63999. * "License"); you may not use this file except in compliance
  64000. * with the License. You may obtain a copy of the License at
  64001. *
  64002. * http://www.apache.org/licenses/LICENSE-2.0
  64003. *
  64004. * Unless required by applicable law or agreed to in writing,
  64005. * software distributed under the License is distributed on an
  64006. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64007. * KIND, either express or implied. See the License for the
  64008. * specific language governing permissions and limitations
  64009. * under the License.
  64010. */
  64011. // import Group from 'zrender/src/container/Group';
  64012. /**
  64013. * @alias module:echarts/component/tooltip/TooltipRichContent
  64014. * @constructor
  64015. */
  64016. function TooltipRichContent(api) {
  64017. this._zr = api.getZr();
  64018. this._show = false;
  64019. /**
  64020. * @private
  64021. */
  64022. this._hideTimeout;
  64023. }
  64024. TooltipRichContent.prototype = {
  64025. constructor: TooltipRichContent,
  64026. /**
  64027. * @private
  64028. * @type {boolean}
  64029. */
  64030. _enterable: true,
  64031. /**
  64032. * Update when tooltip is rendered
  64033. */
  64034. update: function () {
  64035. // noop
  64036. },
  64037. show: function (tooltipModel) {
  64038. if (this._hideTimeout) {
  64039. clearTimeout(this._hideTimeout);
  64040. }
  64041. this.el.attr('show', true);
  64042. this._show = true;
  64043. },
  64044. /**
  64045. * Set tooltip content
  64046. *
  64047. * @param {string} content rich text string of content
  64048. * @param {Object} markerRich rich text style
  64049. * @param {Object} tooltipModel tooltip model
  64050. */
  64051. setContent: function (content, markerRich, tooltipModel) {
  64052. if (this.el) {
  64053. this._zr.remove(this.el);
  64054. }
  64055. var markers = {};
  64056. var text = content;
  64057. var prefix = '{marker';
  64058. var suffix = '|}';
  64059. var startId = text.indexOf(prefix);
  64060. while (startId >= 0) {
  64061. var endId = text.indexOf(suffix);
  64062. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  64063. if (name.indexOf('sub') > -1) {
  64064. markers['marker' + name] = {
  64065. textWidth: 4,
  64066. textHeight: 4,
  64067. textBorderRadius: 2,
  64068. textBackgroundColor: markerRich[name],
  64069. // TODO: textOffset is not implemented for rich text
  64070. textOffset: [3, 0]
  64071. };
  64072. }
  64073. else {
  64074. markers['marker' + name] = {
  64075. textWidth: 10,
  64076. textHeight: 10,
  64077. textBorderRadius: 5,
  64078. textBackgroundColor: markerRich[name]
  64079. };
  64080. }
  64081. text = text.substr(endId + 1);
  64082. startId = text.indexOf('{marker');
  64083. }
  64084. this.el = new Text({
  64085. style: {
  64086. rich: markers,
  64087. text: content,
  64088. textLineHeight: 20,
  64089. textBackgroundColor: tooltipModel.get('backgroundColor'),
  64090. textBorderRadius: tooltipModel.get('borderRadius'),
  64091. textFill: tooltipModel.get('textStyle.color'),
  64092. textPadding: tooltipModel.get('padding')
  64093. },
  64094. z: tooltipModel.get('z')
  64095. });
  64096. this._zr.add(this.el);
  64097. var self = this;
  64098. this.el.on('mouseover', function () {
  64099. // clear the timeout in hideLater and keep showing tooltip
  64100. if (self._enterable) {
  64101. clearTimeout(self._hideTimeout);
  64102. self._show = true;
  64103. }
  64104. self._inContent = true;
  64105. });
  64106. this.el.on('mouseout', function () {
  64107. if (self._enterable) {
  64108. if (self._show) {
  64109. self.hideLater(self._hideDelay);
  64110. }
  64111. }
  64112. self._inContent = false;
  64113. });
  64114. },
  64115. setEnterable: function (enterable) {
  64116. this._enterable = enterable;
  64117. },
  64118. getSize: function () {
  64119. var bounding = this.el.getBoundingRect();
  64120. return [bounding.width, bounding.height];
  64121. },
  64122. moveTo: function (x, y) {
  64123. if (this.el) {
  64124. this.el.attr('position', [x, y]);
  64125. }
  64126. },
  64127. hide: function () {
  64128. this.el.hide();
  64129. this._show = false;
  64130. },
  64131. hideLater: function (time) {
  64132. if (this._show && !(this._inContent && this._enterable)) {
  64133. if (time) {
  64134. this._hideDelay = time;
  64135. // Set show false to avoid invoke hideLater mutiple times
  64136. this._show = false;
  64137. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  64138. }
  64139. else {
  64140. this.hide();
  64141. }
  64142. }
  64143. },
  64144. isShow: function () {
  64145. return this._show;
  64146. },
  64147. getOuterSize: function () {
  64148. return this.getSize();
  64149. }
  64150. };
  64151. /*
  64152. * Licensed to the Apache Software Foundation (ASF) under one
  64153. * or more contributor license agreements. See the NOTICE file
  64154. * distributed with this work for additional information
  64155. * regarding copyright ownership. The ASF licenses this file
  64156. * to you under the Apache License, Version 2.0 (the
  64157. * "License"); you may not use this file except in compliance
  64158. * with the License. You may obtain a copy of the License at
  64159. *
  64160. * http://www.apache.org/licenses/LICENSE-2.0
  64161. *
  64162. * Unless required by applicable law or agreed to in writing,
  64163. * software distributed under the License is distributed on an
  64164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64165. * KIND, either express or implied. See the License for the
  64166. * specific language governing permissions and limitations
  64167. * under the License.
  64168. */
  64169. var bind$3 = bind;
  64170. var each$17 = each$1;
  64171. var parsePercent$2 = parsePercent$1;
  64172. var proxyRect = new Rect({
  64173. shape: {x: -1, y: -1, width: 2, height: 2}
  64174. });
  64175. extendComponentView({
  64176. type: 'tooltip',
  64177. init: function (ecModel, api) {
  64178. if (env$1.node) {
  64179. return;
  64180. }
  64181. var tooltipModel = ecModel.getComponent('tooltip');
  64182. var renderMode = tooltipModel.get('renderMode');
  64183. this._renderMode = getTooltipRenderMode(renderMode);
  64184. var tooltipContent;
  64185. if (this._renderMode === 'html') {
  64186. tooltipContent = new TooltipContent(api.getDom(), api);
  64187. this._newLine = '<br/>';
  64188. }
  64189. else {
  64190. tooltipContent = new TooltipRichContent(api);
  64191. this._newLine = '\n';
  64192. }
  64193. this._tooltipContent = tooltipContent;
  64194. },
  64195. render: function (tooltipModel, ecModel, api) {
  64196. if (env$1.node) {
  64197. return;
  64198. }
  64199. // Reset
  64200. this.group.removeAll();
  64201. /**
  64202. * @private
  64203. * @type {module:echarts/component/tooltip/TooltipModel}
  64204. */
  64205. this._tooltipModel = tooltipModel;
  64206. /**
  64207. * @private
  64208. * @type {module:echarts/model/Global}
  64209. */
  64210. this._ecModel = ecModel;
  64211. /**
  64212. * @private
  64213. * @type {module:echarts/ExtensionAPI}
  64214. */
  64215. this._api = api;
  64216. /**
  64217. * Should be cleaned when render.
  64218. * @private
  64219. * @type {Array.<Array.<Object>>}
  64220. */
  64221. this._lastDataByCoordSys = null;
  64222. /**
  64223. * @private
  64224. * @type {boolean}
  64225. */
  64226. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  64227. var tooltipContent = this._tooltipContent;
  64228. tooltipContent.update();
  64229. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  64230. this._initGlobalListener();
  64231. this._keepShow();
  64232. },
  64233. _initGlobalListener: function () {
  64234. var tooltipModel = this._tooltipModel;
  64235. var triggerOn = tooltipModel.get('triggerOn');
  64236. register(
  64237. 'itemTooltip',
  64238. this._api,
  64239. bind$3(function (currTrigger, e, dispatchAction) {
  64240. // If 'none', it is not controlled by mouse totally.
  64241. if (triggerOn !== 'none') {
  64242. if (triggerOn.indexOf(currTrigger) >= 0) {
  64243. this._tryShow(e, dispatchAction);
  64244. }
  64245. else if (currTrigger === 'leave') {
  64246. this._hide(dispatchAction);
  64247. }
  64248. }
  64249. }, this)
  64250. );
  64251. },
  64252. _keepShow: function () {
  64253. var tooltipModel = this._tooltipModel;
  64254. var ecModel = this._ecModel;
  64255. var api = this._api;
  64256. // Try to keep the tooltip show when refreshing
  64257. if (this._lastX != null
  64258. && this._lastY != null
  64259. // When user is willing to control tooltip totally using API,
  64260. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  64261. // which is not expected.
  64262. && tooltipModel.get('triggerOn') !== 'none'
  64263. ) {
  64264. var self = this;
  64265. clearTimeout(this._refreshUpdateTimeout);
  64266. this._refreshUpdateTimeout = setTimeout(function () {
  64267. // Show tip next tick after other charts are rendered
  64268. // In case highlight action has wrong result
  64269. // FIXME
  64270. self.manuallyShowTip(tooltipModel, ecModel, api, {
  64271. x: self._lastX,
  64272. y: self._lastY
  64273. });
  64274. });
  64275. }
  64276. },
  64277. /**
  64278. * Show tip manually by
  64279. * dispatchAction({
  64280. * type: 'showTip',
  64281. * x: 10,
  64282. * y: 10
  64283. * });
  64284. * Or
  64285. * dispatchAction({
  64286. * type: 'showTip',
  64287. * seriesIndex: 0,
  64288. * dataIndex or dataIndexInside or name
  64289. * });
  64290. *
  64291. * TODO Batch
  64292. */
  64293. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  64294. if (payload.from === this.uid || env$1.node) {
  64295. return;
  64296. }
  64297. var dispatchAction = makeDispatchAction$1(payload, api);
  64298. // Reset ticket
  64299. this._ticket = '';
  64300. // When triggered from axisPointer.
  64301. var dataByCoordSys = payload.dataByCoordSys;
  64302. if (payload.tooltip && payload.x != null && payload.y != null) {
  64303. var el = proxyRect;
  64304. el.position = [payload.x, payload.y];
  64305. el.update();
  64306. el.tooltip = payload.tooltip;
  64307. // Manually show tooltip while view is not using zrender elements.
  64308. this._tryShow({
  64309. offsetX: payload.x,
  64310. offsetY: payload.y,
  64311. target: el
  64312. }, dispatchAction);
  64313. }
  64314. else if (dataByCoordSys) {
  64315. this._tryShow({
  64316. offsetX: payload.x,
  64317. offsetY: payload.y,
  64318. position: payload.position,
  64319. event: {},
  64320. dataByCoordSys: payload.dataByCoordSys,
  64321. tooltipOption: payload.tooltipOption
  64322. }, dispatchAction);
  64323. }
  64324. else if (payload.seriesIndex != null) {
  64325. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  64326. return;
  64327. }
  64328. var pointInfo = findPointFromSeries(payload, ecModel);
  64329. var cx = pointInfo.point[0];
  64330. var cy = pointInfo.point[1];
  64331. if (cx != null && cy != null) {
  64332. this._tryShow({
  64333. offsetX: cx,
  64334. offsetY: cy,
  64335. position: payload.position,
  64336. target: pointInfo.el,
  64337. event: {}
  64338. }, dispatchAction);
  64339. }
  64340. }
  64341. else if (payload.x != null && payload.y != null) {
  64342. // FIXME
  64343. // should wrap dispatchAction like `axisPointer/globalListener` ?
  64344. api.dispatchAction({
  64345. type: 'updateAxisPointer',
  64346. x: payload.x,
  64347. y: payload.y
  64348. });
  64349. this._tryShow({
  64350. offsetX: payload.x,
  64351. offsetY: payload.y,
  64352. position: payload.position,
  64353. target: api.getZr().findHover(payload.x, payload.y).target,
  64354. event: {}
  64355. }, dispatchAction);
  64356. }
  64357. },
  64358. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  64359. var tooltipContent = this._tooltipContent;
  64360. if (!this._alwaysShowContent && this._tooltipModel) {
  64361. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  64362. }
  64363. this._lastX = this._lastY = null;
  64364. if (payload.from !== this.uid) {
  64365. this._hide(makeDispatchAction$1(payload, api));
  64366. }
  64367. },
  64368. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  64369. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  64370. // and tooltip.
  64371. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  64372. var seriesIndex = payload.seriesIndex;
  64373. var dataIndex = payload.dataIndex;
  64374. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  64375. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  64376. return;
  64377. }
  64378. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64379. if (!seriesModel) {
  64380. return;
  64381. }
  64382. var data = seriesModel.getData();
  64383. var tooltipModel = buildTooltipModel([
  64384. data.getItemModel(dataIndex),
  64385. seriesModel,
  64386. (seriesModel.coordinateSystem || {}).model,
  64387. tooltipModel
  64388. ]);
  64389. if (tooltipModel.get('trigger') !== 'axis') {
  64390. return;
  64391. }
  64392. api.dispatchAction({
  64393. type: 'updateAxisPointer',
  64394. seriesIndex: seriesIndex,
  64395. dataIndex: dataIndex,
  64396. position: payload.position
  64397. });
  64398. return true;
  64399. },
  64400. _tryShow: function (e, dispatchAction) {
  64401. var el = e.target;
  64402. var tooltipModel = this._tooltipModel;
  64403. if (!tooltipModel) {
  64404. return;
  64405. }
  64406. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  64407. this._lastX = e.offsetX;
  64408. this._lastY = e.offsetY;
  64409. var dataByCoordSys = e.dataByCoordSys;
  64410. if (dataByCoordSys && dataByCoordSys.length) {
  64411. this._showAxisTooltip(dataByCoordSys, e);
  64412. }
  64413. // Always show item tooltip if mouse is on the element with dataIndex
  64414. else if (el && el.dataIndex != null) {
  64415. this._lastDataByCoordSys = null;
  64416. this._showSeriesItemTooltip(e, el, dispatchAction);
  64417. }
  64418. // Tooltip provided directly. Like legend.
  64419. else if (el && el.tooltip) {
  64420. this._lastDataByCoordSys = null;
  64421. this._showComponentItemTooltip(e, el, dispatchAction);
  64422. }
  64423. else {
  64424. this._lastDataByCoordSys = null;
  64425. this._hide(dispatchAction);
  64426. }
  64427. },
  64428. _showOrMove: function (tooltipModel, cb) {
  64429. // showDelay is used in this case: tooltip.enterable is set
  64430. // as true. User intent to move mouse into tooltip and click
  64431. // something. `showDelay` makes it easyer to enter the content
  64432. // but tooltip do not move immediately.
  64433. var delay = tooltipModel.get('showDelay');
  64434. cb = bind(cb, this);
  64435. clearTimeout(this._showTimout);
  64436. delay > 0
  64437. ? (this._showTimout = setTimeout(cb, delay))
  64438. : cb();
  64439. },
  64440. _showAxisTooltip: function (dataByCoordSys, e) {
  64441. var ecModel = this._ecModel;
  64442. var globalTooltipModel = this._tooltipModel;
  64443. var point = [e.offsetX, e.offsetY];
  64444. var singleDefaultHTML = [];
  64445. var singleParamsList = [];
  64446. var singleTooltipModel = buildTooltipModel([
  64447. e.tooltipOption,
  64448. globalTooltipModel
  64449. ]);
  64450. var renderMode = this._renderMode;
  64451. var newLine = this._newLine;
  64452. var markers = {};
  64453. each$17(dataByCoordSys, function (itemCoordSys) {
  64454. // var coordParamList = [];
  64455. // var coordDefaultHTML = [];
  64456. // var coordTooltipModel = buildTooltipModel([
  64457. // e.tooltipOption,
  64458. // itemCoordSys.tooltipOption,
  64459. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  64460. // globalTooltipModel
  64461. // ]);
  64462. // var displayMode = coordTooltipModel.get('displayMode');
  64463. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  64464. each$17(itemCoordSys.dataByAxis, function (item) {
  64465. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  64466. var axisValue = item.value;
  64467. var seriesDefaultHTML = [];
  64468. if (!axisModel || axisValue == null) {
  64469. return;
  64470. }
  64471. var valueLabel = getValueLabel(
  64472. axisValue, axisModel.axis, ecModel,
  64473. item.seriesDataIndices,
  64474. item.valueLabelOpt
  64475. );
  64476. each$1(item.seriesDataIndices, function (idxItem) {
  64477. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  64478. var dataIndex = idxItem.dataIndexInside;
  64479. var dataParams = series && series.getDataParams(dataIndex);
  64480. dataParams.axisDim = item.axisDim;
  64481. dataParams.axisIndex = item.axisIndex;
  64482. dataParams.axisType = item.axisType;
  64483. dataParams.axisId = item.axisId;
  64484. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  64485. dataParams.axisValueLabel = valueLabel;
  64486. if (dataParams) {
  64487. singleParamsList.push(dataParams);
  64488. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  64489. var html;
  64490. if (isObject$1(seriesTooltip)) {
  64491. html = seriesTooltip.html;
  64492. var newMarkers = seriesTooltip.markers;
  64493. merge(markers, newMarkers);
  64494. }
  64495. else {
  64496. html = seriesTooltip;
  64497. }
  64498. seriesDefaultHTML.push(html);
  64499. }
  64500. });
  64501. // Default tooltip content
  64502. // FIXME
  64503. // (1) shold be the first data which has name?
  64504. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  64505. var firstLine = valueLabel;
  64506. if (renderMode !== 'html') {
  64507. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  64508. }
  64509. else {
  64510. singleDefaultHTML.push(
  64511. (firstLine ? encodeHTML(firstLine) + newLine : '')
  64512. + seriesDefaultHTML.join(newLine)
  64513. );
  64514. }
  64515. });
  64516. }, this);
  64517. // In most case, the second axis is shown upper than the first one.
  64518. singleDefaultHTML.reverse();
  64519. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  64520. var positionExpr = e.position;
  64521. this._showOrMove(singleTooltipModel, function () {
  64522. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  64523. this._updatePosition(
  64524. singleTooltipModel,
  64525. positionExpr,
  64526. point[0], point[1],
  64527. this._tooltipContent,
  64528. singleParamsList
  64529. );
  64530. }
  64531. else {
  64532. this._showTooltipContent(
  64533. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  64534. point[0], point[1], positionExpr, undefined, markers
  64535. );
  64536. }
  64537. });
  64538. // Do not trigger events here, because this branch only be entered
  64539. // from dispatchAction.
  64540. },
  64541. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  64542. var ecModel = this._ecModel;
  64543. // Use dataModel in element if possible
  64544. // Used when mouseover on a element like markPoint or edge
  64545. // In which case, the data is not main data in series.
  64546. var seriesIndex = el.seriesIndex;
  64547. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64548. // For example, graph link.
  64549. var dataModel = el.dataModel || seriesModel;
  64550. var dataIndex = el.dataIndex;
  64551. var dataType = el.dataType;
  64552. var data = dataModel.getData();
  64553. var tooltipModel = buildTooltipModel([
  64554. data.getItemModel(dataIndex),
  64555. dataModel,
  64556. seriesModel && (seriesModel.coordinateSystem || {}).model,
  64557. this._tooltipModel
  64558. ]);
  64559. var tooltipTrigger = tooltipModel.get('trigger');
  64560. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  64561. return;
  64562. }
  64563. var params = dataModel.getDataParams(dataIndex, dataType);
  64564. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  64565. var defaultHtml;
  64566. var markers;
  64567. if (isObject$1(seriesTooltip)) {
  64568. defaultHtml = seriesTooltip.html;
  64569. markers = seriesTooltip.markers;
  64570. }
  64571. else {
  64572. defaultHtml = seriesTooltip;
  64573. markers = null;
  64574. }
  64575. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  64576. this._showOrMove(tooltipModel, function () {
  64577. this._showTooltipContent(
  64578. tooltipModel, defaultHtml, params, asyncTicket,
  64579. e.offsetX, e.offsetY, e.position, e.target, markers
  64580. );
  64581. });
  64582. // FIXME
  64583. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  64584. dispatchAction({
  64585. type: 'showTip',
  64586. dataIndexInside: dataIndex,
  64587. dataIndex: data.getRawIndex(dataIndex),
  64588. seriesIndex: seriesIndex,
  64589. from: this.uid
  64590. });
  64591. },
  64592. _showComponentItemTooltip: function (e, el, dispatchAction) {
  64593. var tooltipOpt = el.tooltip;
  64594. if (typeof tooltipOpt === 'string') {
  64595. var content = tooltipOpt;
  64596. tooltipOpt = {
  64597. content: content,
  64598. // Fixed formatter
  64599. formatter: content
  64600. };
  64601. }
  64602. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  64603. var defaultHtml = subTooltipModel.get('content');
  64604. var asyncTicket = Math.random();
  64605. // Do not check whether `trigger` is 'none' here, because `trigger`
  64606. // only works on cooridinate system. In fact, we have not found case
  64607. // that requires setting `trigger` nothing on component yet.
  64608. this._showOrMove(subTooltipModel, function () {
  64609. this._showTooltipContent(
  64610. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  64611. asyncTicket, e.offsetX, e.offsetY, e.position, el
  64612. );
  64613. });
  64614. // If not dispatch showTip, tip may be hide triggered by axis.
  64615. dispatchAction({
  64616. type: 'showTip',
  64617. from: this.uid
  64618. });
  64619. },
  64620. _showTooltipContent: function (
  64621. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  64622. ) {
  64623. // Reset ticket
  64624. this._ticket = '';
  64625. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  64626. return;
  64627. }
  64628. var tooltipContent = this._tooltipContent;
  64629. var formatter = tooltipModel.get('formatter');
  64630. positionExpr = positionExpr || tooltipModel.get('position');
  64631. var html = defaultHtml;
  64632. if (formatter && typeof formatter === 'string') {
  64633. html = formatTpl(formatter, params, true);
  64634. }
  64635. else if (typeof formatter === 'function') {
  64636. var callback = bind$3(function (cbTicket, html) {
  64637. if (cbTicket === this._ticket) {
  64638. tooltipContent.setContent(html, markers, tooltipModel);
  64639. this._updatePosition(
  64640. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64641. );
  64642. }
  64643. }, this);
  64644. this._ticket = asyncTicket;
  64645. html = formatter(params, asyncTicket, callback);
  64646. }
  64647. tooltipContent.setContent(html, markers, tooltipModel);
  64648. tooltipContent.show(tooltipModel);
  64649. this._updatePosition(
  64650. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64651. );
  64652. },
  64653. /**
  64654. * @param {string|Function|Array.<number>|Object} positionExpr
  64655. * @param {number} x Mouse x
  64656. * @param {number} y Mouse y
  64657. * @param {boolean} confine Whether confine tooltip content in view rect.
  64658. * @param {Object|<Array.<Object>} params
  64659. * @param {module:zrender/Element} el target element
  64660. * @param {module:echarts/ExtensionAPI} api
  64661. * @return {Array.<number>}
  64662. */
  64663. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  64664. var viewWidth = this._api.getWidth();
  64665. var viewHeight = this._api.getHeight();
  64666. positionExpr = positionExpr || tooltipModel.get('position');
  64667. var contentSize = content.getSize();
  64668. var align = tooltipModel.get('align');
  64669. var vAlign = tooltipModel.get('verticalAlign');
  64670. var rect = el && el.getBoundingRect().clone();
  64671. el && rect.applyTransform(el.transform);
  64672. if (typeof positionExpr === 'function') {
  64673. // Callback of position can be an array or a string specify the position
  64674. positionExpr = positionExpr([x, y], params, content.el, rect, {
  64675. viewSize: [viewWidth, viewHeight],
  64676. contentSize: contentSize.slice()
  64677. });
  64678. }
  64679. if (isArray(positionExpr)) {
  64680. x = parsePercent$2(positionExpr[0], viewWidth);
  64681. y = parsePercent$2(positionExpr[1], viewHeight);
  64682. }
  64683. else if (isObject$1(positionExpr)) {
  64684. positionExpr.width = contentSize[0];
  64685. positionExpr.height = contentSize[1];
  64686. var layoutRect = getLayoutRect(
  64687. positionExpr, {width: viewWidth, height: viewHeight}
  64688. );
  64689. x = layoutRect.x;
  64690. y = layoutRect.y;
  64691. align = null;
  64692. // When positionExpr is left/top/right/bottom,
  64693. // align and verticalAlign will not work.
  64694. vAlign = null;
  64695. }
  64696. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  64697. else if (typeof positionExpr === 'string' && el) {
  64698. var pos = calcTooltipPosition(
  64699. positionExpr, rect, contentSize
  64700. );
  64701. x = pos[0];
  64702. y = pos[1];
  64703. }
  64704. else {
  64705. var pos = refixTooltipPosition(
  64706. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  64707. );
  64708. x = pos[0];
  64709. y = pos[1];
  64710. }
  64711. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  64712. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  64713. if (tooltipModel.get('confine')) {
  64714. var pos = confineTooltipPosition(
  64715. x, y, content, viewWidth, viewHeight
  64716. );
  64717. x = pos[0];
  64718. y = pos[1];
  64719. }
  64720. content.moveTo(x, y);
  64721. },
  64722. // FIXME
  64723. // Should we remove this but leave this to user?
  64724. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  64725. var lastCoordSys = this._lastDataByCoordSys;
  64726. var contentNotChanged = !!lastCoordSys
  64727. && lastCoordSys.length === dataByCoordSys.length;
  64728. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  64729. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  64730. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  64731. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  64732. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  64733. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  64734. var thisItem = thisDataByAxis[indexAxis] || {};
  64735. var lastIndices = lastItem.seriesDataIndices || [];
  64736. var newIndices = thisItem.seriesDataIndices || [];
  64737. contentNotChanged
  64738. &= lastItem.value === thisItem.value
  64739. && lastItem.axisType === thisItem.axisType
  64740. && lastItem.axisId === thisItem.axisId
  64741. && lastIndices.length === newIndices.length;
  64742. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  64743. var newIdxItem = newIndices[j];
  64744. contentNotChanged
  64745. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  64746. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  64747. });
  64748. });
  64749. });
  64750. this._lastDataByCoordSys = dataByCoordSys;
  64751. return !!contentNotChanged;
  64752. },
  64753. _hide: function (dispatchAction) {
  64754. // Do not directly hideLater here, because this behavior may be prevented
  64755. // in dispatchAction when showTip is dispatched.
  64756. // FIXME
  64757. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  64758. this._lastDataByCoordSys = null;
  64759. dispatchAction({
  64760. type: 'hideTip',
  64761. from: this.uid
  64762. });
  64763. },
  64764. dispose: function (ecModel, api) {
  64765. if (env$1.node) {
  64766. return;
  64767. }
  64768. this._tooltipContent.hide();
  64769. unregister('itemTooltip', api);
  64770. }
  64771. });
  64772. /**
  64773. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  64774. * From top to bottom. (the last one should be globalTooltipModel);
  64775. */
  64776. function buildTooltipModel(modelCascade) {
  64777. var resultModel = modelCascade.pop();
  64778. while (modelCascade.length) {
  64779. var tooltipOpt = modelCascade.pop();
  64780. if (tooltipOpt) {
  64781. if (Model.isInstance(tooltipOpt)) {
  64782. tooltipOpt = tooltipOpt.get('tooltip', true);
  64783. }
  64784. // In each data item tooltip can be simply write:
  64785. // {
  64786. // value: 10,
  64787. // tooltip: 'Something you need to know'
  64788. // }
  64789. if (typeof tooltipOpt === 'string') {
  64790. tooltipOpt = {formatter: tooltipOpt};
  64791. }
  64792. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  64793. }
  64794. }
  64795. return resultModel;
  64796. }
  64797. function makeDispatchAction$1(payload, api) {
  64798. return payload.dispatchAction || bind(api.dispatchAction, api);
  64799. }
  64800. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  64801. var size = content.getOuterSize();
  64802. var width = size.width;
  64803. var height = size.height;
  64804. if (gapH != null) {
  64805. if (x + width + gapH > viewWidth) {
  64806. x -= width + gapH;
  64807. }
  64808. else {
  64809. x += gapH;
  64810. }
  64811. }
  64812. if (gapV != null) {
  64813. if (y + height + gapV > viewHeight) {
  64814. y -= height + gapV;
  64815. }
  64816. else {
  64817. y += gapV;
  64818. }
  64819. }
  64820. return [x, y];
  64821. }
  64822. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  64823. var size = content.getOuterSize();
  64824. var width = size.width;
  64825. var height = size.height;
  64826. x = Math.min(x + width, viewWidth) - width;
  64827. y = Math.min(y + height, viewHeight) - height;
  64828. x = Math.max(x, 0);
  64829. y = Math.max(y, 0);
  64830. return [x, y];
  64831. }
  64832. function calcTooltipPosition(position, rect, contentSize) {
  64833. var domWidth = contentSize[0];
  64834. var domHeight = contentSize[1];
  64835. var gap = 5;
  64836. var x = 0;
  64837. var y = 0;
  64838. var rectWidth = rect.width;
  64839. var rectHeight = rect.height;
  64840. switch (position) {
  64841. case 'inside':
  64842. x = rect.x + rectWidth / 2 - domWidth / 2;
  64843. y = rect.y + rectHeight / 2 - domHeight / 2;
  64844. break;
  64845. case 'top':
  64846. x = rect.x + rectWidth / 2 - domWidth / 2;
  64847. y = rect.y - domHeight - gap;
  64848. break;
  64849. case 'bottom':
  64850. x = rect.x + rectWidth / 2 - domWidth / 2;
  64851. y = rect.y + rectHeight + gap;
  64852. break;
  64853. case 'left':
  64854. x = rect.x - domWidth - gap;
  64855. y = rect.y + rectHeight / 2 - domHeight / 2;
  64856. break;
  64857. case 'right':
  64858. x = rect.x + rectWidth + gap;
  64859. y = rect.y + rectHeight / 2 - domHeight / 2;
  64860. }
  64861. return [x, y];
  64862. }
  64863. function isCenterAlign(align) {
  64864. return align === 'center' || align === 'middle';
  64865. }
  64866. /*
  64867. * Licensed to the Apache Software Foundation (ASF) under one
  64868. * or more contributor license agreements. See the NOTICE file
  64869. * distributed with this work for additional information
  64870. * regarding copyright ownership. The ASF licenses this file
  64871. * to you under the Apache License, Version 2.0 (the
  64872. * "License"); you may not use this file except in compliance
  64873. * with the License. You may obtain a copy of the License at
  64874. *
  64875. * http://www.apache.org/licenses/LICENSE-2.0
  64876. *
  64877. * Unless required by applicable law or agreed to in writing,
  64878. * software distributed under the License is distributed on an
  64879. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64880. * KIND, either express or implied. See the License for the
  64881. * specific language governing permissions and limitations
  64882. * under the License.
  64883. */
  64884. // FIXME Better way to pack data in graphic element
  64885. /**
  64886. * @action
  64887. * @property {string} type
  64888. * @property {number} seriesIndex
  64889. * @property {number} dataIndex
  64890. * @property {number} [x]
  64891. * @property {number} [y]
  64892. */
  64893. registerAction(
  64894. {
  64895. type: 'showTip',
  64896. event: 'showTip',
  64897. update: 'tooltip:manuallyShowTip'
  64898. },
  64899. // noop
  64900. function () {}
  64901. );
  64902. registerAction(
  64903. {
  64904. type: 'hideTip',
  64905. event: 'hideTip',
  64906. update: 'tooltip:manuallyHideTip'
  64907. },
  64908. // noop
  64909. function () {}
  64910. );
  64911. /*
  64912. * Licensed to the Apache Software Foundation (ASF) under one
  64913. * or more contributor license agreements. See the NOTICE file
  64914. * distributed with this work for additional information
  64915. * regarding copyright ownership. The ASF licenses this file
  64916. * to you under the Apache License, Version 2.0 (the
  64917. * "License"); you may not use this file except in compliance
  64918. * with the License. You may obtain a copy of the License at
  64919. *
  64920. * http://www.apache.org/licenses/LICENSE-2.0
  64921. *
  64922. * Unless required by applicable law or agreed to in writing,
  64923. * software distributed under the License is distributed on an
  64924. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64925. * KIND, either express or implied. See the License for the
  64926. * specific language governing permissions and limitations
  64927. * under the License.
  64928. */
  64929. function getSeriesStackId$1(seriesModel) {
  64930. return seriesModel.get('stack')
  64931. || '__ec_stack_' + seriesModel.seriesIndex;
  64932. }
  64933. function getAxisKey$1(axis) {
  64934. return axis.dim;
  64935. }
  64936. /**
  64937. * @param {string} seriesType
  64938. * @param {module:echarts/model/Global} ecModel
  64939. * @param {module:echarts/ExtensionAPI} api
  64940. */
  64941. function barLayoutPolar(seriesType, ecModel, api) {
  64942. // FIXME
  64943. // Revert becuase it brings bar progressive bug.
  64944. // The complete fix will be added in the next version.
  64945. var width = api.getWidth();
  64946. var height = api.getHeight();
  64947. var lastStackCoords = {};
  64948. var barWidthAndOffset = calRadialBar(
  64949. filter(
  64950. ecModel.getSeriesByType(seriesType),
  64951. function (seriesModel) {
  64952. return !ecModel.isSeriesFiltered(seriesModel)
  64953. && seriesModel.coordinateSystem
  64954. && seriesModel.coordinateSystem.type === 'polar';
  64955. }
  64956. )
  64957. );
  64958. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64959. // Check series coordinate, do layout for polar only
  64960. if (seriesModel.coordinateSystem.type !== 'polar') {
  64961. return;
  64962. }
  64963. var data = seriesModel.getData();
  64964. var polar = seriesModel.coordinateSystem;
  64965. var baseAxis = polar.getBaseAxis();
  64966. var stackId = getSeriesStackId$1(seriesModel);
  64967. var columnLayoutInfo
  64968. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  64969. var columnOffset = columnLayoutInfo.offset;
  64970. var columnWidth = columnLayoutInfo.width;
  64971. var valueAxis = polar.getOtherAxis(baseAxis);
  64972. var cx = seriesModel.coordinateSystem.cx;
  64973. var cy = seriesModel.coordinateSystem.cy;
  64974. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64975. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64976. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64977. var valueDim = data.mapDimension(valueAxis.dim);
  64978. var baseDim = data.mapDimension(baseAxis.dim);
  64979. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64980. var valueAxisStart = valueAxis.getExtent()[0];
  64981. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64982. var value = data.get(valueDim, idx);
  64983. var baseValue = data.get(baseDim, idx);
  64984. if (isNaN(value)) {
  64985. continue;
  64986. }
  64987. var sign = value >= 0 ? 'p' : 'n';
  64988. var baseCoord = valueAxisStart;
  64989. // Because of the barMinHeight, we can not use the value in
  64990. // stackResultDimension directly.
  64991. // Only ordinal axis can be stacked.
  64992. if (stacked) {
  64993. if (!lastStackCoords[stackId][baseValue]) {
  64994. lastStackCoords[stackId][baseValue] = {
  64995. p: valueAxisStart, // Positive stack
  64996. n: valueAxisStart // Negative stack
  64997. };
  64998. }
  64999. // Should also consider #4243
  65000. baseCoord = lastStackCoords[stackId][baseValue][sign];
  65001. }
  65002. var r0;
  65003. var r;
  65004. var startAngle;
  65005. var endAngle;
  65006. // radial sector
  65007. if (valueAxis.dim === 'radius') {
  65008. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  65009. var angle = baseAxis.dataToAngle(baseValue);
  65010. if (Math.abs(radiusSpan) < barMinHeight) {
  65011. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  65012. }
  65013. r0 = baseCoord;
  65014. r = baseCoord + radiusSpan;
  65015. startAngle = angle - columnOffset;
  65016. endAngle = startAngle - columnWidth;
  65017. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  65018. }
  65019. // tangential sector
  65020. else {
  65021. // angleAxis must be clamped.
  65022. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  65023. var radius = baseAxis.dataToRadius(baseValue);
  65024. if (Math.abs(angleSpan) < barMinAngle) {
  65025. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  65026. }
  65027. r0 = radius + columnOffset;
  65028. r = r0 + columnWidth;
  65029. startAngle = baseCoord;
  65030. endAngle = baseCoord + angleSpan;
  65031. // if the previous stack is at the end of the ring,
  65032. // add a round to differentiate it from origin
  65033. // var extent = angleAxis.getExtent();
  65034. // var stackCoord = angle;
  65035. // if (stackCoord === extent[0] && value > 0) {
  65036. // stackCoord = extent[1];
  65037. // }
  65038. // else if (stackCoord === extent[1] && value < 0) {
  65039. // stackCoord = extent[0];
  65040. // }
  65041. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  65042. }
  65043. data.setItemLayout(idx, {
  65044. cx: cx,
  65045. cy: cy,
  65046. r0: r0,
  65047. r: r,
  65048. // Consider that positive angle is anti-clockwise,
  65049. // while positive radian of sector is clockwise
  65050. startAngle: -startAngle * Math.PI / 180,
  65051. endAngle: -endAngle * Math.PI / 180
  65052. });
  65053. }
  65054. }, this);
  65055. }
  65056. /**
  65057. * Calculate bar width and offset for radial bar charts
  65058. */
  65059. function calRadialBar(barSeries, api) {
  65060. // Columns info on each category axis. Key is polar name
  65061. var columnsMap = {};
  65062. each$1(barSeries, function (seriesModel, idx) {
  65063. var data = seriesModel.getData();
  65064. var polar = seriesModel.coordinateSystem;
  65065. var baseAxis = polar.getBaseAxis();
  65066. var axisExtent = baseAxis.getExtent();
  65067. var bandWidth = baseAxis.type === 'category'
  65068. ? baseAxis.getBandWidth()
  65069. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  65070. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  65071. bandWidth: bandWidth,
  65072. remainedWidth: bandWidth,
  65073. autoWidthCount: 0,
  65074. categoryGap: '20%',
  65075. gap: '30%',
  65076. stacks: {}
  65077. };
  65078. var stacks = columnsOnAxis.stacks;
  65079. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  65080. var stackId = getSeriesStackId$1(seriesModel);
  65081. if (!stacks[stackId]) {
  65082. columnsOnAxis.autoWidthCount++;
  65083. }
  65084. stacks[stackId] = stacks[stackId] || {
  65085. width: 0,
  65086. maxWidth: 0
  65087. };
  65088. var barWidth = parsePercent$1(
  65089. seriesModel.get('barWidth'),
  65090. bandWidth
  65091. );
  65092. var barMaxWidth = parsePercent$1(
  65093. seriesModel.get('barMaxWidth'),
  65094. bandWidth
  65095. );
  65096. var barGap = seriesModel.get('barGap');
  65097. var barCategoryGap = seriesModel.get('barCategoryGap');
  65098. if (barWidth && !stacks[stackId].width) {
  65099. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  65100. stacks[stackId].width = barWidth;
  65101. columnsOnAxis.remainedWidth -= barWidth;
  65102. }
  65103. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  65104. (barGap != null) && (columnsOnAxis.gap = barGap);
  65105. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  65106. });
  65107. var result = {};
  65108. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  65109. result[coordSysName] = {};
  65110. var stacks = columnsOnAxis.stacks;
  65111. var bandWidth = columnsOnAxis.bandWidth;
  65112. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  65113. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  65114. var remainedWidth = columnsOnAxis.remainedWidth;
  65115. var autoWidthCount = columnsOnAxis.autoWidthCount;
  65116. var autoWidth = (remainedWidth - categoryGap)
  65117. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65118. autoWidth = Math.max(autoWidth, 0);
  65119. // Find if any auto calculated bar exceeded maxBarWidth
  65120. each$1(stacks, function (column, stack) {
  65121. var maxWidth = column.maxWidth;
  65122. if (maxWidth && maxWidth < autoWidth) {
  65123. maxWidth = Math.min(maxWidth, remainedWidth);
  65124. if (column.width) {
  65125. maxWidth = Math.min(maxWidth, column.width);
  65126. }
  65127. remainedWidth -= maxWidth;
  65128. column.width = maxWidth;
  65129. autoWidthCount--;
  65130. }
  65131. });
  65132. // Recalculate width again
  65133. autoWidth = (remainedWidth - categoryGap)
  65134. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65135. autoWidth = Math.max(autoWidth, 0);
  65136. var widthSum = 0;
  65137. var lastColumn;
  65138. each$1(stacks, function (column, idx) {
  65139. if (!column.width) {
  65140. column.width = autoWidth;
  65141. }
  65142. lastColumn = column;
  65143. widthSum += column.width * (1 + barGapPercent);
  65144. });
  65145. if (lastColumn) {
  65146. widthSum -= lastColumn.width * barGapPercent;
  65147. }
  65148. var offset = -widthSum / 2;
  65149. each$1(stacks, function (column, stackId) {
  65150. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  65151. offset: offset,
  65152. width: column.width
  65153. };
  65154. offset += column.width * (1 + barGapPercent);
  65155. });
  65156. });
  65157. return result;
  65158. }
  65159. /*
  65160. * Licensed to the Apache Software Foundation (ASF) under one
  65161. * or more contributor license agreements. See the NOTICE file
  65162. * distributed with this work for additional information
  65163. * regarding copyright ownership. The ASF licenses this file
  65164. * to you under the Apache License, Version 2.0 (the
  65165. * "License"); you may not use this file except in compliance
  65166. * with the License. You may obtain a copy of the License at
  65167. *
  65168. * http://www.apache.org/licenses/LICENSE-2.0
  65169. *
  65170. * Unless required by applicable law or agreed to in writing,
  65171. * software distributed under the License is distributed on an
  65172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65173. * KIND, either express or implied. See the License for the
  65174. * specific language governing permissions and limitations
  65175. * under the License.
  65176. */
  65177. function RadiusAxis(scale, radiusExtent) {
  65178. Axis.call(this, 'radius', scale, radiusExtent);
  65179. /**
  65180. * Axis type
  65181. * - 'category'
  65182. * - 'value'
  65183. * - 'time'
  65184. * - 'log'
  65185. * @type {string}
  65186. */
  65187. this.type = 'category';
  65188. }
  65189. RadiusAxis.prototype = {
  65190. constructor: RadiusAxis,
  65191. /**
  65192. * @override
  65193. */
  65194. pointToData: function (point, clamp) {
  65195. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65196. },
  65197. dataToRadius: Axis.prototype.dataToCoord,
  65198. radiusToData: Axis.prototype.coordToData
  65199. };
  65200. inherits(RadiusAxis, Axis);
  65201. /*
  65202. * Licensed to the Apache Software Foundation (ASF) under one
  65203. * or more contributor license agreements. See the NOTICE file
  65204. * distributed with this work for additional information
  65205. * regarding copyright ownership. The ASF licenses this file
  65206. * to you under the Apache License, Version 2.0 (the
  65207. * "License"); you may not use this file except in compliance
  65208. * with the License. You may obtain a copy of the License at
  65209. *
  65210. * http://www.apache.org/licenses/LICENSE-2.0
  65211. *
  65212. * Unless required by applicable law or agreed to in writing,
  65213. * software distributed under the License is distributed on an
  65214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65215. * KIND, either express or implied. See the License for the
  65216. * specific language governing permissions and limitations
  65217. * under the License.
  65218. */
  65219. var inner$12 = makeInner();
  65220. function AngleAxis(scale, angleExtent) {
  65221. angleExtent = angleExtent || [0, 360];
  65222. Axis.call(this, 'angle', scale, angleExtent);
  65223. /**
  65224. * Axis type
  65225. * - 'category'
  65226. * - 'value'
  65227. * - 'time'
  65228. * - 'log'
  65229. * @type {string}
  65230. */
  65231. this.type = 'category';
  65232. }
  65233. AngleAxis.prototype = {
  65234. constructor: AngleAxis,
  65235. /**
  65236. * @override
  65237. */
  65238. pointToData: function (point, clamp) {
  65239. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65240. },
  65241. dataToAngle: Axis.prototype.dataToCoord,
  65242. angleToData: Axis.prototype.coordToData,
  65243. /**
  65244. * Only be called in category axis.
  65245. * Angle axis uses text height to decide interval
  65246. *
  65247. * @override
  65248. * @return {number} Auto interval for cateogry axis tick and label
  65249. */
  65250. calculateCategoryInterval: function () {
  65251. var axis = this;
  65252. var labelModel = axis.getLabelModel();
  65253. var ordinalScale = axis.scale;
  65254. var ordinalExtent = ordinalScale.getExtent();
  65255. // Providing this method is for optimization:
  65256. // avoid generating a long array by `getTicks`
  65257. // in large category data case.
  65258. var tickCount = ordinalScale.count();
  65259. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  65260. return 0;
  65261. }
  65262. var tickValue = ordinalExtent[0];
  65263. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  65264. var unitH = Math.abs(unitSpan);
  65265. // Not precise, just use height as text width
  65266. // and each distance from axis line yet.
  65267. var rect = getBoundingRect(
  65268. tickValue, labelModel.getFont(), 'center', 'top'
  65269. );
  65270. var maxH = Math.max(rect.height, 7);
  65271. var dh = maxH / unitH;
  65272. // 0/0 is NaN, 1/0 is Infinity.
  65273. isNaN(dh) && (dh = Infinity);
  65274. var interval = Math.max(0, Math.floor(dh));
  65275. var cache = inner$12(axis.model);
  65276. var lastAutoInterval = cache.lastAutoInterval;
  65277. var lastTickCount = cache.lastTickCount;
  65278. // Use cache to keep interval stable while moving zoom window,
  65279. // otherwise the calculated interval might jitter when the zoom
  65280. // window size is close to the interval-changing size.
  65281. if (lastAutoInterval != null
  65282. && lastTickCount != null
  65283. && Math.abs(lastAutoInterval - interval) <= 1
  65284. && Math.abs(lastTickCount - tickCount) <= 1
  65285. // Always choose the bigger one, otherwise the critical
  65286. // point is not the same when zooming in or zooming out.
  65287. && lastAutoInterval > interval
  65288. ) {
  65289. interval = lastAutoInterval;
  65290. }
  65291. // Only update cache if cache not used, otherwise the
  65292. // changing of interval is too insensitive.
  65293. else {
  65294. cache.lastTickCount = tickCount;
  65295. cache.lastAutoInterval = interval;
  65296. }
  65297. return interval;
  65298. }
  65299. };
  65300. inherits(AngleAxis, Axis);
  65301. /*
  65302. * Licensed to the Apache Software Foundation (ASF) under one
  65303. * or more contributor license agreements. See the NOTICE file
  65304. * distributed with this work for additional information
  65305. * regarding copyright ownership. The ASF licenses this file
  65306. * to you under the Apache License, Version 2.0 (the
  65307. * "License"); you may not use this file except in compliance
  65308. * with the License. You may obtain a copy of the License at
  65309. *
  65310. * http://www.apache.org/licenses/LICENSE-2.0
  65311. *
  65312. * Unless required by applicable law or agreed to in writing,
  65313. * software distributed under the License is distributed on an
  65314. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65315. * KIND, either express or implied. See the License for the
  65316. * specific language governing permissions and limitations
  65317. * under the License.
  65318. */
  65319. /**
  65320. * @module echarts/coord/polar/Polar
  65321. */
  65322. /**
  65323. * @alias {module:echarts/coord/polar/Polar}
  65324. * @constructor
  65325. * @param {string} name
  65326. */
  65327. var Polar = function (name) {
  65328. /**
  65329. * @type {string}
  65330. */
  65331. this.name = name || '';
  65332. /**
  65333. * x of polar center
  65334. * @type {number}
  65335. */
  65336. this.cx = 0;
  65337. /**
  65338. * y of polar center
  65339. * @type {number}
  65340. */
  65341. this.cy = 0;
  65342. /**
  65343. * @type {module:echarts/coord/polar/RadiusAxis}
  65344. * @private
  65345. */
  65346. this._radiusAxis = new RadiusAxis();
  65347. /**
  65348. * @type {module:echarts/coord/polar/AngleAxis}
  65349. * @private
  65350. */
  65351. this._angleAxis = new AngleAxis();
  65352. this._radiusAxis.polar = this._angleAxis.polar = this;
  65353. };
  65354. Polar.prototype = {
  65355. type: 'polar',
  65356. axisPointerEnabled: true,
  65357. constructor: Polar,
  65358. /**
  65359. * @param {Array.<string>}
  65360. * @readOnly
  65361. */
  65362. dimensions: ['radius', 'angle'],
  65363. /**
  65364. * @type {module:echarts/coord/PolarModel}
  65365. */
  65366. model: null,
  65367. /**
  65368. * If contain coord
  65369. * @param {Array.<number>} point
  65370. * @return {boolean}
  65371. */
  65372. containPoint: function (point) {
  65373. var coord = this.pointToCoord(point);
  65374. return this._radiusAxis.contain(coord[0])
  65375. && this._angleAxis.contain(coord[1]);
  65376. },
  65377. /**
  65378. * If contain data
  65379. * @param {Array.<number>} data
  65380. * @return {boolean}
  65381. */
  65382. containData: function (data) {
  65383. return this._radiusAxis.containData(data[0])
  65384. && this._angleAxis.containData(data[1]);
  65385. },
  65386. /**
  65387. * @param {string} dim
  65388. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65389. */
  65390. getAxis: function (dim) {
  65391. return this['_' + dim + 'Axis'];
  65392. },
  65393. /**
  65394. * @return {Array.<module:echarts/coord/Axis>}
  65395. */
  65396. getAxes: function () {
  65397. return [this._radiusAxis, this._angleAxis];
  65398. },
  65399. /**
  65400. * Get axes by type of scale
  65401. * @param {string} scaleType
  65402. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65403. */
  65404. getAxesByScale: function (scaleType) {
  65405. var axes = [];
  65406. var angleAxis = this._angleAxis;
  65407. var radiusAxis = this._radiusAxis;
  65408. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  65409. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  65410. return axes;
  65411. },
  65412. /**
  65413. * @return {module:echarts/coord/polar/AngleAxis}
  65414. */
  65415. getAngleAxis: function () {
  65416. return this._angleAxis;
  65417. },
  65418. /**
  65419. * @return {module:echarts/coord/polar/RadiusAxis}
  65420. */
  65421. getRadiusAxis: function () {
  65422. return this._radiusAxis;
  65423. },
  65424. /**
  65425. * @param {module:echarts/coord/polar/Axis}
  65426. * @return {module:echarts/coord/polar/Axis}
  65427. */
  65428. getOtherAxis: function (axis) {
  65429. var angleAxis = this._angleAxis;
  65430. return axis === angleAxis ? this._radiusAxis : angleAxis;
  65431. },
  65432. /**
  65433. * Base axis will be used on stacking.
  65434. *
  65435. * @return {module:echarts/coord/polar/Axis}
  65436. */
  65437. getBaseAxis: function () {
  65438. return this.getAxesByScale('ordinal')[0]
  65439. || this.getAxesByScale('time')[0]
  65440. || this.getAngleAxis();
  65441. },
  65442. /**
  65443. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  65444. * @return {Object} {baseAxes: [], otherAxes: []}
  65445. */
  65446. getTooltipAxes: function (dim) {
  65447. var baseAxis = (dim != null && dim !== 'auto')
  65448. ? this.getAxis(dim) : this.getBaseAxis();
  65449. return {
  65450. baseAxes: [baseAxis],
  65451. otherAxes: [this.getOtherAxis(baseAxis)]
  65452. };
  65453. },
  65454. /**
  65455. * Convert a single data item to (x, y) point.
  65456. * Parameter data is an array which the first element is radius and the second is angle
  65457. * @param {Array.<number>} data
  65458. * @param {boolean} [clamp=false]
  65459. * @return {Array.<number>}
  65460. */
  65461. dataToPoint: function (data, clamp) {
  65462. return this.coordToPoint([
  65463. this._radiusAxis.dataToRadius(data[0], clamp),
  65464. this._angleAxis.dataToAngle(data[1], clamp)
  65465. ]);
  65466. },
  65467. /**
  65468. * Convert a (x, y) point to data
  65469. * @param {Array.<number>} point
  65470. * @param {boolean} [clamp=false]
  65471. * @return {Array.<number>}
  65472. */
  65473. pointToData: function (point, clamp) {
  65474. var coord = this.pointToCoord(point);
  65475. return [
  65476. this._radiusAxis.radiusToData(coord[0], clamp),
  65477. this._angleAxis.angleToData(coord[1], clamp)
  65478. ];
  65479. },
  65480. /**
  65481. * Convert a (x, y) point to (radius, angle) coord
  65482. * @param {Array.<number>} point
  65483. * @return {Array.<number>}
  65484. */
  65485. pointToCoord: function (point) {
  65486. var dx = point[0] - this.cx;
  65487. var dy = point[1] - this.cy;
  65488. var angleAxis = this.getAngleAxis();
  65489. var extent = angleAxis.getExtent();
  65490. var minAngle = Math.min(extent[0], extent[1]);
  65491. var maxAngle = Math.max(extent[0], extent[1]);
  65492. // Fix fixed extent in polarCreator
  65493. // FIXME
  65494. angleAxis.inverse
  65495. ? (minAngle = maxAngle - 360)
  65496. : (maxAngle = minAngle + 360);
  65497. var radius = Math.sqrt(dx * dx + dy * dy);
  65498. dx /= radius;
  65499. dy /= radius;
  65500. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  65501. // move to angleExtent
  65502. var dir = radian < minAngle ? 1 : -1;
  65503. while (radian < minAngle || radian > maxAngle) {
  65504. radian += dir * 360;
  65505. }
  65506. return [radius, radian];
  65507. },
  65508. /**
  65509. * Convert a (radius, angle) coord to (x, y) point
  65510. * @param {Array.<number>} coord
  65511. * @return {Array.<number>}
  65512. */
  65513. coordToPoint: function (coord) {
  65514. var radius = coord[0];
  65515. var radian = coord[1] / 180 * Math.PI;
  65516. var x = Math.cos(radian) * radius + this.cx;
  65517. // Inverse the y
  65518. var y = -Math.sin(radian) * radius + this.cy;
  65519. return [x, y];
  65520. }
  65521. };
  65522. /*
  65523. * Licensed to the Apache Software Foundation (ASF) under one
  65524. * or more contributor license agreements. See the NOTICE file
  65525. * distributed with this work for additional information
  65526. * regarding copyright ownership. The ASF licenses this file
  65527. * to you under the Apache License, Version 2.0 (the
  65528. * "License"); you may not use this file except in compliance
  65529. * with the License. You may obtain a copy of the License at
  65530. *
  65531. * http://www.apache.org/licenses/LICENSE-2.0
  65532. *
  65533. * Unless required by applicable law or agreed to in writing,
  65534. * software distributed under the License is distributed on an
  65535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65536. * KIND, either express or implied. See the License for the
  65537. * specific language governing permissions and limitations
  65538. * under the License.
  65539. */
  65540. var PolarAxisModel = ComponentModel.extend({
  65541. type: 'polarAxis',
  65542. /**
  65543. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65544. */
  65545. axis: null,
  65546. /**
  65547. * @override
  65548. */
  65549. getCoordSysModel: function () {
  65550. return this.ecModel.queryComponents({
  65551. mainType: 'polar',
  65552. index: this.option.polarIndex,
  65553. id: this.option.polarId
  65554. })[0];
  65555. }
  65556. });
  65557. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  65558. var polarAxisDefaultExtendedOption = {
  65559. angle: {
  65560. // polarIndex: 0,
  65561. // polarId: '',
  65562. startAngle: 90,
  65563. clockwise: true,
  65564. splitNumber: 12,
  65565. axisLabel: {
  65566. rotate: false
  65567. }
  65568. },
  65569. radius: {
  65570. // polarIndex: 0,
  65571. // polarId: '',
  65572. splitNumber: 5
  65573. }
  65574. };
  65575. function getAxisType$3(axisDim, option) {
  65576. // Default axis with data is category axis
  65577. return option.type || (option.data ? 'category' : 'value');
  65578. }
  65579. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  65580. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  65581. /*
  65582. * Licensed to the Apache Software Foundation (ASF) under one
  65583. * or more contributor license agreements. See the NOTICE file
  65584. * distributed with this work for additional information
  65585. * regarding copyright ownership. The ASF licenses this file
  65586. * to you under the Apache License, Version 2.0 (the
  65587. * "License"); you may not use this file except in compliance
  65588. * with the License. You may obtain a copy of the License at
  65589. *
  65590. * http://www.apache.org/licenses/LICENSE-2.0
  65591. *
  65592. * Unless required by applicable law or agreed to in writing,
  65593. * software distributed under the License is distributed on an
  65594. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65595. * KIND, either express or implied. See the License for the
  65596. * specific language governing permissions and limitations
  65597. * under the License.
  65598. */
  65599. extendComponentModel({
  65600. type: 'polar',
  65601. dependencies: ['polarAxis', 'angleAxis'],
  65602. /**
  65603. * @type {module:echarts/coord/polar/Polar}
  65604. */
  65605. coordinateSystem: null,
  65606. /**
  65607. * @param {string} axisType
  65608. * @return {module:echarts/coord/polar/AxisModel}
  65609. */
  65610. findAxisModel: function (axisType) {
  65611. var foundAxisModel;
  65612. var ecModel = this.ecModel;
  65613. ecModel.eachComponent(axisType, function (axisModel) {
  65614. if (axisModel.getCoordSysModel() === this) {
  65615. foundAxisModel = axisModel;
  65616. }
  65617. }, this);
  65618. return foundAxisModel;
  65619. },
  65620. defaultOption: {
  65621. zlevel: 0,
  65622. z: 0,
  65623. center: ['50%', '50%'],
  65624. radius: '80%'
  65625. }
  65626. });
  65627. /*
  65628. * Licensed to the Apache Software Foundation (ASF) under one
  65629. * or more contributor license agreements. See the NOTICE file
  65630. * distributed with this work for additional information
  65631. * regarding copyright ownership. The ASF licenses this file
  65632. * to you under the Apache License, Version 2.0 (the
  65633. * "License"); you may not use this file except in compliance
  65634. * with the License. You may obtain a copy of the License at
  65635. *
  65636. * http://www.apache.org/licenses/LICENSE-2.0
  65637. *
  65638. * Unless required by applicable law or agreed to in writing,
  65639. * software distributed under the License is distributed on an
  65640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65641. * KIND, either express or implied. See the License for the
  65642. * specific language governing permissions and limitations
  65643. * under the License.
  65644. */
  65645. // TODO Axis scale
  65646. /**
  65647. * Resize method bound to the polar
  65648. * @param {module:echarts/coord/polar/PolarModel} polarModel
  65649. * @param {module:echarts/ExtensionAPI} api
  65650. */
  65651. function resizePolar(polar, polarModel, api) {
  65652. var center = polarModel.get('center');
  65653. var width = api.getWidth();
  65654. var height = api.getHeight();
  65655. polar.cx = parsePercent$1(center[0], width);
  65656. polar.cy = parsePercent$1(center[1], height);
  65657. var radiusAxis = polar.getRadiusAxis();
  65658. var size = Math.min(width, height) / 2;
  65659. var radius = parsePercent$1(polarModel.get('radius'), size);
  65660. radiusAxis.inverse
  65661. ? radiusAxis.setExtent(radius, 0)
  65662. : radiusAxis.setExtent(0, radius);
  65663. }
  65664. /**
  65665. * Update polar
  65666. */
  65667. function updatePolarScale(ecModel, api) {
  65668. var polar = this;
  65669. var angleAxis = polar.getAngleAxis();
  65670. var radiusAxis = polar.getRadiusAxis();
  65671. // Reset scale
  65672. angleAxis.scale.setExtent(Infinity, -Infinity);
  65673. radiusAxis.scale.setExtent(Infinity, -Infinity);
  65674. ecModel.eachSeries(function (seriesModel) {
  65675. if (seriesModel.coordinateSystem === polar) {
  65676. var data = seriesModel.getData();
  65677. each$1(data.mapDimension('radius', true), function (dim) {
  65678. radiusAxis.scale.unionExtentFromData(
  65679. data, getStackedDimension(data, dim)
  65680. );
  65681. });
  65682. each$1(data.mapDimension('angle', true), function (dim) {
  65683. angleAxis.scale.unionExtentFromData(
  65684. data, getStackedDimension(data, dim)
  65685. );
  65686. });
  65687. }
  65688. });
  65689. niceScaleExtent(angleAxis.scale, angleAxis.model);
  65690. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  65691. // Fix extent of category angle axis
  65692. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  65693. var extent = angleAxis.getExtent();
  65694. var diff = 360 / angleAxis.scale.count();
  65695. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  65696. angleAxis.setExtent(extent[0], extent[1]);
  65697. }
  65698. }
  65699. /**
  65700. * Set common axis properties
  65701. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65702. * @param {module:echarts/coord/polar/AxisModel}
  65703. * @inner
  65704. */
  65705. function setAxis(axis, axisModel) {
  65706. axis.type = axisModel.get('type');
  65707. axis.scale = createScaleByModel(axisModel);
  65708. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65709. axis.inverse = axisModel.get('inverse');
  65710. if (axisModel.mainType === 'angleAxis') {
  65711. axis.inverse ^= axisModel.get('clockwise');
  65712. var startAngle = axisModel.get('startAngle');
  65713. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65714. }
  65715. // Inject axis instance
  65716. axisModel.axis = axis;
  65717. axis.model = axisModel;
  65718. }
  65719. var polarCreator = {
  65720. dimensions: Polar.prototype.dimensions,
  65721. create: function (ecModel, api) {
  65722. var polarList = [];
  65723. ecModel.eachComponent('polar', function (polarModel, idx) {
  65724. var polar = new Polar(idx);
  65725. // Inject resize and update method
  65726. polar.update = updatePolarScale;
  65727. var radiusAxis = polar.getRadiusAxis();
  65728. var angleAxis = polar.getAngleAxis();
  65729. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65730. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65731. setAxis(radiusAxis, radiusAxisModel);
  65732. setAxis(angleAxis, angleAxisModel);
  65733. resizePolar(polar, polarModel, api);
  65734. polarList.push(polar);
  65735. polarModel.coordinateSystem = polar;
  65736. polar.model = polarModel;
  65737. });
  65738. // Inject coordinateSystem to series
  65739. ecModel.eachSeries(function (seriesModel) {
  65740. if (seriesModel.get('coordinateSystem') === 'polar') {
  65741. var polarModel = ecModel.queryComponents({
  65742. mainType: 'polar',
  65743. index: seriesModel.get('polarIndex'),
  65744. id: seriesModel.get('polarId')
  65745. })[0];
  65746. if (__DEV__) {
  65747. if (!polarModel) {
  65748. throw new Error(
  65749. 'Polar "' + retrieve(
  65750. seriesModel.get('polarIndex'),
  65751. seriesModel.get('polarId'),
  65752. 0
  65753. ) + '" not found'
  65754. );
  65755. }
  65756. }
  65757. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65758. }
  65759. });
  65760. return polarList;
  65761. }
  65762. };
  65763. CoordinateSystemManager.register('polar', polarCreator);
  65764. /*
  65765. * Licensed to the Apache Software Foundation (ASF) under one
  65766. * or more contributor license agreements. See the NOTICE file
  65767. * distributed with this work for additional information
  65768. * regarding copyright ownership. The ASF licenses this file
  65769. * to you under the Apache License, Version 2.0 (the
  65770. * "License"); you may not use this file except in compliance
  65771. * with the License. You may obtain a copy of the License at
  65772. *
  65773. * http://www.apache.org/licenses/LICENSE-2.0
  65774. *
  65775. * Unless required by applicable law or agreed to in writing,
  65776. * software distributed under the License is distributed on an
  65777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65778. * KIND, either express or implied. See the License for the
  65779. * specific language governing permissions and limitations
  65780. * under the License.
  65781. */
  65782. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  65783. function getAxisLineShape(polar, rExtent, angle) {
  65784. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65785. var start = polar.coordToPoint([rExtent[0], angle]);
  65786. var end = polar.coordToPoint([rExtent[1], angle]);
  65787. return {
  65788. x1: start[0],
  65789. y1: start[1],
  65790. x2: end[0],
  65791. y2: end[1]
  65792. };
  65793. }
  65794. function getRadiusIdx(polar) {
  65795. var radiusAxis = polar.getRadiusAxis();
  65796. return radiusAxis.inverse ? 0 : 1;
  65797. }
  65798. // Remove the last tick which will overlap the first tick
  65799. function fixAngleOverlap(list) {
  65800. var firstItem = list[0];
  65801. var lastItem = list[list.length - 1];
  65802. if (firstItem
  65803. && lastItem
  65804. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65805. ) {
  65806. list.pop();
  65807. }
  65808. }
  65809. AxisView.extend({
  65810. type: 'angleAxis',
  65811. axisPointerClass: 'PolarAxisPointer',
  65812. render: function (angleAxisModel, ecModel) {
  65813. this.group.removeAll();
  65814. if (!angleAxisModel.get('show')) {
  65815. return;
  65816. }
  65817. var angleAxis = angleAxisModel.axis;
  65818. var polar = angleAxis.polar;
  65819. var radiusExtent = polar.getRadiusAxis().getExtent();
  65820. var ticksAngles = angleAxis.getTicksCoords();
  65821. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65822. var labelItem = clone(labelItem);
  65823. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65824. return labelItem;
  65825. });
  65826. fixAngleOverlap(labels);
  65827. fixAngleOverlap(ticksAngles);
  65828. each$1(elementList$1, function (name) {
  65829. if (angleAxisModel.get(name + '.show')
  65830. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65831. ) {
  65832. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  65833. }
  65834. }, this);
  65835. },
  65836. /**
  65837. * @private
  65838. */
  65839. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65840. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65841. var circle = new Circle({
  65842. shape: {
  65843. cx: polar.cx,
  65844. cy: polar.cy,
  65845. r: radiusExtent[getRadiusIdx(polar)]
  65846. },
  65847. style: lineStyleModel.getLineStyle(),
  65848. z2: 1,
  65849. silent: true
  65850. });
  65851. circle.style.fill = null;
  65852. this.group.add(circle);
  65853. },
  65854. /**
  65855. * @private
  65856. */
  65857. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65858. var tickModel = angleAxisModel.getModel('axisTick');
  65859. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65860. var radius = radiusExtent[getRadiusIdx(polar)];
  65861. var lines = map(ticksAngles, function (tickAngleItem) {
  65862. return new Line({
  65863. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65864. });
  65865. });
  65866. this.group.add(mergePath(
  65867. lines, {
  65868. style: defaults(
  65869. tickModel.getModel('lineStyle').getLineStyle(),
  65870. {
  65871. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65872. }
  65873. )
  65874. }
  65875. ));
  65876. },
  65877. /**
  65878. * @private
  65879. */
  65880. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  65881. var rawCategoryData = angleAxisModel.getCategories(true);
  65882. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65883. var labelMargin = commonLabelModel.get('margin');
  65884. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65885. each$1(labels, function (labelItem, idx) {
  65886. var labelModel = commonLabelModel;
  65887. var tickValue = labelItem.tickValue;
  65888. var r = radiusExtent[getRadiusIdx(polar)];
  65889. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65890. var cx = polar.cx;
  65891. var cy = polar.cy;
  65892. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65893. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65894. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  65895. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  65896. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  65897. labelModel = new Model(
  65898. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  65899. );
  65900. }
  65901. var textEl = new Text({silent: true});
  65902. this.group.add(textEl);
  65903. setTextStyle(textEl.style, labelModel, {
  65904. x: p[0],
  65905. y: p[1],
  65906. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  65907. text: labelItem.formattedLabel,
  65908. textAlign: labelTextAlign,
  65909. textVerticalAlign: labelTextVerticalAlign
  65910. });
  65911. }, this);
  65912. },
  65913. /**
  65914. * @private
  65915. */
  65916. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65917. var splitLineModel = angleAxisModel.getModel('splitLine');
  65918. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65919. var lineColors = lineStyleModel.get('color');
  65920. var lineCount = 0;
  65921. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65922. var splitLines = [];
  65923. for (var i = 0; i < ticksAngles.length; i++) {
  65924. var colorIndex = (lineCount++) % lineColors.length;
  65925. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65926. splitLines[colorIndex].push(new Line({
  65927. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65928. }));
  65929. }
  65930. // Simple optimization
  65931. // Batching the lines if color are the same
  65932. for (var i = 0; i < splitLines.length; i++) {
  65933. this.group.add(mergePath(splitLines[i], {
  65934. style: defaults({
  65935. stroke: lineColors[i % lineColors.length]
  65936. }, lineStyleModel.getLineStyle()),
  65937. silent: true,
  65938. z: angleAxisModel.get('z')
  65939. }));
  65940. }
  65941. },
  65942. /**
  65943. * @private
  65944. */
  65945. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65946. if (!ticksAngles.length) {
  65947. return;
  65948. }
  65949. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65950. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65951. var areaColors = areaStyleModel.get('color');
  65952. var lineCount = 0;
  65953. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65954. var splitAreas = [];
  65955. var RADIAN = Math.PI / 180;
  65956. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65957. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65958. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65959. var clockwise = angleAxisModel.get('clockwise');
  65960. for (var i = 1; i < ticksAngles.length; i++) {
  65961. var colorIndex = (lineCount++) % areaColors.length;
  65962. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65963. splitAreas[colorIndex].push(new Sector({
  65964. shape: {
  65965. cx: polar.cx,
  65966. cy: polar.cy,
  65967. r0: r0,
  65968. r: r1,
  65969. startAngle: prevAngle,
  65970. endAngle: -ticksAngles[i].coord * RADIAN,
  65971. clockwise: clockwise
  65972. },
  65973. silent: true
  65974. }));
  65975. prevAngle = -ticksAngles[i].coord * RADIAN;
  65976. }
  65977. // Simple optimization
  65978. // Batching the lines if color are the same
  65979. for (var i = 0; i < splitAreas.length; i++) {
  65980. this.group.add(mergePath(splitAreas[i], {
  65981. style: defaults({
  65982. fill: areaColors[i % areaColors.length]
  65983. }, areaStyleModel.getAreaStyle()),
  65984. silent: true
  65985. }));
  65986. }
  65987. }
  65988. });
  65989. /*
  65990. * Licensed to the Apache Software Foundation (ASF) under one
  65991. * or more contributor license agreements. See the NOTICE file
  65992. * distributed with this work for additional information
  65993. * regarding copyright ownership. The ASF licenses this file
  65994. * to you under the Apache License, Version 2.0 (the
  65995. * "License"); you may not use this file except in compliance
  65996. * with the License. You may obtain a copy of the License at
  65997. *
  65998. * http://www.apache.org/licenses/LICENSE-2.0
  65999. *
  66000. * Unless required by applicable law or agreed to in writing,
  66001. * software distributed under the License is distributed on an
  66002. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66003. * KIND, either express or implied. See the License for the
  66004. * specific language governing permissions and limitations
  66005. * under the License.
  66006. */
  66007. /*
  66008. * Licensed to the Apache Software Foundation (ASF) under one
  66009. * or more contributor license agreements. See the NOTICE file
  66010. * distributed with this work for additional information
  66011. * regarding copyright ownership. The ASF licenses this file
  66012. * to you under the Apache License, Version 2.0 (the
  66013. * "License"); you may not use this file except in compliance
  66014. * with the License. You may obtain a copy of the License at
  66015. *
  66016. * http://www.apache.org/licenses/LICENSE-2.0
  66017. *
  66018. * Unless required by applicable law or agreed to in writing,
  66019. * software distributed under the License is distributed on an
  66020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66021. * KIND, either express or implied. See the License for the
  66022. * specific language governing permissions and limitations
  66023. * under the License.
  66024. */
  66025. var axisBuilderAttrs$3 = [
  66026. 'axisLine', 'axisTickLabel', 'axisName'
  66027. ];
  66028. var selfBuilderAttrs$1 = [
  66029. 'splitLine', 'splitArea'
  66030. ];
  66031. AxisView.extend({
  66032. type: 'radiusAxis',
  66033. axisPointerClass: 'PolarAxisPointer',
  66034. render: function (radiusAxisModel, ecModel) {
  66035. this.group.removeAll();
  66036. if (!radiusAxisModel.get('show')) {
  66037. return;
  66038. }
  66039. var radiusAxis = radiusAxisModel.axis;
  66040. var polar = radiusAxis.polar;
  66041. var angleAxis = polar.getAngleAxis();
  66042. var ticksCoords = radiusAxis.getTicksCoords();
  66043. var axisAngle = angleAxis.getExtent()[0];
  66044. var radiusExtent = radiusAxis.getExtent();
  66045. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  66046. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  66047. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  66048. this.group.add(axisBuilder.getGroup());
  66049. each$1(selfBuilderAttrs$1, function (name) {
  66050. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  66051. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  66052. }
  66053. }, this);
  66054. },
  66055. /**
  66056. * @private
  66057. */
  66058. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66059. var splitLineModel = radiusAxisModel.getModel('splitLine');
  66060. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66061. var lineColors = lineStyleModel.get('color');
  66062. var lineCount = 0;
  66063. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66064. var splitLines = [];
  66065. for (var i = 0; i < ticksCoords.length; i++) {
  66066. var colorIndex = (lineCount++) % lineColors.length;
  66067. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66068. splitLines[colorIndex].push(new Circle({
  66069. shape: {
  66070. cx: polar.cx,
  66071. cy: polar.cy,
  66072. r: ticksCoords[i].coord
  66073. },
  66074. silent: true
  66075. }));
  66076. }
  66077. // Simple optimization
  66078. // Batching the lines if color are the same
  66079. for (var i = 0; i < splitLines.length; i++) {
  66080. this.group.add(mergePath(splitLines[i], {
  66081. style: defaults({
  66082. stroke: lineColors[i % lineColors.length],
  66083. fill: null
  66084. }, lineStyleModel.getLineStyle()),
  66085. silent: true
  66086. }));
  66087. }
  66088. },
  66089. /**
  66090. * @private
  66091. */
  66092. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66093. if (!ticksCoords.length) {
  66094. return;
  66095. }
  66096. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66097. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66098. var areaColors = areaStyleModel.get('color');
  66099. var lineCount = 0;
  66100. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66101. var splitAreas = [];
  66102. var prevRadius = ticksCoords[0].coord;
  66103. for (var i = 1; i < ticksCoords.length; i++) {
  66104. var colorIndex = (lineCount++) % areaColors.length;
  66105. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66106. splitAreas[colorIndex].push(new Sector({
  66107. shape: {
  66108. cx: polar.cx,
  66109. cy: polar.cy,
  66110. r0: prevRadius,
  66111. r: ticksCoords[i].coord,
  66112. startAngle: 0,
  66113. endAngle: Math.PI * 2
  66114. },
  66115. silent: true
  66116. }));
  66117. prevRadius = ticksCoords[i].coord;
  66118. }
  66119. // Simple optimization
  66120. // Batching the lines if color are the same
  66121. for (var i = 0; i < splitAreas.length; i++) {
  66122. this.group.add(mergePath(splitAreas[i], {
  66123. style: defaults({
  66124. fill: areaColors[i % areaColors.length]
  66125. }, areaStyleModel.getAreaStyle()),
  66126. silent: true
  66127. }));
  66128. }
  66129. }
  66130. });
  66131. /**
  66132. * @inner
  66133. */
  66134. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66135. return {
  66136. position: [polar.cx, polar.cy],
  66137. rotation: axisAngle / 180 * Math.PI,
  66138. labelDirection: -1,
  66139. tickDirection: -1,
  66140. nameDirection: 1,
  66141. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66142. // Over splitLine and splitArea
  66143. z2: 1
  66144. };
  66145. }
  66146. /*
  66147. * Licensed to the Apache Software Foundation (ASF) under one
  66148. * or more contributor license agreements. See the NOTICE file
  66149. * distributed with this work for additional information
  66150. * regarding copyright ownership. The ASF licenses this file
  66151. * to you under the Apache License, Version 2.0 (the
  66152. * "License"); you may not use this file except in compliance
  66153. * with the License. You may obtain a copy of the License at
  66154. *
  66155. * http://www.apache.org/licenses/LICENSE-2.0
  66156. *
  66157. * Unless required by applicable law or agreed to in writing,
  66158. * software distributed under the License is distributed on an
  66159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66160. * KIND, either express or implied. See the License for the
  66161. * specific language governing permissions and limitations
  66162. * under the License.
  66163. */
  66164. /*
  66165. * Licensed to the Apache Software Foundation (ASF) under one
  66166. * or more contributor license agreements. See the NOTICE file
  66167. * distributed with this work for additional information
  66168. * regarding copyright ownership. The ASF licenses this file
  66169. * to you under the Apache License, Version 2.0 (the
  66170. * "License"); you may not use this file except in compliance
  66171. * with the License. You may obtain a copy of the License at
  66172. *
  66173. * http://www.apache.org/licenses/LICENSE-2.0
  66174. *
  66175. * Unless required by applicable law or agreed to in writing,
  66176. * software distributed under the License is distributed on an
  66177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66178. * KIND, either express or implied. See the License for the
  66179. * specific language governing permissions and limitations
  66180. * under the License.
  66181. */
  66182. var PolarAxisPointer = BaseAxisPointer.extend({
  66183. /**
  66184. * @override
  66185. */
  66186. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  66187. var axis = axisModel.axis;
  66188. if (axis.dim === 'angle') {
  66189. this.animationThreshold = Math.PI / 18;
  66190. }
  66191. var polar = axis.polar;
  66192. var otherAxis = polar.getOtherAxis(axis);
  66193. var otherExtent = otherAxis.getExtent();
  66194. var coordValue;
  66195. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  66196. var axisPointerType = axisPointerModel.get('type');
  66197. if (axisPointerType && axisPointerType !== 'none') {
  66198. var elStyle = buildElStyle(axisPointerModel);
  66199. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  66200. axis, polar, coordValue, otherExtent, elStyle
  66201. );
  66202. pointerOption.style = elStyle;
  66203. elOption.graphicKey = pointerOption.type;
  66204. elOption.pointer = pointerOption;
  66205. }
  66206. var labelMargin = axisPointerModel.get('label.margin');
  66207. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  66208. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  66209. }
  66210. // Do not support handle, utill any user requires it.
  66211. });
  66212. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  66213. var axis = axisModel.axis;
  66214. var coord = axis.dataToCoord(value);
  66215. var axisAngle = polar.getAngleAxis().getExtent()[0];
  66216. axisAngle = axisAngle / 180 * Math.PI;
  66217. var radiusExtent = polar.getRadiusAxis().getExtent();
  66218. var position;
  66219. var align;
  66220. var verticalAlign;
  66221. if (axis.dim === 'radius') {
  66222. var transform = create$1();
  66223. rotate(transform, transform, axisAngle);
  66224. translate(transform, transform, [polar.cx, polar.cy]);
  66225. position = applyTransform$1([coord, -labelMargin], transform);
  66226. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  66227. var labelLayout = AxisBuilder.innerTextLayout(
  66228. axisAngle, labelRotation * Math.PI / 180, -1
  66229. );
  66230. align = labelLayout.textAlign;
  66231. verticalAlign = labelLayout.textVerticalAlign;
  66232. }
  66233. else { // angle axis
  66234. var r = radiusExtent[1];
  66235. position = polar.coordToPoint([r + labelMargin, coord]);
  66236. var cx = polar.cx;
  66237. var cy = polar.cy;
  66238. align = Math.abs(position[0] - cx) / r < 0.3
  66239. ? 'center' : (position[0] > cx ? 'left' : 'right');
  66240. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  66241. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  66242. }
  66243. return {
  66244. position: position,
  66245. align: align,
  66246. verticalAlign: verticalAlign
  66247. };
  66248. }
  66249. var pointerShapeBuilder$2 = {
  66250. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  66251. return axis.dim === 'angle'
  66252. ? {
  66253. type: 'Line',
  66254. shape: makeLineShape(
  66255. polar.coordToPoint([otherExtent[0], coordValue]),
  66256. polar.coordToPoint([otherExtent[1], coordValue])
  66257. )
  66258. }
  66259. : {
  66260. type: 'Circle',
  66261. shape: {
  66262. cx: polar.cx,
  66263. cy: polar.cy,
  66264. r: coordValue
  66265. }
  66266. };
  66267. },
  66268. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  66269. var bandWidth = Math.max(1, axis.getBandWidth());
  66270. var radian = Math.PI / 180;
  66271. return axis.dim === 'angle'
  66272. ? {
  66273. type: 'Sector',
  66274. shape: makeSectorShape(
  66275. polar.cx, polar.cy,
  66276. otherExtent[0], otherExtent[1],
  66277. // In ECharts y is negative if angle is positive
  66278. (-coordValue - bandWidth / 2) * radian,
  66279. (-coordValue + bandWidth / 2) * radian
  66280. )
  66281. }
  66282. : {
  66283. type: 'Sector',
  66284. shape: makeSectorShape(
  66285. polar.cx, polar.cy,
  66286. coordValue - bandWidth / 2,
  66287. coordValue + bandWidth / 2,
  66288. 0, Math.PI * 2
  66289. )
  66290. };
  66291. }
  66292. };
  66293. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  66294. /*
  66295. * Licensed to the Apache Software Foundation (ASF) under one
  66296. * or more contributor license agreements. See the NOTICE file
  66297. * distributed with this work for additional information
  66298. * regarding copyright ownership. The ASF licenses this file
  66299. * to you under the Apache License, Version 2.0 (the
  66300. * "License"); you may not use this file except in compliance
  66301. * with the License. You may obtain a copy of the License at
  66302. *
  66303. * http://www.apache.org/licenses/LICENSE-2.0
  66304. *
  66305. * Unless required by applicable law or agreed to in writing,
  66306. * software distributed under the License is distributed on an
  66307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66308. * KIND, either express or implied. See the License for the
  66309. * specific language governing permissions and limitations
  66310. * under the License.
  66311. */
  66312. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  66313. registerLayout(curry(barLayoutPolar, 'bar'));
  66314. // Polar view
  66315. extendComponentView({
  66316. type: 'polar'
  66317. });
  66318. /*
  66319. * Licensed to the Apache Software Foundation (ASF) under one
  66320. * or more contributor license agreements. See the NOTICE file
  66321. * distributed with this work for additional information
  66322. * regarding copyright ownership. The ASF licenses this file
  66323. * to you under the Apache License, Version 2.0 (the
  66324. * "License"); you may not use this file except in compliance
  66325. * with the License. You may obtain a copy of the License at
  66326. *
  66327. * http://www.apache.org/licenses/LICENSE-2.0
  66328. *
  66329. * Unless required by applicable law or agreed to in writing,
  66330. * software distributed under the License is distributed on an
  66331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66332. * KIND, either express or implied. See the License for the
  66333. * specific language governing permissions and limitations
  66334. * under the License.
  66335. */
  66336. var GeoModel = ComponentModel.extend({
  66337. type: 'geo',
  66338. /**
  66339. * @type {module:echarts/coord/geo/Geo}
  66340. */
  66341. coordinateSystem: null,
  66342. layoutMode: 'box',
  66343. init: function (option) {
  66344. ComponentModel.prototype.init.apply(this, arguments);
  66345. // Default label emphasis `show`
  66346. defaultEmphasis(option, 'label', ['show']);
  66347. },
  66348. optionUpdated: function () {
  66349. var option = this.option;
  66350. var self = this;
  66351. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  66352. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  66353. if (regionOpt.name) {
  66354. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  66355. }
  66356. return optionModelMap;
  66357. }, createHashMap());
  66358. this.updateSelectedMap(option.regions);
  66359. },
  66360. defaultOption: {
  66361. zlevel: 0,
  66362. z: 0,
  66363. show: true,
  66364. left: 'center',
  66365. top: 'center',
  66366. // width:,
  66367. // height:,
  66368. // right
  66369. // bottom
  66370. // Aspect is width / height. Inited to be geoJson bbox aspect
  66371. // This parameter is used for scale this aspect
  66372. // If svg used, aspectScale is 1 by default.
  66373. // aspectScale: 0.75,
  66374. aspectScale: null,
  66375. ///// Layout with center and size
  66376. // If you wan't to put map in a fixed size box with right aspect ratio
  66377. // This two properties may more conveninet
  66378. // layoutCenter: [50%, 50%]
  66379. // layoutSize: 100
  66380. silent: false,
  66381. // Map type
  66382. map: '',
  66383. // Define left-top, right-bottom coords to control view
  66384. // For example, [ [180, 90], [-180, -90] ]
  66385. boundingCoords: null,
  66386. // Default on center of map
  66387. center: null,
  66388. zoom: 1,
  66389. scaleLimit: null,
  66390. // selectedMode: false
  66391. label: {
  66392. show: false,
  66393. color: '#000'
  66394. },
  66395. itemStyle: {
  66396. // color: 各异,
  66397. borderWidth: 0.5,
  66398. borderColor: '#444',
  66399. color: '#eee'
  66400. },
  66401. emphasis: {
  66402. label: {
  66403. show: true,
  66404. color: 'rgb(100,0,0)'
  66405. },
  66406. itemStyle: {
  66407. color: 'rgba(255,215,0,0.8)'
  66408. }
  66409. },
  66410. regions: []
  66411. },
  66412. /**
  66413. * Get model of region
  66414. * @param {string} name
  66415. * @return {module:echarts/model/Model}
  66416. */
  66417. getRegionModel: function (name) {
  66418. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  66419. },
  66420. /**
  66421. * Format label
  66422. * @param {string} name Region name
  66423. * @param {string} [status='normal'] 'normal' or 'emphasis'
  66424. * @return {string}
  66425. */
  66426. getFormattedLabel: function (name, status) {
  66427. var regionModel = this.getRegionModel(name);
  66428. var formatter = regionModel.get('label.' + status + '.formatter');
  66429. var params = {
  66430. name: name
  66431. };
  66432. if (typeof formatter === 'function') {
  66433. params.status = status;
  66434. return formatter(params);
  66435. }
  66436. else if (typeof formatter === 'string') {
  66437. return formatter.replace('{a}', name != null ? name : '');
  66438. }
  66439. },
  66440. setZoom: function (zoom) {
  66441. this.option.zoom = zoom;
  66442. },
  66443. setCenter: function (center) {
  66444. this.option.center = center;
  66445. }
  66446. });
  66447. mixin(GeoModel, selectableMixin);
  66448. /*
  66449. * Licensed to the Apache Software Foundation (ASF) under one
  66450. * or more contributor license agreements. See the NOTICE file
  66451. * distributed with this work for additional information
  66452. * regarding copyright ownership. The ASF licenses this file
  66453. * to you under the Apache License, Version 2.0 (the
  66454. * "License"); you may not use this file except in compliance
  66455. * with the License. You may obtain a copy of the License at
  66456. *
  66457. * http://www.apache.org/licenses/LICENSE-2.0
  66458. *
  66459. * Unless required by applicable law or agreed to in writing,
  66460. * software distributed under the License is distributed on an
  66461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66462. * KIND, either express or implied. See the License for the
  66463. * specific language governing permissions and limitations
  66464. * under the License.
  66465. */
  66466. extendComponentView({
  66467. type: 'geo',
  66468. init: function (ecModel, api) {
  66469. var mapDraw = new MapDraw(api, true);
  66470. this._mapDraw = mapDraw;
  66471. this.group.add(mapDraw.group);
  66472. },
  66473. render: function (geoModel, ecModel, api, payload) {
  66474. // Not render if it is an toggleSelect action from self
  66475. if (payload && payload.type === 'geoToggleSelect'
  66476. && payload.from === this.uid
  66477. ) {
  66478. return;
  66479. }
  66480. var mapDraw = this._mapDraw;
  66481. if (geoModel.get('show')) {
  66482. mapDraw.draw(geoModel, ecModel, api, this, payload);
  66483. }
  66484. else {
  66485. this._mapDraw.group.removeAll();
  66486. }
  66487. this.group.silent = geoModel.get('silent');
  66488. },
  66489. dispose: function () {
  66490. this._mapDraw && this._mapDraw.remove();
  66491. }
  66492. });
  66493. /*
  66494. * Licensed to the Apache Software Foundation (ASF) under one
  66495. * or more contributor license agreements. See the NOTICE file
  66496. * distributed with this work for additional information
  66497. * regarding copyright ownership. The ASF licenses this file
  66498. * to you under the Apache License, Version 2.0 (the
  66499. * "License"); you may not use this file except in compliance
  66500. * with the License. You may obtain a copy of the License at
  66501. *
  66502. * http://www.apache.org/licenses/LICENSE-2.0
  66503. *
  66504. * Unless required by applicable law or agreed to in writing,
  66505. * software distributed under the License is distributed on an
  66506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66507. * KIND, either express or implied. See the License for the
  66508. * specific language governing permissions and limitations
  66509. * under the License.
  66510. */
  66511. function makeAction(method, actionInfo) {
  66512. actionInfo.update = 'updateView';
  66513. registerAction(actionInfo, function (payload, ecModel) {
  66514. var selected = {};
  66515. ecModel.eachComponent(
  66516. { mainType: 'geo', query: payload},
  66517. function (geoModel) {
  66518. geoModel[method](payload.name);
  66519. var geo = geoModel.coordinateSystem;
  66520. each$1(geo.regions, function (region) {
  66521. selected[region.name] = geoModel.isSelected(region.name) || false;
  66522. });
  66523. }
  66524. );
  66525. return {
  66526. selected: selected,
  66527. name: payload.name
  66528. };
  66529. });
  66530. }
  66531. makeAction('toggleSelected', {
  66532. type: 'geoToggleSelect',
  66533. event: 'geoselectchanged'
  66534. });
  66535. makeAction('select', {
  66536. type: 'geoSelect',
  66537. event: 'geoselected'
  66538. });
  66539. makeAction('unSelect', {
  66540. type: 'geoUnSelect',
  66541. event: 'geounselected'
  66542. });
  66543. /*
  66544. * Licensed to the Apache Software Foundation (ASF) under one
  66545. * or more contributor license agreements. See the NOTICE file
  66546. * distributed with this work for additional information
  66547. * regarding copyright ownership. The ASF licenses this file
  66548. * to you under the Apache License, Version 2.0 (the
  66549. * "License"); you may not use this file except in compliance
  66550. * with the License. You may obtain a copy of the License at
  66551. *
  66552. * http://www.apache.org/licenses/LICENSE-2.0
  66553. *
  66554. * Unless required by applicable law or agreed to in writing,
  66555. * software distributed under the License is distributed on an
  66556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66557. * KIND, either express or implied. See the License for the
  66558. * specific language governing permissions and limitations
  66559. * under the License.
  66560. */
  66561. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  66562. var preprocessor$1 = function (option, isNew) {
  66563. var brushComponents = option && option.brush;
  66564. if (!isArray(brushComponents)) {
  66565. brushComponents = brushComponents ? [brushComponents] : [];
  66566. }
  66567. if (!brushComponents.length) {
  66568. return;
  66569. }
  66570. var brushComponentSpecifiedBtns = [];
  66571. each$1(brushComponents, function (brushOpt) {
  66572. var tbs = brushOpt.hasOwnProperty('toolbox')
  66573. ? brushOpt.toolbox : [];
  66574. if (tbs instanceof Array) {
  66575. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  66576. }
  66577. });
  66578. var toolbox = option && option.toolbox;
  66579. if (isArray(toolbox)) {
  66580. toolbox = toolbox[0];
  66581. }
  66582. if (!toolbox) {
  66583. toolbox = {feature: {}};
  66584. option.toolbox = [toolbox];
  66585. }
  66586. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  66587. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  66588. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  66589. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  66590. removeDuplicate(brushTypes);
  66591. if (isNew && !brushTypes.length) {
  66592. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  66593. }
  66594. };
  66595. function removeDuplicate(arr) {
  66596. var map$$1 = {};
  66597. each$1(arr, function (val) {
  66598. map$$1[val] = 1;
  66599. });
  66600. arr.length = 0;
  66601. each$1(map$$1, function (flag, val) {
  66602. arr.push(val);
  66603. });
  66604. }
  66605. /*
  66606. * Licensed to the Apache Software Foundation (ASF) under one
  66607. * or more contributor license agreements. See the NOTICE file
  66608. * distributed with this work for additional information
  66609. * regarding copyright ownership. The ASF licenses this file
  66610. * to you under the Apache License, Version 2.0 (the
  66611. * "License"); you may not use this file except in compliance
  66612. * with the License. You may obtain a copy of the License at
  66613. *
  66614. * http://www.apache.org/licenses/LICENSE-2.0
  66615. *
  66616. * Unless required by applicable law or agreed to in writing,
  66617. * software distributed under the License is distributed on an
  66618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66619. * KIND, either express or implied. See the License for the
  66620. * specific language governing permissions and limitations
  66621. * under the License.
  66622. */
  66623. /**
  66624. * @file Visual solution, for consistent option specification.
  66625. */
  66626. var each$19 = each$1;
  66627. function hasKeys(obj) {
  66628. if (obj) {
  66629. for (var name in obj) {
  66630. if (obj.hasOwnProperty(name)) {
  66631. return true;
  66632. }
  66633. }
  66634. }
  66635. }
  66636. /**
  66637. * @param {Object} option
  66638. * @param {Array.<string>} stateList
  66639. * @param {Function} [supplementVisualOption]
  66640. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  66641. */
  66642. function createVisualMappings(option, stateList, supplementVisualOption) {
  66643. var visualMappings = {};
  66644. each$19(stateList, function (state) {
  66645. var mappings = visualMappings[state] = createMappings();
  66646. each$19(option[state], function (visualData, visualType) {
  66647. if (!VisualMapping.isValidType(visualType)) {
  66648. return;
  66649. }
  66650. var mappingOption = {
  66651. type: visualType,
  66652. visual: visualData
  66653. };
  66654. supplementVisualOption && supplementVisualOption(mappingOption, state);
  66655. mappings[visualType] = new VisualMapping(mappingOption);
  66656. // Prepare a alpha for opacity, for some case that opacity
  66657. // is not supported, such as rendering using gradient color.
  66658. if (visualType === 'opacity') {
  66659. mappingOption = clone(mappingOption);
  66660. mappingOption.type = 'colorAlpha';
  66661. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  66662. }
  66663. });
  66664. });
  66665. return visualMappings;
  66666. function createMappings() {
  66667. var Creater = function () {};
  66668. // Make sure hidden fields will not be visited by
  66669. // object iteration (with hasOwnProperty checking).
  66670. Creater.prototype.__hidden = Creater.prototype;
  66671. var obj = new Creater();
  66672. return obj;
  66673. }
  66674. }
  66675. /**
  66676. * @param {Object} thisOption
  66677. * @param {Object} newOption
  66678. * @param {Array.<string>} keys
  66679. */
  66680. function replaceVisualOption(thisOption, newOption, keys) {
  66681. // Visual attributes merge is not supported, otherwise it
  66682. // brings overcomplicated merge logic. See #2853. So if
  66683. // newOption has anyone of these keys, all of these keys
  66684. // will be reset. Otherwise, all keys remain.
  66685. var has;
  66686. each$1(keys, function (key) {
  66687. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66688. has = true;
  66689. }
  66690. });
  66691. has && each$1(keys, function (key) {
  66692. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66693. thisOption[key] = clone(newOption[key]);
  66694. }
  66695. else {
  66696. delete thisOption[key];
  66697. }
  66698. });
  66699. }
  66700. /**
  66701. * @param {Array.<string>} stateList
  66702. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66703. * @param {module:echarts/data/List} list
  66704. * @param {Function} getValueState param: valueOrIndex, return: state.
  66705. * @param {object} [scope] Scope for getValueState
  66706. * @param {string} [dimension] Concrete dimension, if used.
  66707. */
  66708. // ???! handle brush?
  66709. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  66710. var visualTypesMap = {};
  66711. each$1(stateList, function (state) {
  66712. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66713. visualTypesMap[state] = visualTypes;
  66714. });
  66715. var dataIndex;
  66716. function getVisual(key) {
  66717. return data.getItemVisual(dataIndex, key);
  66718. }
  66719. function setVisual(key, value) {
  66720. data.setItemVisual(dataIndex, key, value);
  66721. }
  66722. if (dimension == null) {
  66723. data.each(eachItem);
  66724. }
  66725. else {
  66726. data.each([dimension], eachItem);
  66727. }
  66728. function eachItem(valueOrIndex, index) {
  66729. dataIndex = dimension == null ? valueOrIndex : index;
  66730. var rawDataItem = data.getRawDataItem(dataIndex);
  66731. // Consider performance
  66732. if (rawDataItem && rawDataItem.visualMap === false) {
  66733. return;
  66734. }
  66735. var valueState = getValueState.call(scope, valueOrIndex);
  66736. var mappings = visualMappings[valueState];
  66737. var visualTypes = visualTypesMap[valueState];
  66738. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66739. var type = visualTypes[i];
  66740. mappings[type] && mappings[type].applyVisual(
  66741. valueOrIndex, getVisual, setVisual
  66742. );
  66743. }
  66744. }
  66745. }
  66746. /**
  66747. * @param {module:echarts/data/List} data
  66748. * @param {Array.<string>} stateList
  66749. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66750. * @param {Function} getValueState param: valueOrIndex, return: state.
  66751. * @param {number} [dim] dimension or dimension index.
  66752. */
  66753. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  66754. var visualTypesMap = {};
  66755. each$1(stateList, function (state) {
  66756. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66757. visualTypesMap[state] = visualTypes;
  66758. });
  66759. function progress(params, data) {
  66760. if (dim != null) {
  66761. dim = data.getDimension(dim);
  66762. }
  66763. function getVisual(key) {
  66764. return data.getItemVisual(dataIndex, key);
  66765. }
  66766. function setVisual(key, value) {
  66767. data.setItemVisual(dataIndex, key, value);
  66768. }
  66769. var dataIndex;
  66770. while ((dataIndex = params.next()) != null) {
  66771. var rawDataItem = data.getRawDataItem(dataIndex);
  66772. // Consider performance
  66773. if (rawDataItem && rawDataItem.visualMap === false) {
  66774. continue;
  66775. }
  66776. var value = dim != null
  66777. ? data.get(dim, dataIndex, true)
  66778. : dataIndex;
  66779. var valueState = getValueState(value);
  66780. var mappings = visualMappings[valueState];
  66781. var visualTypes = visualTypesMap[valueState];
  66782. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66783. var type = visualTypes[i];
  66784. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  66785. }
  66786. }
  66787. }
  66788. return {progress: progress};
  66789. }
  66790. /*
  66791. * Licensed to the Apache Software Foundation (ASF) under one
  66792. * or more contributor license agreements. See the NOTICE file
  66793. * distributed with this work for additional information
  66794. * regarding copyright ownership. The ASF licenses this file
  66795. * to you under the Apache License, Version 2.0 (the
  66796. * "License"); you may not use this file except in compliance
  66797. * with the License. You may obtain a copy of the License at
  66798. *
  66799. * http://www.apache.org/licenses/LICENSE-2.0
  66800. *
  66801. * Unless required by applicable law or agreed to in writing,
  66802. * software distributed under the License is distributed on an
  66803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66804. * KIND, either express or implied. See the License for the
  66805. * specific language governing permissions and limitations
  66806. * under the License.
  66807. */
  66808. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  66809. // Key of the second level is chart element type: `point`, `rect`.
  66810. // See moudule:echarts/component/helper/BrushController
  66811. // function param:
  66812. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  66813. // {Object} selectors {point: selector, rect: selector, ...}
  66814. // {Object} area {range: [[], [], ..], boudingRect}
  66815. // function return:
  66816. // {boolean} Whether in the given brush.
  66817. var selector = {
  66818. lineX: getLineSelectors(0),
  66819. lineY: getLineSelectors(1),
  66820. rect: {
  66821. point: function (itemLayout, selectors, area) {
  66822. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  66823. },
  66824. rect: function (itemLayout, selectors, area) {
  66825. return itemLayout && area.boundingRect.intersect(itemLayout);
  66826. }
  66827. },
  66828. polygon: {
  66829. point: function (itemLayout, selectors, area) {
  66830. return itemLayout
  66831. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  66832. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  66833. },
  66834. rect: function (itemLayout, selectors, area) {
  66835. var points = area.range;
  66836. if (!itemLayout || points.length <= 1) {
  66837. return false;
  66838. }
  66839. var x = itemLayout.x;
  66840. var y = itemLayout.y;
  66841. var width = itemLayout.width;
  66842. var height = itemLayout.height;
  66843. var p = points[0];
  66844. if (contain$1(points, x, y)
  66845. || contain$1(points, x + width, y)
  66846. || contain$1(points, x, y + height)
  66847. || contain$1(points, x + width, y + height)
  66848. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  66849. || lineIntersectPolygon(x, y, x + width, y, points)
  66850. || lineIntersectPolygon(x, y, x, y + height, points)
  66851. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  66852. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  66853. ) {
  66854. return true;
  66855. }
  66856. }
  66857. }
  66858. };
  66859. function getLineSelectors(xyIndex) {
  66860. var xy = ['x', 'y'];
  66861. var wh = ['width', 'height'];
  66862. return {
  66863. point: function (itemLayout, selectors, area) {
  66864. if (itemLayout) {
  66865. var range = area.range;
  66866. var p = itemLayout[xyIndex];
  66867. return inLineRange(p, range);
  66868. }
  66869. },
  66870. rect: function (itemLayout, selectors, area) {
  66871. if (itemLayout) {
  66872. var range = area.range;
  66873. var layoutRange = [
  66874. itemLayout[xy[xyIndex]],
  66875. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  66876. ];
  66877. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  66878. return inLineRange(layoutRange[0], range)
  66879. || inLineRange(layoutRange[1], range)
  66880. || inLineRange(range[0], layoutRange)
  66881. || inLineRange(range[1], layoutRange);
  66882. }
  66883. }
  66884. };
  66885. }
  66886. function inLineRange(p, range) {
  66887. return range[0] <= p && p <= range[1];
  66888. }
  66889. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  66890. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  66891. var p = points[i];
  66892. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  66893. return true;
  66894. }
  66895. p2 = p;
  66896. }
  66897. }
  66898. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  66899. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  66900. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  66901. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  66902. if (nearZero(delta)) { // parallel
  66903. return false;
  66904. }
  66905. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  66906. if (namenda < 0 || namenda > 1) {
  66907. return false;
  66908. }
  66909. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  66910. if (miu < 0 || miu > 1) {
  66911. return false;
  66912. }
  66913. return true;
  66914. }
  66915. function nearZero(val) {
  66916. return val <= (1e-6) && val >= -(1e-6);
  66917. }
  66918. function determinant(v1, v2, v3, v4) {
  66919. return v1 * v4 - v2 * v3;
  66920. }
  66921. /*
  66922. * Licensed to the Apache Software Foundation (ASF) under one
  66923. * or more contributor license agreements. See the NOTICE file
  66924. * distributed with this work for additional information
  66925. * regarding copyright ownership. The ASF licenses this file
  66926. * to you under the Apache License, Version 2.0 (the
  66927. * "License"); you may not use this file except in compliance
  66928. * with the License. You may obtain a copy of the License at
  66929. *
  66930. * http://www.apache.org/licenses/LICENSE-2.0
  66931. *
  66932. * Unless required by applicable law or agreed to in writing,
  66933. * software distributed under the License is distributed on an
  66934. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66935. * KIND, either express or implied. See the License for the
  66936. * specific language governing permissions and limitations
  66937. * under the License.
  66938. */
  66939. var each$20 = each$1;
  66940. var indexOf$1 = indexOf;
  66941. var curry$5 = curry;
  66942. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  66943. // FIXME
  66944. // how to genarialize to more coordinate systems.
  66945. var INCLUDE_FINDER_MAIN_TYPES = [
  66946. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  66947. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  66948. ];
  66949. /**
  66950. * [option in constructor]:
  66951. * {
  66952. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66953. * }
  66954. *
  66955. *
  66956. * [targetInfo]:
  66957. *
  66958. * There can be multiple axes in a single targetInfo. Consider the case
  66959. * of `grid` component, a targetInfo represents a grid which contains one or more
  66960. * cartesian and one or more axes. And consider the case of parallel system,
  66961. * which has multiple axes in a coordinate system.
  66962. * Can be {
  66963. * panelId: ...,
  66964. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  66965. * coordSyses: all cartesians.
  66966. * gridModel: <grid component>
  66967. * xAxes: correspond to coordSyses on index
  66968. * yAxes: correspond to coordSyses on index
  66969. * }
  66970. * or {
  66971. * panelId: ...,
  66972. * coordSys: <geo coord sys>
  66973. * coordSyses: [<geo coord sys>]
  66974. * geoModel: <geo component>
  66975. * }
  66976. *
  66977. *
  66978. * [panelOpt]:
  66979. *
  66980. * Make from targetInfo. Input to BrushController.
  66981. * {
  66982. * panelId: ...,
  66983. * rect: ...
  66984. * }
  66985. *
  66986. *
  66987. * [area]:
  66988. *
  66989. * Generated by BrushController or user input.
  66990. * {
  66991. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  66992. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  66993. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66994. * range: pixel range.
  66995. * coordRange: representitive coord range (the first one of coordRanges).
  66996. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  66997. * }
  66998. */
  66999. /**
  67000. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  67001. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  67002. * @param {module:echarts/model/Global} ecModel
  67003. * @param {Object} [opt]
  67004. * @param {Array.<string>} [opt.include] include coordinate system types.
  67005. */
  67006. function BrushTargetManager(option, ecModel, opt) {
  67007. /**
  67008. * @private
  67009. * @type {Array.<Object>}
  67010. */
  67011. var targetInfoList = this._targetInfoList = [];
  67012. var info = {};
  67013. var foundCpts = parseFinder$1(ecModel, option);
  67014. each$20(targetInfoBuilders, function (builder, type) {
  67015. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  67016. builder(foundCpts, targetInfoList, info);
  67017. }
  67018. });
  67019. }
  67020. var proto$2 = BrushTargetManager.prototype;
  67021. proto$2.setOutputRanges = function (areas, ecModel) {
  67022. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  67023. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  67024. // area.coordRange is the first of area.coordRanges
  67025. if (!area.coordRange) {
  67026. area.coordRange = coordRange;
  67027. // In 'category' axis, coord to pixel is not reversible, so we can not
  67028. // rebuild range by coordRange accrately, which may bring trouble when
  67029. // brushing only one item. So we use __rangeOffset to rebuilding range
  67030. // by coordRange. And this it only used in brush component so it is no
  67031. // need to be adapted to coordRanges.
  67032. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  67033. area.__rangeOffset = {
  67034. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  67035. xyMinMax: result.xyMinMax
  67036. };
  67037. }
  67038. });
  67039. };
  67040. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  67041. each$20(areas, function (area) {
  67042. var targetInfo = this.findTargetInfo(area, ecModel);
  67043. if (targetInfo && targetInfo !== true) {
  67044. each$1(
  67045. targetInfo.coordSyses,
  67046. function (coordSys) {
  67047. var result = coordConvert[area.brushType](1, coordSys, area.range);
  67048. cb(area, result.values, coordSys, ecModel);
  67049. }
  67050. );
  67051. }
  67052. }, this);
  67053. };
  67054. proto$2.setInputRanges = function (areas, ecModel) {
  67055. each$20(areas, function (area) {
  67056. var targetInfo = this.findTargetInfo(area, ecModel);
  67057. if (__DEV__) {
  67058. assert$1(
  67059. !targetInfo || targetInfo === true || area.coordRange,
  67060. 'coordRange must be specified when coord index specified.'
  67061. );
  67062. assert$1(
  67063. !targetInfo || targetInfo !== true || area.range,
  67064. 'range must be specified in global brush.'
  67065. );
  67066. }
  67067. area.range = area.range || [];
  67068. // convert coordRange to global range and set panelId.
  67069. if (targetInfo && targetInfo !== true) {
  67070. area.panelId = targetInfo.panelId;
  67071. // (1) area.range shoule always be calculate from coordRange but does
  67072. // not keep its original value, for the sake of the dataZoom scenario,
  67073. // where area.coordRange remains unchanged but area.range may be changed.
  67074. // (2) Only support converting one coordRange to pixel range in brush
  67075. // component. So do not consider `coordRanges`.
  67076. // (3) About __rangeOffset, see comment above.
  67077. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  67078. var rangeOffset = area.__rangeOffset;
  67079. area.range = rangeOffset
  67080. ? diffProcessor[area.brushType](
  67081. result.values,
  67082. rangeOffset.offset,
  67083. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  67084. )
  67085. : result.values;
  67086. }
  67087. }, this);
  67088. };
  67089. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  67090. return map(this._targetInfoList, function (targetInfo) {
  67091. var rect = targetInfo.getPanelRect();
  67092. return {
  67093. panelId: targetInfo.panelId,
  67094. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  67095. clipPath: makeRectPanelClipPath(rect),
  67096. isTargetByCursor: makeRectIsTargetByCursor(
  67097. rect, api, targetInfo.coordSysModel
  67098. ),
  67099. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  67100. };
  67101. });
  67102. };
  67103. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  67104. // Check whether area is bound in coord, and series do not belong to that coord.
  67105. // If do not do this check, some brush (like lineX) will controll all axes.
  67106. var targetInfo = this.findTargetInfo(area, ecModel);
  67107. return targetInfo === true || (
  67108. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  67109. );
  67110. };
  67111. /**
  67112. * If return Object, a coord found.
  67113. * If reutrn true, global found.
  67114. * Otherwise nothing found.
  67115. *
  67116. * @param {Object} area
  67117. * @param {Array} targetInfoList
  67118. * @return {Object|boolean}
  67119. */
  67120. proto$2.findTargetInfo = function (area, ecModel) {
  67121. var targetInfoList = this._targetInfoList;
  67122. var foundCpts = parseFinder$1(ecModel, area);
  67123. for (var i = 0; i < targetInfoList.length; i++) {
  67124. var targetInfo = targetInfoList[i];
  67125. var areaPanelId = area.panelId;
  67126. if (areaPanelId) {
  67127. if (targetInfo.panelId === areaPanelId) {
  67128. return targetInfo;
  67129. }
  67130. }
  67131. else {
  67132. for (var i = 0; i < targetInfoMatchers.length; i++) {
  67133. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  67134. return targetInfo;
  67135. }
  67136. }
  67137. }
  67138. }
  67139. return true;
  67140. };
  67141. function formatMinMax(minMax) {
  67142. minMax[0] > minMax[1] && minMax.reverse();
  67143. return minMax;
  67144. }
  67145. function parseFinder$1(ecModel, option) {
  67146. return parseFinder(
  67147. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  67148. );
  67149. }
  67150. var targetInfoBuilders = {
  67151. grid: function (foundCpts, targetInfoList) {
  67152. var xAxisModels = foundCpts.xAxisModels;
  67153. var yAxisModels = foundCpts.yAxisModels;
  67154. var gridModels = foundCpts.gridModels;
  67155. // Remove duplicated.
  67156. var gridModelMap = createHashMap();
  67157. var xAxesHas = {};
  67158. var yAxesHas = {};
  67159. if (!xAxisModels && !yAxisModels && !gridModels) {
  67160. return;
  67161. }
  67162. each$20(xAxisModels, function (axisModel) {
  67163. var gridModel = axisModel.axis.grid.model;
  67164. gridModelMap.set(gridModel.id, gridModel);
  67165. xAxesHas[gridModel.id] = true;
  67166. });
  67167. each$20(yAxisModels, function (axisModel) {
  67168. var gridModel = axisModel.axis.grid.model;
  67169. gridModelMap.set(gridModel.id, gridModel);
  67170. yAxesHas[gridModel.id] = true;
  67171. });
  67172. each$20(gridModels, function (gridModel) {
  67173. gridModelMap.set(gridModel.id, gridModel);
  67174. xAxesHas[gridModel.id] = true;
  67175. yAxesHas[gridModel.id] = true;
  67176. });
  67177. gridModelMap.each(function (gridModel) {
  67178. var grid = gridModel.coordinateSystem;
  67179. var cartesians = [];
  67180. each$20(grid.getCartesians(), function (cartesian, index) {
  67181. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  67182. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  67183. ) {
  67184. cartesians.push(cartesian);
  67185. }
  67186. });
  67187. targetInfoList.push({
  67188. panelId: 'grid--' + gridModel.id,
  67189. gridModel: gridModel,
  67190. coordSysModel: gridModel,
  67191. // Use the first one as the representitive coordSys.
  67192. coordSys: cartesians[0],
  67193. coordSyses: cartesians,
  67194. getPanelRect: panelRectBuilder.grid,
  67195. xAxisDeclared: xAxesHas[gridModel.id],
  67196. yAxisDeclared: yAxesHas[gridModel.id]
  67197. });
  67198. });
  67199. },
  67200. geo: function (foundCpts, targetInfoList) {
  67201. each$20(foundCpts.geoModels, function (geoModel) {
  67202. var coordSys = geoModel.coordinateSystem;
  67203. targetInfoList.push({
  67204. panelId: 'geo--' + geoModel.id,
  67205. geoModel: geoModel,
  67206. coordSysModel: geoModel,
  67207. coordSys: coordSys,
  67208. coordSyses: [coordSys],
  67209. getPanelRect: panelRectBuilder.geo
  67210. });
  67211. });
  67212. }
  67213. };
  67214. var targetInfoMatchers = [
  67215. // grid
  67216. function (foundCpts, targetInfo) {
  67217. var xAxisModel = foundCpts.xAxisModel;
  67218. var yAxisModel = foundCpts.yAxisModel;
  67219. var gridModel = foundCpts.gridModel;
  67220. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  67221. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  67222. return gridModel && gridModel === targetInfo.gridModel;
  67223. },
  67224. // geo
  67225. function (foundCpts, targetInfo) {
  67226. var geoModel = foundCpts.geoModel;
  67227. return geoModel && geoModel === targetInfo.geoModel;
  67228. }
  67229. ];
  67230. var panelRectBuilder = {
  67231. grid: function () {
  67232. // grid is not Transformable.
  67233. return this.coordSys.grid.getRect().clone();
  67234. },
  67235. geo: function () {
  67236. var coordSys = this.coordSys;
  67237. var rect = coordSys.getBoundingRect().clone();
  67238. // geo roam and zoom transform
  67239. rect.applyTransform(getTransform(coordSys));
  67240. return rect;
  67241. }
  67242. };
  67243. var coordConvert = {
  67244. lineX: curry$5(axisConvert, 0),
  67245. lineY: curry$5(axisConvert, 1),
  67246. rect: function (to, coordSys, rangeOrCoordRange) {
  67247. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  67248. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  67249. var values = [
  67250. formatMinMax([xminymin[0], xmaxymax[0]]),
  67251. formatMinMax([xminymin[1], xmaxymax[1]])
  67252. ];
  67253. return {values: values, xyMinMax: values};
  67254. },
  67255. polygon: function (to, coordSys, rangeOrCoordRange) {
  67256. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  67257. var values = map(rangeOrCoordRange, function (item) {
  67258. var p = coordSys[COORD_CONVERTS[to]](item);
  67259. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  67260. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  67261. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  67262. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  67263. return p;
  67264. });
  67265. return {values: values, xyMinMax: xyMinMax};
  67266. }
  67267. };
  67268. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  67269. if (__DEV__) {
  67270. assert$1(
  67271. coordSys.type === 'cartesian2d',
  67272. 'lineX/lineY brush is available only in cartesian2d.'
  67273. );
  67274. }
  67275. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  67276. var values = formatMinMax(map([0, 1], function (i) {
  67277. return to
  67278. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  67279. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  67280. }));
  67281. var xyMinMax = [];
  67282. xyMinMax[axisNameIndex] = values;
  67283. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  67284. return {values: values, xyMinMax: xyMinMax};
  67285. }
  67286. var diffProcessor = {
  67287. lineX: curry$5(axisDiffProcessor, 0),
  67288. lineY: curry$5(axisDiffProcessor, 1),
  67289. rect: function (values, refer, scales) {
  67290. return [
  67291. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  67292. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  67293. ];
  67294. },
  67295. polygon: function (values, refer, scales) {
  67296. return map(values, function (item, idx) {
  67297. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  67298. });
  67299. }
  67300. };
  67301. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  67302. return [
  67303. values[0] - scales[axisNameIndex] * refer[0],
  67304. values[1] - scales[axisNameIndex] * refer[1]
  67305. ];
  67306. }
  67307. // We have to process scale caused by dataZoom manually,
  67308. // although it might be not accurate.
  67309. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  67310. var sizeCurr = getSize(xyMinMaxCurr);
  67311. var sizeOrigin = getSize(xyMinMaxOrigin);
  67312. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  67313. isNaN(scales[0]) && (scales[0] = 1);
  67314. isNaN(scales[1]) && (scales[1] = 1);
  67315. return scales;
  67316. }
  67317. function getSize(xyMinMax) {
  67318. return xyMinMax
  67319. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  67320. : [NaN, NaN];
  67321. }
  67322. /*
  67323. * Licensed to the Apache Software Foundation (ASF) under one
  67324. * or more contributor license agreements. See the NOTICE file
  67325. * distributed with this work for additional information
  67326. * regarding copyright ownership. The ASF licenses this file
  67327. * to you under the Apache License, Version 2.0 (the
  67328. * "License"); you may not use this file except in compliance
  67329. * with the License. You may obtain a copy of the License at
  67330. *
  67331. * http://www.apache.org/licenses/LICENSE-2.0
  67332. *
  67333. * Unless required by applicable law or agreed to in writing,
  67334. * software distributed under the License is distributed on an
  67335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67336. * KIND, either express or implied. See the License for the
  67337. * specific language governing permissions and limitations
  67338. * under the License.
  67339. */
  67340. var STATE_LIST = ['inBrush', 'outOfBrush'];
  67341. var DISPATCH_METHOD = '__ecBrushSelect';
  67342. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  67343. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  67344. /**
  67345. * Layout for visual, the priority higher than other layout, and before brush visual.
  67346. */
  67347. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  67348. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  67349. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  67350. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  67351. );
  67352. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  67353. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  67354. });
  67355. });
  67356. /**
  67357. * Register the visual encoding if this modules required.
  67358. */
  67359. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  67360. var brushSelected = [];
  67361. var throttleType;
  67362. var throttleDelay;
  67363. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  67364. var thisBrushSelected = {
  67365. brushId: brushModel.id,
  67366. brushIndex: brushIndex,
  67367. brushName: brushModel.name,
  67368. areas: clone(brushModel.areas),
  67369. selected: []
  67370. };
  67371. // Every brush component exists in event params, convenient
  67372. // for user to find by index.
  67373. brushSelected.push(thisBrushSelected);
  67374. var brushOption = brushModel.option;
  67375. var brushLink = brushOption.brushLink;
  67376. var linkedSeriesMap = [];
  67377. var selectedDataIndexForLink = [];
  67378. var rangeInfoBySeries = [];
  67379. var hasBrushExists = 0;
  67380. if (!brushIndex) { // Only the first throttle setting works.
  67381. throttleType = brushOption.throttleType;
  67382. throttleDelay = brushOption.throttleDelay;
  67383. }
  67384. // Add boundingRect and selectors to range.
  67385. var areas = map(brushModel.areas, function (area) {
  67386. return bindSelector(
  67387. defaults(
  67388. {boundingRect: boundingRectBuilders[area.brushType](area)},
  67389. area
  67390. )
  67391. );
  67392. });
  67393. var visualMappings = createVisualMappings(
  67394. brushModel.option, STATE_LIST, function (mappingOption) {
  67395. mappingOption.mappingMethod = 'fixed';
  67396. }
  67397. );
  67398. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  67399. linkedSeriesMap[seriesIndex] = 1;
  67400. });
  67401. function linkOthers(seriesIndex) {
  67402. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  67403. }
  67404. // If no supported brush or no brush on the series,
  67405. // all visuals should be in original state.
  67406. function brushed(rangeInfoList) {
  67407. return !!rangeInfoList.length;
  67408. }
  67409. /**
  67410. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  67411. *
  67412. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  67413. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  67414. * └!hasBrushExist┘ └nothing.
  67415. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  67416. * └!hasBrushExist┘ └nothing.
  67417. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  67418. * !brushed┘ └nothing.
  67419. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  67420. */
  67421. // Step A
  67422. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  67423. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  67424. seriesModel.subType === 'parallel'
  67425. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  67426. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  67427. });
  67428. function stepAParallel(seriesModel, seriesIndex) {
  67429. var coordSys = seriesModel.coordinateSystem;
  67430. hasBrushExists |= coordSys.hasAxisBrushed();
  67431. linkOthers(seriesIndex) && coordSys.eachActiveState(
  67432. seriesModel.getData(),
  67433. function (activeState, dataIndex) {
  67434. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  67435. }
  67436. );
  67437. }
  67438. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  67439. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  67440. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  67441. return;
  67442. }
  67443. each$1(areas, function (area) {
  67444. selectorsByBrushType[area.brushType]
  67445. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  67446. && rangeInfoList.push(area);
  67447. hasBrushExists |= brushed(rangeInfoList);
  67448. });
  67449. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  67450. var data = seriesModel.getData();
  67451. data.each(function (dataIndex) {
  67452. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  67453. selectedDataIndexForLink[dataIndex] = 1;
  67454. }
  67455. });
  67456. }
  67457. }
  67458. // Step B
  67459. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  67460. var seriesBrushSelected = {
  67461. seriesId: seriesModel.id,
  67462. seriesIndex: seriesIndex,
  67463. seriesName: seriesModel.name,
  67464. dataIndex: []
  67465. };
  67466. // Every series exists in event params, convenient
  67467. // for user to find series by seriesIndex.
  67468. thisBrushSelected.selected.push(seriesBrushSelected);
  67469. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  67470. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  67471. var data = seriesModel.getData();
  67472. var getValueState = linkOthers(seriesIndex)
  67473. ? function (dataIndex) {
  67474. return selectedDataIndexForLink[dataIndex]
  67475. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  67476. : 'outOfBrush';
  67477. }
  67478. : function (dataIndex) {
  67479. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  67480. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  67481. : 'outOfBrush';
  67482. };
  67483. // If no supported brush or no brush, all visuals are in original state.
  67484. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  67485. && applyVisual(
  67486. STATE_LIST, visualMappings, data, getValueState
  67487. );
  67488. });
  67489. });
  67490. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  67491. });
  67492. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  67493. // This event will not be triggered when `setOpion`, otherwise dead lock may
  67494. // triggered when do `setOption` in event listener, which we do not find
  67495. // satisfactory way to solve yet. Some considered resolutions:
  67496. // (a) Diff with prevoius selected data ant only trigger event when changed.
  67497. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  67498. // also detect value changes in selected data) might bring complexity or fragility.
  67499. // (b) Use spectial param like `silent` to suppress event triggering.
  67500. // But such kind of volatile param may be weird in `setOption`.
  67501. if (!payload) {
  67502. return;
  67503. }
  67504. var zr = api.getZr();
  67505. if (zr[DISPATCH_FLAG]) {
  67506. return;
  67507. }
  67508. if (!zr[DISPATCH_METHOD]) {
  67509. zr[DISPATCH_METHOD] = doDispatch;
  67510. }
  67511. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  67512. fn(api, brushSelected);
  67513. }
  67514. function doDispatch(api, brushSelected) {
  67515. if (!api.isDisposed()) {
  67516. var zr = api.getZr();
  67517. zr[DISPATCH_FLAG] = true;
  67518. api.dispatchAction({
  67519. type: 'brushSelect',
  67520. batch: brushSelected
  67521. });
  67522. zr[DISPATCH_FLAG] = false;
  67523. }
  67524. }
  67525. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  67526. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  67527. var area = rangeInfoList[i];
  67528. if (selectorsByBrushType[area.brushType](
  67529. dataIndex, data, area.selectors, area
  67530. )) {
  67531. return true;
  67532. }
  67533. }
  67534. }
  67535. function getSelectorsByBrushType(seriesModel) {
  67536. var brushSelector = seriesModel.brushSelector;
  67537. if (isString(brushSelector)) {
  67538. var sels = [];
  67539. each$1(selector, function (selectorsByElementType, brushType) {
  67540. sels[brushType] = function (dataIndex, data, selectors, area) {
  67541. var itemLayout = data.getItemLayout(dataIndex);
  67542. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  67543. };
  67544. });
  67545. return sels;
  67546. }
  67547. else if (isFunction$1(brushSelector)) {
  67548. var bSelector = {};
  67549. each$1(selector, function (sel, brushType) {
  67550. bSelector[brushType] = brushSelector;
  67551. });
  67552. return bSelector;
  67553. }
  67554. return brushSelector;
  67555. }
  67556. function brushModelNotControll(brushModel, seriesIndex) {
  67557. var seriesIndices = brushModel.option.seriesIndex;
  67558. return seriesIndices != null
  67559. && seriesIndices !== 'all'
  67560. && (
  67561. isArray(seriesIndices)
  67562. ? indexOf(seriesIndices, seriesIndex) < 0
  67563. : seriesIndex !== seriesIndices
  67564. );
  67565. }
  67566. function bindSelector(area) {
  67567. var selectors = area.selectors = {};
  67568. each$1(selector[area.brushType], function (selFn, elType) {
  67569. // Do not use function binding or curry for performance.
  67570. selectors[elType] = function (itemLayout) {
  67571. return selFn(itemLayout, selectors, area);
  67572. };
  67573. });
  67574. return area;
  67575. }
  67576. var boundingRectBuilders = {
  67577. lineX: noop,
  67578. lineY: noop,
  67579. rect: function (area) {
  67580. return getBoundingRectFromMinMax(area.range);
  67581. },
  67582. polygon: function (area) {
  67583. var minMax;
  67584. var range = area.range;
  67585. for (var i = 0, len = range.length; i < len; i++) {
  67586. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  67587. var rg = range[i];
  67588. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  67589. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  67590. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  67591. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  67592. }
  67593. return minMax && getBoundingRectFromMinMax(minMax);
  67594. }
  67595. };
  67596. function getBoundingRectFromMinMax(minMax) {
  67597. return new BoundingRect(
  67598. minMax[0][0],
  67599. minMax[1][0],
  67600. minMax[0][1] - minMax[0][0],
  67601. minMax[1][1] - minMax[1][0]
  67602. );
  67603. }
  67604. /*
  67605. * Licensed to the Apache Software Foundation (ASF) under one
  67606. * or more contributor license agreements. See the NOTICE file
  67607. * distributed with this work for additional information
  67608. * regarding copyright ownership. The ASF licenses this file
  67609. * to you under the Apache License, Version 2.0 (the
  67610. * "License"); you may not use this file except in compliance
  67611. * with the License. You may obtain a copy of the License at
  67612. *
  67613. * http://www.apache.org/licenses/LICENSE-2.0
  67614. *
  67615. * Unless required by applicable law or agreed to in writing,
  67616. * software distributed under the License is distributed on an
  67617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67618. * KIND, either express or implied. See the License for the
  67619. * specific language governing permissions and limitations
  67620. * under the License.
  67621. */
  67622. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  67623. var BrushModel = extendComponentModel({
  67624. type: 'brush',
  67625. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  67626. /**
  67627. * @protected
  67628. */
  67629. defaultOption: {
  67630. // inBrush: null,
  67631. // outOfBrush: null,
  67632. toolbox: null, // Default value see preprocessor.
  67633. brushLink: null, // Series indices array, broadcast using dataIndex.
  67634. // or 'all', which means all series. 'none' or null means no series.
  67635. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  67636. geoIndex: null, //
  67637. xAxisIndex: null,
  67638. yAxisIndex: null,
  67639. brushType: 'rect', // Default brushType, see BrushController.
  67640. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  67641. transformable: true, // Default transformable.
  67642. brushStyle: { // Default brushStyle
  67643. borderWidth: 1,
  67644. color: 'rgba(120,140,180,0.3)',
  67645. borderColor: 'rgba(120,140,180,0.8)'
  67646. },
  67647. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  67648. // If null, no throttle. Valid only in the first brush component
  67649. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  67650. // FIXME
  67651. // 试验效果
  67652. removeOnClick: true,
  67653. z: 10000
  67654. },
  67655. /**
  67656. * @readOnly
  67657. * @type {Array.<Object>}
  67658. */
  67659. areas: [],
  67660. /**
  67661. * Current activated brush type.
  67662. * If null, brush is inactived.
  67663. * see module:echarts/component/helper/BrushController
  67664. * @readOnly
  67665. * @type {string}
  67666. */
  67667. brushType: null,
  67668. /**
  67669. * Current brush opt.
  67670. * see module:echarts/component/helper/BrushController
  67671. * @readOnly
  67672. * @type {Object}
  67673. */
  67674. brushOption: {},
  67675. /**
  67676. * @readOnly
  67677. * @type {Array.<Object>}
  67678. */
  67679. coordInfoList: [],
  67680. optionUpdated: function (newOption, isInit) {
  67681. var thisOption = this.option;
  67682. !isInit && replaceVisualOption(
  67683. thisOption, newOption, ['inBrush', 'outOfBrush']
  67684. );
  67685. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  67686. // Always give default visual, consider setOption at the second time.
  67687. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  67688. if (!inBrush.hasOwnProperty('liftZ')) {
  67689. // Bigger than the highlight z lift, otherwise it will
  67690. // be effected by the highlight z when brush.
  67691. inBrush.liftZ = 5;
  67692. }
  67693. },
  67694. /**
  67695. * If ranges is null/undefined, range state remain.
  67696. *
  67697. * @param {Array.<Object>} [ranges]
  67698. */
  67699. setAreas: function (areas) {
  67700. if (__DEV__) {
  67701. assert$1(isArray(areas));
  67702. each$1(areas, function (area) {
  67703. assert$1(area.brushType, 'Illegal areas');
  67704. });
  67705. }
  67706. // If ranges is null/undefined, range state remain.
  67707. // This helps user to dispatchAction({type: 'brush'}) with no areas
  67708. // set but just want to get the current brush select info from a `brush` event.
  67709. if (!areas) {
  67710. return;
  67711. }
  67712. this.areas = map(areas, function (area) {
  67713. return generateBrushOption(this.option, area);
  67714. }, this);
  67715. },
  67716. /**
  67717. * see module:echarts/component/helper/BrushController
  67718. * @param {Object} brushOption
  67719. */
  67720. setBrushOption: function (brushOption) {
  67721. this.brushOption = generateBrushOption(this.option, brushOption);
  67722. this.brushType = this.brushOption.brushType;
  67723. }
  67724. });
  67725. function generateBrushOption(option, brushOption) {
  67726. return merge(
  67727. {
  67728. brushType: option.brushType,
  67729. brushMode: option.brushMode,
  67730. transformable: option.transformable,
  67731. brushStyle: new Model(option.brushStyle).getItemStyle(),
  67732. removeOnClick: option.removeOnClick,
  67733. z: option.z
  67734. },
  67735. brushOption,
  67736. true
  67737. );
  67738. }
  67739. /*
  67740. * Licensed to the Apache Software Foundation (ASF) under one
  67741. * or more contributor license agreements. See the NOTICE file
  67742. * distributed with this work for additional information
  67743. * regarding copyright ownership. The ASF licenses this file
  67744. * to you under the Apache License, Version 2.0 (the
  67745. * "License"); you may not use this file except in compliance
  67746. * with the License. You may obtain a copy of the License at
  67747. *
  67748. * http://www.apache.org/licenses/LICENSE-2.0
  67749. *
  67750. * Unless required by applicable law or agreed to in writing,
  67751. * software distributed under the License is distributed on an
  67752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67753. * KIND, either express or implied. See the License for the
  67754. * specific language governing permissions and limitations
  67755. * under the License.
  67756. */
  67757. extendComponentView({
  67758. type: 'brush',
  67759. init: function (ecModel, api) {
  67760. /**
  67761. * @readOnly
  67762. * @type {module:echarts/model/Global}
  67763. */
  67764. this.ecModel = ecModel;
  67765. /**
  67766. * @readOnly
  67767. * @type {module:echarts/ExtensionAPI}
  67768. */
  67769. this.api = api;
  67770. /**
  67771. * @readOnly
  67772. * @type {module:echarts/component/brush/BrushModel}
  67773. */
  67774. this.model;
  67775. /**
  67776. * @private
  67777. * @type {module:echarts/component/helper/BrushController}
  67778. */
  67779. (this._brushController = new BrushController(api.getZr()))
  67780. .on('brush', bind(this._onBrush, this))
  67781. .mount();
  67782. },
  67783. /**
  67784. * @override
  67785. */
  67786. render: function (brushModel) {
  67787. this.model = brushModel;
  67788. return updateController.apply(this, arguments);
  67789. },
  67790. /**
  67791. * @override
  67792. */
  67793. updateTransform: updateController,
  67794. /**
  67795. * @override
  67796. */
  67797. updateView: updateController,
  67798. // /**
  67799. // * @override
  67800. // */
  67801. // updateLayout: updateController,
  67802. // /**
  67803. // * @override
  67804. // */
  67805. // updateVisual: updateController,
  67806. /**
  67807. * @override
  67808. */
  67809. dispose: function () {
  67810. this._brushController.dispose();
  67811. },
  67812. /**
  67813. * @private
  67814. */
  67815. _onBrush: function (areas, opt) {
  67816. var modelId = this.model.id;
  67817. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  67818. // Action is not dispatched on drag end, because the drag end
  67819. // emits the same params with the last drag move event, and
  67820. // may have some delay when using touch pad, which makes
  67821. // animation not smooth (when using debounce).
  67822. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  67823. type: 'brush',
  67824. brushId: modelId,
  67825. areas: clone(areas),
  67826. $from: modelId
  67827. });
  67828. }
  67829. });
  67830. function updateController(brushModel, ecModel, api, payload) {
  67831. // Do not update controller when drawing.
  67832. (!payload || payload.$from !== brushModel.id) && this._brushController
  67833. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  67834. .enableBrush(brushModel.brushOption)
  67835. .updateCovers(brushModel.areas.slice());
  67836. }
  67837. /*
  67838. * Licensed to the Apache Software Foundation (ASF) under one
  67839. * or more contributor license agreements. See the NOTICE file
  67840. * distributed with this work for additional information
  67841. * regarding copyright ownership. The ASF licenses this file
  67842. * to you under the Apache License, Version 2.0 (the
  67843. * "License"); you may not use this file except in compliance
  67844. * with the License. You may obtain a copy of the License at
  67845. *
  67846. * http://www.apache.org/licenses/LICENSE-2.0
  67847. *
  67848. * Unless required by applicable law or agreed to in writing,
  67849. * software distributed under the License is distributed on an
  67850. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67851. * KIND, either express or implied. See the License for the
  67852. * specific language governing permissions and limitations
  67853. * under the License.
  67854. */
  67855. /**
  67856. * payload: {
  67857. * brushIndex: number, or,
  67858. * brushId: string, or,
  67859. * brushName: string,
  67860. * globalRanges: Array
  67861. * }
  67862. */
  67863. registerAction(
  67864. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  67865. function (payload, ecModel) {
  67866. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  67867. brushModel.setAreas(payload.areas);
  67868. });
  67869. }
  67870. );
  67871. /**
  67872. * payload: {
  67873. * brushComponents: [
  67874. * {
  67875. * brushId,
  67876. * brushIndex,
  67877. * brushName,
  67878. * series: [
  67879. * {
  67880. * seriesId,
  67881. * seriesIndex,
  67882. * seriesName,
  67883. * rawIndices: [21, 34, ...]
  67884. * },
  67885. * ...
  67886. * ]
  67887. * },
  67888. * ...
  67889. * ]
  67890. * }
  67891. */
  67892. registerAction(
  67893. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  67894. function () {}
  67895. );
  67896. /*
  67897. * Licensed to the Apache Software Foundation (ASF) under one
  67898. * or more contributor license agreements. See the NOTICE file
  67899. * distributed with this work for additional information
  67900. * regarding copyright ownership. The ASF licenses this file
  67901. * to you under the Apache License, Version 2.0 (the
  67902. * "License"); you may not use this file except in compliance
  67903. * with the License. You may obtain a copy of the License at
  67904. *
  67905. * http://www.apache.org/licenses/LICENSE-2.0
  67906. *
  67907. * Unless required by applicable law or agreed to in writing,
  67908. * software distributed under the License is distributed on an
  67909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67910. * KIND, either express or implied. See the License for the
  67911. * specific language governing permissions and limitations
  67912. * under the License.
  67913. */
  67914. var features = {};
  67915. function register$1(name, ctor) {
  67916. features[name] = ctor;
  67917. }
  67918. function get$1(name) {
  67919. return features[name];
  67920. }
  67921. /*
  67922. * Licensed to the Apache Software Foundation (ASF) under one
  67923. * or more contributor license agreements. See the NOTICE file
  67924. * distributed with this work for additional information
  67925. * regarding copyright ownership. The ASF licenses this file
  67926. * to you under the Apache License, Version 2.0 (the
  67927. * "License"); you may not use this file except in compliance
  67928. * with the License. You may obtain a copy of the License at
  67929. *
  67930. * http://www.apache.org/licenses/LICENSE-2.0
  67931. *
  67932. * Unless required by applicable law or agreed to in writing,
  67933. * software distributed under the License is distributed on an
  67934. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67935. * KIND, either express or implied. See the License for the
  67936. * specific language governing permissions and limitations
  67937. * under the License.
  67938. */
  67939. var brushLang = lang.toolbox.brush;
  67940. function Brush(model, ecModel, api) {
  67941. this.model = model;
  67942. this.ecModel = ecModel;
  67943. this.api = api;
  67944. /**
  67945. * @private
  67946. * @type {string}
  67947. */
  67948. this._brushType;
  67949. /**
  67950. * @private
  67951. * @type {string}
  67952. */
  67953. this._brushMode;
  67954. }
  67955. Brush.defaultOption = {
  67956. show: true,
  67957. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  67958. icon: {
  67959. /* eslint-disable */
  67960. 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
  67961. 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
  67962. 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
  67963. 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
  67964. 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
  67965. 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
  67966. /* eslint-enable */
  67967. },
  67968. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  67969. title: clone(brushLang.title)
  67970. };
  67971. var proto$3 = Brush.prototype;
  67972. // proto.updateLayout = function (featureModel, ecModel, api) {
  67973. /* eslint-disable */
  67974. proto$3.render =
  67975. /* eslint-enable */
  67976. proto$3.updateView = function (featureModel, ecModel, api) {
  67977. var brushType;
  67978. var brushMode;
  67979. var isBrushed;
  67980. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  67981. brushType = brushModel.brushType;
  67982. brushMode = brushModel.brushOption.brushMode || 'single';
  67983. isBrushed |= brushModel.areas.length;
  67984. });
  67985. this._brushType = brushType;
  67986. this._brushMode = brushMode;
  67987. each$1(featureModel.get('type', true), function (type) {
  67988. featureModel.setIconStatus(
  67989. type,
  67990. (
  67991. type === 'keep'
  67992. ? brushMode === 'multiple'
  67993. : type === 'clear'
  67994. ? isBrushed
  67995. : type === brushType
  67996. ) ? 'emphasis' : 'normal'
  67997. );
  67998. });
  67999. };
  68000. proto$3.getIcons = function () {
  68001. var model = this.model;
  68002. var availableIcons = model.get('icon', true);
  68003. var icons = {};
  68004. each$1(model.get('type', true), function (type) {
  68005. if (availableIcons[type]) {
  68006. icons[type] = availableIcons[type];
  68007. }
  68008. });
  68009. return icons;
  68010. };
  68011. proto$3.onclick = function (ecModel, api, type) {
  68012. var brushType = this._brushType;
  68013. var brushMode = this._brushMode;
  68014. if (type === 'clear') {
  68015. // Trigger parallel action firstly
  68016. api.dispatchAction({
  68017. type: 'axisAreaSelect',
  68018. intervals: []
  68019. });
  68020. api.dispatchAction({
  68021. type: 'brush',
  68022. command: 'clear',
  68023. // Clear all areas of all brush components.
  68024. areas: []
  68025. });
  68026. }
  68027. else {
  68028. api.dispatchAction({
  68029. type: 'takeGlobalCursor',
  68030. key: 'brush',
  68031. brushOption: {
  68032. brushType: type === 'keep'
  68033. ? brushType
  68034. : (brushType === type ? false : type),
  68035. brushMode: type === 'keep'
  68036. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  68037. : brushMode
  68038. }
  68039. });
  68040. }
  68041. };
  68042. register$1('brush', Brush);
  68043. /*
  68044. * Licensed to the Apache Software Foundation (ASF) under one
  68045. * or more contributor license agreements. See the NOTICE file
  68046. * distributed with this work for additional information
  68047. * regarding copyright ownership. The ASF licenses this file
  68048. * to you under the Apache License, Version 2.0 (the
  68049. * "License"); you may not use this file except in compliance
  68050. * with the License. You may obtain a copy of the License at
  68051. *
  68052. * http://www.apache.org/licenses/LICENSE-2.0
  68053. *
  68054. * Unless required by applicable law or agreed to in writing,
  68055. * software distributed under the License is distributed on an
  68056. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68057. * KIND, either express or implied. See the License for the
  68058. * specific language governing permissions and limitations
  68059. * under the License.
  68060. */
  68061. /**
  68062. * Brush component entry
  68063. */
  68064. registerPreprocessor(preprocessor$1);
  68065. /*
  68066. * Licensed to the Apache Software Foundation (ASF) under one
  68067. * or more contributor license agreements. See the NOTICE file
  68068. * distributed with this work for additional information
  68069. * regarding copyright ownership. The ASF licenses this file
  68070. * to you under the Apache License, Version 2.0 (the
  68071. * "License"); you may not use this file except in compliance
  68072. * with the License. You may obtain a copy of the License at
  68073. *
  68074. * http://www.apache.org/licenses/LICENSE-2.0
  68075. *
  68076. * Unless required by applicable law or agreed to in writing,
  68077. * software distributed under the License is distributed on an
  68078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68079. * KIND, either express or implied. See the License for the
  68080. * specific language governing permissions and limitations
  68081. * under the License.
  68082. */
  68083. // (24*60*60*1000)
  68084. var PROXIMATE_ONE_DAY = 86400000;
  68085. /**
  68086. * Calendar
  68087. *
  68088. * @constructor
  68089. *
  68090. * @param {Object} calendarModel calendarModel
  68091. * @param {Object} ecModel ecModel
  68092. * @param {Object} api api
  68093. */
  68094. function Calendar(calendarModel, ecModel, api) {
  68095. this._model = calendarModel;
  68096. }
  68097. Calendar.prototype = {
  68098. constructor: Calendar,
  68099. type: 'calendar',
  68100. dimensions: ['time', 'value'],
  68101. // Required in createListFromData
  68102. getDimensionsInfo: function () {
  68103. return [{name: 'time', type: 'time'}, 'value'];
  68104. },
  68105. getRangeInfo: function () {
  68106. return this._rangeInfo;
  68107. },
  68108. getModel: function () {
  68109. return this._model;
  68110. },
  68111. getRect: function () {
  68112. return this._rect;
  68113. },
  68114. getCellWidth: function () {
  68115. return this._sw;
  68116. },
  68117. getCellHeight: function () {
  68118. return this._sh;
  68119. },
  68120. getOrient: function () {
  68121. return this._orient;
  68122. },
  68123. /**
  68124. * getFirstDayOfWeek
  68125. *
  68126. * @example
  68127. * 0 : start at Sunday
  68128. * 1 : start at Monday
  68129. *
  68130. * @return {number}
  68131. */
  68132. getFirstDayOfWeek: function () {
  68133. return this._firstDayOfWeek;
  68134. },
  68135. /**
  68136. * get date info
  68137. *
  68138. * @param {string|number} date date
  68139. * @return {Object}
  68140. * {
  68141. * y: string, local full year, eg., '1940',
  68142. * m: string, local month, from '01' ot '12',
  68143. * d: string, local date, from '01' to '31' (if exists),
  68144. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  68145. * time: timestamp,
  68146. * formatedDate: string, yyyy-MM-dd,
  68147. * date: original date object.
  68148. * }
  68149. */
  68150. getDateInfo: function (date) {
  68151. date = parseDate(date);
  68152. var y = date.getFullYear();
  68153. var m = date.getMonth() + 1;
  68154. m = m < 10 ? '0' + m : m;
  68155. var d = date.getDate();
  68156. d = d < 10 ? '0' + d : d;
  68157. var day = date.getDay();
  68158. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  68159. return {
  68160. y: y,
  68161. m: m,
  68162. d: d,
  68163. day: day,
  68164. time: date.getTime(),
  68165. formatedDate: y + '-' + m + '-' + d,
  68166. date: date
  68167. };
  68168. },
  68169. getNextNDay: function (date, n) {
  68170. n = n || 0;
  68171. if (n === 0) {
  68172. return this.getDateInfo(date);
  68173. }
  68174. date = new Date(this.getDateInfo(date).time);
  68175. date.setDate(date.getDate() + n);
  68176. return this.getDateInfo(date);
  68177. },
  68178. update: function (ecModel, api) {
  68179. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  68180. this._orient = this._model.get('orient');
  68181. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  68182. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  68183. var weeks = this._rangeInfo.weeks || 1;
  68184. var whNames = ['width', 'height'];
  68185. var cellSize = this._model.get('cellSize').slice();
  68186. var layoutParams = this._model.getBoxLayoutParams();
  68187. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  68188. each$1([0, 1], function (idx) {
  68189. if (cellSizeSpecified(cellSize, idx)) {
  68190. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  68191. }
  68192. });
  68193. var whGlobal = {
  68194. width: api.getWidth(),
  68195. height: api.getHeight()
  68196. };
  68197. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  68198. each$1([0, 1], function (idx) {
  68199. if (!cellSizeSpecified(cellSize, idx)) {
  68200. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  68201. }
  68202. });
  68203. function cellSizeSpecified(cellSize, idx) {
  68204. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  68205. }
  68206. this._sw = cellSize[0];
  68207. this._sh = cellSize[1];
  68208. },
  68209. /**
  68210. * Convert a time data(time, value) item to (x, y) point.
  68211. *
  68212. * @override
  68213. * @param {Array|number} data data
  68214. * @param {boolean} [clamp=true] out of range
  68215. * @return {Array} point
  68216. */
  68217. dataToPoint: function (data, clamp) {
  68218. isArray(data) && (data = data[0]);
  68219. clamp == null && (clamp = true);
  68220. var dayInfo = this.getDateInfo(data);
  68221. var range = this._rangeInfo;
  68222. var date = dayInfo.formatedDate;
  68223. // if not in range return [NaN, NaN]
  68224. if (clamp && !(
  68225. dayInfo.time >= range.start.time
  68226. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  68227. )) {
  68228. return [NaN, NaN];
  68229. }
  68230. var week = dayInfo.day;
  68231. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  68232. if (this._orient === 'vertical') {
  68233. return [
  68234. this._rect.x + week * this._sw + this._sw / 2,
  68235. this._rect.y + nthWeek * this._sh + this._sh / 2
  68236. ];
  68237. }
  68238. return [
  68239. this._rect.x + nthWeek * this._sw + this._sw / 2,
  68240. this._rect.y + week * this._sh + this._sh / 2
  68241. ];
  68242. },
  68243. /**
  68244. * Convert a (x, y) point to time data
  68245. *
  68246. * @override
  68247. * @param {string} point point
  68248. * @return {string} data
  68249. */
  68250. pointToData: function (point) {
  68251. var date = this.pointToDate(point);
  68252. return date && date.time;
  68253. },
  68254. /**
  68255. * Convert a time date item to (x, y) four point.
  68256. *
  68257. * @param {Array} data date[0] is date
  68258. * @param {boolean} [clamp=true] out of range
  68259. * @return {Object} point
  68260. */
  68261. dataToRect: function (data, clamp) {
  68262. var point = this.dataToPoint(data, clamp);
  68263. return {
  68264. contentShape: {
  68265. x: point[0] - (this._sw - this._lineWidth) / 2,
  68266. y: point[1] - (this._sh - this._lineWidth) / 2,
  68267. width: this._sw - this._lineWidth,
  68268. height: this._sh - this._lineWidth
  68269. },
  68270. center: point,
  68271. tl: [
  68272. point[0] - this._sw / 2,
  68273. point[1] - this._sh / 2
  68274. ],
  68275. tr: [
  68276. point[0] + this._sw / 2,
  68277. point[1] - this._sh / 2
  68278. ],
  68279. br: [
  68280. point[0] + this._sw / 2,
  68281. point[1] + this._sh / 2
  68282. ],
  68283. bl: [
  68284. point[0] - this._sw / 2,
  68285. point[1] + this._sh / 2
  68286. ]
  68287. };
  68288. },
  68289. /**
  68290. * Convert a (x, y) point to time date
  68291. *
  68292. * @param {Array} point point
  68293. * @return {Object} date
  68294. */
  68295. pointToDate: function (point) {
  68296. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  68297. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  68298. var range = this._rangeInfo.range;
  68299. if (this._orient === 'vertical') {
  68300. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  68301. }
  68302. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  68303. },
  68304. /**
  68305. * @inheritDoc
  68306. */
  68307. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  68308. /**
  68309. * @inheritDoc
  68310. */
  68311. convertFromPixel: curry(doConvert$2, 'pointToData'),
  68312. /**
  68313. * initRange
  68314. *
  68315. * @private
  68316. * @return {Array} [start, end]
  68317. */
  68318. _initRangeOption: function () {
  68319. var range = this._model.get('range');
  68320. var rg = range;
  68321. if (isArray(rg) && rg.length === 1) {
  68322. rg = rg[0];
  68323. }
  68324. if (/^\d{4}$/.test(rg)) {
  68325. range = [rg + '-01-01', rg + '-12-31'];
  68326. }
  68327. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  68328. var start = this.getDateInfo(rg);
  68329. var firstDay = start.date;
  68330. firstDay.setMonth(firstDay.getMonth() + 1);
  68331. var end = this.getNextNDay(firstDay, -1);
  68332. range = [start.formatedDate, end.formatedDate];
  68333. }
  68334. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  68335. range = [rg, rg];
  68336. }
  68337. var tmp = this._getRangeInfo(range);
  68338. if (tmp.start.time > tmp.end.time) {
  68339. range.reverse();
  68340. }
  68341. return range;
  68342. },
  68343. /**
  68344. * range info
  68345. *
  68346. * @private
  68347. * @param {Array} range range ['2017-01-01', '2017-07-08']
  68348. * If range[0] > range[1], they will not be reversed.
  68349. * @return {Object} obj
  68350. */
  68351. _getRangeInfo: function (range) {
  68352. range = [
  68353. this.getDateInfo(range[0]),
  68354. this.getDateInfo(range[1])
  68355. ];
  68356. var reversed;
  68357. if (range[0].time > range[1].time) {
  68358. reversed = true;
  68359. range.reverse();
  68360. }
  68361. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  68362. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  68363. // Consider case:
  68364. // Firstly set system timezone as "Time Zone: America/Toronto",
  68365. // ```
  68366. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  68367. // var second = new Date(1478412000000);
  68368. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  68369. // ```
  68370. // will get wrong result because of DST. So we should fix it.
  68371. var date = new Date(range[0].time);
  68372. var startDateNum = date.getDate();
  68373. var endDateNum = range[1].date.getDate();
  68374. date.setDate(startDateNum + allDay - 1);
  68375. // The bias can not over a month, so just compare date.
  68376. if (date.getDate() !== endDateNum) {
  68377. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  68378. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  68379. allDay -= sign;
  68380. date.setDate(startDateNum + allDay - 1);
  68381. }
  68382. }
  68383. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  68384. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  68385. reversed && range.reverse();
  68386. return {
  68387. range: [range[0].formatedDate, range[1].formatedDate],
  68388. start: range[0],
  68389. end: range[1],
  68390. allDay: allDay,
  68391. weeks: weeks,
  68392. // From 0.
  68393. nthWeek: nthWeek,
  68394. fweek: range[0].day,
  68395. lweek: range[1].day
  68396. };
  68397. },
  68398. /**
  68399. * get date by nthWeeks and week day in range
  68400. *
  68401. * @private
  68402. * @param {number} nthWeek the week
  68403. * @param {number} day the week day
  68404. * @param {Array} range [d1, d2]
  68405. * @return {Object}
  68406. */
  68407. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  68408. var rangeInfo = this._getRangeInfo(range);
  68409. if (nthWeek > rangeInfo.weeks
  68410. || (nthWeek === 0 && day < rangeInfo.fweek)
  68411. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  68412. ) {
  68413. return false;
  68414. }
  68415. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  68416. var date = new Date(rangeInfo.start.time);
  68417. date.setDate(rangeInfo.start.d + nthDay);
  68418. return this.getDateInfo(date);
  68419. }
  68420. };
  68421. Calendar.dimensions = Calendar.prototype.dimensions;
  68422. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  68423. Calendar.create = function (ecModel, api) {
  68424. var calendarList = [];
  68425. ecModel.eachComponent('calendar', function (calendarModel) {
  68426. var calendar = new Calendar(calendarModel, ecModel, api);
  68427. calendarList.push(calendar);
  68428. calendarModel.coordinateSystem = calendar;
  68429. });
  68430. ecModel.eachSeries(function (calendarSeries) {
  68431. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  68432. // Inject coordinate system
  68433. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  68434. }
  68435. });
  68436. return calendarList;
  68437. };
  68438. function doConvert$2(methodName, ecModel, finder, value) {
  68439. var calendarModel = finder.calendarModel;
  68440. var seriesModel = finder.seriesModel;
  68441. var coordSys = calendarModel
  68442. ? calendarModel.coordinateSystem
  68443. : seriesModel
  68444. ? seriesModel.coordinateSystem
  68445. : null;
  68446. return coordSys === this ? coordSys[methodName](value) : null;
  68447. }
  68448. CoordinateSystemManager.register('calendar', Calendar);
  68449. /*
  68450. * Licensed to the Apache Software Foundation (ASF) under one
  68451. * or more contributor license agreements. See the NOTICE file
  68452. * distributed with this work for additional information
  68453. * regarding copyright ownership. The ASF licenses this file
  68454. * to you under the Apache License, Version 2.0 (the
  68455. * "License"); you may not use this file except in compliance
  68456. * with the License. You may obtain a copy of the License at
  68457. *
  68458. * http://www.apache.org/licenses/LICENSE-2.0
  68459. *
  68460. * Unless required by applicable law or agreed to in writing,
  68461. * software distributed under the License is distributed on an
  68462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68463. * KIND, either express or implied. See the License for the
  68464. * specific language governing permissions and limitations
  68465. * under the License.
  68466. */
  68467. var CalendarModel = ComponentModel.extend({
  68468. type: 'calendar',
  68469. /**
  68470. * @type {module:echarts/coord/calendar/Calendar}
  68471. */
  68472. coordinateSystem: null,
  68473. defaultOption: {
  68474. zlevel: 0,
  68475. z: 2,
  68476. left: 80,
  68477. top: 60,
  68478. cellSize: 20,
  68479. // horizontal vertical
  68480. orient: 'horizontal',
  68481. // month separate line style
  68482. splitLine: {
  68483. show: true,
  68484. lineStyle: {
  68485. color: '#000',
  68486. width: 1,
  68487. type: 'solid'
  68488. }
  68489. },
  68490. // rect style temporarily unused emphasis
  68491. itemStyle: {
  68492. color: '#fff',
  68493. borderWidth: 1,
  68494. borderColor: '#ccc'
  68495. },
  68496. // week text style
  68497. dayLabel: {
  68498. show: true,
  68499. // a week first day
  68500. firstDay: 0,
  68501. // start end
  68502. position: 'start',
  68503. margin: '50%', // 50% of cellSize
  68504. nameMap: 'en',
  68505. color: '#000'
  68506. },
  68507. // month text style
  68508. monthLabel: {
  68509. show: true,
  68510. // start end
  68511. position: 'start',
  68512. margin: 5,
  68513. // center or left
  68514. align: 'center',
  68515. // cn en []
  68516. nameMap: 'en',
  68517. formatter: null,
  68518. color: '#000'
  68519. },
  68520. // year text style
  68521. yearLabel: {
  68522. show: true,
  68523. // top bottom left right
  68524. position: null,
  68525. margin: 30,
  68526. formatter: null,
  68527. color: '#ccc',
  68528. fontFamily: 'sans-serif',
  68529. fontWeight: 'bolder',
  68530. fontSize: 20
  68531. }
  68532. },
  68533. /**
  68534. * @override
  68535. */
  68536. init: function (option, parentModel, ecModel, extraOpt) {
  68537. var inputPositionParams = getLayoutParams(option);
  68538. CalendarModel.superApply(this, 'init', arguments);
  68539. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  68540. },
  68541. /**
  68542. * @override
  68543. */
  68544. mergeOption: function (option, extraOpt) {
  68545. CalendarModel.superApply(this, 'mergeOption', arguments);
  68546. mergeAndNormalizeLayoutParams$1(this.option, option);
  68547. }
  68548. });
  68549. function mergeAndNormalizeLayoutParams$1(target, raw) {
  68550. // Normalize cellSize
  68551. var cellSize = target.cellSize;
  68552. if (!isArray(cellSize)) {
  68553. cellSize = target.cellSize = [cellSize, cellSize];
  68554. }
  68555. else if (cellSize.length === 1) {
  68556. cellSize[1] = cellSize[0];
  68557. }
  68558. var ignoreSize = map([0, 1], function (hvIdx) {
  68559. // If user have set `width` or both `left` and `right`, cellSize
  68560. // will be automatically set to 'auto', otherwise the default
  68561. // setting of cellSize will make `width` setting not work.
  68562. if (sizeCalculable(raw, hvIdx)) {
  68563. cellSize[hvIdx] = 'auto';
  68564. }
  68565. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  68566. });
  68567. mergeLayoutParam(target, raw, {
  68568. type: 'box', ignoreSize: ignoreSize
  68569. });
  68570. }
  68571. /*
  68572. * Licensed to the Apache Software Foundation (ASF) under one
  68573. * or more contributor license agreements. See the NOTICE file
  68574. * distributed with this work for additional information
  68575. * regarding copyright ownership. The ASF licenses this file
  68576. * to you under the Apache License, Version 2.0 (the
  68577. * "License"); you may not use this file except in compliance
  68578. * with the License. You may obtain a copy of the License at
  68579. *
  68580. * http://www.apache.org/licenses/LICENSE-2.0
  68581. *
  68582. * Unless required by applicable law or agreed to in writing,
  68583. * software distributed under the License is distributed on an
  68584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68585. * KIND, either express or implied. See the License for the
  68586. * specific language governing permissions and limitations
  68587. * under the License.
  68588. */
  68589. var MONTH_TEXT = {
  68590. EN: [
  68591. 'Jan', 'Feb', 'Mar',
  68592. 'Apr', 'May', 'Jun',
  68593. 'Jul', 'Aug', 'Sep',
  68594. 'Oct', 'Nov', 'Dec'
  68595. ],
  68596. CN: [
  68597. '一月', '二月', '三月',
  68598. '四月', '五月', '六月',
  68599. '七月', '八月', '九月',
  68600. '十月', '十一月', '十二月'
  68601. ]
  68602. };
  68603. var WEEK_TEXT = {
  68604. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  68605. CN: ['日', '一', '二', '三', '四', '五', '六']
  68606. };
  68607. extendComponentView({
  68608. type: 'calendar',
  68609. /**
  68610. * top/left line points
  68611. * @private
  68612. */
  68613. _tlpoints: null,
  68614. /**
  68615. * bottom/right line points
  68616. * @private
  68617. */
  68618. _blpoints: null,
  68619. /**
  68620. * first day of month
  68621. * @private
  68622. */
  68623. _firstDayOfMonth: null,
  68624. /**
  68625. * first day point of month
  68626. * @private
  68627. */
  68628. _firstDayPoints: null,
  68629. render: function (calendarModel, ecModel, api) {
  68630. var group = this.group;
  68631. group.removeAll();
  68632. var coordSys = calendarModel.coordinateSystem;
  68633. // range info
  68634. var rangeData = coordSys.getRangeInfo();
  68635. var orient = coordSys.getOrient();
  68636. this._renderDayRect(calendarModel, rangeData, group);
  68637. // _renderLines must be called prior to following function
  68638. this._renderLines(calendarModel, rangeData, orient, group);
  68639. this._renderYearText(calendarModel, rangeData, orient, group);
  68640. this._renderMonthText(calendarModel, orient, group);
  68641. this._renderWeekText(calendarModel, rangeData, orient, group);
  68642. },
  68643. // render day rect
  68644. _renderDayRect: function (calendarModel, rangeData, group) {
  68645. var coordSys = calendarModel.coordinateSystem;
  68646. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  68647. var sw = coordSys.getCellWidth();
  68648. var sh = coordSys.getCellHeight();
  68649. for (var i = rangeData.start.time;
  68650. i <= rangeData.end.time;
  68651. i = coordSys.getNextNDay(i, 1).time
  68652. ) {
  68653. var point = coordSys.dataToRect([i], false).tl;
  68654. // every rect
  68655. var rect = new Rect({
  68656. shape: {
  68657. x: point[0],
  68658. y: point[1],
  68659. width: sw,
  68660. height: sh
  68661. },
  68662. cursor: 'default',
  68663. style: itemRectStyleModel
  68664. });
  68665. group.add(rect);
  68666. }
  68667. },
  68668. // render separate line
  68669. _renderLines: function (calendarModel, rangeData, orient, group) {
  68670. var self = this;
  68671. var coordSys = calendarModel.coordinateSystem;
  68672. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  68673. var show = calendarModel.get('splitLine.show');
  68674. var lineWidth = lineStyleModel.lineWidth;
  68675. this._tlpoints = [];
  68676. this._blpoints = [];
  68677. this._firstDayOfMonth = [];
  68678. this._firstDayPoints = [];
  68679. var firstDay = rangeData.start;
  68680. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  68681. addPoints(firstDay.formatedDate);
  68682. if (i === 0) {
  68683. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  68684. }
  68685. var date = firstDay.date;
  68686. date.setMonth(date.getMonth() + 1);
  68687. firstDay = coordSys.getDateInfo(date);
  68688. }
  68689. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  68690. function addPoints(date) {
  68691. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  68692. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  68693. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  68694. self._tlpoints.push(points[0]);
  68695. self._blpoints.push(points[points.length - 1]);
  68696. show && self._drawSplitline(points, lineStyleModel, group);
  68697. }
  68698. // render top/left line
  68699. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  68700. // render bottom/right line
  68701. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  68702. },
  68703. // get points at both ends
  68704. _getEdgesPoints: function (points, lineWidth, orient) {
  68705. var rs = [points[0].slice(), points[points.length - 1].slice()];
  68706. var idx = orient === 'horizontal' ? 0 : 1;
  68707. // both ends of the line are extend half lineWidth
  68708. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  68709. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  68710. return rs;
  68711. },
  68712. // render split line
  68713. _drawSplitline: function (points, lineStyleModel, group) {
  68714. var poyline = new Polyline({
  68715. z2: 20,
  68716. shape: {
  68717. points: points
  68718. },
  68719. style: lineStyleModel
  68720. });
  68721. group.add(poyline);
  68722. },
  68723. // render month line of one week points
  68724. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  68725. var coordSys = calendarModel.coordinateSystem;
  68726. date = coordSys.getDateInfo(date);
  68727. var points = [];
  68728. for (var i = 0; i < 7; i++) {
  68729. var tmpD = coordSys.getNextNDay(date.time, i);
  68730. var point = coordSys.dataToRect([tmpD.time], false);
  68731. points[2 * tmpD.day] = point.tl;
  68732. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  68733. }
  68734. return points;
  68735. },
  68736. _formatterLabel: function (formatter, params) {
  68737. if (typeof formatter === 'string' && formatter) {
  68738. return formatTplSimple(formatter, params);
  68739. }
  68740. if (typeof formatter === 'function') {
  68741. return formatter(params);
  68742. }
  68743. return params.nameMap;
  68744. },
  68745. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  68746. point = point.slice();
  68747. var aligns = ['center', 'bottom'];
  68748. if (position === 'bottom') {
  68749. point[1] += margin;
  68750. aligns = ['center', 'top'];
  68751. }
  68752. else if (position === 'left') {
  68753. point[0] -= margin;
  68754. }
  68755. else if (position === 'right') {
  68756. point[0] += margin;
  68757. aligns = ['center', 'top'];
  68758. }
  68759. else { // top
  68760. point[1] -= margin;
  68761. }
  68762. var rotate = 0;
  68763. if (position === 'left' || position === 'right') {
  68764. rotate = Math.PI / 2;
  68765. }
  68766. return {
  68767. rotation: rotate,
  68768. position: point,
  68769. style: {
  68770. textAlign: aligns[0],
  68771. textVerticalAlign: aligns[1]
  68772. }
  68773. };
  68774. },
  68775. // render year
  68776. _renderYearText: function (calendarModel, rangeData, orient, group) {
  68777. var yearLabel = calendarModel.getModel('yearLabel');
  68778. if (!yearLabel.get('show')) {
  68779. return;
  68780. }
  68781. var margin = yearLabel.get('margin');
  68782. var pos = yearLabel.get('position');
  68783. if (!pos) {
  68784. pos = orient !== 'horizontal' ? 'top' : 'left';
  68785. }
  68786. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  68787. var xc = (points[0][0] + points[1][0]) / 2;
  68788. var yc = (points[0][1] + points[1][1]) / 2;
  68789. var idx = orient === 'horizontal' ? 0 : 1;
  68790. var posPoints = {
  68791. top: [xc, points[idx][1]],
  68792. bottom: [xc, points[1 - idx][1]],
  68793. left: [points[1 - idx][0], yc],
  68794. right: [points[idx][0], yc]
  68795. };
  68796. var name = rangeData.start.y;
  68797. if (+rangeData.end.y > +rangeData.start.y) {
  68798. name = name + '-' + rangeData.end.y;
  68799. }
  68800. var formatter = yearLabel.get('formatter');
  68801. var params = {
  68802. start: rangeData.start.y,
  68803. end: rangeData.end.y,
  68804. nameMap: name
  68805. };
  68806. var content = this._formatterLabel(formatter, params);
  68807. var yearText = new Text({z2: 30});
  68808. setTextStyle(yearText.style, yearLabel, {text: content}),
  68809. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  68810. group.add(yearText);
  68811. },
  68812. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  68813. var align = 'left';
  68814. var vAlign = 'top';
  68815. var x = point[0];
  68816. var y = point[1];
  68817. if (orient === 'horizontal') {
  68818. y = y + margin;
  68819. if (isCenter) {
  68820. align = 'center';
  68821. }
  68822. if (position === 'start') {
  68823. vAlign = 'bottom';
  68824. }
  68825. }
  68826. else {
  68827. x = x + margin;
  68828. if (isCenter) {
  68829. vAlign = 'middle';
  68830. }
  68831. if (position === 'start') {
  68832. align = 'right';
  68833. }
  68834. }
  68835. return {
  68836. x: x,
  68837. y: y,
  68838. textAlign: align,
  68839. textVerticalAlign: vAlign
  68840. };
  68841. },
  68842. // render month and year text
  68843. _renderMonthText: function (calendarModel, orient, group) {
  68844. var monthLabel = calendarModel.getModel('monthLabel');
  68845. if (!monthLabel.get('show')) {
  68846. return;
  68847. }
  68848. var nameMap = monthLabel.get('nameMap');
  68849. var margin = monthLabel.get('margin');
  68850. var pos = monthLabel.get('position');
  68851. var align = monthLabel.get('align');
  68852. var termPoints = [this._tlpoints, this._blpoints];
  68853. if (isString(nameMap)) {
  68854. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  68855. }
  68856. var idx = pos === 'start' ? 0 : 1;
  68857. var axis = orient === 'horizontal' ? 0 : 1;
  68858. margin = pos === 'start' ? -margin : margin;
  68859. var isCenter = (align === 'center');
  68860. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  68861. var tmp = termPoints[idx][i].slice();
  68862. var firstDay = this._firstDayOfMonth[i];
  68863. if (isCenter) {
  68864. var firstDayPoints = this._firstDayPoints[i];
  68865. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  68866. }
  68867. var formatter = monthLabel.get('formatter');
  68868. var name = nameMap[+firstDay.m - 1];
  68869. var params = {
  68870. yyyy: firstDay.y,
  68871. yy: (firstDay.y + '').slice(2),
  68872. MM: firstDay.m,
  68873. M: +firstDay.m,
  68874. nameMap: name
  68875. };
  68876. var content = this._formatterLabel(formatter, params);
  68877. var monthText = new Text({z2: 30});
  68878. extend(
  68879. setTextStyle(monthText.style, monthLabel, {text: content}),
  68880. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  68881. );
  68882. group.add(monthText);
  68883. }
  68884. },
  68885. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  68886. var align = 'center';
  68887. var vAlign = 'middle';
  68888. var x = point[0];
  68889. var y = point[1];
  68890. var isStart = position === 'start';
  68891. if (orient === 'horizontal') {
  68892. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  68893. align = isStart ? 'right' : 'left';
  68894. }
  68895. else {
  68896. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  68897. vAlign = isStart ? 'bottom' : 'top';
  68898. }
  68899. return {
  68900. x: x,
  68901. y: y,
  68902. textAlign: align,
  68903. textVerticalAlign: vAlign
  68904. };
  68905. },
  68906. // render weeks
  68907. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  68908. var dayLabel = calendarModel.getModel('dayLabel');
  68909. if (!dayLabel.get('show')) {
  68910. return;
  68911. }
  68912. var coordSys = calendarModel.coordinateSystem;
  68913. var pos = dayLabel.get('position');
  68914. var nameMap = dayLabel.get('nameMap');
  68915. var margin = dayLabel.get('margin');
  68916. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  68917. if (isString(nameMap)) {
  68918. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  68919. }
  68920. var start = coordSys.getNextNDay(
  68921. rangeData.end.time, (7 - rangeData.lweek)
  68922. ).time;
  68923. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  68924. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  68925. if (pos === 'start') {
  68926. start = coordSys.getNextNDay(
  68927. rangeData.start.time, -(7 + rangeData.fweek)
  68928. ).time;
  68929. margin = -margin;
  68930. }
  68931. for (var i = 0; i < 7; i++) {
  68932. var tmpD = coordSys.getNextNDay(start, i);
  68933. var point = coordSys.dataToRect([tmpD.time], false).center;
  68934. var day = i;
  68935. day = Math.abs((i + firstDayOfWeek) % 7);
  68936. var weekText = new Text({z2: 30});
  68937. extend(
  68938. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  68939. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  68940. );
  68941. group.add(weekText);
  68942. }
  68943. }
  68944. });
  68945. /*
  68946. * Licensed to the Apache Software Foundation (ASF) under one
  68947. * or more contributor license agreements. See the NOTICE file
  68948. * distributed with this work for additional information
  68949. * regarding copyright ownership. The ASF licenses this file
  68950. * to you under the Apache License, Version 2.0 (the
  68951. * "License"); you may not use this file except in compliance
  68952. * with the License. You may obtain a copy of the License at
  68953. *
  68954. * http://www.apache.org/licenses/LICENSE-2.0
  68955. *
  68956. * Unless required by applicable law or agreed to in writing,
  68957. * software distributed under the License is distributed on an
  68958. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68959. * KIND, either express or implied. See the License for the
  68960. * specific language governing permissions and limitations
  68961. * under the License.
  68962. */
  68963. /**
  68964. * @file calendar.js
  68965. * @author dxh
  68966. */
  68967. /*
  68968. * Licensed to the Apache Software Foundation (ASF) under one
  68969. * or more contributor license agreements. See the NOTICE file
  68970. * distributed with this work for additional information
  68971. * regarding copyright ownership. The ASF licenses this file
  68972. * to you under the Apache License, Version 2.0 (the
  68973. * "License"); you may not use this file except in compliance
  68974. * with the License. You may obtain a copy of the License at
  68975. *
  68976. * http://www.apache.org/licenses/LICENSE-2.0
  68977. *
  68978. * Unless required by applicable law or agreed to in writing,
  68979. * software distributed under the License is distributed on an
  68980. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68981. * KIND, either express or implied. See the License for the
  68982. * specific language governing permissions and limitations
  68983. * under the License.
  68984. */
  68985. // Model
  68986. extendComponentModel({
  68987. type: 'title',
  68988. layoutMode: {type: 'box', ignoreSize: true},
  68989. defaultOption: {
  68990. // 一级层叠
  68991. zlevel: 0,
  68992. // 二级层叠
  68993. z: 6,
  68994. show: true,
  68995. text: '',
  68996. // 超链接跳转
  68997. // link: null,
  68998. // 仅支持self | blank
  68999. target: 'blank',
  69000. subtext: '',
  69001. // 超链接跳转
  69002. // sublink: null,
  69003. // 仅支持self | blank
  69004. subtarget: 'blank',
  69005. // 'center' ¦ 'left' ¦ 'right'
  69006. // ¦ {number}(x坐标,单位px)
  69007. left: 0,
  69008. // 'top' ¦ 'bottom' ¦ 'center'
  69009. // ¦ {number}(y坐标,单位px)
  69010. top: 0,
  69011. // 水平对齐
  69012. // 'auto' | 'left' | 'right' | 'center'
  69013. // 默认根据 left 的位置判断是左对齐还是右对齐
  69014. // textAlign: null
  69015. //
  69016. // 垂直对齐
  69017. // 'auto' | 'top' | 'bottom' | 'middle'
  69018. // 默认根据 top 位置判断是上对齐还是下对齐
  69019. // textBaseline: null
  69020. backgroundColor: 'rgba(0,0,0,0)',
  69021. // 标题边框颜色
  69022. borderColor: '#ccc',
  69023. // 标题边框线宽,单位px,默认为0(无边框)
  69024. borderWidth: 0,
  69025. // 标题内边距,单位px,默认各方向内边距为5,
  69026. // 接受数组分别设定上右下左边距,同css
  69027. padding: 5,
  69028. // 主副标题纵向间隔,单位px,默认为10,
  69029. itemGap: 10,
  69030. textStyle: {
  69031. fontSize: 18,
  69032. fontWeight: 'bolder',
  69033. color: '#333'
  69034. },
  69035. subtextStyle: {
  69036. color: '#aaa'
  69037. }
  69038. }
  69039. });
  69040. // View
  69041. extendComponentView({
  69042. type: 'title',
  69043. render: function (titleModel, ecModel, api) {
  69044. this.group.removeAll();
  69045. if (!titleModel.get('show')) {
  69046. return;
  69047. }
  69048. var group = this.group;
  69049. var textStyleModel = titleModel.getModel('textStyle');
  69050. var subtextStyleModel = titleModel.getModel('subtextStyle');
  69051. var textAlign = titleModel.get('textAlign');
  69052. var textBaseline = titleModel.get('textBaseline');
  69053. var textEl = new Text({
  69054. style: setTextStyle({}, textStyleModel, {
  69055. text: titleModel.get('text'),
  69056. textFill: textStyleModel.getTextColor()
  69057. }, {disableBox: true}),
  69058. z2: 10
  69059. });
  69060. var textRect = textEl.getBoundingRect();
  69061. var subText = titleModel.get('subtext');
  69062. var subTextEl = new Text({
  69063. style: setTextStyle({}, subtextStyleModel, {
  69064. text: subText,
  69065. textFill: subtextStyleModel.getTextColor(),
  69066. y: textRect.height + titleModel.get('itemGap'),
  69067. textVerticalAlign: 'top'
  69068. }, {disableBox: true}),
  69069. z2: 10
  69070. });
  69071. var link = titleModel.get('link');
  69072. var sublink = titleModel.get('sublink');
  69073. var triggerEvent = titleModel.get('triggerEvent', true);
  69074. textEl.silent = !link && !triggerEvent;
  69075. subTextEl.silent = !sublink && !triggerEvent;
  69076. if (link) {
  69077. textEl.on('click', function () {
  69078. window.open(link, '_' + titleModel.get('target'));
  69079. });
  69080. }
  69081. if (sublink) {
  69082. subTextEl.on('click', function () {
  69083. window.open(sublink, '_' + titleModel.get('subtarget'));
  69084. });
  69085. }
  69086. textEl.eventData = subTextEl.eventData = triggerEvent
  69087. ? {
  69088. componentType: 'title',
  69089. componentIndex: titleModel.componentIndex
  69090. }
  69091. : null;
  69092. group.add(textEl);
  69093. subText && group.add(subTextEl);
  69094. // If no subText, but add subTextEl, there will be an empty line.
  69095. var groupRect = group.getBoundingRect();
  69096. var layoutOption = titleModel.getBoxLayoutParams();
  69097. layoutOption.width = groupRect.width;
  69098. layoutOption.height = groupRect.height;
  69099. var layoutRect = getLayoutRect(
  69100. layoutOption, {
  69101. width: api.getWidth(),
  69102. height: api.getHeight()
  69103. }, titleModel.get('padding')
  69104. );
  69105. // Adjust text align based on position
  69106. if (!textAlign) {
  69107. // Align left if title is on the left. center and right is same
  69108. textAlign = titleModel.get('left') || titleModel.get('right');
  69109. if (textAlign === 'middle') {
  69110. textAlign = 'center';
  69111. }
  69112. // Adjust layout by text align
  69113. if (textAlign === 'right') {
  69114. layoutRect.x += layoutRect.width;
  69115. }
  69116. else if (textAlign === 'center') {
  69117. layoutRect.x += layoutRect.width / 2;
  69118. }
  69119. }
  69120. if (!textBaseline) {
  69121. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  69122. if (textBaseline === 'center') {
  69123. textBaseline = 'middle';
  69124. }
  69125. if (textBaseline === 'bottom') {
  69126. layoutRect.y += layoutRect.height;
  69127. }
  69128. else if (textBaseline === 'middle') {
  69129. layoutRect.y += layoutRect.height / 2;
  69130. }
  69131. textBaseline = textBaseline || 'top';
  69132. }
  69133. group.attr('position', [layoutRect.x, layoutRect.y]);
  69134. var alignStyle = {
  69135. textAlign: textAlign,
  69136. textVerticalAlign: textBaseline
  69137. };
  69138. textEl.setStyle(alignStyle);
  69139. subTextEl.setStyle(alignStyle);
  69140. // Render background
  69141. // Get groupRect again because textAlign has been changed
  69142. groupRect = group.getBoundingRect();
  69143. var padding = layoutRect.margin;
  69144. var style = titleModel.getItemStyle(['color', 'opacity']);
  69145. style.fill = titleModel.get('backgroundColor');
  69146. var rect = new Rect({
  69147. shape: {
  69148. x: groupRect.x - padding[3],
  69149. y: groupRect.y - padding[0],
  69150. width: groupRect.width + padding[1] + padding[3],
  69151. height: groupRect.height + padding[0] + padding[2],
  69152. r: titleModel.get('borderRadius')
  69153. },
  69154. style: style,
  69155. silent: true
  69156. });
  69157. subPixelOptimizeRect(rect);
  69158. group.add(rect);
  69159. }
  69160. });
  69161. /*
  69162. * Licensed to the Apache Software Foundation (ASF) under one
  69163. * or more contributor license agreements. See the NOTICE file
  69164. * distributed with this work for additional information
  69165. * regarding copyright ownership. The ASF licenses this file
  69166. * to you under the Apache License, Version 2.0 (the
  69167. * "License"); you may not use this file except in compliance
  69168. * with the License. You may obtain a copy of the License at
  69169. *
  69170. * http://www.apache.org/licenses/LICENSE-2.0
  69171. *
  69172. * Unless required by applicable law or agreed to in writing,
  69173. * software distributed under the License is distributed on an
  69174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69175. * KIND, either express or implied. See the License for the
  69176. * specific language governing permissions and limitations
  69177. * under the License.
  69178. */
  69179. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  69180. // Default 'slider' when no type specified.
  69181. return 'slider';
  69182. });
  69183. /*
  69184. * Licensed to the Apache Software Foundation (ASF) under one
  69185. * or more contributor license agreements. See the NOTICE file
  69186. * distributed with this work for additional information
  69187. * regarding copyright ownership. The ASF licenses this file
  69188. * to you under the Apache License, Version 2.0 (the
  69189. * "License"); you may not use this file except in compliance
  69190. * with the License. You may obtain a copy of the License at
  69191. *
  69192. * http://www.apache.org/licenses/LICENSE-2.0
  69193. *
  69194. * Unless required by applicable law or agreed to in writing,
  69195. * software distributed under the License is distributed on an
  69196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69197. * KIND, either express or implied. See the License for the
  69198. * specific language governing permissions and limitations
  69199. * under the License.
  69200. */
  69201. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  69202. // Supported coords.
  69203. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  69204. /**
  69205. * @param {string} coordType
  69206. * @return {boolean}
  69207. */
  69208. function isCoordSupported(coordType) {
  69209. return indexOf(COORDS, coordType) >= 0;
  69210. }
  69211. /**
  69212. * Create "each" method to iterate names.
  69213. *
  69214. * @pubilc
  69215. * @param {Array.<string>} names
  69216. * @param {Array.<string>=} attrs
  69217. * @return {Function}
  69218. */
  69219. function createNameEach(names, attrs) {
  69220. names = names.slice();
  69221. var capitalNames = map(names, capitalFirst);
  69222. attrs = (attrs || []).slice();
  69223. var capitalAttrs = map(attrs, capitalFirst);
  69224. return function (callback, context) {
  69225. each$1(names, function (name, index) {
  69226. var nameObj = {name: name, capital: capitalNames[index]};
  69227. for (var j = 0; j < attrs.length; j++) {
  69228. nameObj[attrs[j]] = name + capitalAttrs[j];
  69229. }
  69230. callback.call(context, nameObj);
  69231. });
  69232. };
  69233. }
  69234. /**
  69235. * Iterate each dimension name.
  69236. *
  69237. * @public
  69238. * @param {Function} callback The parameter is like:
  69239. * {
  69240. * name: 'angle',
  69241. * capital: 'Angle',
  69242. * axis: 'angleAxis',
  69243. * axisIndex: 'angleAixs',
  69244. * index: 'angleIndex'
  69245. * }
  69246. * @param {Object} context
  69247. */
  69248. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  69249. /**
  69250. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  69251. * dataZoomModels and 'links' make up one or more graphics.
  69252. * This function finds the graphic where the source dataZoomModel is in.
  69253. *
  69254. * @public
  69255. * @param {Function} forEachNode Node iterator.
  69256. * @param {Function} forEachEdgeType edgeType iterator
  69257. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  69258. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  69259. */
  69260. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  69261. return function (sourceNode) {
  69262. var result = {
  69263. nodes: [],
  69264. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  69265. };
  69266. forEachEdgeType(function (edgeType) {
  69267. result.records[edgeType.name] = {};
  69268. });
  69269. if (!sourceNode) {
  69270. return result;
  69271. }
  69272. absorb(sourceNode, result);
  69273. var existsLink;
  69274. do {
  69275. existsLink = false;
  69276. forEachNode(processSingleNode);
  69277. }
  69278. while (existsLink);
  69279. function processSingleNode(node) {
  69280. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  69281. absorb(node, result);
  69282. existsLink = true;
  69283. }
  69284. }
  69285. return result;
  69286. };
  69287. function isNodeAbsorded(node, result) {
  69288. return indexOf(result.nodes, node) >= 0;
  69289. }
  69290. function isLinked(node, result) {
  69291. var hasLink = false;
  69292. forEachEdgeType(function (edgeType) {
  69293. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69294. result.records[edgeType.name][edgeId] && (hasLink = true);
  69295. });
  69296. });
  69297. return hasLink;
  69298. }
  69299. function absorb(node, result) {
  69300. result.nodes.push(node);
  69301. forEachEdgeType(function (edgeType) {
  69302. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69303. result.records[edgeType.name][edgeId] = true;
  69304. });
  69305. });
  69306. }
  69307. }
  69308. /*
  69309. * Licensed to the Apache Software Foundation (ASF) under one
  69310. * or more contributor license agreements. See the NOTICE file
  69311. * distributed with this work for additional information
  69312. * regarding copyright ownership. The ASF licenses this file
  69313. * to you under the Apache License, Version 2.0 (the
  69314. * "License"); you may not use this file except in compliance
  69315. * with the License. You may obtain a copy of the License at
  69316. *
  69317. * http://www.apache.org/licenses/LICENSE-2.0
  69318. *
  69319. * Unless required by applicable law or agreed to in writing,
  69320. * software distributed under the License is distributed on an
  69321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69322. * KIND, either express or implied. See the License for the
  69323. * specific language governing permissions and limitations
  69324. * under the License.
  69325. */
  69326. var each$22 = each$1;
  69327. var asc$1 = asc;
  69328. /**
  69329. * Operate single axis.
  69330. * One axis can only operated by one axis operator.
  69331. * Different dataZoomModels may be defined to operate the same axis.
  69332. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69333. * So dataZoomModels share one axisProxy in that case.
  69334. *
  69335. * @class
  69336. */
  69337. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  69338. /**
  69339. * @private
  69340. * @type {string}
  69341. */
  69342. this._dimName = dimName;
  69343. /**
  69344. * @private
  69345. */
  69346. this._axisIndex = axisIndex;
  69347. /**
  69348. * @private
  69349. * @type {Array.<number>}
  69350. */
  69351. this._valueWindow;
  69352. /**
  69353. * @private
  69354. * @type {Array.<number>}
  69355. */
  69356. this._percentWindow;
  69357. /**
  69358. * @private
  69359. * @type {Array.<number>}
  69360. */
  69361. this._dataExtent;
  69362. /**
  69363. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  69364. * @private
  69365. * @type {Object}
  69366. */
  69367. this._minMaxSpan;
  69368. /**
  69369. * @readOnly
  69370. * @type {module: echarts/model/Global}
  69371. */
  69372. this.ecModel = ecModel;
  69373. /**
  69374. * @private
  69375. * @type {module: echarts/component/dataZoom/DataZoomModel}
  69376. */
  69377. this._dataZoomModel = dataZoomModel;
  69378. // /**
  69379. // * @readOnly
  69380. // * @private
  69381. // */
  69382. // this.hasSeriesStacked;
  69383. };
  69384. AxisProxy.prototype = {
  69385. constructor: AxisProxy,
  69386. /**
  69387. * Whether the axisProxy is hosted by dataZoomModel.
  69388. *
  69389. * @public
  69390. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69391. * @return {boolean}
  69392. */
  69393. hostedBy: function (dataZoomModel) {
  69394. return this._dataZoomModel === dataZoomModel;
  69395. },
  69396. /**
  69397. * @return {Array.<number>} Value can only be NaN or finite value.
  69398. */
  69399. getDataValueWindow: function () {
  69400. return this._valueWindow.slice();
  69401. },
  69402. /**
  69403. * @return {Array.<number>}
  69404. */
  69405. getDataPercentWindow: function () {
  69406. return this._percentWindow.slice();
  69407. },
  69408. /**
  69409. * @public
  69410. * @param {number} axisIndex
  69411. * @return {Array} seriesModels
  69412. */
  69413. getTargetSeriesModels: function () {
  69414. var seriesModels = [];
  69415. var ecModel = this.ecModel;
  69416. ecModel.eachSeries(function (seriesModel) {
  69417. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  69418. var dimName = this._dimName;
  69419. var axisModel = ecModel.queryComponents({
  69420. mainType: dimName + 'Axis',
  69421. index: seriesModel.get(dimName + 'AxisIndex'),
  69422. id: seriesModel.get(dimName + 'AxisId')
  69423. })[0];
  69424. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  69425. seriesModels.push(seriesModel);
  69426. }
  69427. }
  69428. }, this);
  69429. return seriesModels;
  69430. },
  69431. getAxisModel: function () {
  69432. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69433. },
  69434. getOtherAxisModel: function () {
  69435. var axisDim = this._dimName;
  69436. var ecModel = this.ecModel;
  69437. var axisModel = this.getAxisModel();
  69438. var isCartesian = axisDim === 'x' || axisDim === 'y';
  69439. var otherAxisDim;
  69440. var coordSysIndexName;
  69441. if (isCartesian) {
  69442. coordSysIndexName = 'gridIndex';
  69443. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  69444. }
  69445. else {
  69446. coordSysIndexName = 'polarIndex';
  69447. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  69448. }
  69449. var foundOtherAxisModel;
  69450. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  69451. if ((otherAxisModel.get(coordSysIndexName) || 0)
  69452. === (axisModel.get(coordSysIndexName) || 0)
  69453. ) {
  69454. foundOtherAxisModel = otherAxisModel;
  69455. }
  69456. });
  69457. return foundOtherAxisModel;
  69458. },
  69459. getMinMaxSpan: function () {
  69460. return clone(this._minMaxSpan);
  69461. },
  69462. /**
  69463. * Only calculate by given range and this._dataExtent, do not change anything.
  69464. *
  69465. * @param {Object} opt
  69466. * @param {number} [opt.start]
  69467. * @param {number} [opt.end]
  69468. * @param {number} [opt.startValue]
  69469. * @param {number} [opt.endValue]
  69470. */
  69471. calculateDataWindow: function (opt) {
  69472. var dataExtent = this._dataExtent;
  69473. var axisModel = this.getAxisModel();
  69474. var scale = axisModel.axis.scale;
  69475. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69476. var percentExtent = [0, 100];
  69477. var percentWindow = [
  69478. opt.start,
  69479. opt.end
  69480. ];
  69481. var valueWindow = [];
  69482. each$22(['startValue', 'endValue'], function (prop) {
  69483. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  69484. });
  69485. // Normalize bound.
  69486. each$22([0, 1], function (idx) {
  69487. var boundValue = valueWindow[idx];
  69488. var boundPercent = percentWindow[idx];
  69489. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69490. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  69491. // for cases that a dataZoom component controls multiple axes with different
  69492. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  69493. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  69494. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  69495. // accurately (because all of values that are overflow the `dataExtent` will
  69496. // be calculated to percent '100%'). So we have to use
  69497. // `dataZoom.getRangePropMode()` to mark which prop is used.
  69498. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  69499. // it remains its original value.
  69500. if (rangePropMode[idx] === 'percent') {
  69501. if (boundPercent == null) {
  69502. boundPercent = percentExtent[idx];
  69503. }
  69504. // Use scale.parse to math round for category or time axis.
  69505. boundValue = scale.parse(linearMap(
  69506. boundPercent, percentExtent, dataExtent, true
  69507. ));
  69508. }
  69509. else {
  69510. // Calculating `percent` from `value` may be not accurate, because
  69511. // This calculation can not be inversed, because all of values that
  69512. // are overflow the `dataExtent` will be calculated to percent '100%'
  69513. boundPercent = linearMap(
  69514. boundValue, dataExtent, percentExtent, true
  69515. );
  69516. }
  69517. // valueWindow[idx] = round(boundValue);
  69518. // percentWindow[idx] = round(boundPercent);
  69519. valueWindow[idx] = boundValue;
  69520. percentWindow[idx] = boundPercent;
  69521. });
  69522. return {
  69523. valueWindow: asc$1(valueWindow),
  69524. percentWindow: asc$1(percentWindow)
  69525. };
  69526. },
  69527. /**
  69528. * Notice: reset should not be called before series.restoreData() called,
  69529. * so it is recommanded to be called in "process stage" but not "model init
  69530. * stage".
  69531. *
  69532. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69533. */
  69534. reset: function (dataZoomModel) {
  69535. if (dataZoomModel !== this._dataZoomModel) {
  69536. return;
  69537. }
  69538. var targetSeries = this.getTargetSeriesModels();
  69539. // Culculate data window and data extent, and record them.
  69540. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  69541. // this.hasSeriesStacked = false;
  69542. // each(targetSeries, function (series) {
  69543. // var data = series.getData();
  69544. // var dataDim = data.mapDimension(this._dimName);
  69545. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  69546. // if (stackedDimension && stackedDimension === dataDim) {
  69547. // this.hasSeriesStacked = true;
  69548. // }
  69549. // }, this);
  69550. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  69551. this._valueWindow = dataWindow.valueWindow;
  69552. this._percentWindow = dataWindow.percentWindow;
  69553. setMinMaxSpan(this);
  69554. // Update axis setting then.
  69555. setAxisModel(this);
  69556. },
  69557. /**
  69558. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69559. */
  69560. restore: function (dataZoomModel) {
  69561. if (dataZoomModel !== this._dataZoomModel) {
  69562. return;
  69563. }
  69564. this._valueWindow = this._percentWindow = null;
  69565. setAxisModel(this, true);
  69566. },
  69567. /**
  69568. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69569. */
  69570. filterData: function (dataZoomModel, api) {
  69571. if (dataZoomModel !== this._dataZoomModel) {
  69572. return;
  69573. }
  69574. var axisDim = this._dimName;
  69575. var seriesModels = this.getTargetSeriesModels();
  69576. var filterMode = dataZoomModel.get('filterMode');
  69577. var valueWindow = this._valueWindow;
  69578. if (filterMode === 'none') {
  69579. return;
  69580. }
  69581. // FIXME
  69582. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69583. // with NaN data, NaN will be filtered and stack will be wrong.
  69584. // So we need to force the mode to be set empty.
  69585. // In fect, it is not a big deal that do not support filterMode-'filter'
  69586. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69587. // selection" some day, which might need "adapt to data extent on the
  69588. // otherAxis", which is disabled by filterMode-'empty'.
  69589. // But currently, stack has been fixed to based on value but not index,
  69590. // so this is not an issue any more.
  69591. // var otherAxisModel = this.getOtherAxisModel();
  69592. // if (dataZoomModel.get('$fromToolbox')
  69593. // && otherAxisModel
  69594. // && otherAxisModel.hasSeriesStacked
  69595. // ) {
  69596. // filterMode = 'empty';
  69597. // }
  69598. // TODO
  69599. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69600. each$22(seriesModels, function (seriesModel) {
  69601. var seriesData = seriesModel.getData();
  69602. var dataDims = seriesData.mapDimension(axisDim, true);
  69603. if (!dataDims.length) {
  69604. return;
  69605. }
  69606. if (filterMode === 'weakFilter') {
  69607. seriesData.filterSelf(function (dataIndex) {
  69608. var leftOut;
  69609. var rightOut;
  69610. var hasValue;
  69611. for (var i = 0; i < dataDims.length; i++) {
  69612. var value = seriesData.get(dataDims[i], dataIndex);
  69613. var thisHasValue = !isNaN(value);
  69614. var thisLeftOut = value < valueWindow[0];
  69615. var thisRightOut = value > valueWindow[1];
  69616. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69617. return true;
  69618. }
  69619. thisHasValue && (hasValue = true);
  69620. thisLeftOut && (leftOut = true);
  69621. thisRightOut && (rightOut = true);
  69622. }
  69623. // If both left out and right out, do not filter.
  69624. return hasValue && leftOut && rightOut;
  69625. });
  69626. }
  69627. else {
  69628. each$22(dataDims, function (dim) {
  69629. if (filterMode === 'empty') {
  69630. seriesModel.setData(
  69631. seriesData.map(dim, function (value) {
  69632. return !isInWindow(value) ? NaN : value;
  69633. })
  69634. );
  69635. }
  69636. else {
  69637. var range = {};
  69638. range[dim] = valueWindow;
  69639. // console.time('select');
  69640. seriesData.selectRange(range);
  69641. // console.timeEnd('select');
  69642. }
  69643. });
  69644. }
  69645. each$22(dataDims, function (dim) {
  69646. seriesData.setApproximateExtent(valueWindow, dim);
  69647. });
  69648. });
  69649. function isInWindow(value) {
  69650. return value >= valueWindow[0] && value <= valueWindow[1];
  69651. }
  69652. }
  69653. };
  69654. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69655. var dataExtent = [Infinity, -Infinity];
  69656. each$22(seriesModels, function (seriesModel) {
  69657. var seriesData = seriesModel.getData();
  69658. if (seriesData) {
  69659. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  69660. var seriesExtent = seriesData.getApproximateExtent(dim);
  69661. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  69662. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  69663. });
  69664. }
  69665. });
  69666. if (dataExtent[1] < dataExtent[0]) {
  69667. dataExtent = [NaN, NaN];
  69668. }
  69669. // It is important to get "consistent" extent when more then one axes is
  69670. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69671. // when zooming. But it is difficult to know what is "consistent", considering
  69672. // axes have different type or even different meanings (For example, two
  69673. // time axes are used to compare data of the same date in different years).
  69674. // So basically dataZoom just obtains extent by series.data (in category axis
  69675. // extent can be obtained from axis.data).
  69676. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69677. // consistent.
  69678. fixExtentByAxis(axisProxy, dataExtent);
  69679. return dataExtent;
  69680. }
  69681. function fixExtentByAxis(axisProxy, dataExtent) {
  69682. var axisModel = axisProxy.getAxisModel();
  69683. var min = axisModel.getMin(true);
  69684. // For category axis, if min/max/scale are not set, extent is determined
  69685. // by axis.data by default.
  69686. var isCategoryAxis = axisModel.get('type') === 'category';
  69687. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  69688. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  69689. dataExtent[0] = min;
  69690. }
  69691. else if (isCategoryAxis) {
  69692. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  69693. }
  69694. var max = axisModel.getMax(true);
  69695. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  69696. dataExtent[1] = max;
  69697. }
  69698. else if (isCategoryAxis) {
  69699. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  69700. }
  69701. if (!axisModel.get('scale', true)) {
  69702. dataExtent[0] > 0 && (dataExtent[0] = 0);
  69703. dataExtent[1] < 0 && (dataExtent[1] = 0);
  69704. }
  69705. // For value axis, if min/max/scale are not set, we just use the extent obtained
  69706. // by series data, which may be a little different from the extent calculated by
  69707. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69708. // little when zooming. So it will not be fixed until some users require it strongly.
  69709. return dataExtent;
  69710. }
  69711. function setAxisModel(axisProxy, isRestore) {
  69712. var axisModel = axisProxy.getAxisModel();
  69713. var percentWindow = axisProxy._percentWindow;
  69714. var valueWindow = axisProxy._valueWindow;
  69715. if (!percentWindow) {
  69716. return;
  69717. }
  69718. // [0, 500]: arbitrary value, guess axis extent.
  69719. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69720. precision = Math.min(precision, 20);
  69721. // isRestore or isFull
  69722. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  69723. axisModel.setRange(
  69724. useOrigin ? null : +valueWindow[0].toFixed(precision),
  69725. useOrigin ? null : +valueWindow[1].toFixed(precision)
  69726. );
  69727. }
  69728. function setMinMaxSpan(axisProxy) {
  69729. var minMaxSpan = axisProxy._minMaxSpan = {};
  69730. var dataZoomModel = axisProxy._dataZoomModel;
  69731. each$22(['min', 'max'], function (minMax) {
  69732. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  69733. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69734. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69735. if (valueSpan != null) {
  69736. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69737. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  69738. if (valueSpan != null) {
  69739. var dataExtent = axisProxy._dataExtent;
  69740. minMaxSpan[minMax + 'Span'] = linearMap(
  69741. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  69742. );
  69743. }
  69744. }
  69745. });
  69746. }
  69747. /*
  69748. * Licensed to the Apache Software Foundation (ASF) under one
  69749. * or more contributor license agreements. See the NOTICE file
  69750. * distributed with this work for additional information
  69751. * regarding copyright ownership. The ASF licenses this file
  69752. * to you under the Apache License, Version 2.0 (the
  69753. * "License"); you may not use this file except in compliance
  69754. * with the License. You may obtain a copy of the License at
  69755. *
  69756. * http://www.apache.org/licenses/LICENSE-2.0
  69757. *
  69758. * Unless required by applicable law or agreed to in writing,
  69759. * software distributed under the License is distributed on an
  69760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69761. * KIND, either express or implied. See the License for the
  69762. * specific language governing permissions and limitations
  69763. * under the License.
  69764. */
  69765. var each$21 = each$1;
  69766. var eachAxisDim = eachAxisDim$1;
  69767. var DataZoomModel = extendComponentModel({
  69768. type: 'dataZoom',
  69769. dependencies: [
  69770. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  69771. ],
  69772. /**
  69773. * @protected
  69774. */
  69775. defaultOption: {
  69776. zlevel: 0,
  69777. z: 4, // Higher than normal component (z: 2).
  69778. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  69779. xAxisIndex: null, // Default the first horizontal category axis.
  69780. yAxisIndex: null, // Default the first vertical category axis.
  69781. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  69782. // 'filter': data items which are out of window will be removed. This option is
  69783. // applicable when filtering outliers. For each data item, it will be
  69784. // filtered if one of the relevant dimensions is out of the window.
  69785. // 'weakFilter': data items which are out of window will be removed. This option
  69786. // is applicable when filtering outliers. For each data item, it will be
  69787. // filtered only if all of the relevant dimensions are out of the same
  69788. // side of the window.
  69789. // 'empty': data items which are out of window will be set to empty.
  69790. // This option is applicable when user should not neglect
  69791. // that there are some data items out of window.
  69792. // 'none': Do not filter.
  69793. // Taking line chart as an example, line will be broken in
  69794. // the filtered points when filterModel is set to 'empty', but
  69795. // be connected when set to 'filter'.
  69796. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  69797. // default 100. Do not throttle when use null/undefined.
  69798. // If animation === true and animationDurationUpdate > 0,
  69799. // default value is 100, otherwise 20.
  69800. start: 0, // Start percent. 0 ~ 100
  69801. end: 100, // End percent. 0 ~ 100
  69802. startValue: null, // Start value. If startValue specified, start is ignored.
  69803. endValue: null, // End value. If endValue specified, end is ignored.
  69804. minSpan: null, // 0 ~ 100
  69805. maxSpan: null, // 0 ~ 100
  69806. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  69807. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  69808. rangeMode: null // Array, can be 'value' or 'percent'.
  69809. },
  69810. /**
  69811. * @override
  69812. */
  69813. init: function (option, parentModel, ecModel) {
  69814. /**
  69815. * key like x_0, y_1
  69816. * @private
  69817. * @type {Object}
  69818. */
  69819. this._dataIntervalByAxis = {};
  69820. /**
  69821. * @private
  69822. */
  69823. this._dataInfo = {};
  69824. /**
  69825. * key like x_0, y_1
  69826. * @private
  69827. */
  69828. this._axisProxies = {};
  69829. /**
  69830. * @readOnly
  69831. */
  69832. this.textStyleModel;
  69833. /**
  69834. * @private
  69835. */
  69836. this._autoThrottle = true;
  69837. /**
  69838. * 'percent' or 'value'
  69839. * @private
  69840. */
  69841. this._rangePropMode = ['percent', 'percent'];
  69842. var rawOption = retrieveRaw(option);
  69843. this.mergeDefaultAndTheme(option, ecModel);
  69844. this.doInit(rawOption);
  69845. },
  69846. /**
  69847. * @override
  69848. */
  69849. mergeOption: function (newOption) {
  69850. var rawOption = retrieveRaw(newOption);
  69851. //FIX #2591
  69852. merge(this.option, newOption, true);
  69853. this.doInit(rawOption);
  69854. },
  69855. /**
  69856. * @protected
  69857. */
  69858. doInit: function (rawOption) {
  69859. var thisOption = this.option;
  69860. // Disable realtime view update if canvas is not supported.
  69861. if (!env$1.canvasSupported) {
  69862. thisOption.realtime = false;
  69863. }
  69864. this._setDefaultThrottle(rawOption);
  69865. updateRangeUse(this, rawOption);
  69866. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69867. // start/end has higher priority over startValue/endValue if they
  69868. // both set, but we should make chart.setOption({endValue: 1000})
  69869. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69870. if (this._rangePropMode[index] === 'value') {
  69871. thisOption[names[0]] = null;
  69872. }
  69873. // Otherwise do nothing and use the merge result.
  69874. }, this);
  69875. this.textStyleModel = this.getModel('textStyle');
  69876. this._resetTarget();
  69877. this._giveAxisProxies();
  69878. },
  69879. /**
  69880. * @private
  69881. */
  69882. _giveAxisProxies: function () {
  69883. var axisProxies = this._axisProxies;
  69884. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  69885. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  69886. // If exists, share axisProxy with other dataZoomModels.
  69887. var axisProxy = axisModel.__dzAxisProxy || (
  69888. // Use the first dataZoomModel as the main model of axisProxy.
  69889. axisModel.__dzAxisProxy = new AxisProxy(
  69890. dimNames.name, axisIndex, this, ecModel
  69891. )
  69892. );
  69893. // FIXME
  69894. // dispose __dzAxisProxy
  69895. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  69896. }, this);
  69897. },
  69898. /**
  69899. * @private
  69900. */
  69901. _resetTarget: function () {
  69902. var thisOption = this.option;
  69903. var autoMode = this._judgeAutoMode();
  69904. eachAxisDim(function (dimNames) {
  69905. var axisIndexName = dimNames.axisIndex;
  69906. thisOption[axisIndexName] = normalizeToArray(
  69907. thisOption[axisIndexName]
  69908. );
  69909. }, this);
  69910. if (autoMode === 'axisIndex') {
  69911. this._autoSetAxisIndex();
  69912. }
  69913. else if (autoMode === 'orient') {
  69914. this._autoSetOrient();
  69915. }
  69916. },
  69917. /**
  69918. * @private
  69919. */
  69920. _judgeAutoMode: function () {
  69921. // Auto set only works for setOption at the first time.
  69922. // The following is user's reponsibility. So using merged
  69923. // option is OK.
  69924. var thisOption = this.option;
  69925. var hasIndexSpecified = false;
  69926. eachAxisDim(function (dimNames) {
  69927. // When user set axisIndex as a empty array, we think that user specify axisIndex
  69928. // but do not want use auto mode. Because empty array may be encountered when
  69929. // some error occured.
  69930. if (thisOption[dimNames.axisIndex] != null) {
  69931. hasIndexSpecified = true;
  69932. }
  69933. }, this);
  69934. var orient = thisOption.orient;
  69935. if (orient == null && hasIndexSpecified) {
  69936. return 'orient';
  69937. }
  69938. else if (!hasIndexSpecified) {
  69939. if (orient == null) {
  69940. thisOption.orient = 'horizontal';
  69941. }
  69942. return 'axisIndex';
  69943. }
  69944. },
  69945. /**
  69946. * @private
  69947. */
  69948. _autoSetAxisIndex: function () {
  69949. var autoAxisIndex = true;
  69950. var orient = this.get('orient', true);
  69951. var thisOption = this.option;
  69952. var dependentModels = this.dependentModels;
  69953. if (autoAxisIndex) {
  69954. // Find axis that parallel to dataZoom as default.
  69955. var dimName = orient === 'vertical' ? 'y' : 'x';
  69956. if (dependentModels[dimName + 'Axis'].length) {
  69957. thisOption[dimName + 'AxisIndex'] = [0];
  69958. autoAxisIndex = false;
  69959. }
  69960. else {
  69961. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  69962. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  69963. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  69964. autoAxisIndex = false;
  69965. }
  69966. });
  69967. }
  69968. }
  69969. if (autoAxisIndex) {
  69970. // Find the first category axis as default. (consider polar)
  69971. eachAxisDim(function (dimNames) {
  69972. if (!autoAxisIndex) {
  69973. return;
  69974. }
  69975. var axisIndices = [];
  69976. var axisModels = this.dependentModels[dimNames.axis];
  69977. if (axisModels.length && !axisIndices.length) {
  69978. for (var i = 0, len = axisModels.length; i < len; i++) {
  69979. if (axisModels[i].get('type') === 'category') {
  69980. axisIndices.push(i);
  69981. }
  69982. }
  69983. }
  69984. thisOption[dimNames.axisIndex] = axisIndices;
  69985. if (axisIndices.length) {
  69986. autoAxisIndex = false;
  69987. }
  69988. }, this);
  69989. }
  69990. if (autoAxisIndex) {
  69991. // FIXME
  69992. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  69993. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  69994. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  69995. // dataZoom component auto adopts series that reference to
  69996. // both xAxis and yAxis which type is 'value'.
  69997. this.ecModel.eachSeries(function (seriesModel) {
  69998. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  69999. eachAxisDim(function (dimNames) {
  70000. var axisIndices = thisOption[dimNames.axisIndex];
  70001. var axisIndex = seriesModel.get(dimNames.axisIndex);
  70002. var axisId = seriesModel.get(dimNames.axisId);
  70003. var axisModel = seriesModel.ecModel.queryComponents({
  70004. mainType: dimNames.axis,
  70005. index: axisIndex,
  70006. id: axisId
  70007. })[0];
  70008. if (__DEV__) {
  70009. if (!axisModel) {
  70010. throw new Error(
  70011. dimNames.axis + ' "' + retrieve(
  70012. axisIndex,
  70013. axisId,
  70014. 0
  70015. ) + '" not found'
  70016. );
  70017. }
  70018. }
  70019. axisIndex = axisModel.componentIndex;
  70020. if (indexOf(axisIndices, axisIndex) < 0) {
  70021. axisIndices.push(axisIndex);
  70022. }
  70023. });
  70024. }
  70025. }, this);
  70026. }
  70027. },
  70028. /**
  70029. * @private
  70030. */
  70031. _autoSetOrient: function () {
  70032. var dim;
  70033. // Find the first axis
  70034. this.eachTargetAxis(function (dimNames) {
  70035. !dim && (dim = dimNames.name);
  70036. }, this);
  70037. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  70038. },
  70039. /**
  70040. * @private
  70041. */
  70042. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  70043. // FIXME
  70044. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  70045. // 例如series.type === scatter时。
  70046. var is = true;
  70047. eachAxisDim(function (dimNames) {
  70048. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  70049. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  70050. if (!axisModel || axisModel.get('type') !== axisType) {
  70051. is = false;
  70052. }
  70053. }, this);
  70054. return is;
  70055. },
  70056. /**
  70057. * @private
  70058. */
  70059. _setDefaultThrottle: function (rawOption) {
  70060. // When first time user set throttle, auto throttle ends.
  70061. if (rawOption.hasOwnProperty('throttle')) {
  70062. this._autoThrottle = false;
  70063. }
  70064. if (this._autoThrottle) {
  70065. var globalOption = this.ecModel.option;
  70066. this.option.throttle
  70067. = (globalOption.animation && globalOption.animationDurationUpdate > 0)
  70068. ? 100 : 20;
  70069. }
  70070. },
  70071. /**
  70072. * @public
  70073. */
  70074. getFirstTargetAxisModel: function () {
  70075. var firstAxisModel;
  70076. eachAxisDim(function (dimNames) {
  70077. if (firstAxisModel == null) {
  70078. var indices = this.get(dimNames.axisIndex);
  70079. if (indices.length) {
  70080. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  70081. }
  70082. }
  70083. }, this);
  70084. return firstAxisModel;
  70085. },
  70086. /**
  70087. * @public
  70088. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  70089. */
  70090. eachTargetAxis: function (callback, context) {
  70091. var ecModel = this.ecModel;
  70092. eachAxisDim(function (dimNames) {
  70093. each$21(
  70094. this.get(dimNames.axisIndex),
  70095. function (axisIndex) {
  70096. callback.call(context, dimNames, axisIndex, this, ecModel);
  70097. },
  70098. this
  70099. );
  70100. }, this);
  70101. },
  70102. /**
  70103. * @param {string} dimName
  70104. * @param {number} axisIndex
  70105. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  70106. */
  70107. getAxisProxy: function (dimName, axisIndex) {
  70108. return this._axisProxies[dimName + '_' + axisIndex];
  70109. },
  70110. /**
  70111. * @param {string} dimName
  70112. * @param {number} axisIndex
  70113. * @return {module:echarts/model/Model} If not found, return null/undefined.
  70114. */
  70115. getAxisModel: function (dimName, axisIndex) {
  70116. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  70117. return axisProxy && axisProxy.getAxisModel();
  70118. },
  70119. /**
  70120. * If not specified, set to undefined.
  70121. *
  70122. * @public
  70123. * @param {Object} opt
  70124. * @param {number} [opt.start]
  70125. * @param {number} [opt.end]
  70126. * @param {number} [opt.startValue]
  70127. * @param {number} [opt.endValue]
  70128. * @param {boolean} [ignoreUpdateRangeUsg=false]
  70129. */
  70130. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  70131. var option = this.option;
  70132. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  70133. // If only one of 'start' and 'startValue' is not null/undefined, the other
  70134. // should be cleared, which enable clear the option.
  70135. // If both of them are not set, keep option with the original value, which
  70136. // enable use only set start but not set end when calling `dispatchAction`.
  70137. // The same as 'end' and 'endValue'.
  70138. if (opt[names[0]] != null || opt[names[1]] != null) {
  70139. option[names[0]] = opt[names[0]];
  70140. option[names[1]] = opt[names[1]];
  70141. }
  70142. }, this);
  70143. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  70144. },
  70145. /**
  70146. * @public
  70147. * @return {Array.<number>} [startPercent, endPercent]
  70148. */
  70149. getPercentRange: function () {
  70150. var axisProxy = this.findRepresentativeAxisProxy();
  70151. if (axisProxy) {
  70152. return axisProxy.getDataPercentWindow();
  70153. }
  70154. },
  70155. /**
  70156. * @public
  70157. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  70158. *
  70159. * @param {string} [axisDimName]
  70160. * @param {number} [axisIndex]
  70161. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  70162. */
  70163. getValueRange: function (axisDimName, axisIndex) {
  70164. if (axisDimName == null && axisIndex == null) {
  70165. var axisProxy = this.findRepresentativeAxisProxy();
  70166. if (axisProxy) {
  70167. return axisProxy.getDataValueWindow();
  70168. }
  70169. }
  70170. else {
  70171. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  70172. }
  70173. },
  70174. /**
  70175. * @public
  70176. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  70177. * corresponding to the axisModel
  70178. * @return {module:echarts/component/dataZoom/AxisProxy}
  70179. */
  70180. findRepresentativeAxisProxy: function (axisModel) {
  70181. if (axisModel) {
  70182. return axisModel.__dzAxisProxy;
  70183. }
  70184. // Find the first hosted axisProxy
  70185. var axisProxies = this._axisProxies;
  70186. for (var key in axisProxies) {
  70187. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  70188. return axisProxies[key];
  70189. }
  70190. }
  70191. // If no hosted axis find not hosted axisProxy.
  70192. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  70193. // and the option.start or option.end settings are different. The percentRange
  70194. // should follow axisProxy.
  70195. // (We encounter this problem in toolbox data zoom.)
  70196. for (var key in axisProxies) {
  70197. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  70198. return axisProxies[key];
  70199. }
  70200. }
  70201. },
  70202. /**
  70203. * @return {Array.<string>}
  70204. */
  70205. getRangePropMode: function () {
  70206. return this._rangePropMode.slice();
  70207. }
  70208. });
  70209. function retrieveRaw(option) {
  70210. var ret = {};
  70211. each$21(
  70212. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  70213. function (name) {
  70214. option.hasOwnProperty(name) && (ret[name] = option[name]);
  70215. }
  70216. );
  70217. return ret;
  70218. }
  70219. function updateRangeUse(dataZoomModel, rawOption) {
  70220. var rangePropMode = dataZoomModel._rangePropMode;
  70221. var rangeModeInOption = dataZoomModel.get('rangeMode');
  70222. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70223. var percentSpecified = rawOption[names[0]] != null;
  70224. var valueSpecified = rawOption[names[1]] != null;
  70225. if (percentSpecified && !valueSpecified) {
  70226. rangePropMode[index] = 'percent';
  70227. }
  70228. else if (!percentSpecified && valueSpecified) {
  70229. rangePropMode[index] = 'value';
  70230. }
  70231. else if (rangeModeInOption) {
  70232. rangePropMode[index] = rangeModeInOption[index];
  70233. }
  70234. else if (percentSpecified) { // percentSpecified && valueSpecified
  70235. rangePropMode[index] = 'percent';
  70236. }
  70237. // else remain its original setting.
  70238. });
  70239. }
  70240. /*
  70241. * Licensed to the Apache Software Foundation (ASF) under one
  70242. * or more contributor license agreements. See the NOTICE file
  70243. * distributed with this work for additional information
  70244. * regarding copyright ownership. The ASF licenses this file
  70245. * to you under the Apache License, Version 2.0 (the
  70246. * "License"); you may not use this file except in compliance
  70247. * with the License. You may obtain a copy of the License at
  70248. *
  70249. * http://www.apache.org/licenses/LICENSE-2.0
  70250. *
  70251. * Unless required by applicable law or agreed to in writing,
  70252. * software distributed under the License is distributed on an
  70253. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70254. * KIND, either express or implied. See the License for the
  70255. * specific language governing permissions and limitations
  70256. * under the License.
  70257. */
  70258. var DataZoomView = Component.extend({
  70259. type: 'dataZoom',
  70260. render: function (dataZoomModel, ecModel, api, payload) {
  70261. this.dataZoomModel = dataZoomModel;
  70262. this.ecModel = ecModel;
  70263. this.api = api;
  70264. },
  70265. /**
  70266. * Find the first target coordinate system.
  70267. *
  70268. * @protected
  70269. * @return {Object} {
  70270. * grid: [
  70271. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  70272. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  70273. * ...
  70274. * ], // cartesians must not be null/undefined.
  70275. * polar: [
  70276. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  70277. * ...
  70278. * ], // polars must not be null/undefined.
  70279. * singleAxis: [
  70280. * {model: coord0, axisModels: [], coordIndex: 0}
  70281. * ]
  70282. */
  70283. getTargetCoordInfo: function () {
  70284. var dataZoomModel = this.dataZoomModel;
  70285. var ecModel = this.ecModel;
  70286. var coordSysLists = {};
  70287. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70288. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  70289. if (axisModel) {
  70290. var coordModel = axisModel.getCoordSysModel();
  70291. coordModel && save(
  70292. coordModel,
  70293. axisModel,
  70294. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  70295. coordModel.componentIndex
  70296. );
  70297. }
  70298. }, this);
  70299. function save(coordModel, axisModel, store, coordIndex) {
  70300. var item;
  70301. for (var i = 0; i < store.length; i++) {
  70302. if (store[i].model === coordModel) {
  70303. item = store[i];
  70304. break;
  70305. }
  70306. }
  70307. if (!item) {
  70308. store.push(item = {
  70309. model: coordModel, axisModels: [], coordIndex: coordIndex
  70310. });
  70311. }
  70312. item.axisModels.push(axisModel);
  70313. }
  70314. return coordSysLists;
  70315. }
  70316. });
  70317. /*
  70318. * Licensed to the Apache Software Foundation (ASF) under one
  70319. * or more contributor license agreements. See the NOTICE file
  70320. * distributed with this work for additional information
  70321. * regarding copyright ownership. The ASF licenses this file
  70322. * to you under the Apache License, Version 2.0 (the
  70323. * "License"); you may not use this file except in compliance
  70324. * with the License. You may obtain a copy of the License at
  70325. *
  70326. * http://www.apache.org/licenses/LICENSE-2.0
  70327. *
  70328. * Unless required by applicable law or agreed to in writing,
  70329. * software distributed under the License is distributed on an
  70330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70331. * KIND, either express or implied. See the License for the
  70332. * specific language governing permissions and limitations
  70333. * under the License.
  70334. */
  70335. var SliderZoomModel = DataZoomModel.extend({
  70336. type: 'dataZoom.slider',
  70337. layoutMode: 'box',
  70338. /**
  70339. * @protected
  70340. */
  70341. defaultOption: {
  70342. show: true,
  70343. // ph => placeholder. Using placehoder here because
  70344. // deault value can only be drived in view stage.
  70345. right: 'ph', // Default align to grid rect.
  70346. top: 'ph', // Default align to grid rect.
  70347. width: 'ph', // Default align to grid rect.
  70348. height: 'ph', // Default align to grid rect.
  70349. left: null, // Default align to grid rect.
  70350. bottom: null, // Default align to grid rect.
  70351. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  70352. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  70353. // highest priority, remain for compatibility of
  70354. // previous version, but not recommended any more.
  70355. dataBackground: {
  70356. lineStyle: {
  70357. color: '#2f4554',
  70358. width: 0.5,
  70359. opacity: 0.3
  70360. },
  70361. areaStyle: {
  70362. color: 'rgba(47,69,84,0.3)',
  70363. opacity: 0.3
  70364. }
  70365. },
  70366. borderColor: '#ddd', // border color of the box. For compatibility,
  70367. // if dataBackgroundColor is set, borderColor
  70368. // is ignored.
  70369. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  70370. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  70371. // 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',
  70372. /* eslint-disable */
  70373. 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',
  70374. /* eslint-enable */
  70375. // Percent of the slider height
  70376. handleSize: '100%',
  70377. handleStyle: {
  70378. color: '#a7b7cc'
  70379. },
  70380. labelPrecision: null,
  70381. labelFormatter: null,
  70382. showDetail: true,
  70383. showDataShadow: 'auto', // Default auto decision.
  70384. realtime: true,
  70385. zoomLock: false, // Whether disable zoom.
  70386. textStyle: {
  70387. color: '#333'
  70388. }
  70389. }
  70390. });
  70391. /*
  70392. * Licensed to the Apache Software Foundation (ASF) under one
  70393. * or more contributor license agreements. See the NOTICE file
  70394. * distributed with this work for additional information
  70395. * regarding copyright ownership. The ASF licenses this file
  70396. * to you under the Apache License, Version 2.0 (the
  70397. * "License"); you may not use this file except in compliance
  70398. * with the License. You may obtain a copy of the License at
  70399. *
  70400. * http://www.apache.org/licenses/LICENSE-2.0
  70401. *
  70402. * Unless required by applicable law or agreed to in writing,
  70403. * software distributed under the License is distributed on an
  70404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70405. * KIND, either express or implied. See the License for the
  70406. * specific language governing permissions and limitations
  70407. * under the License.
  70408. */
  70409. var Rect$2 = Rect;
  70410. var linearMap$1 = linearMap;
  70411. var asc$2 = asc;
  70412. var bind$4 = bind;
  70413. var each$23 = each$1;
  70414. // Constants
  70415. var DEFAULT_LOCATION_EDGE_GAP = 7;
  70416. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  70417. var DEFAULT_FILLER_SIZE = 30;
  70418. var HORIZONTAL = 'horizontal';
  70419. var VERTICAL = 'vertical';
  70420. var LABEL_GAP = 5;
  70421. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  70422. var SliderZoomView = DataZoomView.extend({
  70423. type: 'dataZoom.slider',
  70424. init: function (ecModel, api) {
  70425. /**
  70426. * @private
  70427. * @type {Object}
  70428. */
  70429. this._displayables = {};
  70430. /**
  70431. * @private
  70432. * @type {string}
  70433. */
  70434. this._orient;
  70435. /**
  70436. * [0, 100]
  70437. * @private
  70438. */
  70439. this._range;
  70440. /**
  70441. * [coord of the first handle, coord of the second handle]
  70442. * @private
  70443. */
  70444. this._handleEnds;
  70445. /**
  70446. * [length, thick]
  70447. * @private
  70448. * @type {Array.<number>}
  70449. */
  70450. this._size;
  70451. /**
  70452. * @private
  70453. * @type {number}
  70454. */
  70455. this._handleWidth;
  70456. /**
  70457. * @private
  70458. * @type {number}
  70459. */
  70460. this._handleHeight;
  70461. /**
  70462. * @private
  70463. */
  70464. this._location;
  70465. /**
  70466. * @private
  70467. */
  70468. this._dragging;
  70469. /**
  70470. * @private
  70471. */
  70472. this._dataShadowInfo;
  70473. this.api = api;
  70474. },
  70475. /**
  70476. * @override
  70477. */
  70478. render: function (dataZoomModel, ecModel, api, payload) {
  70479. SliderZoomView.superApply(this, 'render', arguments);
  70480. createOrUpdate(
  70481. this,
  70482. '_dispatchZoomAction',
  70483. this.dataZoomModel.get('throttle'),
  70484. 'fixRate'
  70485. );
  70486. this._orient = dataZoomModel.get('orient');
  70487. if (this.dataZoomModel.get('show') === false) {
  70488. this.group.removeAll();
  70489. return;
  70490. }
  70491. // Notice: this._resetInterval() should not be executed when payload.type
  70492. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  70493. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  70494. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  70495. this._buildView();
  70496. }
  70497. this._updateView();
  70498. },
  70499. /**
  70500. * @override
  70501. */
  70502. remove: function () {
  70503. SliderZoomView.superApply(this, 'remove', arguments);
  70504. clear(this, '_dispatchZoomAction');
  70505. },
  70506. /**
  70507. * @override
  70508. */
  70509. dispose: function () {
  70510. SliderZoomView.superApply(this, 'dispose', arguments);
  70511. clear(this, '_dispatchZoomAction');
  70512. },
  70513. _buildView: function () {
  70514. var thisGroup = this.group;
  70515. thisGroup.removeAll();
  70516. this._resetLocation();
  70517. this._resetInterval();
  70518. var barGroup = this._displayables.barGroup = new Group();
  70519. this._renderBackground();
  70520. this._renderHandle();
  70521. this._renderDataShadow();
  70522. thisGroup.add(barGroup);
  70523. this._positionGroup();
  70524. },
  70525. /**
  70526. * @private
  70527. */
  70528. _resetLocation: function () {
  70529. var dataZoomModel = this.dataZoomModel;
  70530. var api = this.api;
  70531. // If some of x/y/width/height are not specified,
  70532. // auto-adapt according to target grid.
  70533. var coordRect = this._findCoordRect();
  70534. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  70535. // Default align by coordinate system rect.
  70536. var positionInfo = this._orient === HORIZONTAL
  70537. ? {
  70538. // Why using 'right', because right should be used in vertical,
  70539. // and it is better to be consistent for dealing with position param merge.
  70540. right: ecSize.width - coordRect.x - coordRect.width,
  70541. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  70542. width: coordRect.width,
  70543. height: DEFAULT_FILLER_SIZE
  70544. }
  70545. : { // vertical
  70546. right: DEFAULT_LOCATION_EDGE_GAP,
  70547. top: coordRect.y,
  70548. width: DEFAULT_FILLER_SIZE,
  70549. height: coordRect.height
  70550. };
  70551. // Do not write back to option and replace value 'ph', because
  70552. // the 'ph' value should be recalculated when resize.
  70553. var layoutParams = getLayoutParams(dataZoomModel.option);
  70554. // Replace the placeholder value.
  70555. each$1(['right', 'top', 'width', 'height'], function (name) {
  70556. if (layoutParams[name] === 'ph') {
  70557. layoutParams[name] = positionInfo[name];
  70558. }
  70559. });
  70560. var layoutRect = getLayoutRect(
  70561. layoutParams,
  70562. ecSize,
  70563. dataZoomModel.padding
  70564. );
  70565. this._location = {x: layoutRect.x, y: layoutRect.y};
  70566. this._size = [layoutRect.width, layoutRect.height];
  70567. this._orient === VERTICAL && this._size.reverse();
  70568. },
  70569. /**
  70570. * @private
  70571. */
  70572. _positionGroup: function () {
  70573. var thisGroup = this.group;
  70574. var location = this._location;
  70575. var orient = this._orient;
  70576. // Just use the first axis to determine mapping.
  70577. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  70578. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  70579. var barGroup = this._displayables.barGroup;
  70580. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  70581. // Transform barGroup.
  70582. barGroup.attr(
  70583. (orient === HORIZONTAL && !inverse)
  70584. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  70585. : (orient === HORIZONTAL && inverse)
  70586. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  70587. : (orient === VERTICAL && !inverse)
  70588. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  70589. // Dont use Math.PI, considering shadow direction.
  70590. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  70591. );
  70592. // Position barGroup
  70593. var rect = thisGroup.getBoundingRect([barGroup]);
  70594. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  70595. },
  70596. /**
  70597. * @private
  70598. */
  70599. _getViewExtent: function () {
  70600. return [0, this._size[0]];
  70601. },
  70602. _renderBackground: function () {
  70603. var dataZoomModel = this.dataZoomModel;
  70604. var size = this._size;
  70605. var barGroup = this._displayables.barGroup;
  70606. barGroup.add(new Rect$2({
  70607. silent: true,
  70608. shape: {
  70609. x: 0, y: 0, width: size[0], height: size[1]
  70610. },
  70611. style: {
  70612. fill: dataZoomModel.get('backgroundColor')
  70613. },
  70614. z2: -40
  70615. }));
  70616. // Click panel, over shadow, below handles.
  70617. barGroup.add(new Rect$2({
  70618. shape: {
  70619. x: 0, y: 0, width: size[0], height: size[1]
  70620. },
  70621. style: {
  70622. fill: 'transparent'
  70623. },
  70624. z2: 0,
  70625. onclick: bind(this._onClickPanelClick, this)
  70626. }));
  70627. },
  70628. _renderDataShadow: function () {
  70629. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  70630. if (!info) {
  70631. return;
  70632. }
  70633. var size = this._size;
  70634. var seriesModel = info.series;
  70635. var data = seriesModel.getRawData();
  70636. var otherDim = seriesModel.getShadowDim
  70637. ? seriesModel.getShadowDim() // @see candlestick
  70638. : info.otherDim;
  70639. if (otherDim == null) {
  70640. return;
  70641. }
  70642. var otherDataExtent = data.getDataExtent(otherDim);
  70643. // Nice extent.
  70644. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  70645. otherDataExtent = [
  70646. otherDataExtent[0] - otherOffset,
  70647. otherDataExtent[1] + otherOffset
  70648. ];
  70649. var otherShadowExtent = [0, size[1]];
  70650. var thisShadowExtent = [0, size[0]];
  70651. var areaPoints = [[size[0], 0], [0, 0]];
  70652. var linePoints = [];
  70653. var step = thisShadowExtent[1] / (data.count() - 1);
  70654. var thisCoord = 0;
  70655. // Optimize for large data shadow
  70656. var stride = Math.round(data.count() / size[0]);
  70657. var lastIsEmpty;
  70658. data.each([otherDim], function (value, index) {
  70659. if (stride > 0 && (index % stride)) {
  70660. thisCoord += step;
  70661. return;
  70662. }
  70663. // FIXME
  70664. // Should consider axis.min/axis.max when drawing dataShadow.
  70665. // FIXME
  70666. // 应该使用统一的空判断?还是在list里进行空判断?
  70667. var isEmpty = value == null || isNaN(value) || value === '';
  70668. // See #4235.
  70669. var otherCoord = isEmpty
  70670. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  70671. // Attempt to draw data shadow precisely when there are empty value.
  70672. if (isEmpty && !lastIsEmpty && index) {
  70673. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  70674. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  70675. }
  70676. else if (!isEmpty && lastIsEmpty) {
  70677. areaPoints.push([thisCoord, 0]);
  70678. linePoints.push([thisCoord, 0]);
  70679. }
  70680. areaPoints.push([thisCoord, otherCoord]);
  70681. linePoints.push([thisCoord, otherCoord]);
  70682. thisCoord += step;
  70683. lastIsEmpty = isEmpty;
  70684. });
  70685. var dataZoomModel = this.dataZoomModel;
  70686. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  70687. this._displayables.barGroup.add(new Polygon({
  70688. shape: {points: areaPoints},
  70689. style: defaults(
  70690. {fill: dataZoomModel.get('dataBackgroundColor')},
  70691. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  70692. ),
  70693. silent: true,
  70694. z2: -20
  70695. }));
  70696. this._displayables.barGroup.add(new Polyline({
  70697. shape: {points: linePoints},
  70698. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  70699. silent: true,
  70700. z2: -19
  70701. }));
  70702. },
  70703. _prepareDataShadowInfo: function () {
  70704. var dataZoomModel = this.dataZoomModel;
  70705. var showDataShadow = dataZoomModel.get('showDataShadow');
  70706. if (showDataShadow === false) {
  70707. return;
  70708. }
  70709. // Find a representative series.
  70710. var result;
  70711. var ecModel = this.ecModel;
  70712. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70713. var seriesModels = dataZoomModel
  70714. .getAxisProxy(dimNames.name, axisIndex)
  70715. .getTargetSeriesModels();
  70716. each$1(seriesModels, function (seriesModel) {
  70717. if (result) {
  70718. return;
  70719. }
  70720. if (showDataShadow !== true && indexOf(
  70721. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  70722. ) < 0
  70723. ) {
  70724. return;
  70725. }
  70726. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  70727. var otherDim = getOtherDim(dimNames.name);
  70728. var otherAxisInverse;
  70729. var coordSys = seriesModel.coordinateSystem;
  70730. if (otherDim != null && coordSys.getOtherAxis) {
  70731. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  70732. }
  70733. otherDim = seriesModel.getData().mapDimension(otherDim);
  70734. result = {
  70735. thisAxis: thisAxis,
  70736. series: seriesModel,
  70737. thisDim: dimNames.name,
  70738. otherDim: otherDim,
  70739. otherAxisInverse: otherAxisInverse
  70740. };
  70741. }, this);
  70742. }, this);
  70743. return result;
  70744. },
  70745. _renderHandle: function () {
  70746. var displaybles = this._displayables;
  70747. var handles = displaybles.handles = [];
  70748. var handleLabels = displaybles.handleLabels = [];
  70749. var barGroup = this._displayables.barGroup;
  70750. var size = this._size;
  70751. var dataZoomModel = this.dataZoomModel;
  70752. barGroup.add(displaybles.filler = new Rect$2({
  70753. draggable: true,
  70754. cursor: getCursor(this._orient),
  70755. drift: bind$4(this._onDragMove, this, 'all'),
  70756. onmousemove: function (e) {
  70757. // Fot mobile devicem, prevent screen slider on the button.
  70758. stop(e.event);
  70759. },
  70760. ondragstart: bind$4(this._showDataInfo, this, true),
  70761. ondragend: bind$4(this._onDragEnd, this),
  70762. onmouseover: bind$4(this._showDataInfo, this, true),
  70763. onmouseout: bind$4(this._showDataInfo, this, false),
  70764. style: {
  70765. fill: dataZoomModel.get('fillerColor'),
  70766. textPosition: 'inside'
  70767. }
  70768. }));
  70769. // Frame border.
  70770. barGroup.add(new Rect$2(subPixelOptimizeRect({
  70771. silent: true,
  70772. shape: {
  70773. x: 0,
  70774. y: 0,
  70775. width: size[0],
  70776. height: size[1]
  70777. },
  70778. style: {
  70779. stroke: dataZoomModel.get('dataBackgroundColor')
  70780. || dataZoomModel.get('borderColor'),
  70781. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  70782. fill: 'rgba(0,0,0,0)'
  70783. }
  70784. })));
  70785. each$23([0, 1], function (handleIndex) {
  70786. var path = createIcon(
  70787. dataZoomModel.get('handleIcon'),
  70788. {
  70789. cursor: getCursor(this._orient),
  70790. draggable: true,
  70791. drift: bind$4(this._onDragMove, this, handleIndex),
  70792. onmousemove: function (e) {
  70793. // Fot mobile devicem, prevent screen slider on the button.
  70794. stop(e.event);
  70795. },
  70796. ondragend: bind$4(this._onDragEnd, this),
  70797. onmouseover: bind$4(this._showDataInfo, this, true),
  70798. onmouseout: bind$4(this._showDataInfo, this, false)
  70799. },
  70800. {x: -1, y: 0, width: 2, height: 2}
  70801. );
  70802. var bRect = path.getBoundingRect();
  70803. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  70804. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  70805. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  70806. var handleColor = dataZoomModel.get('handleColor');
  70807. // Compatitable with previous version
  70808. if (handleColor != null) {
  70809. path.style.fill = handleColor;
  70810. }
  70811. barGroup.add(handles[handleIndex] = path);
  70812. var textStyleModel = dataZoomModel.textStyleModel;
  70813. this.group.add(
  70814. handleLabels[handleIndex] = new Text({
  70815. silent: true,
  70816. invisible: true,
  70817. style: {
  70818. x: 0, y: 0, text: '',
  70819. textVerticalAlign: 'middle',
  70820. textAlign: 'center',
  70821. textFill: textStyleModel.getTextColor(),
  70822. textFont: textStyleModel.getFont()
  70823. },
  70824. z2: 10
  70825. }));
  70826. }, this);
  70827. },
  70828. /**
  70829. * @private
  70830. */
  70831. _resetInterval: function () {
  70832. var range = this._range = this.dataZoomModel.getPercentRange();
  70833. var viewExtent = this._getViewExtent();
  70834. this._handleEnds = [
  70835. linearMap$1(range[0], [0, 100], viewExtent, true),
  70836. linearMap$1(range[1], [0, 100], viewExtent, true)
  70837. ];
  70838. },
  70839. /**
  70840. * @private
  70841. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  70842. * @param {number} delta
  70843. * @return {boolean} changed
  70844. */
  70845. _updateInterval: function (handleIndex, delta) {
  70846. var dataZoomModel = this.dataZoomModel;
  70847. var handleEnds = this._handleEnds;
  70848. var viewExtend = this._getViewExtent();
  70849. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  70850. var percentExtent = [0, 100];
  70851. sliderMove(
  70852. delta,
  70853. handleEnds,
  70854. viewExtend,
  70855. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  70856. minMaxSpan.minSpan != null
  70857. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  70858. minMaxSpan.maxSpan != null
  70859. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  70860. );
  70861. var lastRange = this._range;
  70862. var range = this._range = asc$2([
  70863. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  70864. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  70865. ]);
  70866. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  70867. },
  70868. /**
  70869. * @private
  70870. */
  70871. _updateView: function (nonRealtime) {
  70872. var displaybles = this._displayables;
  70873. var handleEnds = this._handleEnds;
  70874. var handleInterval = asc$2(handleEnds.slice());
  70875. var size = this._size;
  70876. each$23([0, 1], function (handleIndex) {
  70877. // Handles
  70878. var handle = displaybles.handles[handleIndex];
  70879. var handleHeight = this._handleHeight;
  70880. handle.attr({
  70881. scale: [handleHeight / 2, handleHeight / 2],
  70882. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  70883. });
  70884. }, this);
  70885. // Filler
  70886. displaybles.filler.setShape({
  70887. x: handleInterval[0],
  70888. y: 0,
  70889. width: handleInterval[1] - handleInterval[0],
  70890. height: size[1]
  70891. });
  70892. this._updateDataInfo(nonRealtime);
  70893. },
  70894. /**
  70895. * @private
  70896. */
  70897. _updateDataInfo: function (nonRealtime) {
  70898. var dataZoomModel = this.dataZoomModel;
  70899. var displaybles = this._displayables;
  70900. var handleLabels = displaybles.handleLabels;
  70901. var orient = this._orient;
  70902. var labelTexts = ['', ''];
  70903. // FIXME
  70904. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  70905. if (dataZoomModel.get('showDetail')) {
  70906. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  70907. if (axisProxy) {
  70908. var axis = axisProxy.getAxisModel().axis;
  70909. var range = this._range;
  70910. var dataInterval = nonRealtime
  70911. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  70912. ? axisProxy.calculateDataWindow({
  70913. start: range[0], end: range[1]
  70914. }).valueWindow
  70915. : axisProxy.getDataValueWindow();
  70916. labelTexts = [
  70917. this._formatLabel(dataInterval[0], axis),
  70918. this._formatLabel(dataInterval[1], axis)
  70919. ];
  70920. }
  70921. }
  70922. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  70923. setLabel.call(this, 0);
  70924. setLabel.call(this, 1);
  70925. function setLabel(handleIndex) {
  70926. // Label
  70927. // Text should not transform by barGroup.
  70928. // Ignore handlers transform
  70929. var barTransform = getTransform(
  70930. displaybles.handles[handleIndex].parent, this.group
  70931. );
  70932. var direction = transformDirection(
  70933. handleIndex === 0 ? 'right' : 'left', barTransform
  70934. );
  70935. var offset = this._handleWidth / 2 + LABEL_GAP;
  70936. var textPoint = applyTransform$1(
  70937. [
  70938. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  70939. this._size[1] / 2
  70940. ],
  70941. barTransform
  70942. );
  70943. handleLabels[handleIndex].setStyle({
  70944. x: textPoint[0],
  70945. y: textPoint[1],
  70946. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  70947. textAlign: orient === HORIZONTAL ? direction : 'center',
  70948. text: labelTexts[handleIndex]
  70949. });
  70950. }
  70951. },
  70952. /**
  70953. * @private
  70954. */
  70955. _formatLabel: function (value, axis) {
  70956. var dataZoomModel = this.dataZoomModel;
  70957. var labelFormatter = dataZoomModel.get('labelFormatter');
  70958. var labelPrecision = dataZoomModel.get('labelPrecision');
  70959. if (labelPrecision == null || labelPrecision === 'auto') {
  70960. labelPrecision = axis.getPixelPrecision();
  70961. }
  70962. var valueStr = (value == null || isNaN(value))
  70963. ? ''
  70964. // FIXME Glue code
  70965. : (axis.type === 'category' || axis.type === 'time')
  70966. ? axis.scale.getLabel(Math.round(value))
  70967. // param of toFixed should less then 20.
  70968. : value.toFixed(Math.min(labelPrecision, 20));
  70969. return isFunction$1(labelFormatter)
  70970. ? labelFormatter(value, valueStr)
  70971. : isString(labelFormatter)
  70972. ? labelFormatter.replace('{value}', valueStr)
  70973. : valueStr;
  70974. },
  70975. /**
  70976. * @private
  70977. * @param {boolean} showOrHide true: show, false: hide
  70978. */
  70979. _showDataInfo: function (showOrHide) {
  70980. // Always show when drgging.
  70981. showOrHide = this._dragging || showOrHide;
  70982. var handleLabels = this._displayables.handleLabels;
  70983. handleLabels[0].attr('invisible', !showOrHide);
  70984. handleLabels[1].attr('invisible', !showOrHide);
  70985. },
  70986. _onDragMove: function (handleIndex, dx, dy) {
  70987. this._dragging = true;
  70988. // Transform dx, dy to bar coordination.
  70989. var barTransform = this._displayables.barGroup.getLocalTransform();
  70990. var vertex = applyTransform$1([dx, dy], barTransform, true);
  70991. var changed = this._updateInterval(handleIndex, vertex[0]);
  70992. var realtime = this.dataZoomModel.get('realtime');
  70993. this._updateView(!realtime);
  70994. // Avoid dispatch dataZoom repeatly but range not changed,
  70995. // which cause bad visual effect when progressive enabled.
  70996. changed && realtime && this._dispatchZoomAction();
  70997. },
  70998. _onDragEnd: function () {
  70999. this._dragging = false;
  71000. this._showDataInfo(false);
  71001. // While in realtime mode and stream mode, dispatch action when
  71002. // drag end will cause the whole view rerender, which is unnecessary.
  71003. var realtime = this.dataZoomModel.get('realtime');
  71004. !realtime && this._dispatchZoomAction();
  71005. },
  71006. _onClickPanelClick: function (e) {
  71007. var size = this._size;
  71008. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  71009. if (localPoint[0] < 0 || localPoint[0] > size[0]
  71010. || localPoint[1] < 0 || localPoint[1] > size[1]
  71011. ) {
  71012. return;
  71013. }
  71014. var handleEnds = this._handleEnds;
  71015. var center = (handleEnds[0] + handleEnds[1]) / 2;
  71016. var changed = this._updateInterval('all', localPoint[0] - center);
  71017. this._updateView();
  71018. changed && this._dispatchZoomAction();
  71019. },
  71020. /**
  71021. * This action will be throttled.
  71022. * @private
  71023. */
  71024. _dispatchZoomAction: function () {
  71025. var range = this._range;
  71026. this.api.dispatchAction({
  71027. type: 'dataZoom',
  71028. from: this.uid,
  71029. dataZoomId: this.dataZoomModel.id,
  71030. start: range[0],
  71031. end: range[1]
  71032. });
  71033. },
  71034. /**
  71035. * @private
  71036. */
  71037. _findCoordRect: function () {
  71038. // Find the grid coresponding to the first axis referred by dataZoom.
  71039. var rect;
  71040. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  71041. if (!rect && coordInfoList.length) {
  71042. var coordSys = coordInfoList[0].model.coordinateSystem;
  71043. rect = coordSys.getRect && coordSys.getRect();
  71044. }
  71045. });
  71046. if (!rect) {
  71047. var width = this.api.getWidth();
  71048. var height = this.api.getHeight();
  71049. rect = {
  71050. x: width * 0.2,
  71051. y: height * 0.2,
  71052. width: width * 0.6,
  71053. height: height * 0.6
  71054. };
  71055. }
  71056. return rect;
  71057. }
  71058. });
  71059. function getOtherDim(thisDim) {
  71060. // FIXME
  71061. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  71062. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  71063. return map$$1[thisDim];
  71064. }
  71065. function getCursor(orient) {
  71066. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  71067. }
  71068. /*
  71069. * Licensed to the Apache Software Foundation (ASF) under one
  71070. * or more contributor license agreements. See the NOTICE file
  71071. * distributed with this work for additional information
  71072. * regarding copyright ownership. The ASF licenses this file
  71073. * to you under the Apache License, Version 2.0 (the
  71074. * "License"); you may not use this file except in compliance
  71075. * with the License. You may obtain a copy of the License at
  71076. *
  71077. * http://www.apache.org/licenses/LICENSE-2.0
  71078. *
  71079. * Unless required by applicable law or agreed to in writing,
  71080. * software distributed under the License is distributed on an
  71081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71082. * KIND, either express or implied. See the License for the
  71083. * specific language governing permissions and limitations
  71084. * under the License.
  71085. */
  71086. DataZoomModel.extend({
  71087. type: 'dataZoom.inside',
  71088. /**
  71089. * @protected
  71090. */
  71091. defaultOption: {
  71092. disabled: false, // Whether disable this inside zoom.
  71093. zoomLock: false, // Whether disable zoom but only pan.
  71094. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71095. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71096. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71097. preventDefaultMouseMove: true
  71098. }
  71099. });
  71100. /*
  71101. * Licensed to the Apache Software Foundation (ASF) under one
  71102. * or more contributor license agreements. See the NOTICE file
  71103. * distributed with this work for additional information
  71104. * regarding copyright ownership. The ASF licenses this file
  71105. * to you under the Apache License, Version 2.0 (the
  71106. * "License"); you may not use this file except in compliance
  71107. * with the License. You may obtain a copy of the License at
  71108. *
  71109. * http://www.apache.org/licenses/LICENSE-2.0
  71110. *
  71111. * Unless required by applicable law or agreed to in writing,
  71112. * software distributed under the License is distributed on an
  71113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71114. * KIND, either express or implied. See the License for the
  71115. * specific language governing permissions and limitations
  71116. * under the License.
  71117. */
  71118. // Only create one roam controller for each coordinate system.
  71119. // one roam controller might be refered by two inside data zoom
  71120. // components (for example, one for x and one for y). When user
  71121. // pan or zoom, only dispatch one action for those data zoom
  71122. // components.
  71123. var ATTR$1 = '\0_ec_dataZoom_roams';
  71124. /**
  71125. * @public
  71126. * @param {module:echarts/ExtensionAPI} api
  71127. * @param {Object} dataZoomInfo
  71128. * @param {string} dataZoomInfo.coordId
  71129. * @param {Function} dataZoomInfo.containsPoint
  71130. * @param {Array.<string>} dataZoomInfo.allCoordIds
  71131. * @param {string} dataZoomInfo.dataZoomId
  71132. * @param {Object} dataZoomInfo.getRange
  71133. * @param {Function} dataZoomInfo.getRange.pan
  71134. * @param {Function} dataZoomInfo.getRange.zoom
  71135. * @param {Function} dataZoomInfo.getRange.scrollMove
  71136. * @param {boolean} dataZoomInfo.dataZoomModel
  71137. */
  71138. function register$2(api, dataZoomInfo) {
  71139. var store = giveStore(api);
  71140. var theDataZoomId = dataZoomInfo.dataZoomId;
  71141. var theCoordId = dataZoomInfo.coordId;
  71142. // Do clean when a dataZoom changes its target coordnate system.
  71143. // Avoid memory leak, dispose all not-used-registered.
  71144. each$1(store, function (record, coordId) {
  71145. var dataZoomInfos = record.dataZoomInfos;
  71146. if (dataZoomInfos[theDataZoomId]
  71147. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  71148. ) {
  71149. delete dataZoomInfos[theDataZoomId];
  71150. record.count--;
  71151. }
  71152. });
  71153. cleanStore(store);
  71154. var record = store[theCoordId];
  71155. // Create if needed.
  71156. if (!record) {
  71157. record = store[theCoordId] = {
  71158. coordId: theCoordId,
  71159. dataZoomInfos: {},
  71160. count: 0
  71161. };
  71162. record.controller = createController(api, record);
  71163. record.dispatchAction = curry(dispatchAction$1, api);
  71164. }
  71165. // Update reference of dataZoom.
  71166. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  71167. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  71168. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  71169. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  71170. // Consider resize, area should be always updated.
  71171. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  71172. // Update throttle.
  71173. createOrUpdate(
  71174. record,
  71175. 'dispatchAction',
  71176. dataZoomInfo.dataZoomModel.get('throttle', true),
  71177. 'fixRate'
  71178. );
  71179. }
  71180. /**
  71181. * @public
  71182. * @param {module:echarts/ExtensionAPI} api
  71183. * @param {string} dataZoomId
  71184. */
  71185. function unregister$1(api, dataZoomId) {
  71186. var store = giveStore(api);
  71187. each$1(store, function (record) {
  71188. record.controller.dispose();
  71189. var dataZoomInfos = record.dataZoomInfos;
  71190. if (dataZoomInfos[dataZoomId]) {
  71191. delete dataZoomInfos[dataZoomId];
  71192. record.count--;
  71193. }
  71194. });
  71195. cleanStore(store);
  71196. }
  71197. /**
  71198. * @public
  71199. */
  71200. function generateCoordId(coordModel) {
  71201. return coordModel.type + '\0_' + coordModel.id;
  71202. }
  71203. /**
  71204. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  71205. * @type {Array.<Object>}
  71206. */
  71207. function giveStore(api) {
  71208. // Mount store on zrender instance, so that we do not
  71209. // need to worry about dispose.
  71210. var zr = api.getZr();
  71211. return zr[ATTR$1] || (zr[ATTR$1] = {});
  71212. }
  71213. function createController(api, newRecord) {
  71214. var controller = new RoamController(api.getZr());
  71215. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  71216. controller.on(eventName, function (event) {
  71217. var batch = [];
  71218. each$1(newRecord.dataZoomInfos, function (info) {
  71219. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  71220. // moveOnMouseWheel, ...) enabled.
  71221. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  71222. return;
  71223. }
  71224. var method = (info.getRange || {})[eventName];
  71225. var range = method && method(newRecord.controller, event);
  71226. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  71227. dataZoomId: info.dataZoomId,
  71228. start: range[0],
  71229. end: range[1]
  71230. });
  71231. });
  71232. batch.length && newRecord.dispatchAction(batch);
  71233. });
  71234. });
  71235. return controller;
  71236. }
  71237. function cleanStore(store) {
  71238. each$1(store, function (record, coordId) {
  71239. if (!record.count) {
  71240. record.controller.dispose();
  71241. delete store[coordId];
  71242. }
  71243. });
  71244. }
  71245. /**
  71246. * This action will be throttled.
  71247. */
  71248. function dispatchAction$1(api, batch) {
  71249. api.dispatchAction({
  71250. type: 'dataZoom',
  71251. batch: batch
  71252. });
  71253. }
  71254. /**
  71255. * Merge roamController settings when multiple dataZooms share one roamController.
  71256. */
  71257. function mergeControllerParams(dataZoomInfos) {
  71258. var controlType;
  71259. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  71260. // as string, it is probably revert to reserved word by compress tool. See #7411.
  71261. var prefix = 'type_';
  71262. var typePriority = {
  71263. 'type_true': 2,
  71264. 'type_move': 1,
  71265. 'type_false': 0,
  71266. 'type_undefined': -1
  71267. };
  71268. var preventDefaultMouseMove = true;
  71269. each$1(dataZoomInfos, function (dataZoomInfo) {
  71270. var dataZoomModel = dataZoomInfo.dataZoomModel;
  71271. var oneType = dataZoomModel.get('disabled', true)
  71272. ? false
  71273. : dataZoomModel.get('zoomLock', true)
  71274. ? 'move'
  71275. : true;
  71276. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  71277. controlType = oneType;
  71278. }
  71279. // Prevent default move event by default. If one false, do not prevent. Otherwise
  71280. // users may be confused why it does not work when multiple insideZooms exist.
  71281. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  71282. });
  71283. return {
  71284. controlType: controlType,
  71285. opt: {
  71286. // RoamController will enable all of these functionalities,
  71287. // and the final behavior is determined by its event listener
  71288. // provided by each inside zoom.
  71289. zoomOnMouseWheel: true,
  71290. moveOnMouseMove: true,
  71291. moveOnMouseWheel: true,
  71292. preventDefaultMouseMove: !!preventDefaultMouseMove
  71293. }
  71294. };
  71295. }
  71296. /*
  71297. * Licensed to the Apache Software Foundation (ASF) under one
  71298. * or more contributor license agreements. See the NOTICE file
  71299. * distributed with this work for additional information
  71300. * regarding copyright ownership. The ASF licenses this file
  71301. * to you under the Apache License, Version 2.0 (the
  71302. * "License"); you may not use this file except in compliance
  71303. * with the License. You may obtain a copy of the License at
  71304. *
  71305. * http://www.apache.org/licenses/LICENSE-2.0
  71306. *
  71307. * Unless required by applicable law or agreed to in writing,
  71308. * software distributed under the License is distributed on an
  71309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71310. * KIND, either express or implied. See the License for the
  71311. * specific language governing permissions and limitations
  71312. * under the License.
  71313. */
  71314. var bind$5 = bind;
  71315. var InsideZoomView = DataZoomView.extend({
  71316. type: 'dataZoom.inside',
  71317. /**
  71318. * @override
  71319. */
  71320. init: function (ecModel, api) {
  71321. /**
  71322. * 'throttle' is used in this.dispatchAction, so we save range
  71323. * to avoid missing some 'pan' info.
  71324. * @private
  71325. * @type {Array.<number>}
  71326. */
  71327. this._range;
  71328. },
  71329. /**
  71330. * @override
  71331. */
  71332. render: function (dataZoomModel, ecModel, api, payload) {
  71333. InsideZoomView.superApply(this, 'render', arguments);
  71334. // Hance the `throttle` util ensures to preserve command order,
  71335. // here simply updating range all the time will not cause missing
  71336. // any of the the roam change.
  71337. this._range = dataZoomModel.getPercentRange();
  71338. // Reset controllers.
  71339. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  71340. var allCoordIds = map(coordInfoList, function (coordInfo) {
  71341. return generateCoordId(coordInfo.model);
  71342. });
  71343. each$1(coordInfoList, function (coordInfo) {
  71344. var coordModel = coordInfo.model;
  71345. var getRange = {};
  71346. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  71347. getRange[eventName] = bind$5(roamHandlers[eventName], this, coordInfo, coordSysName);
  71348. }, this);
  71349. register$2(
  71350. api,
  71351. {
  71352. coordId: generateCoordId(coordModel),
  71353. allCoordIds: allCoordIds,
  71354. containsPoint: function (e, x, y) {
  71355. return coordModel.coordinateSystem.containPoint([x, y]);
  71356. },
  71357. dataZoomId: dataZoomModel.id,
  71358. dataZoomModel: dataZoomModel,
  71359. getRange: getRange
  71360. }
  71361. );
  71362. }, this);
  71363. }, this);
  71364. },
  71365. /**
  71366. * @override
  71367. */
  71368. dispose: function () {
  71369. unregister$1(this.api, this.dataZoomModel.id);
  71370. InsideZoomView.superApply(this, 'dispose', arguments);
  71371. this._range = null;
  71372. }
  71373. });
  71374. var roamHandlers = {
  71375. /**
  71376. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71377. */
  71378. zoom: function (coordInfo, coordSysName, controller, e) {
  71379. var lastRange = this._range;
  71380. var range = lastRange.slice();
  71381. // Calculate transform by the first axis.
  71382. var axisModel = coordInfo.axisModels[0];
  71383. if (!axisModel) {
  71384. return;
  71385. }
  71386. var directionInfo = getDirectionInfo[coordSysName](
  71387. null, [e.originX, e.originY], axisModel, controller, coordInfo
  71388. );
  71389. var percentPoint = (
  71390. directionInfo.signal > 0
  71391. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  71392. : (directionInfo.pixel - directionInfo.pixelStart)
  71393. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  71394. var scale = Math.max(1 / e.scale, 0);
  71395. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  71396. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  71397. // Restrict range.
  71398. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  71399. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  71400. this._range = range;
  71401. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  71402. return range;
  71403. }
  71404. },
  71405. /**
  71406. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71407. */
  71408. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  71409. var directionInfo = getDirectionInfo[coordSysName](
  71410. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  71411. );
  71412. return directionInfo.signal
  71413. * (range[1] - range[0])
  71414. * directionInfo.pixel / directionInfo.pixelLength;
  71415. }),
  71416. /**
  71417. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71418. */
  71419. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  71420. var directionInfo = getDirectionInfo[coordSysName](
  71421. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  71422. );
  71423. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  71424. })
  71425. };
  71426. function makeMover(getPercentDelta) {
  71427. return function (coordInfo, coordSysName, controller, e) {
  71428. var lastRange = this._range;
  71429. var range = lastRange.slice();
  71430. // Calculate transform by the first axis.
  71431. var axisModel = coordInfo.axisModels[0];
  71432. if (!axisModel) {
  71433. return;
  71434. }
  71435. var percentDelta = getPercentDelta(
  71436. range, axisModel, coordInfo, coordSysName, controller, e
  71437. );
  71438. sliderMove(percentDelta, range, [0, 100], 'all');
  71439. this._range = range;
  71440. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  71441. return range;
  71442. }
  71443. };
  71444. }
  71445. var getDirectionInfo = {
  71446. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71447. var axis = axisModel.axis;
  71448. var ret = {};
  71449. var rect = coordInfo.model.coordinateSystem.getRect();
  71450. oldPoint = oldPoint || [0, 0];
  71451. if (axis.dim === 'x') {
  71452. ret.pixel = newPoint[0] - oldPoint[0];
  71453. ret.pixelLength = rect.width;
  71454. ret.pixelStart = rect.x;
  71455. ret.signal = axis.inverse ? 1 : -1;
  71456. }
  71457. else { // axis.dim === 'y'
  71458. ret.pixel = newPoint[1] - oldPoint[1];
  71459. ret.pixelLength = rect.height;
  71460. ret.pixelStart = rect.y;
  71461. ret.signal = axis.inverse ? -1 : 1;
  71462. }
  71463. return ret;
  71464. },
  71465. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71466. var axis = axisModel.axis;
  71467. var ret = {};
  71468. var polar = coordInfo.model.coordinateSystem;
  71469. var radiusExtent = polar.getRadiusAxis().getExtent();
  71470. var angleExtent = polar.getAngleAxis().getExtent();
  71471. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  71472. newPoint = polar.pointToCoord(newPoint);
  71473. if (axisModel.mainType === 'radiusAxis') {
  71474. ret.pixel = newPoint[0] - oldPoint[0];
  71475. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  71476. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  71477. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  71478. ret.pixelStart = radiusExtent[0];
  71479. ret.signal = axis.inverse ? 1 : -1;
  71480. }
  71481. else { // 'angleAxis'
  71482. ret.pixel = newPoint[1] - oldPoint[1];
  71483. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  71484. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  71485. ret.pixelLength = angleExtent[1] - angleExtent[0];
  71486. ret.pixelStart = angleExtent[0];
  71487. ret.signal = axis.inverse ? -1 : 1;
  71488. }
  71489. return ret;
  71490. },
  71491. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71492. var axis = axisModel.axis;
  71493. var rect = coordInfo.model.coordinateSystem.getRect();
  71494. var ret = {};
  71495. oldPoint = oldPoint || [0, 0];
  71496. if (axis.orient === 'horizontal') {
  71497. ret.pixel = newPoint[0] - oldPoint[0];
  71498. ret.pixelLength = rect.width;
  71499. ret.pixelStart = rect.x;
  71500. ret.signal = axis.inverse ? 1 : -1;
  71501. }
  71502. else { // 'vertical'
  71503. ret.pixel = newPoint[1] - oldPoint[1];
  71504. ret.pixelLength = rect.height;
  71505. ret.pixelStart = rect.y;
  71506. ret.signal = axis.inverse ? -1 : 1;
  71507. }
  71508. return ret;
  71509. }
  71510. };
  71511. /*
  71512. * Licensed to the Apache Software Foundation (ASF) under one
  71513. * or more contributor license agreements. See the NOTICE file
  71514. * distributed with this work for additional information
  71515. * regarding copyright ownership. The ASF licenses this file
  71516. * to you under the Apache License, Version 2.0 (the
  71517. * "License"); you may not use this file except in compliance
  71518. * with the License. You may obtain a copy of the License at
  71519. *
  71520. * http://www.apache.org/licenses/LICENSE-2.0
  71521. *
  71522. * Unless required by applicable law or agreed to in writing,
  71523. * software distributed under the License is distributed on an
  71524. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71525. * KIND, either express or implied. See the License for the
  71526. * specific language governing permissions and limitations
  71527. * under the License.
  71528. */
  71529. registerProcessor({
  71530. // `dataZoomProcessor` will only be performed in needed series. Consider if
  71531. // there is a line series and a pie series, it is better not to update the
  71532. // line series if only pie series is needed to be updated.
  71533. getTargetSeries: function (ecModel) {
  71534. var seriesModelMap = createHashMap();
  71535. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71536. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71537. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  71538. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  71539. seriesModelMap.set(seriesModel.uid, seriesModel);
  71540. });
  71541. });
  71542. });
  71543. return seriesModelMap;
  71544. },
  71545. modifyOutputEnd: true,
  71546. // Consider appendData, where filter should be performed. Because data process is
  71547. // in block mode currently, it is not need to worry about that the overallProgress
  71548. // execute every frame.
  71549. overallReset: function (ecModel, api) {
  71550. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71551. // We calculate window and reset axis here but not in model
  71552. // init stage and not after action dispatch handler, because
  71553. // reset should be called after seriesData.restoreData.
  71554. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71555. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  71556. });
  71557. // Caution: data zoom filtering is order sensitive when using
  71558. // percent range and no min/max/scale set on axis.
  71559. // For example, we have dataZoom definition:
  71560. // [
  71561. // {xAxisIndex: 0, start: 30, end: 70},
  71562. // {yAxisIndex: 0, start: 20, end: 80}
  71563. // ]
  71564. // In this case, [20, 80] of y-dataZoom should be based on data
  71565. // that have filtered by x-dataZoom using range of [30, 70],
  71566. // but should not be based on full raw data. Thus sliding
  71567. // x-dataZoom will change both ranges of xAxis and yAxis,
  71568. // while sliding y-dataZoom will only change the range of yAxis.
  71569. // So we should filter x-axis after reset x-axis immediately,
  71570. // and then reset y-axis and filter y-axis.
  71571. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71572. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  71573. });
  71574. });
  71575. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71576. // Fullfill all of the range props so that user
  71577. // is able to get them from chart.getOption().
  71578. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  71579. var percentRange = axisProxy.getDataPercentWindow();
  71580. var valueRange = axisProxy.getDataValueWindow();
  71581. dataZoomModel.setRawRange({
  71582. start: percentRange[0],
  71583. end: percentRange[1],
  71584. startValue: valueRange[0],
  71585. endValue: valueRange[1]
  71586. }, true);
  71587. });
  71588. }
  71589. });
  71590. /*
  71591. * Licensed to the Apache Software Foundation (ASF) under one
  71592. * or more contributor license agreements. See the NOTICE file
  71593. * distributed with this work for additional information
  71594. * regarding copyright ownership. The ASF licenses this file
  71595. * to you under the Apache License, Version 2.0 (the
  71596. * "License"); you may not use this file except in compliance
  71597. * with the License. You may obtain a copy of the License at
  71598. *
  71599. * http://www.apache.org/licenses/LICENSE-2.0
  71600. *
  71601. * Unless required by applicable law or agreed to in writing,
  71602. * software distributed under the License is distributed on an
  71603. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71604. * KIND, either express or implied. See the License for the
  71605. * specific language governing permissions and limitations
  71606. * under the License.
  71607. */
  71608. registerAction('dataZoom', function (payload, ecModel) {
  71609. var linkedNodesFinder = createLinkedNodesFinder(
  71610. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  71611. eachAxisDim$1,
  71612. function (model, dimNames) {
  71613. return model.get(dimNames.axisIndex);
  71614. }
  71615. );
  71616. var effectedModels = [];
  71617. ecModel.eachComponent(
  71618. {mainType: 'dataZoom', query: payload},
  71619. function (model, index) {
  71620. effectedModels.push.apply(
  71621. effectedModels, linkedNodesFinder(model).nodes
  71622. );
  71623. }
  71624. );
  71625. each$1(effectedModels, function (dataZoomModel, index) {
  71626. dataZoomModel.setRawRange({
  71627. start: payload.start,
  71628. end: payload.end,
  71629. startValue: payload.startValue,
  71630. endValue: payload.endValue
  71631. });
  71632. });
  71633. });
  71634. /*
  71635. * Licensed to the Apache Software Foundation (ASF) under one
  71636. * or more contributor license agreements. See the NOTICE file
  71637. * distributed with this work for additional information
  71638. * regarding copyright ownership. The ASF licenses this file
  71639. * to you under the Apache License, Version 2.0 (the
  71640. * "License"); you may not use this file except in compliance
  71641. * with the License. You may obtain a copy of the License at
  71642. *
  71643. * http://www.apache.org/licenses/LICENSE-2.0
  71644. *
  71645. * Unless required by applicable law or agreed to in writing,
  71646. * software distributed under the License is distributed on an
  71647. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71648. * KIND, either express or implied. See the License for the
  71649. * specific language governing permissions and limitations
  71650. * under the License.
  71651. */
  71652. /**
  71653. * DataZoom component entry
  71654. */
  71655. /*
  71656. * Licensed to the Apache Software Foundation (ASF) under one
  71657. * or more contributor license agreements. See the NOTICE file
  71658. * distributed with this work for additional information
  71659. * regarding copyright ownership. The ASF licenses this file
  71660. * to you under the Apache License, Version 2.0 (the
  71661. * "License"); you may not use this file except in compliance
  71662. * with the License. You may obtain a copy of the License at
  71663. *
  71664. * http://www.apache.org/licenses/LICENSE-2.0
  71665. *
  71666. * Unless required by applicable law or agreed to in writing,
  71667. * software distributed under the License is distributed on an
  71668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71669. * KIND, either express or implied. See the License for the
  71670. * specific language governing permissions and limitations
  71671. * under the License.
  71672. */
  71673. var each$24 = each$1;
  71674. var preprocessor$2 = function (option) {
  71675. var visualMap = option && option.visualMap;
  71676. if (!isArray(visualMap)) {
  71677. visualMap = visualMap ? [visualMap] : [];
  71678. }
  71679. each$24(visualMap, function (opt) {
  71680. if (!opt) {
  71681. return;
  71682. }
  71683. // rename splitList to pieces
  71684. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  71685. opt.pieces = opt.splitList;
  71686. delete opt.splitList;
  71687. }
  71688. var pieces = opt.pieces;
  71689. if (pieces && isArray(pieces)) {
  71690. each$24(pieces, function (piece) {
  71691. if (isObject$1(piece)) {
  71692. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  71693. piece.min = piece.start;
  71694. }
  71695. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  71696. piece.max = piece.end;
  71697. }
  71698. }
  71699. });
  71700. }
  71701. });
  71702. };
  71703. function has$1(obj, name) {
  71704. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  71705. }
  71706. /*
  71707. * Licensed to the Apache Software Foundation (ASF) under one
  71708. * or more contributor license agreements. See the NOTICE file
  71709. * distributed with this work for additional information
  71710. * regarding copyright ownership. The ASF licenses this file
  71711. * to you under the Apache License, Version 2.0 (the
  71712. * "License"); you may not use this file except in compliance
  71713. * with the License. You may obtain a copy of the License at
  71714. *
  71715. * http://www.apache.org/licenses/LICENSE-2.0
  71716. *
  71717. * Unless required by applicable law or agreed to in writing,
  71718. * software distributed under the License is distributed on an
  71719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71720. * KIND, either express or implied. See the License for the
  71721. * specific language governing permissions and limitations
  71722. * under the License.
  71723. */
  71724. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  71725. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  71726. return (
  71727. !option.categories
  71728. && (
  71729. !(
  71730. option.pieces
  71731. ? option.pieces.length > 0
  71732. : option.splitNumber > 0
  71733. )
  71734. || option.calculable
  71735. )
  71736. )
  71737. ? 'continuous' : 'piecewise';
  71738. });
  71739. /*
  71740. * Licensed to the Apache Software Foundation (ASF) under one
  71741. * or more contributor license agreements. See the NOTICE file
  71742. * distributed with this work for additional information
  71743. * regarding copyright ownership. The ASF licenses this file
  71744. * to you under the Apache License, Version 2.0 (the
  71745. * "License"); you may not use this file except in compliance
  71746. * with the License. You may obtain a copy of the License at
  71747. *
  71748. * http://www.apache.org/licenses/LICENSE-2.0
  71749. *
  71750. * Unless required by applicable law or agreed to in writing,
  71751. * software distributed under the License is distributed on an
  71752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71753. * KIND, either express or implied. See the License for the
  71754. * specific language governing permissions and limitations
  71755. * under the License.
  71756. */
  71757. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  71758. registerVisual(VISUAL_PRIORITY, {
  71759. createOnAllSeries: true,
  71760. reset: function (seriesModel, ecModel) {
  71761. var resetDefines = [];
  71762. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71763. var pipelineContext = seriesModel.pipelineContext;
  71764. if (!visualMapModel.isTargetSeries(seriesModel)
  71765. || (pipelineContext && pipelineContext.large)
  71766. ) {
  71767. return;
  71768. }
  71769. resetDefines.push(incrementalApplyVisual(
  71770. visualMapModel.stateList,
  71771. visualMapModel.targetVisuals,
  71772. bind(visualMapModel.getValueState, visualMapModel),
  71773. visualMapModel.getDataDimension(seriesModel.getData())
  71774. ));
  71775. });
  71776. return resetDefines;
  71777. }
  71778. });
  71779. // Only support color.
  71780. registerVisual(VISUAL_PRIORITY, {
  71781. createOnAllSeries: true,
  71782. reset: function (seriesModel, ecModel) {
  71783. var data = seriesModel.getData();
  71784. var visualMetaList = [];
  71785. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71786. if (visualMapModel.isTargetSeries(seriesModel)) {
  71787. var visualMeta = visualMapModel.getVisualMeta(
  71788. bind(getColorVisual, null, seriesModel, visualMapModel)
  71789. ) || {stops: [], outerColors: []};
  71790. var concreteDim = visualMapModel.getDataDimension(data);
  71791. var dimInfo = data.getDimensionInfo(concreteDim);
  71792. if (dimInfo != null) {
  71793. // visualMeta.dimension should be dimension index, but not concrete dimension.
  71794. visualMeta.dimension = dimInfo.index;
  71795. visualMetaList.push(visualMeta);
  71796. }
  71797. }
  71798. });
  71799. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  71800. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  71801. }
  71802. });
  71803. // FIXME
  71804. // performance and export for heatmap?
  71805. // value can be Infinity or -Infinity
  71806. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  71807. var mappings = visualMapModel.targetVisuals[valueState];
  71808. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  71809. var resultVisual = {
  71810. color: seriesModel.getData().getVisual('color') // default color.
  71811. };
  71812. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71813. var type = visualTypes[i];
  71814. var mapping = mappings[
  71815. type === 'opacity' ? '__alphaForOpacity' : type
  71816. ];
  71817. mapping && mapping.applyVisual(value, getVisual, setVisual);
  71818. }
  71819. return resultVisual.color;
  71820. function getVisual(key) {
  71821. return resultVisual[key];
  71822. }
  71823. function setVisual(key, value) {
  71824. resultVisual[key] = value;
  71825. }
  71826. }
  71827. /*
  71828. * Licensed to the Apache Software Foundation (ASF) under one
  71829. * or more contributor license agreements. See the NOTICE file
  71830. * distributed with this work for additional information
  71831. * regarding copyright ownership. The ASF licenses this file
  71832. * to you under the Apache License, Version 2.0 (the
  71833. * "License"); you may not use this file except in compliance
  71834. * with the License. You may obtain a copy of the License at
  71835. *
  71836. * http://www.apache.org/licenses/LICENSE-2.0
  71837. *
  71838. * Unless required by applicable law or agreed to in writing,
  71839. * software distributed under the License is distributed on an
  71840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71841. * KIND, either express or implied. See the License for the
  71842. * specific language governing permissions and limitations
  71843. * under the License.
  71844. */
  71845. /**
  71846. * @file Visual mapping.
  71847. */
  71848. var visualDefault = {
  71849. /**
  71850. * @public
  71851. */
  71852. get: function (visualType, key, isCategory) {
  71853. var value = clone(
  71854. (defaultOption$3[visualType] || {})[key]
  71855. );
  71856. return isCategory
  71857. ? (isArray(value) ? value[value.length - 1] : value)
  71858. : value;
  71859. }
  71860. };
  71861. var defaultOption$3 = {
  71862. color: {
  71863. active: ['#006edd', '#e0ffff'],
  71864. inactive: ['rgba(0,0,0,0)']
  71865. },
  71866. colorHue: {
  71867. active: [0, 360],
  71868. inactive: [0, 0]
  71869. },
  71870. colorSaturation: {
  71871. active: [0.3, 1],
  71872. inactive: [0, 0]
  71873. },
  71874. colorLightness: {
  71875. active: [0.9, 0.5],
  71876. inactive: [0, 0]
  71877. },
  71878. colorAlpha: {
  71879. active: [0.3, 1],
  71880. inactive: [0, 0]
  71881. },
  71882. opacity: {
  71883. active: [0.3, 1],
  71884. inactive: [0, 0]
  71885. },
  71886. symbol: {
  71887. active: ['circle', 'roundRect', 'diamond'],
  71888. inactive: ['none']
  71889. },
  71890. symbolSize: {
  71891. active: [10, 50],
  71892. inactive: [0, 0]
  71893. }
  71894. };
  71895. /*
  71896. * Licensed to the Apache Software Foundation (ASF) under one
  71897. * or more contributor license agreements. See the NOTICE file
  71898. * distributed with this work for additional information
  71899. * regarding copyright ownership. The ASF licenses this file
  71900. * to you under the Apache License, Version 2.0 (the
  71901. * "License"); you may not use this file except in compliance
  71902. * with the License. You may obtain a copy of the License at
  71903. *
  71904. * http://www.apache.org/licenses/LICENSE-2.0
  71905. *
  71906. * Unless required by applicable law or agreed to in writing,
  71907. * software distributed under the License is distributed on an
  71908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71909. * KIND, either express or implied. See the License for the
  71910. * specific language governing permissions and limitations
  71911. * under the License.
  71912. */
  71913. var mapVisual$2 = VisualMapping.mapVisual;
  71914. var eachVisual = VisualMapping.eachVisual;
  71915. var isArray$3 = isArray;
  71916. var each$25 = each$1;
  71917. var asc$3 = asc;
  71918. var linearMap$2 = linearMap;
  71919. var noop$2 = noop;
  71920. var VisualMapModel = extendComponentModel({
  71921. type: 'visualMap',
  71922. dependencies: ['series'],
  71923. /**
  71924. * @readOnly
  71925. * @type {Array.<string>}
  71926. */
  71927. stateList: ['inRange', 'outOfRange'],
  71928. /**
  71929. * @readOnly
  71930. * @type {Array.<string>}
  71931. */
  71932. replacableOptionKeys: [
  71933. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  71934. ],
  71935. /**
  71936. * [lowerBound, upperBound]
  71937. *
  71938. * @readOnly
  71939. * @type {Array.<number>}
  71940. */
  71941. dataBound: [-Infinity, Infinity],
  71942. /**
  71943. * @readOnly
  71944. * @type {string|Object}
  71945. */
  71946. layoutMode: {type: 'box', ignoreSize: true},
  71947. /**
  71948. * @protected
  71949. */
  71950. defaultOption: {
  71951. show: true,
  71952. zlevel: 0,
  71953. z: 4,
  71954. seriesIndex: 'all', // 'all' or null/undefined: all series.
  71955. // A number or an array of number: the specified series.
  71956. // set min: 0, max: 200, only for campatible with ec2.
  71957. // In fact min max should not have default value.
  71958. min: 0, // min value, must specified if pieces is not specified.
  71959. max: 200, // max value, must specified if pieces is not specified.
  71960. dimension: null,
  71961. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  71962. // 'symbol', 'symbolSize'
  71963. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  71964. // 'colorLightness', 'colorAlpha',
  71965. // 'symbol', 'symbolSize'
  71966. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  71967. right: null, // The same as left.
  71968. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  71969. bottom: 0, // The same as top.
  71970. itemWidth: null,
  71971. itemHeight: null,
  71972. inverse: false,
  71973. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  71974. backgroundColor: 'rgba(0,0,0,0)',
  71975. borderColor: '#ccc', // 值域边框颜色
  71976. contentColor: '#5793f3',
  71977. inactiveColor: '#aaa',
  71978. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  71979. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  71980. // 接受数组分别设定上右下左边距,同css
  71981. textGap: 10, //
  71982. precision: 0, // 小数精度,默认为0,无小数点
  71983. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  71984. formatter: null,
  71985. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  71986. textStyle: {
  71987. color: '#333' // 值域文字颜色
  71988. }
  71989. },
  71990. /**
  71991. * @protected
  71992. */
  71993. init: function (option, parentModel, ecModel) {
  71994. /**
  71995. * @private
  71996. * @type {Array.<number>}
  71997. */
  71998. this._dataExtent;
  71999. /**
  72000. * @readOnly
  72001. */
  72002. this.targetVisuals = {};
  72003. /**
  72004. * @readOnly
  72005. */
  72006. this.controllerVisuals = {};
  72007. /**
  72008. * @readOnly
  72009. */
  72010. this.textStyleModel;
  72011. /**
  72012. * [width, height]
  72013. * @readOnly
  72014. * @type {Array.<number>}
  72015. */
  72016. this.itemSize;
  72017. this.mergeDefaultAndTheme(option, ecModel);
  72018. },
  72019. /**
  72020. * @protected
  72021. */
  72022. optionUpdated: function (newOption, isInit) {
  72023. var thisOption = this.option;
  72024. // FIXME
  72025. // necessary?
  72026. // Disable realtime view update if canvas is not supported.
  72027. if (!env$1.canvasSupported) {
  72028. thisOption.realtime = false;
  72029. }
  72030. !isInit && replaceVisualOption(
  72031. thisOption, newOption, this.replacableOptionKeys
  72032. );
  72033. this.textStyleModel = this.getModel('textStyle');
  72034. this.resetItemSize();
  72035. this.completeVisualOption();
  72036. },
  72037. /**
  72038. * @protected
  72039. */
  72040. resetVisual: function (supplementVisualOption) {
  72041. var stateList = this.stateList;
  72042. supplementVisualOption = bind(supplementVisualOption, this);
  72043. this.controllerVisuals = createVisualMappings(
  72044. this.option.controller, stateList, supplementVisualOption
  72045. );
  72046. this.targetVisuals = createVisualMappings(
  72047. this.option.target, stateList, supplementVisualOption
  72048. );
  72049. },
  72050. /**
  72051. * @protected
  72052. * @return {Array.<number>} An array of series indices.
  72053. */
  72054. getTargetSeriesIndices: function () {
  72055. var optionSeriesIndex = this.option.seriesIndex;
  72056. var seriesIndices = [];
  72057. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  72058. this.ecModel.eachSeries(function (seriesModel, index) {
  72059. seriesIndices.push(index);
  72060. });
  72061. }
  72062. else {
  72063. seriesIndices = normalizeToArray(optionSeriesIndex);
  72064. }
  72065. return seriesIndices;
  72066. },
  72067. /**
  72068. * @public
  72069. */
  72070. eachTargetSeries: function (callback, context) {
  72071. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  72072. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  72073. }, this);
  72074. },
  72075. /**
  72076. * @pubilc
  72077. */
  72078. isTargetSeries: function (seriesModel) {
  72079. var is = false;
  72080. this.eachTargetSeries(function (model) {
  72081. model === seriesModel && (is = true);
  72082. });
  72083. return is;
  72084. },
  72085. /**
  72086. * @example
  72087. * this.formatValueText(someVal); // format single numeric value to text.
  72088. * this.formatValueText(someVal, true); // format single category value to text.
  72089. * this.formatValueText([min, max]); // format numeric min-max to text.
  72090. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  72091. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  72092. *
  72093. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  72094. * @param {boolean} [isCategory=false] Only available when value is number.
  72095. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  72096. * @return {string}
  72097. * @protected
  72098. */
  72099. formatValueText: function (value, isCategory, edgeSymbols) {
  72100. var option = this.option;
  72101. var precision = option.precision;
  72102. var dataBound = this.dataBound;
  72103. var formatter = option.formatter;
  72104. var isMinMax;
  72105. var textValue;
  72106. edgeSymbols = edgeSymbols || ['<', '>'];
  72107. if (isArray(value)) {
  72108. value = value.slice();
  72109. isMinMax = true;
  72110. }
  72111. textValue = isCategory
  72112. ? value
  72113. : (isMinMax
  72114. ? [toFixed(value[0]), toFixed(value[1])]
  72115. : toFixed(value)
  72116. );
  72117. if (isString(formatter)) {
  72118. return formatter
  72119. .replace('{value}', isMinMax ? textValue[0] : textValue)
  72120. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  72121. }
  72122. else if (isFunction$1(formatter)) {
  72123. return isMinMax
  72124. ? formatter(value[0], value[1])
  72125. : formatter(value);
  72126. }
  72127. if (isMinMax) {
  72128. if (value[0] === dataBound[0]) {
  72129. return edgeSymbols[0] + ' ' + textValue[1];
  72130. }
  72131. else if (value[1] === dataBound[1]) {
  72132. return edgeSymbols[1] + ' ' + textValue[0];
  72133. }
  72134. else {
  72135. return textValue[0] + ' - ' + textValue[1];
  72136. }
  72137. }
  72138. else { // Format single value (includes category case).
  72139. return textValue;
  72140. }
  72141. function toFixed(val) {
  72142. return val === dataBound[0]
  72143. ? 'min'
  72144. : val === dataBound[1]
  72145. ? 'max'
  72146. : (+val).toFixed(Math.min(precision, 20));
  72147. }
  72148. },
  72149. /**
  72150. * @protected
  72151. */
  72152. resetExtent: function () {
  72153. var thisOption = this.option;
  72154. // Can not calculate data extent by data here.
  72155. // Because series and data may be modified in processing stage.
  72156. // So we do not support the feature "auto min/max".
  72157. var extent = asc$3([thisOption.min, thisOption.max]);
  72158. this._dataExtent = extent;
  72159. },
  72160. /**
  72161. * @public
  72162. * @param {module:echarts/data/List} list
  72163. * @return {string} Concrete dimention. If return null/undefined,
  72164. * no dimension used.
  72165. */
  72166. getDataDimension: function (list) {
  72167. var optDim = this.option.dimension;
  72168. var listDimensions = list.dimensions;
  72169. if (optDim == null && !listDimensions.length) {
  72170. return;
  72171. }
  72172. if (optDim != null) {
  72173. return list.getDimension(optDim);
  72174. }
  72175. var dimNames = list.dimensions;
  72176. for (var i = dimNames.length - 1; i >= 0; i--) {
  72177. var dimName = dimNames[i];
  72178. var dimInfo = list.getDimensionInfo(dimName);
  72179. if (!dimInfo.isCalculationCoord) {
  72180. return dimName;
  72181. }
  72182. }
  72183. },
  72184. /**
  72185. * @public
  72186. * @override
  72187. */
  72188. getExtent: function () {
  72189. return this._dataExtent.slice();
  72190. },
  72191. /**
  72192. * @protected
  72193. */
  72194. completeVisualOption: function () {
  72195. var ecModel = this.ecModel;
  72196. var thisOption = this.option;
  72197. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  72198. var target = thisOption.target || (thisOption.target = {});
  72199. var controller = thisOption.controller || (thisOption.controller = {});
  72200. merge(target, base); // Do not override
  72201. merge(controller, base); // Do not override
  72202. var isCategory = this.isCategory();
  72203. completeSingle.call(this, target);
  72204. completeSingle.call(this, controller);
  72205. completeInactive.call(this, target, 'inRange', 'outOfRange');
  72206. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  72207. completeController.call(this, controller);
  72208. function completeSingle(base) {
  72209. // Compatible with ec2 dataRange.color.
  72210. // The mapping order of dataRange.color is: [high value, ..., low value]
  72211. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  72212. // Notice: ec2 has no inverse.
  72213. if (isArray$3(thisOption.color)
  72214. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  72215. // So adding color only when no inRange defined.
  72216. && !base.inRange
  72217. ) {
  72218. base.inRange = {color: thisOption.color.slice().reverse()};
  72219. }
  72220. // Compatible with previous logic, always give a defautl color, otherwise
  72221. // simple config with no inRange and outOfRange will not work.
  72222. // Originally we use visualMap.color as the default color, but setOption at
  72223. // the second time the default color will be erased. So we change to use
  72224. // constant DEFAULT_COLOR.
  72225. // If user do not want the defualt color, set inRange: {color: null}.
  72226. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  72227. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  72228. each$25(this.stateList, function (state) {
  72229. var visualType = base[state];
  72230. if (isString(visualType)) {
  72231. var defa = visualDefault.get(visualType, 'active', isCategory);
  72232. if (defa) {
  72233. base[state] = {};
  72234. base[state][visualType] = defa;
  72235. }
  72236. else {
  72237. // Mark as not specified.
  72238. delete base[state];
  72239. }
  72240. }
  72241. }, this);
  72242. }
  72243. function completeInactive(base, stateExist, stateAbsent) {
  72244. var optExist = base[stateExist];
  72245. var optAbsent = base[stateAbsent];
  72246. if (optExist && !optAbsent) {
  72247. optAbsent = base[stateAbsent] = {};
  72248. each$25(optExist, function (visualData, visualType) {
  72249. if (!VisualMapping.isValidType(visualType)) {
  72250. return;
  72251. }
  72252. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  72253. if (defa != null) {
  72254. optAbsent[visualType] = defa;
  72255. // Compatibable with ec2:
  72256. // Only inactive color to rgba(0,0,0,0) can not
  72257. // make label transparent, so use opacity also.
  72258. if (visualType === 'color'
  72259. && !optAbsent.hasOwnProperty('opacity')
  72260. && !optAbsent.hasOwnProperty('colorAlpha')
  72261. ) {
  72262. optAbsent.opacity = [0, 0];
  72263. }
  72264. }
  72265. });
  72266. }
  72267. }
  72268. function completeController(controller) {
  72269. var symbolExists = (controller.inRange || {}).symbol
  72270. || (controller.outOfRange || {}).symbol;
  72271. var symbolSizeExists = (controller.inRange || {}).symbolSize
  72272. || (controller.outOfRange || {}).symbolSize;
  72273. var inactiveColor = this.get('inactiveColor');
  72274. each$25(this.stateList, function (state) {
  72275. var itemSize = this.itemSize;
  72276. var visuals = controller[state];
  72277. // Set inactive color for controller if no other color
  72278. // attr (like colorAlpha) specified.
  72279. if (!visuals) {
  72280. visuals = controller[state] = {
  72281. color: isCategory ? inactiveColor : [inactiveColor]
  72282. };
  72283. }
  72284. // Consistent symbol and symbolSize if not specified.
  72285. if (visuals.symbol == null) {
  72286. visuals.symbol = symbolExists
  72287. && clone(symbolExists)
  72288. || (isCategory ? 'roundRect' : ['roundRect']);
  72289. }
  72290. if (visuals.symbolSize == null) {
  72291. visuals.symbolSize = symbolSizeExists
  72292. && clone(symbolSizeExists)
  72293. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  72294. }
  72295. // Filter square and none.
  72296. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  72297. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  72298. });
  72299. // Normalize symbolSize
  72300. var symbolSize = visuals.symbolSize;
  72301. if (symbolSize != null) {
  72302. var max = -Infinity;
  72303. // symbolSize can be object when categories defined.
  72304. eachVisual(symbolSize, function (value) {
  72305. value > max && (max = value);
  72306. });
  72307. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  72308. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  72309. });
  72310. }
  72311. }, this);
  72312. }
  72313. },
  72314. /**
  72315. * @protected
  72316. */
  72317. resetItemSize: function () {
  72318. this.itemSize = [
  72319. parseFloat(this.get('itemWidth')),
  72320. parseFloat(this.get('itemHeight'))
  72321. ];
  72322. },
  72323. /**
  72324. * @public
  72325. */
  72326. isCategory: function () {
  72327. return !!this.option.categories;
  72328. },
  72329. /**
  72330. * @public
  72331. * @abstract
  72332. */
  72333. setSelected: noop$2,
  72334. /**
  72335. * @public
  72336. * @abstract
  72337. * @param {*|module:echarts/data/List} valueOrData
  72338. * @param {number} dataIndex
  72339. * @return {string} state See this.stateList
  72340. */
  72341. getValueState: noop$2,
  72342. /**
  72343. * FIXME
  72344. * Do not publish to thirt-part-dev temporarily
  72345. * util the interface is stable. (Should it return
  72346. * a function but not visual meta?)
  72347. *
  72348. * @pubilc
  72349. * @abstract
  72350. * @param {Function} getColorVisual
  72351. * params: value, valueState
  72352. * return: color
  72353. * @return {Object} visualMeta
  72354. * should includes {stops, outerColors}
  72355. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  72356. */
  72357. getVisualMeta: noop$2
  72358. });
  72359. /*
  72360. * Licensed to the Apache Software Foundation (ASF) under one
  72361. * or more contributor license agreements. See the NOTICE file
  72362. * distributed with this work for additional information
  72363. * regarding copyright ownership. The ASF licenses this file
  72364. * to you under the Apache License, Version 2.0 (the
  72365. * "License"); you may not use this file except in compliance
  72366. * with the License. You may obtain a copy of the License at
  72367. *
  72368. * http://www.apache.org/licenses/LICENSE-2.0
  72369. *
  72370. * Unless required by applicable law or agreed to in writing,
  72371. * software distributed under the License is distributed on an
  72372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72373. * KIND, either express or implied. See the License for the
  72374. * specific language governing permissions and limitations
  72375. * under the License.
  72376. */
  72377. // Constant
  72378. var DEFAULT_BAR_BOUND = [20, 140];
  72379. var ContinuousModel = VisualMapModel.extend({
  72380. type: 'visualMap.continuous',
  72381. /**
  72382. * @protected
  72383. */
  72384. defaultOption: {
  72385. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  72386. calculable: false, // This prop effect default component type determine,
  72387. // See echarts/component/visualMap/typeDefaulter.
  72388. range: null, // selected range. In default case `range` is [min, max]
  72389. // and can auto change along with modification of min max,
  72390. // util use specifid a range.
  72391. realtime: true, // Whether realtime update.
  72392. itemHeight: null, // The length of the range control edge.
  72393. itemWidth: null, // The length of the other side.
  72394. hoverLink: true, // Enable hover highlight.
  72395. hoverLinkDataSize: null, // The size of hovered data.
  72396. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  72397. // If not specified, follow the value of `realtime`.
  72398. },
  72399. /**
  72400. * @override
  72401. */
  72402. optionUpdated: function (newOption, isInit) {
  72403. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  72404. this.resetExtent();
  72405. this.resetVisual(function (mappingOption) {
  72406. mappingOption.mappingMethod = 'linear';
  72407. mappingOption.dataExtent = this.getExtent();
  72408. });
  72409. this._resetRange();
  72410. },
  72411. /**
  72412. * @protected
  72413. * @override
  72414. */
  72415. resetItemSize: function () {
  72416. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  72417. var itemSize = this.itemSize;
  72418. this._orient === 'horizontal' && itemSize.reverse();
  72419. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  72420. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  72421. },
  72422. /**
  72423. * @private
  72424. */
  72425. _resetRange: function () {
  72426. var dataExtent = this.getExtent();
  72427. var range = this.option.range;
  72428. if (!range || range.auto) {
  72429. // `range` should always be array (so we dont use other
  72430. // value like 'auto') for user-friend. (consider getOption).
  72431. dataExtent.auto = 1;
  72432. this.option.range = dataExtent;
  72433. }
  72434. else if (isArray(range)) {
  72435. if (range[0] > range[1]) {
  72436. range.reverse();
  72437. }
  72438. range[0] = Math.max(range[0], dataExtent[0]);
  72439. range[1] = Math.min(range[1], dataExtent[1]);
  72440. }
  72441. },
  72442. /**
  72443. * @protected
  72444. * @override
  72445. */
  72446. completeVisualOption: function () {
  72447. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  72448. each$1(this.stateList, function (state) {
  72449. var symbolSize = this.option.controller[state].symbolSize;
  72450. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  72451. symbolSize[0] = 0; // For good looking.
  72452. }
  72453. }, this);
  72454. },
  72455. /**
  72456. * @override
  72457. */
  72458. setSelected: function (selected) {
  72459. this.option.range = selected.slice();
  72460. this._resetRange();
  72461. },
  72462. /**
  72463. * @public
  72464. */
  72465. getSelected: function () {
  72466. var dataExtent = this.getExtent();
  72467. var dataInterval = asc(
  72468. (this.get('range') || []).slice()
  72469. );
  72470. // Clamp
  72471. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  72472. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  72473. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  72474. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  72475. return dataInterval;
  72476. },
  72477. /**
  72478. * @override
  72479. */
  72480. getValueState: function (value) {
  72481. var range = this.option.range;
  72482. var dataExtent = this.getExtent();
  72483. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  72484. // range[1] is processed likewise.
  72485. return (
  72486. (range[0] <= dataExtent[0] || range[0] <= value)
  72487. && (range[1] >= dataExtent[1] || value <= range[1])
  72488. ) ? 'inRange' : 'outOfRange';
  72489. },
  72490. /**
  72491. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  72492. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  72493. */
  72494. findTargetDataIndices: function (range) {
  72495. var result = [];
  72496. this.eachTargetSeries(function (seriesModel) {
  72497. var dataIndices = [];
  72498. var data = seriesModel.getData();
  72499. data.each(this.getDataDimension(data), function (value, dataIndex) {
  72500. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  72501. }, this);
  72502. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  72503. }, this);
  72504. return result;
  72505. },
  72506. /**
  72507. * @implement
  72508. */
  72509. getVisualMeta: function (getColorVisual) {
  72510. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  72511. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  72512. var stops = [];
  72513. function setStop(value, valueState) {
  72514. stops.push({
  72515. value: value,
  72516. color: getColorVisual(value, valueState)
  72517. });
  72518. }
  72519. // Format to: outOfRange -- inRange -- outOfRange.
  72520. var iIdx = 0;
  72521. var oIdx = 0;
  72522. var iLen = iVals.length;
  72523. var oLen = oVals.length;
  72524. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  72525. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  72526. if (oVals[oIdx] < iVals[iIdx]) {
  72527. setStop(oVals[oIdx], 'outOfRange');
  72528. }
  72529. }
  72530. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  72531. // If range is full, value beyond min, max will be clamped.
  72532. // make a singularity
  72533. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  72534. setStop(iVals[iIdx], 'inRange');
  72535. }
  72536. for (var first = 1; oIdx < oLen; oIdx++) {
  72537. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  72538. // make a singularity
  72539. if (first) {
  72540. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  72541. first = 0;
  72542. }
  72543. setStop(oVals[oIdx], 'outOfRange');
  72544. }
  72545. }
  72546. var stopsLen = stops.length;
  72547. return {
  72548. stops: stops,
  72549. outerColors: [
  72550. stopsLen ? stops[0].color : 'transparent',
  72551. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  72552. ]
  72553. };
  72554. }
  72555. });
  72556. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  72557. if (dataExtent[0] === dataExtent[1]) {
  72558. return dataExtent.slice();
  72559. }
  72560. // When using colorHue mapping, it is not linear color any more.
  72561. // Moreover, canvas gradient seems not to be accurate linear.
  72562. // FIXME
  72563. // Should be arbitrary value 100? or based on pixel size?
  72564. var count = 200;
  72565. var step = (dataExtent[1] - dataExtent[0]) / count;
  72566. var value = dataExtent[0];
  72567. var stopValues = [];
  72568. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  72569. stopValues.push(value);
  72570. value += step;
  72571. }
  72572. stopValues.push(dataExtent[1]);
  72573. return stopValues;
  72574. }
  72575. /*
  72576. * Licensed to the Apache Software Foundation (ASF) under one
  72577. * or more contributor license agreements. See the NOTICE file
  72578. * distributed with this work for additional information
  72579. * regarding copyright ownership. The ASF licenses this file
  72580. * to you under the Apache License, Version 2.0 (the
  72581. * "License"); you may not use this file except in compliance
  72582. * with the License. You may obtain a copy of the License at
  72583. *
  72584. * http://www.apache.org/licenses/LICENSE-2.0
  72585. *
  72586. * Unless required by applicable law or agreed to in writing,
  72587. * software distributed under the License is distributed on an
  72588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72589. * KIND, either express or implied. See the License for the
  72590. * specific language governing permissions and limitations
  72591. * under the License.
  72592. */
  72593. var VisualMapView = extendComponentView({
  72594. type: 'visualMap',
  72595. /**
  72596. * @readOnly
  72597. * @type {Object}
  72598. */
  72599. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  72600. init: function (ecModel, api) {
  72601. /**
  72602. * @readOnly
  72603. * @type {module:echarts/model/Global}
  72604. */
  72605. this.ecModel = ecModel;
  72606. /**
  72607. * @readOnly
  72608. * @type {module:echarts/ExtensionAPI}
  72609. */
  72610. this.api = api;
  72611. /**
  72612. * @readOnly
  72613. * @type {module:echarts/component/visualMap/visualMapModel}
  72614. */
  72615. this.visualMapModel;
  72616. },
  72617. /**
  72618. * @protected
  72619. */
  72620. render: function (visualMapModel, ecModel, api, payload) {
  72621. this.visualMapModel = visualMapModel;
  72622. if (visualMapModel.get('show') === false) {
  72623. this.group.removeAll();
  72624. return;
  72625. }
  72626. this.doRender.apply(this, arguments);
  72627. },
  72628. /**
  72629. * @protected
  72630. */
  72631. renderBackground: function (group) {
  72632. var visualMapModel = this.visualMapModel;
  72633. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  72634. var rect = group.getBoundingRect();
  72635. group.add(new Rect({
  72636. z2: -1, // Lay background rect on the lowest layer.
  72637. silent: true,
  72638. shape: {
  72639. x: rect.x - padding[3],
  72640. y: rect.y - padding[0],
  72641. width: rect.width + padding[3] + padding[1],
  72642. height: rect.height + padding[0] + padding[2]
  72643. },
  72644. style: {
  72645. fill: visualMapModel.get('backgroundColor'),
  72646. stroke: visualMapModel.get('borderColor'),
  72647. lineWidth: visualMapModel.get('borderWidth')
  72648. }
  72649. }));
  72650. },
  72651. /**
  72652. * @protected
  72653. * @param {number} targetValue can be Infinity or -Infinity
  72654. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  72655. * @param {Object} [opts]
  72656. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  72657. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  72658. * @return {*} Visual value.
  72659. */
  72660. getControllerVisual: function (targetValue, visualCluster, opts) {
  72661. opts = opts || {};
  72662. var forceState = opts.forceState;
  72663. var visualMapModel = this.visualMapModel;
  72664. var visualObj = {};
  72665. // Default values.
  72666. if (visualCluster === 'symbol') {
  72667. visualObj.symbol = visualMapModel.get('itemSymbol');
  72668. }
  72669. if (visualCluster === 'color') {
  72670. var defaultColor = visualMapModel.get('contentColor');
  72671. visualObj.color = defaultColor;
  72672. }
  72673. function getter(key) {
  72674. return visualObj[key];
  72675. }
  72676. function setter(key, value) {
  72677. visualObj[key] = value;
  72678. }
  72679. var mappings = visualMapModel.controllerVisuals[
  72680. forceState || visualMapModel.getValueState(targetValue)
  72681. ];
  72682. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  72683. each$1(visualTypes, function (type) {
  72684. var visualMapping = mappings[type];
  72685. if (opts.convertOpacityToAlpha && type === 'opacity') {
  72686. type = 'colorAlpha';
  72687. visualMapping = mappings.__alphaForOpacity;
  72688. }
  72689. if (VisualMapping.dependsOn(type, visualCluster)) {
  72690. visualMapping && visualMapping.applyVisual(
  72691. targetValue, getter, setter
  72692. );
  72693. }
  72694. });
  72695. return visualObj[visualCluster];
  72696. },
  72697. /**
  72698. * @protected
  72699. */
  72700. positionGroup: function (group) {
  72701. var model = this.visualMapModel;
  72702. var api = this.api;
  72703. positionElement(
  72704. group,
  72705. model.getBoxLayoutParams(),
  72706. {width: api.getWidth(), height: api.getHeight()}
  72707. );
  72708. },
  72709. /**
  72710. * @protected
  72711. * @abstract
  72712. */
  72713. doRender: noop
  72714. });
  72715. /*
  72716. * Licensed to the Apache Software Foundation (ASF) under one
  72717. * or more contributor license agreements. See the NOTICE file
  72718. * distributed with this work for additional information
  72719. * regarding copyright ownership. The ASF licenses this file
  72720. * to you under the Apache License, Version 2.0 (the
  72721. * "License"); you may not use this file except in compliance
  72722. * with the License. You may obtain a copy of the License at
  72723. *
  72724. * http://www.apache.org/licenses/LICENSE-2.0
  72725. *
  72726. * Unless required by applicable law or agreed to in writing,
  72727. * software distributed under the License is distributed on an
  72728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72729. * KIND, either express or implied. See the License for the
  72730. * specific language governing permissions and limitations
  72731. * under the License.
  72732. */
  72733. /**
  72734. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  72735. * @param {module:echarts/ExtensionAPI} api
  72736. * @param {Array.<number>} itemSize always [short, long]
  72737. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  72738. */
  72739. function getItemAlign(visualMapModel, api, itemSize) {
  72740. var modelOption = visualMapModel.option;
  72741. var itemAlign = modelOption.align;
  72742. if (itemAlign != null && itemAlign !== 'auto') {
  72743. return itemAlign;
  72744. }
  72745. // Auto decision align.
  72746. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  72747. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  72748. var paramsSet = [
  72749. ['left', 'right', 'width'],
  72750. ['top', 'bottom', 'height']
  72751. ];
  72752. var reals = paramsSet[realIndex];
  72753. var fakeValue = [0, null, 10];
  72754. var layoutInput = {};
  72755. for (var i = 0; i < 3; i++) {
  72756. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  72757. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  72758. }
  72759. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  72760. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  72761. return reals[
  72762. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  72763. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  72764. ];
  72765. }
  72766. /**
  72767. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  72768. * dataIndexInside means filtered index.
  72769. */
  72770. function convertDataIndex(batch) {
  72771. each$1(batch || [], function (batchItem) {
  72772. if (batch.dataIndex != null) {
  72773. batch.dataIndexInside = batch.dataIndex;
  72774. batch.dataIndex = null;
  72775. }
  72776. });
  72777. return batch;
  72778. }
  72779. /*
  72780. * Licensed to the Apache Software Foundation (ASF) under one
  72781. * or more contributor license agreements. See the NOTICE file
  72782. * distributed with this work for additional information
  72783. * regarding copyright ownership. The ASF licenses this file
  72784. * to you under the Apache License, Version 2.0 (the
  72785. * "License"); you may not use this file except in compliance
  72786. * with the License. You may obtain a copy of the License at
  72787. *
  72788. * http://www.apache.org/licenses/LICENSE-2.0
  72789. *
  72790. * Unless required by applicable law or agreed to in writing,
  72791. * software distributed under the License is distributed on an
  72792. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72793. * KIND, either express or implied. See the License for the
  72794. * specific language governing permissions and limitations
  72795. * under the License.
  72796. */
  72797. var linearMap$3 = linearMap;
  72798. var each$26 = each$1;
  72799. var mathMin$7 = Math.min;
  72800. var mathMax$7 = Math.max;
  72801. // Arbitrary value
  72802. var HOVER_LINK_SIZE = 12;
  72803. var HOVER_LINK_OUT = 6;
  72804. // Notice:
  72805. // Any "interval" should be by the order of [low, high].
  72806. // "handle0" (handleIndex === 0) maps to
  72807. // low data value: this._dataInterval[0] and has low coord.
  72808. // "handle1" (handleIndex === 1) maps to
  72809. // high data value: this._dataInterval[1] and has high coord.
  72810. // The logic of transform is implemented in this._createBarGroup.
  72811. var ContinuousView = VisualMapView.extend({
  72812. type: 'visualMap.continuous',
  72813. /**
  72814. * @override
  72815. */
  72816. init: function () {
  72817. ContinuousView.superApply(this, 'init', arguments);
  72818. /**
  72819. * @private
  72820. */
  72821. this._shapes = {};
  72822. /**
  72823. * @private
  72824. */
  72825. this._dataInterval = [];
  72826. /**
  72827. * @private
  72828. */
  72829. this._handleEnds = [];
  72830. /**
  72831. * @private
  72832. */
  72833. this._orient;
  72834. /**
  72835. * @private
  72836. */
  72837. this._useHandle;
  72838. /**
  72839. * @private
  72840. */
  72841. this._hoverLinkDataIndices = [];
  72842. /**
  72843. * @private
  72844. */
  72845. this._dragging;
  72846. /**
  72847. * @private
  72848. */
  72849. this._hovering;
  72850. },
  72851. /**
  72852. * @protected
  72853. * @override
  72854. */
  72855. doRender: function (visualMapModel, ecModel, api, payload) {
  72856. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  72857. this._buildView();
  72858. }
  72859. },
  72860. /**
  72861. * @private
  72862. */
  72863. _buildView: function () {
  72864. this.group.removeAll();
  72865. var visualMapModel = this.visualMapModel;
  72866. var thisGroup = this.group;
  72867. this._orient = visualMapModel.get('orient');
  72868. this._useHandle = visualMapModel.get('calculable');
  72869. this._resetInterval();
  72870. this._renderBar(thisGroup);
  72871. var dataRangeText = visualMapModel.get('text');
  72872. this._renderEndsText(thisGroup, dataRangeText, 0);
  72873. this._renderEndsText(thisGroup, dataRangeText, 1);
  72874. // Do this for background size calculation.
  72875. this._updateView(true);
  72876. // After updating view, inner shapes is built completely,
  72877. // and then background can be rendered.
  72878. this.renderBackground(thisGroup);
  72879. // Real update view
  72880. this._updateView();
  72881. this._enableHoverLinkToSeries();
  72882. this._enableHoverLinkFromSeries();
  72883. this.positionGroup(thisGroup);
  72884. },
  72885. /**
  72886. * @private
  72887. */
  72888. _renderEndsText: function (group, dataRangeText, endsIndex) {
  72889. if (!dataRangeText) {
  72890. return;
  72891. }
  72892. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  72893. var text = dataRangeText[1 - endsIndex];
  72894. text = text != null ? text + '' : '';
  72895. var visualMapModel = this.visualMapModel;
  72896. var textGap = visualMapModel.get('textGap');
  72897. var itemSize = visualMapModel.itemSize;
  72898. var barGroup = this._shapes.barGroup;
  72899. var position = this._applyTransform(
  72900. [
  72901. itemSize[0] / 2,
  72902. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  72903. ],
  72904. barGroup
  72905. );
  72906. var align = this._applyTransform(
  72907. endsIndex === 0 ? 'bottom' : 'top',
  72908. barGroup
  72909. );
  72910. var orient = this._orient;
  72911. var textStyleModel = this.visualMapModel.textStyleModel;
  72912. this.group.add(new Text({
  72913. style: {
  72914. x: position[0],
  72915. y: position[1],
  72916. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  72917. textAlign: orient === 'horizontal' ? align : 'center',
  72918. text: text,
  72919. textFont: textStyleModel.getFont(),
  72920. textFill: textStyleModel.getTextColor()
  72921. }
  72922. }));
  72923. },
  72924. /**
  72925. * @private
  72926. */
  72927. _renderBar: function (targetGroup) {
  72928. var visualMapModel = this.visualMapModel;
  72929. var shapes = this._shapes;
  72930. var itemSize = visualMapModel.itemSize;
  72931. var orient = this._orient;
  72932. var useHandle = this._useHandle;
  72933. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  72934. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  72935. // Bar
  72936. barGroup.add(shapes.outOfRange = createPolygon());
  72937. barGroup.add(shapes.inRange = createPolygon(
  72938. null,
  72939. useHandle ? getCursor$1(this._orient) : null,
  72940. bind(this._dragHandle, this, 'all', false),
  72941. bind(this._dragHandle, this, 'all', true)
  72942. ));
  72943. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  72944. var textSize = mathMax$7(textRect.width, textRect.height);
  72945. // Handle
  72946. if (useHandle) {
  72947. shapes.handleThumbs = [];
  72948. shapes.handleLabels = [];
  72949. shapes.handleLabelPoints = [];
  72950. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  72951. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  72952. }
  72953. this._createIndicator(barGroup, itemSize, textSize, orient);
  72954. targetGroup.add(barGroup);
  72955. },
  72956. /**
  72957. * @private
  72958. */
  72959. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  72960. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  72961. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  72962. var handleThumb = createPolygon(
  72963. createHandlePoints(handleIndex, textSize),
  72964. getCursor$1(this._orient),
  72965. onDrift,
  72966. onDragEnd
  72967. );
  72968. handleThumb.position[0] = itemSize[0];
  72969. barGroup.add(handleThumb);
  72970. // Text is always horizontal layout but should not be effected by
  72971. // transform (orient/inverse). So label is built separately but not
  72972. // use zrender/graphic/helper/RectText, and is located based on view
  72973. // group (according to handleLabelPoint) but not barGroup.
  72974. var textStyleModel = this.visualMapModel.textStyleModel;
  72975. var handleLabel = new Text({
  72976. draggable: true,
  72977. drift: onDrift,
  72978. onmousemove: function (e) {
  72979. // Fot mobile devicem, prevent screen slider on the button.
  72980. stop(e.event);
  72981. },
  72982. ondragend: onDragEnd,
  72983. style: {
  72984. x: 0, y: 0, text: '',
  72985. textFont: textStyleModel.getFont(),
  72986. textFill: textStyleModel.getTextColor()
  72987. }
  72988. });
  72989. this.group.add(handleLabel);
  72990. var handleLabelPoint = [
  72991. orient === 'horizontal'
  72992. ? textSize / 2
  72993. : textSize * 1.5,
  72994. orient === 'horizontal'
  72995. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  72996. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  72997. ];
  72998. var shapes = this._shapes;
  72999. shapes.handleThumbs[handleIndex] = handleThumb;
  73000. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  73001. shapes.handleLabels[handleIndex] = handleLabel;
  73002. },
  73003. /**
  73004. * @private
  73005. */
  73006. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  73007. var indicator = createPolygon([[0, 0]], 'move');
  73008. indicator.position[0] = itemSize[0];
  73009. indicator.attr({invisible: true, silent: true});
  73010. barGroup.add(indicator);
  73011. var textStyleModel = this.visualMapModel.textStyleModel;
  73012. var indicatorLabel = new Text({
  73013. silent: true,
  73014. invisible: true,
  73015. style: {
  73016. x: 0, y: 0, text: '',
  73017. textFont: textStyleModel.getFont(),
  73018. textFill: textStyleModel.getTextColor()
  73019. }
  73020. });
  73021. this.group.add(indicatorLabel);
  73022. var indicatorLabelPoint = [
  73023. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  73024. 0
  73025. ];
  73026. var shapes = this._shapes;
  73027. shapes.indicator = indicator;
  73028. shapes.indicatorLabel = indicatorLabel;
  73029. shapes.indicatorLabelPoint = indicatorLabelPoint;
  73030. },
  73031. /**
  73032. * @private
  73033. */
  73034. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  73035. if (!this._useHandle) {
  73036. return;
  73037. }
  73038. this._dragging = !isEnd;
  73039. if (!isEnd) {
  73040. // Transform dx, dy to bar coordination.
  73041. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  73042. this._updateInterval(handleIndex, vertex[1]);
  73043. // Considering realtime, update view should be executed
  73044. // before dispatch action.
  73045. this._updateView();
  73046. }
  73047. // dragEnd do not dispatch action when realtime.
  73048. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  73049. this.api.dispatchAction({
  73050. type: 'selectDataRange',
  73051. from: this.uid,
  73052. visualMapId: this.visualMapModel.id,
  73053. selected: this._dataInterval.slice()
  73054. });
  73055. }
  73056. if (isEnd) {
  73057. !this._hovering && this._clearHoverLinkToSeries();
  73058. }
  73059. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  73060. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  73061. }
  73062. },
  73063. /**
  73064. * @private
  73065. */
  73066. _resetInterval: function () {
  73067. var visualMapModel = this.visualMapModel;
  73068. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  73069. var dataExtent = visualMapModel.getExtent();
  73070. var sizeExtent = [0, visualMapModel.itemSize[1]];
  73071. this._handleEnds = [
  73072. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  73073. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  73074. ];
  73075. },
  73076. /**
  73077. * @private
  73078. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  73079. * @param {number} dx
  73080. * @param {number} dy
  73081. */
  73082. _updateInterval: function (handleIndex, delta) {
  73083. delta = delta || 0;
  73084. var visualMapModel = this.visualMapModel;
  73085. var handleEnds = this._handleEnds;
  73086. var sizeExtent = [0, visualMapModel.itemSize[1]];
  73087. sliderMove(
  73088. delta,
  73089. handleEnds,
  73090. sizeExtent,
  73091. handleIndex,
  73092. // cross is forbiden
  73093. 0
  73094. );
  73095. var dataExtent = visualMapModel.getExtent();
  73096. // Update data interval.
  73097. this._dataInterval = [
  73098. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  73099. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  73100. ];
  73101. },
  73102. /**
  73103. * @private
  73104. */
  73105. _updateView: function (forSketch) {
  73106. var visualMapModel = this.visualMapModel;
  73107. var dataExtent = visualMapModel.getExtent();
  73108. var shapes = this._shapes;
  73109. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  73110. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  73111. var visualInRange = this._createBarVisual(
  73112. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  73113. );
  73114. var visualOutOfRange = this._createBarVisual(
  73115. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  73116. );
  73117. shapes.inRange
  73118. .setStyle({
  73119. fill: visualInRange.barColor,
  73120. opacity: visualInRange.opacity
  73121. })
  73122. .setShape('points', visualInRange.barPoints);
  73123. shapes.outOfRange
  73124. .setStyle({
  73125. fill: visualOutOfRange.barColor,
  73126. opacity: visualOutOfRange.opacity
  73127. })
  73128. .setShape('points', visualOutOfRange.barPoints);
  73129. this._updateHandle(inRangeHandleEnds, visualInRange);
  73130. },
  73131. /**
  73132. * @private
  73133. */
  73134. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  73135. var opts = {
  73136. forceState: forceState,
  73137. convertOpacityToAlpha: true
  73138. };
  73139. var colorStops = this._makeColorGradient(dataInterval, opts);
  73140. var symbolSizes = [
  73141. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  73142. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  73143. ];
  73144. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  73145. return {
  73146. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  73147. barPoints: barPoints,
  73148. handlesColor: [
  73149. colorStops[0].color,
  73150. colorStops[colorStops.length - 1].color
  73151. ]
  73152. };
  73153. },
  73154. /**
  73155. * @private
  73156. */
  73157. _makeColorGradient: function (dataInterval, opts) {
  73158. // Considering colorHue, which is not linear, so we have to sample
  73159. // to calculate gradient color stops, but not only caculate head
  73160. // and tail.
  73161. var sampleNumber = 100; // Arbitrary value.
  73162. var colorStops = [];
  73163. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  73164. colorStops.push({
  73165. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  73166. offset: 0
  73167. });
  73168. for (var i = 1; i < sampleNumber; i++) {
  73169. var currValue = dataInterval[0] + step * i;
  73170. if (currValue > dataInterval[1]) {
  73171. break;
  73172. }
  73173. colorStops.push({
  73174. color: this.getControllerVisual(currValue, 'color', opts),
  73175. offset: i / sampleNumber
  73176. });
  73177. }
  73178. colorStops.push({
  73179. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  73180. offset: 1
  73181. });
  73182. return colorStops;
  73183. },
  73184. /**
  73185. * @private
  73186. */
  73187. _createBarPoints: function (handleEnds, symbolSizes) {
  73188. var itemSize = this.visualMapModel.itemSize;
  73189. return [
  73190. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  73191. [itemSize[0], handleEnds[0]],
  73192. [itemSize[0], handleEnds[1]],
  73193. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  73194. ];
  73195. },
  73196. /**
  73197. * @private
  73198. */
  73199. _createBarGroup: function (itemAlign) {
  73200. var orient = this._orient;
  73201. var inverse = this.visualMapModel.get('inverse');
  73202. return new Group(
  73203. (orient === 'horizontal' && !inverse)
  73204. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  73205. : (orient === 'horizontal' && inverse)
  73206. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  73207. : (orient === 'vertical' && !inverse)
  73208. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  73209. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  73210. );
  73211. },
  73212. /**
  73213. * @private
  73214. */
  73215. _updateHandle: function (handleEnds, visualInRange) {
  73216. if (!this._useHandle) {
  73217. return;
  73218. }
  73219. var shapes = this._shapes;
  73220. var visualMapModel = this.visualMapModel;
  73221. var handleThumbs = shapes.handleThumbs;
  73222. var handleLabels = shapes.handleLabels;
  73223. each$26([0, 1], function (handleIndex) {
  73224. var handleThumb = handleThumbs[handleIndex];
  73225. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  73226. handleThumb.position[1] = handleEnds[handleIndex];
  73227. // Update handle label position.
  73228. var textPoint = applyTransform$1(
  73229. shapes.handleLabelPoints[handleIndex],
  73230. getTransform(handleThumb, this.group)
  73231. );
  73232. handleLabels[handleIndex].setStyle({
  73233. x: textPoint[0],
  73234. y: textPoint[1],
  73235. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  73236. textVerticalAlign: 'middle',
  73237. textAlign: this._applyTransform(
  73238. this._orient === 'horizontal'
  73239. ? (handleIndex === 0 ? 'bottom' : 'top')
  73240. : 'left',
  73241. shapes.barGroup
  73242. )
  73243. });
  73244. }, this);
  73245. },
  73246. /**
  73247. * @private
  73248. * @param {number} cursorValue
  73249. * @param {number} textValue
  73250. * @param {string} [rangeSymbol]
  73251. * @param {number} [halfHoverLinkSize]
  73252. */
  73253. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  73254. var visualMapModel = this.visualMapModel;
  73255. var dataExtent = visualMapModel.getExtent();
  73256. var itemSize = visualMapModel.itemSize;
  73257. var sizeExtent = [0, itemSize[1]];
  73258. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  73259. var shapes = this._shapes;
  73260. var indicator = shapes.indicator;
  73261. if (!indicator) {
  73262. return;
  73263. }
  73264. indicator.position[1] = pos;
  73265. indicator.attr('invisible', false);
  73266. indicator.setShape('points', createIndicatorPoints(
  73267. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  73268. ));
  73269. var opts = {convertOpacityToAlpha: true};
  73270. var color = this.getControllerVisual(cursorValue, 'color', opts);
  73271. indicator.setStyle('fill', color);
  73272. // Update handle label position.
  73273. var textPoint = applyTransform$1(
  73274. shapes.indicatorLabelPoint,
  73275. getTransform(indicator, this.group)
  73276. );
  73277. var indicatorLabel = shapes.indicatorLabel;
  73278. indicatorLabel.attr('invisible', false);
  73279. var align = this._applyTransform('left', shapes.barGroup);
  73280. var orient = this._orient;
  73281. indicatorLabel.setStyle({
  73282. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  73283. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  73284. textAlign: orient === 'horizontal' ? 'center' : align,
  73285. x: textPoint[0],
  73286. y: textPoint[1]
  73287. });
  73288. },
  73289. /**
  73290. * @private
  73291. */
  73292. _enableHoverLinkToSeries: function () {
  73293. var self = this;
  73294. this._shapes.barGroup
  73295. .on('mousemove', function (e) {
  73296. self._hovering = true;
  73297. if (!self._dragging) {
  73298. var itemSize = self.visualMapModel.itemSize;
  73299. var pos = self._applyTransform(
  73300. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  73301. );
  73302. // For hover link show when hover handle, which might be
  73303. // below or upper than sizeExtent.
  73304. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  73305. self._doHoverLinkToSeries(
  73306. pos[1],
  73307. 0 <= pos[0] && pos[0] <= itemSize[0]
  73308. );
  73309. }
  73310. })
  73311. .on('mouseout', function () {
  73312. // When mouse is out of handle, hoverLink still need
  73313. // to be displayed when realtime is set as false.
  73314. self._hovering = false;
  73315. !self._dragging && self._clearHoverLinkToSeries();
  73316. });
  73317. },
  73318. /**
  73319. * @private
  73320. */
  73321. _enableHoverLinkFromSeries: function () {
  73322. var zr = this.api.getZr();
  73323. if (this.visualMapModel.option.hoverLink) {
  73324. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  73325. zr.on('mouseout', this._hideIndicator, this);
  73326. }
  73327. else {
  73328. this._clearHoverLinkFromSeries();
  73329. }
  73330. },
  73331. /**
  73332. * @private
  73333. */
  73334. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  73335. var visualMapModel = this.visualMapModel;
  73336. var itemSize = visualMapModel.itemSize;
  73337. if (!visualMapModel.option.hoverLink) {
  73338. return;
  73339. }
  73340. var sizeExtent = [0, itemSize[1]];
  73341. var dataExtent = visualMapModel.getExtent();
  73342. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  73343. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  73344. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  73345. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  73346. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  73347. var valueRange = [
  73348. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  73349. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  73350. ];
  73351. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  73352. // where china and india has very large population.
  73353. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  73354. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  73355. // Do not show indicator when mouse is over handle,
  73356. // otherwise labels overlap, especially when dragging.
  73357. if (hoverOnBar) {
  73358. if (valueRange[0] === -Infinity) {
  73359. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  73360. }
  73361. else if (valueRange[1] === Infinity) {
  73362. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  73363. }
  73364. else {
  73365. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  73366. }
  73367. }
  73368. // When realtime is set as false, handles, which are in barGroup,
  73369. // also trigger hoverLink, which help user to realize where they
  73370. // focus on when dragging. (see test/heatmap-large.html)
  73371. // When realtime is set as true, highlight will not show when hover
  73372. // handle, because the label on handle, which displays a exact value
  73373. // but not range, might mislead users.
  73374. var oldBatch = this._hoverLinkDataIndices;
  73375. var newBatch = [];
  73376. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  73377. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  73378. }
  73379. var resultBatches = compressBatches(oldBatch, newBatch);
  73380. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  73381. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  73382. },
  73383. /**
  73384. * @private
  73385. */
  73386. _hoverLinkFromSeriesMouseOver: function (e) {
  73387. var el = e.target;
  73388. var visualMapModel = this.visualMapModel;
  73389. if (!el || el.dataIndex == null) {
  73390. return;
  73391. }
  73392. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  73393. if (!visualMapModel.isTargetSeries(dataModel)) {
  73394. return;
  73395. }
  73396. var data = dataModel.getData(el.dataType);
  73397. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  73398. if (!isNaN(value)) {
  73399. this._showIndicator(value, value);
  73400. }
  73401. },
  73402. /**
  73403. * @private
  73404. */
  73405. _hideIndicator: function () {
  73406. var shapes = this._shapes;
  73407. shapes.indicator && shapes.indicator.attr('invisible', true);
  73408. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  73409. },
  73410. /**
  73411. * @private
  73412. */
  73413. _clearHoverLinkToSeries: function () {
  73414. this._hideIndicator();
  73415. var indices = this._hoverLinkDataIndices;
  73416. this._dispatchHighDown('downplay', convertDataIndex(indices));
  73417. indices.length = 0;
  73418. },
  73419. /**
  73420. * @private
  73421. */
  73422. _clearHoverLinkFromSeries: function () {
  73423. this._hideIndicator();
  73424. var zr = this.api.getZr();
  73425. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  73426. zr.off('mouseout', this._hideIndicator);
  73427. },
  73428. /**
  73429. * @private
  73430. */
  73431. _applyTransform: function (vertex, element, inverse, global) {
  73432. var transform = getTransform(element, global ? null : this.group);
  73433. return graphic[
  73434. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  73435. ](vertex, transform, inverse);
  73436. },
  73437. /**
  73438. * @private
  73439. */
  73440. _dispatchHighDown: function (type, batch) {
  73441. batch && batch.length && this.api.dispatchAction({
  73442. type: type,
  73443. batch: batch
  73444. });
  73445. },
  73446. /**
  73447. * @override
  73448. */
  73449. dispose: function () {
  73450. this._clearHoverLinkFromSeries();
  73451. this._clearHoverLinkToSeries();
  73452. },
  73453. /**
  73454. * @override
  73455. */
  73456. remove: function () {
  73457. this._clearHoverLinkFromSeries();
  73458. this._clearHoverLinkToSeries();
  73459. }
  73460. });
  73461. function createPolygon(points, cursor, onDrift, onDragEnd) {
  73462. return new Polygon({
  73463. shape: {points: points},
  73464. draggable: !!onDrift,
  73465. cursor: cursor,
  73466. drift: onDrift,
  73467. onmousemove: function (e) {
  73468. // Fot mobile devicem, prevent screen slider on the button.
  73469. stop(e.event);
  73470. },
  73471. ondragend: onDragEnd
  73472. });
  73473. }
  73474. function createHandlePoints(handleIndex, textSize) {
  73475. return handleIndex === 0
  73476. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  73477. : [[0, 0], [textSize, 0], [textSize, textSize]];
  73478. }
  73479. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  73480. return isRange
  73481. ? [ // indicate range
  73482. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  73483. [HOVER_LINK_OUT, 0],
  73484. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  73485. ]
  73486. : [ // indicate single value
  73487. [0, 0], [5, -5], [5, 5]
  73488. ];
  73489. }
  73490. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  73491. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  73492. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  73493. if (hoverLinkDataSize) {
  73494. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  73495. }
  73496. return halfHoverLinkSize;
  73497. }
  73498. function useHoverLinkOnHandle(visualMapModel) {
  73499. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  73500. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  73501. }
  73502. function getCursor$1(orient) {
  73503. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  73504. }
  73505. /*
  73506. * Licensed to the Apache Software Foundation (ASF) under one
  73507. * or more contributor license agreements. See the NOTICE file
  73508. * distributed with this work for additional information
  73509. * regarding copyright ownership. The ASF licenses this file
  73510. * to you under the Apache License, Version 2.0 (the
  73511. * "License"); you may not use this file except in compliance
  73512. * with the License. You may obtain a copy of the License at
  73513. *
  73514. * http://www.apache.org/licenses/LICENSE-2.0
  73515. *
  73516. * Unless required by applicable law or agreed to in writing,
  73517. * software distributed under the License is distributed on an
  73518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73519. * KIND, either express or implied. See the License for the
  73520. * specific language governing permissions and limitations
  73521. * under the License.
  73522. */
  73523. var actionInfo$2 = {
  73524. type: 'selectDataRange',
  73525. event: 'dataRangeSelected',
  73526. // FIXME use updateView appears wrong
  73527. update: 'update'
  73528. };
  73529. registerAction(actionInfo$2, function (payload, ecModel) {
  73530. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  73531. model.setSelected(payload.selected);
  73532. });
  73533. });
  73534. /*
  73535. * Licensed to the Apache Software Foundation (ASF) under one
  73536. * or more contributor license agreements. See the NOTICE file
  73537. * distributed with this work for additional information
  73538. * regarding copyright ownership. The ASF licenses this file
  73539. * to you under the Apache License, Version 2.0 (the
  73540. * "License"); you may not use this file except in compliance
  73541. * with the License. You may obtain a copy of the License at
  73542. *
  73543. * http://www.apache.org/licenses/LICENSE-2.0
  73544. *
  73545. * Unless required by applicable law or agreed to in writing,
  73546. * software distributed under the License is distributed on an
  73547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73548. * KIND, either express or implied. See the License for the
  73549. * specific language governing permissions and limitations
  73550. * under the License.
  73551. */
  73552. /**
  73553. * DataZoom component entry
  73554. */
  73555. registerPreprocessor(preprocessor$2);
  73556. /*
  73557. * Licensed to the Apache Software Foundation (ASF) under one
  73558. * or more contributor license agreements. See the NOTICE file
  73559. * distributed with this work for additional information
  73560. * regarding copyright ownership. The ASF licenses this file
  73561. * to you under the Apache License, Version 2.0 (the
  73562. * "License"); you may not use this file except in compliance
  73563. * with the License. You may obtain a copy of the License at
  73564. *
  73565. * http://www.apache.org/licenses/LICENSE-2.0
  73566. *
  73567. * Unless required by applicable law or agreed to in writing,
  73568. * software distributed under the License is distributed on an
  73569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73570. * KIND, either express or implied. See the License for the
  73571. * specific language governing permissions and limitations
  73572. * under the License.
  73573. */
  73574. var PiecewiseModel = VisualMapModel.extend({
  73575. type: 'visualMap.piecewise',
  73576. /**
  73577. * Order Rule:
  73578. *
  73579. * option.categories / option.pieces / option.text / option.selected:
  73580. * If !option.inverse,
  73581. * Order when vertical: ['top', ..., 'bottom'].
  73582. * Order when horizontal: ['left', ..., 'right'].
  73583. * If option.inverse, the meaning of
  73584. * the order should be reversed.
  73585. *
  73586. * this._pieceList:
  73587. * The order is always [low, ..., high].
  73588. *
  73589. * Mapping from location to low-high:
  73590. * If !option.inverse
  73591. * When vertical, top is high.
  73592. * When horizontal, right is high.
  73593. * If option.inverse, reverse.
  73594. */
  73595. /**
  73596. * @protected
  73597. */
  73598. defaultOption: {
  73599. selected: null, // Object. If not specified, means selected.
  73600. // When pieces and splitNumber: {'0': true, '5': true}
  73601. // When categories: {'cate1': false, 'cate3': true}
  73602. // When selected === false, means all unselected.
  73603. minOpen: false, // Whether include values that smaller than `min`.
  73604. maxOpen: false, // Whether include values that bigger than `max`.
  73605. align: 'auto', // 'auto', 'left', 'right'
  73606. itemWidth: 20, // When put the controller vertically, it is the length of
  73607. // horizontal side of each item. Otherwise, vertical side.
  73608. itemHeight: 14, // When put the controller vertically, it is the length of
  73609. // vertical side of each item. Otherwise, horizontal side.
  73610. itemSymbol: 'roundRect',
  73611. pieceList: null, // Each item is Object, with some of those attrs:
  73612. // {min, max, lt, gt, lte, gte, value,
  73613. // color, colorSaturation, colorAlpha, opacity,
  73614. // symbol, symbolSize}, which customize the range or visual
  73615. // coding of the certain piece. Besides, see "Order Rule".
  73616. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  73617. // Attr min/max are ignored when categories set. See "Order Rule"
  73618. splitNumber: 5, // If set to 5, auto split five pieces equally.
  73619. // If set to 0 and component type not set, component type will be
  73620. // determined as "continuous". (It is less reasonable but for ec2
  73621. // compatibility, see echarts/component/visualMap/typeDefaulter)
  73622. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  73623. itemGap: 10, // The gap between two items, in px.
  73624. hoverLink: true, // Enable hover highlight.
  73625. showLabel: null // By default, when text is used, label will hide (the logic
  73626. // is remained for compatibility reason)
  73627. },
  73628. /**
  73629. * @override
  73630. */
  73631. optionUpdated: function (newOption, isInit) {
  73632. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  73633. /**
  73634. * The order is always [low, ..., high].
  73635. * [{text: string, interval: Array.<number>}, ...]
  73636. * @private
  73637. * @type {Array.<Object>}
  73638. */
  73639. this._pieceList = [];
  73640. this.resetExtent();
  73641. /**
  73642. * 'pieces', 'categories', 'splitNumber'
  73643. * @type {string}
  73644. */
  73645. var mode = this._mode = this._determineMode();
  73646. resetMethods[this._mode].call(this);
  73647. this._resetSelected(newOption, isInit);
  73648. var categories = this.option.categories;
  73649. this.resetVisual(function (mappingOption, state) {
  73650. if (mode === 'categories') {
  73651. mappingOption.mappingMethod = 'category';
  73652. mappingOption.categories = clone(categories);
  73653. }
  73654. else {
  73655. mappingOption.dataExtent = this.getExtent();
  73656. mappingOption.mappingMethod = 'piecewise';
  73657. mappingOption.pieceList = map(this._pieceList, function (piece) {
  73658. var piece = clone(piece);
  73659. if (state !== 'inRange') {
  73660. // FIXME
  73661. // outOfRange do not support special visual in pieces.
  73662. piece.visual = null;
  73663. }
  73664. return piece;
  73665. });
  73666. }
  73667. });
  73668. },
  73669. /**
  73670. * @protected
  73671. * @override
  73672. */
  73673. completeVisualOption: function () {
  73674. // Consider this case:
  73675. // visualMap: {
  73676. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  73677. // }
  73678. // where no inRange/outOfRange set but only pieces. So we should make
  73679. // default inRange/outOfRange for this case, otherwise visuals that only
  73680. // appear in `pieces` will not be taken into account in visual encoding.
  73681. var option = this.option;
  73682. var visualTypesInPieces = {};
  73683. var visualTypes = VisualMapping.listVisualTypes();
  73684. var isCategory = this.isCategory();
  73685. each$1(option.pieces, function (piece) {
  73686. each$1(visualTypes, function (visualType) {
  73687. if (piece.hasOwnProperty(visualType)) {
  73688. visualTypesInPieces[visualType] = 1;
  73689. }
  73690. });
  73691. });
  73692. each$1(visualTypesInPieces, function (v, visualType) {
  73693. var exists = 0;
  73694. each$1(this.stateList, function (state) {
  73695. exists |= has(option, state, visualType)
  73696. || has(option.target, state, visualType);
  73697. }, this);
  73698. !exists && each$1(this.stateList, function (state) {
  73699. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  73700. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  73701. );
  73702. });
  73703. }, this);
  73704. function has(obj, state, visualType) {
  73705. return obj && obj[state] && (
  73706. isObject$1(obj[state])
  73707. ? obj[state].hasOwnProperty(visualType)
  73708. : obj[state] === visualType // e.g., inRange: 'symbol'
  73709. );
  73710. }
  73711. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  73712. },
  73713. _resetSelected: function (newOption, isInit) {
  73714. var thisOption = this.option;
  73715. var pieceList = this._pieceList;
  73716. // Selected do not merge but all override.
  73717. var selected = (isInit ? thisOption : newOption).selected || {};
  73718. thisOption.selected = selected;
  73719. // Consider 'not specified' means true.
  73720. each$1(pieceList, function (piece, index) {
  73721. var key = this.getSelectedMapKey(piece);
  73722. if (!selected.hasOwnProperty(key)) {
  73723. selected[key] = true;
  73724. }
  73725. }, this);
  73726. if (thisOption.selectedMode === 'single') {
  73727. // Ensure there is only one selected.
  73728. var hasSel = false;
  73729. each$1(pieceList, function (piece, index) {
  73730. var key = this.getSelectedMapKey(piece);
  73731. if (selected[key]) {
  73732. hasSel
  73733. ? (selected[key] = false)
  73734. : (hasSel = true);
  73735. }
  73736. }, this);
  73737. }
  73738. // thisOption.selectedMode === 'multiple', default: all selected.
  73739. },
  73740. /**
  73741. * @public
  73742. */
  73743. getSelectedMapKey: function (piece) {
  73744. return this._mode === 'categories'
  73745. ? piece.value + '' : piece.index + '';
  73746. },
  73747. /**
  73748. * @public
  73749. */
  73750. getPieceList: function () {
  73751. return this._pieceList;
  73752. },
  73753. /**
  73754. * @private
  73755. * @return {string}
  73756. */
  73757. _determineMode: function () {
  73758. var option = this.option;
  73759. return option.pieces && option.pieces.length > 0
  73760. ? 'pieces'
  73761. : this.option.categories
  73762. ? 'categories'
  73763. : 'splitNumber';
  73764. },
  73765. /**
  73766. * @public
  73767. * @override
  73768. */
  73769. setSelected: function (selected) {
  73770. this.option.selected = clone(selected);
  73771. },
  73772. /**
  73773. * @public
  73774. * @override
  73775. */
  73776. getValueState: function (value) {
  73777. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  73778. return index != null
  73779. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  73780. ? 'inRange' : 'outOfRange'
  73781. )
  73782. : 'outOfRange';
  73783. },
  73784. /**
  73785. * @public
  73786. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  73787. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  73788. */
  73789. findTargetDataIndices: function (pieceIndex) {
  73790. var result = [];
  73791. this.eachTargetSeries(function (seriesModel) {
  73792. var dataIndices = [];
  73793. var data = seriesModel.getData();
  73794. data.each(this.getDataDimension(data), function (value, dataIndex) {
  73795. // Should always base on model pieceList, because it is order sensitive.
  73796. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  73797. pIdx === pieceIndex && dataIndices.push(dataIndex);
  73798. }, this);
  73799. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  73800. }, this);
  73801. return result;
  73802. },
  73803. /**
  73804. * @private
  73805. * @param {Object} piece piece.value or piece.interval is required.
  73806. * @return {number} Can be Infinity or -Infinity
  73807. */
  73808. getRepresentValue: function (piece) {
  73809. var representValue;
  73810. if (this.isCategory()) {
  73811. representValue = piece.value;
  73812. }
  73813. else {
  73814. if (piece.value != null) {
  73815. representValue = piece.value;
  73816. }
  73817. else {
  73818. var pieceInterval = piece.interval || [];
  73819. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  73820. ? 0
  73821. : (pieceInterval[0] + pieceInterval[1]) / 2;
  73822. }
  73823. }
  73824. return representValue;
  73825. },
  73826. getVisualMeta: function (getColorVisual) {
  73827. // Do not support category. (category axis is ordinal, numerical)
  73828. if (this.isCategory()) {
  73829. return;
  73830. }
  73831. var stops = [];
  73832. var outerColors = [];
  73833. var visualMapModel = this;
  73834. function setStop(interval, valueState) {
  73835. var representValue = visualMapModel.getRepresentValue({interval: interval});
  73836. if (!valueState) {
  73837. valueState = visualMapModel.getValueState(representValue);
  73838. }
  73839. var color = getColorVisual(representValue, valueState);
  73840. if (interval[0] === -Infinity) {
  73841. outerColors[0] = color;
  73842. }
  73843. else if (interval[1] === Infinity) {
  73844. outerColors[1] = color;
  73845. }
  73846. else {
  73847. stops.push(
  73848. {value: interval[0], color: color},
  73849. {value: interval[1], color: color}
  73850. );
  73851. }
  73852. }
  73853. // Suplement
  73854. var pieceList = this._pieceList.slice();
  73855. if (!pieceList.length) {
  73856. pieceList.push({interval: [-Infinity, Infinity]});
  73857. }
  73858. else {
  73859. var edge = pieceList[0].interval[0];
  73860. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  73861. edge = pieceList[pieceList.length - 1].interval[1];
  73862. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  73863. }
  73864. var curr = -Infinity;
  73865. each$1(pieceList, function (piece) {
  73866. var interval = piece.interval;
  73867. if (interval) {
  73868. // Fulfill gap.
  73869. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  73870. setStop(interval.slice());
  73871. curr = interval[1];
  73872. }
  73873. }, this);
  73874. return {stops: stops, outerColors: outerColors};
  73875. }
  73876. });
  73877. /**
  73878. * Key is this._mode
  73879. * @type {Object}
  73880. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  73881. */
  73882. var resetMethods = {
  73883. splitNumber: function () {
  73884. var thisOption = this.option;
  73885. var pieceList = this._pieceList;
  73886. var precision = Math.min(thisOption.precision, 20);
  73887. var dataExtent = this.getExtent();
  73888. var splitNumber = thisOption.splitNumber;
  73889. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  73890. thisOption.splitNumber = splitNumber;
  73891. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  73892. // Precision auto-adaption
  73893. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  73894. precision++;
  73895. }
  73896. thisOption.precision = precision;
  73897. splitStep = +splitStep.toFixed(precision);
  73898. var index = 0;
  73899. if (thisOption.minOpen) {
  73900. pieceList.push({
  73901. index: index++,
  73902. interval: [-Infinity, dataExtent[0]],
  73903. close: [0, 0]
  73904. });
  73905. }
  73906. for (
  73907. var curr = dataExtent[0], len = index + splitNumber;
  73908. index < len;
  73909. curr += splitStep
  73910. ) {
  73911. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  73912. pieceList.push({
  73913. index: index++,
  73914. interval: [curr, max],
  73915. close: [1, 1]
  73916. });
  73917. }
  73918. if (thisOption.maxOpen) {
  73919. pieceList.push({
  73920. index: index++,
  73921. interval: [dataExtent[1], Infinity],
  73922. close: [0, 0]
  73923. });
  73924. }
  73925. reformIntervals(pieceList);
  73926. each$1(pieceList, function (piece) {
  73927. piece.text = this.formatValueText(piece.interval);
  73928. }, this);
  73929. },
  73930. categories: function () {
  73931. var thisOption = this.option;
  73932. each$1(thisOption.categories, function (cate) {
  73933. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  73934. // 是否改一致。
  73935. this._pieceList.push({
  73936. text: this.formatValueText(cate, true),
  73937. value: cate
  73938. });
  73939. }, this);
  73940. // See "Order Rule".
  73941. normalizeReverse(thisOption, this._pieceList);
  73942. },
  73943. pieces: function () {
  73944. var thisOption = this.option;
  73945. var pieceList = this._pieceList;
  73946. each$1(thisOption.pieces, function (pieceListItem, index) {
  73947. if (!isObject$1(pieceListItem)) {
  73948. pieceListItem = {value: pieceListItem};
  73949. }
  73950. var item = {text: '', index: index};
  73951. if (pieceListItem.label != null) {
  73952. item.text = pieceListItem.label;
  73953. }
  73954. if (pieceListItem.hasOwnProperty('value')) {
  73955. var value = item.value = pieceListItem.value;
  73956. item.interval = [value, value];
  73957. item.close = [1, 1];
  73958. }
  73959. else {
  73960. // `min` `max` is legacy option.
  73961. // `lt` `gt` `lte` `gte` is recommanded.
  73962. var interval = item.interval = [];
  73963. var close = item.close = [0, 0];
  73964. var closeList = [1, 0, 1];
  73965. var infinityList = [-Infinity, Infinity];
  73966. var useMinMax = [];
  73967. for (var lg = 0; lg < 2; lg++) {
  73968. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  73969. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  73970. interval[lg] = pieceListItem[names[i]];
  73971. close[lg] = closeList[i];
  73972. useMinMax[lg] = i === 2;
  73973. }
  73974. interval[lg] == null && (interval[lg] = infinityList[lg]);
  73975. }
  73976. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  73977. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  73978. if (__DEV__) {
  73979. if (interval[0] > interval[1]) {
  73980. console.warn(
  73981. 'Piece ' + index + 'is illegal: ' + interval
  73982. + ' lower bound should not greater then uppper bound.'
  73983. );
  73984. }
  73985. }
  73986. if (interval[0] === interval[1] && close[0] && close[1]) {
  73987. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  73988. // we use value to lift the priority when min === max
  73989. item.value = interval[0];
  73990. }
  73991. }
  73992. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  73993. pieceList.push(item);
  73994. }, this);
  73995. // See "Order Rule".
  73996. normalizeReverse(thisOption, pieceList);
  73997. // Only pieces
  73998. reformIntervals(pieceList);
  73999. each$1(pieceList, function (piece) {
  74000. var close = piece.close;
  74001. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  74002. piece.text = piece.text || this.formatValueText(
  74003. piece.value != null ? piece.value : piece.interval,
  74004. false,
  74005. edgeSymbols
  74006. );
  74007. }, this);
  74008. }
  74009. };
  74010. function normalizeReverse(thisOption, pieceList) {
  74011. var inverse = thisOption.inverse;
  74012. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  74013. pieceList.reverse();
  74014. }
  74015. }
  74016. /*
  74017. * Licensed to the Apache Software Foundation (ASF) under one
  74018. * or more contributor license agreements. See the NOTICE file
  74019. * distributed with this work for additional information
  74020. * regarding copyright ownership. The ASF licenses this file
  74021. * to you under the Apache License, Version 2.0 (the
  74022. * "License"); you may not use this file except in compliance
  74023. * with the License. You may obtain a copy of the License at
  74024. *
  74025. * http://www.apache.org/licenses/LICENSE-2.0
  74026. *
  74027. * Unless required by applicable law or agreed to in writing,
  74028. * software distributed under the License is distributed on an
  74029. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74030. * KIND, either express or implied. See the License for the
  74031. * specific language governing permissions and limitations
  74032. * under the License.
  74033. */
  74034. var PiecewiseVisualMapView = VisualMapView.extend({
  74035. type: 'visualMap.piecewise',
  74036. /**
  74037. * @protected
  74038. * @override
  74039. */
  74040. doRender: function () {
  74041. var thisGroup = this.group;
  74042. thisGroup.removeAll();
  74043. var visualMapModel = this.visualMapModel;
  74044. var textGap = visualMapModel.get('textGap');
  74045. var textStyleModel = visualMapModel.textStyleModel;
  74046. var textFont = textStyleModel.getFont();
  74047. var textFill = textStyleModel.getTextColor();
  74048. var itemAlign = this._getItemAlign();
  74049. var itemSize = visualMapModel.itemSize;
  74050. var viewData = this._getViewData();
  74051. var endsText = viewData.endsText;
  74052. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  74053. endsText && this._renderEndsText(
  74054. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  74055. );
  74056. each$1(viewData.viewPieceList, renderItem, this);
  74057. endsText && this._renderEndsText(
  74058. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  74059. );
  74060. box(
  74061. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  74062. );
  74063. this.renderBackground(thisGroup);
  74064. this.positionGroup(thisGroup);
  74065. function renderItem(item) {
  74066. var piece = item.piece;
  74067. var itemGroup = new Group();
  74068. itemGroup.onclick = bind(this._onItemClick, this, piece);
  74069. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  74070. var representValue = visualMapModel.getRepresentValue(piece);
  74071. this._createItemSymbol(
  74072. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  74073. );
  74074. if (showLabel) {
  74075. var visualState = this.visualMapModel.getValueState(representValue);
  74076. itemGroup.add(new Text({
  74077. style: {
  74078. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  74079. y: itemSize[1] / 2,
  74080. text: piece.text,
  74081. textVerticalAlign: 'middle',
  74082. textAlign: itemAlign,
  74083. textFont: textFont,
  74084. textFill: textFill,
  74085. opacity: visualState === 'outOfRange' ? 0.5 : 1
  74086. }
  74087. }));
  74088. }
  74089. thisGroup.add(itemGroup);
  74090. }
  74091. },
  74092. /**
  74093. * @private
  74094. */
  74095. _enableHoverLink: function (itemGroup, pieceIndex) {
  74096. itemGroup
  74097. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  74098. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  74099. function onHoverLink(method) {
  74100. var visualMapModel = this.visualMapModel;
  74101. visualMapModel.option.hoverLink && this.api.dispatchAction({
  74102. type: method,
  74103. batch: convertDataIndex(
  74104. visualMapModel.findTargetDataIndices(pieceIndex)
  74105. )
  74106. });
  74107. }
  74108. },
  74109. /**
  74110. * @private
  74111. */
  74112. _getItemAlign: function () {
  74113. var visualMapModel = this.visualMapModel;
  74114. var modelOption = visualMapModel.option;
  74115. if (modelOption.orient === 'vertical') {
  74116. return getItemAlign(
  74117. visualMapModel, this.api, visualMapModel.itemSize
  74118. );
  74119. }
  74120. else { // horizontal, most case left unless specifying right.
  74121. var align = modelOption.align;
  74122. if (!align || align === 'auto') {
  74123. align = 'left';
  74124. }
  74125. return align;
  74126. }
  74127. },
  74128. /**
  74129. * @private
  74130. */
  74131. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  74132. if (!text) {
  74133. return;
  74134. }
  74135. var itemGroup = new Group();
  74136. var textStyleModel = this.visualMapModel.textStyleModel;
  74137. itemGroup.add(new Text({
  74138. style: {
  74139. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  74140. y: itemSize[1] / 2,
  74141. textVerticalAlign: 'middle',
  74142. textAlign: showLabel ? itemAlign : 'center',
  74143. text: text,
  74144. textFont: textStyleModel.getFont(),
  74145. textFill: textStyleModel.getTextColor()
  74146. }
  74147. }));
  74148. group.add(itemGroup);
  74149. },
  74150. /**
  74151. * @private
  74152. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  74153. */
  74154. _getViewData: function () {
  74155. var visualMapModel = this.visualMapModel;
  74156. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  74157. return {piece: piece, indexInModelPieceList: index};
  74158. });
  74159. var endsText = visualMapModel.get('text');
  74160. // Consider orient and inverse.
  74161. var orient = visualMapModel.get('orient');
  74162. var inverse = visualMapModel.get('inverse');
  74163. // Order of model pieceList is always [low, ..., high]
  74164. if (orient === 'horizontal' ? inverse : !inverse) {
  74165. viewPieceList.reverse();
  74166. }
  74167. // Origin order of endsText is [high, low]
  74168. else if (endsText) {
  74169. endsText = endsText.slice().reverse();
  74170. }
  74171. return {viewPieceList: viewPieceList, endsText: endsText};
  74172. },
  74173. /**
  74174. * @private
  74175. */
  74176. _createItemSymbol: function (group, representValue, shapeParam) {
  74177. group.add(createSymbol(
  74178. this.getControllerVisual(representValue, 'symbol'),
  74179. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  74180. this.getControllerVisual(representValue, 'color')
  74181. ));
  74182. },
  74183. /**
  74184. * @private
  74185. */
  74186. _onItemClick: function (piece) {
  74187. var visualMapModel = this.visualMapModel;
  74188. var option = visualMapModel.option;
  74189. var selected = clone(option.selected);
  74190. var newKey = visualMapModel.getSelectedMapKey(piece);
  74191. if (option.selectedMode === 'single') {
  74192. selected[newKey] = true;
  74193. each$1(selected, function (o, key) {
  74194. selected[key] = key === newKey;
  74195. });
  74196. }
  74197. else {
  74198. selected[newKey] = !selected[newKey];
  74199. }
  74200. this.api.dispatchAction({
  74201. type: 'selectDataRange',
  74202. from: this.uid,
  74203. visualMapId: this.visualMapModel.id,
  74204. selected: selected
  74205. });
  74206. }
  74207. });
  74208. /*
  74209. * Licensed to the Apache Software Foundation (ASF) under one
  74210. * or more contributor license agreements. See the NOTICE file
  74211. * distributed with this work for additional information
  74212. * regarding copyright ownership. The ASF licenses this file
  74213. * to you under the Apache License, Version 2.0 (the
  74214. * "License"); you may not use this file except in compliance
  74215. * with the License. You may obtain a copy of the License at
  74216. *
  74217. * http://www.apache.org/licenses/LICENSE-2.0
  74218. *
  74219. * Unless required by applicable law or agreed to in writing,
  74220. * software distributed under the License is distributed on an
  74221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74222. * KIND, either express or implied. See the License for the
  74223. * specific language governing permissions and limitations
  74224. * under the License.
  74225. */
  74226. /**
  74227. * DataZoom component entry
  74228. */
  74229. registerPreprocessor(preprocessor$2);
  74230. /*
  74231. * Licensed to the Apache Software Foundation (ASF) under one
  74232. * or more contributor license agreements. See the NOTICE file
  74233. * distributed with this work for additional information
  74234. * regarding copyright ownership. The ASF licenses this file
  74235. * to you under the Apache License, Version 2.0 (the
  74236. * "License"); you may not use this file except in compliance
  74237. * with the License. You may obtain a copy of the License at
  74238. *
  74239. * http://www.apache.org/licenses/LICENSE-2.0
  74240. *
  74241. * Unless required by applicable law or agreed to in writing,
  74242. * software distributed under the License is distributed on an
  74243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74244. * KIND, either express or implied. See the License for the
  74245. * specific language governing permissions and limitations
  74246. * under the License.
  74247. */
  74248. /**
  74249. * visualMap component entry
  74250. */
  74251. /*
  74252. * Licensed to the Apache Software Foundation (ASF) under one
  74253. * or more contributor license agreements. See the NOTICE file
  74254. * distributed with this work for additional information
  74255. * regarding copyright ownership. The ASF licenses this file
  74256. * to you under the Apache License, Version 2.0 (the
  74257. * "License"); you may not use this file except in compliance
  74258. * with the License. You may obtain a copy of the License at
  74259. *
  74260. * http://www.apache.org/licenses/LICENSE-2.0
  74261. *
  74262. * Unless required by applicable law or agreed to in writing,
  74263. * software distributed under the License is distributed on an
  74264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74265. * KIND, either express or implied. See the License for the
  74266. * specific language governing permissions and limitations
  74267. * under the License.
  74268. */
  74269. var addCommas$1 = addCommas;
  74270. var encodeHTML$1 = encodeHTML;
  74271. function fillLabel(opt) {
  74272. defaultEmphasis(opt, 'label', ['show']);
  74273. }
  74274. var MarkerModel = extendComponentModel({
  74275. type: 'marker',
  74276. dependencies: ['series', 'grid', 'polar', 'geo'],
  74277. /**
  74278. * @overrite
  74279. */
  74280. init: function (option, parentModel, ecModel, extraOpt) {
  74281. if (__DEV__) {
  74282. if (this.type === 'marker') {
  74283. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74284. }
  74285. }
  74286. this.mergeDefaultAndTheme(option, ecModel);
  74287. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  74288. },
  74289. /**
  74290. * @return {boolean}
  74291. */
  74292. isAnimationEnabled: function () {
  74293. if (env$1.node) {
  74294. return false;
  74295. }
  74296. var hostSeries = this.__hostSeries;
  74297. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74298. },
  74299. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  74300. var MarkerModel = this.constructor;
  74301. var modelPropName = this.mainType + 'Model';
  74302. if (!createdBySelf) {
  74303. ecModel.eachSeries(function (seriesModel) {
  74304. var markerOpt = seriesModel.get(this.mainType, true);
  74305. var markerModel = seriesModel[modelPropName];
  74306. if (!markerOpt || !markerOpt.data) {
  74307. seriesModel[modelPropName] = null;
  74308. return;
  74309. }
  74310. if (!markerModel) {
  74311. if (isInit) {
  74312. // Default label emphasis `position` and `show`
  74313. fillLabel(markerOpt);
  74314. }
  74315. each$1(markerOpt.data, function (item) {
  74316. // FIXME Overwrite fillLabel method ?
  74317. if (item instanceof Array) {
  74318. fillLabel(item[0]);
  74319. fillLabel(item[1]);
  74320. }
  74321. else {
  74322. fillLabel(item);
  74323. }
  74324. });
  74325. markerModel = new MarkerModel(
  74326. markerOpt, this, ecModel
  74327. );
  74328. extend(markerModel, {
  74329. mainType: this.mainType,
  74330. // Use the same series index and name
  74331. seriesIndex: seriesModel.seriesIndex,
  74332. name: seriesModel.name,
  74333. createdBySelf: true
  74334. });
  74335. markerModel.__hostSeries = seriesModel;
  74336. }
  74337. else {
  74338. markerModel.mergeOption(markerOpt, ecModel, true);
  74339. }
  74340. seriesModel[modelPropName] = markerModel;
  74341. }, this);
  74342. }
  74343. },
  74344. formatTooltip: function (dataIndex) {
  74345. var data = this.getData();
  74346. var value = this.getRawValue(dataIndex);
  74347. var formattedValue = isArray(value)
  74348. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  74349. var name = data.getName(dataIndex);
  74350. var html = encodeHTML$1(this.name);
  74351. if (value != null || name) {
  74352. html += '<br />';
  74353. }
  74354. if (name) {
  74355. html += encodeHTML$1(name);
  74356. if (value != null) {
  74357. html += ' : ';
  74358. }
  74359. }
  74360. if (value != null) {
  74361. html += encodeHTML$1(formattedValue);
  74362. }
  74363. return html;
  74364. },
  74365. getData: function () {
  74366. return this._data;
  74367. },
  74368. setData: function (data) {
  74369. this._data = data;
  74370. }
  74371. });
  74372. mixin(MarkerModel, dataFormatMixin);
  74373. /*
  74374. * Licensed to the Apache Software Foundation (ASF) under one
  74375. * or more contributor license agreements. See the NOTICE file
  74376. * distributed with this work for additional information
  74377. * regarding copyright ownership. The ASF licenses this file
  74378. * to you under the Apache License, Version 2.0 (the
  74379. * "License"); you may not use this file except in compliance
  74380. * with the License. You may obtain a copy of the License at
  74381. *
  74382. * http://www.apache.org/licenses/LICENSE-2.0
  74383. *
  74384. * Unless required by applicable law or agreed to in writing,
  74385. * software distributed under the License is distributed on an
  74386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74387. * KIND, either express or implied. See the License for the
  74388. * specific language governing permissions and limitations
  74389. * under the License.
  74390. */
  74391. MarkerModel.extend({
  74392. type: 'markPoint',
  74393. defaultOption: {
  74394. zlevel: 0,
  74395. z: 5,
  74396. symbol: 'pin',
  74397. symbolSize: 50,
  74398. //symbolRotate: 0,
  74399. //symbolOffset: [0, 0]
  74400. tooltip: {
  74401. trigger: 'item'
  74402. },
  74403. label: {
  74404. show: true,
  74405. position: 'inside'
  74406. },
  74407. itemStyle: {
  74408. borderWidth: 2
  74409. },
  74410. emphasis: {
  74411. label: {
  74412. show: true
  74413. }
  74414. }
  74415. }
  74416. });
  74417. /*
  74418. * Licensed to the Apache Software Foundation (ASF) under one
  74419. * or more contributor license agreements. See the NOTICE file
  74420. * distributed with this work for additional information
  74421. * regarding copyright ownership. The ASF licenses this file
  74422. * to you under the Apache License, Version 2.0 (the
  74423. * "License"); you may not use this file except in compliance
  74424. * with the License. You may obtain a copy of the License at
  74425. *
  74426. * http://www.apache.org/licenses/LICENSE-2.0
  74427. *
  74428. * Unless required by applicable law or agreed to in writing,
  74429. * software distributed under the License is distributed on an
  74430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74431. * KIND, either express or implied. See the License for the
  74432. * specific language governing permissions and limitations
  74433. * under the License.
  74434. */
  74435. var indexOf$2 = indexOf;
  74436. function hasXOrY(item) {
  74437. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74438. }
  74439. function hasXAndY(item) {
  74440. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74441. }
  74442. // Make it simple, do not visit all stacked value to count precision.
  74443. // function getPrecision(data, valueAxisDim, dataIndex) {
  74444. // var precision = -1;
  74445. // var stackedDim = data.mapDimension(valueAxisDim);
  74446. // do {
  74447. // precision = Math.max(
  74448. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  74449. // precision
  74450. // );
  74451. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  74452. // if (stackedOnSeries) {
  74453. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  74454. // data = stackedOnSeries.getData();
  74455. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  74456. // stackedDim = data.getCalculationInfo('stackedDimension');
  74457. // }
  74458. // else {
  74459. // data = null;
  74460. // }
  74461. // } while (data);
  74462. // return precision;
  74463. // }
  74464. function markerTypeCalculatorWithExtent(
  74465. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  74466. ) {
  74467. var coordArr = [];
  74468. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  74469. var calcDataDim = stacked
  74470. ? data.getCalculationInfo('stackResultDimension')
  74471. : targetDataDim;
  74472. var value = numCalculate(data, calcDataDim, mlType);
  74473. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74474. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74475. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  74476. // Make it simple, do not visit all stacked value to count precision.
  74477. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74478. precision = Math.min(precision, 20);
  74479. if (precision >= 0) {
  74480. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74481. }
  74482. return coordArr;
  74483. }
  74484. var curry$6 = curry;
  74485. // TODO Specified percent
  74486. var markerTypeCalculator = {
  74487. /**
  74488. * @method
  74489. * @param {module:echarts/data/List} data
  74490. * @param {string} baseAxisDim
  74491. * @param {string} valueAxisDim
  74492. */
  74493. min: curry$6(markerTypeCalculatorWithExtent, 'min'),
  74494. /**
  74495. * @method
  74496. * @param {module:echarts/data/List} data
  74497. * @param {string} baseAxisDim
  74498. * @param {string} valueAxisDim
  74499. */
  74500. max: curry$6(markerTypeCalculatorWithExtent, 'max'),
  74501. /**
  74502. * @method
  74503. * @param {module:echarts/data/List} data
  74504. * @param {string} baseAxisDim
  74505. * @param {string} valueAxisDim
  74506. */
  74507. average: curry$6(markerTypeCalculatorWithExtent, 'average')
  74508. };
  74509. /**
  74510. * Transform markPoint data item to format used in List by do the following
  74511. * 1. Calculate statistic like `max`, `min`, `average`
  74512. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74513. * @param {module:echarts/model/Series} seriesModel
  74514. * @param {module:echarts/coord/*} [coordSys]
  74515. * @param {Object} item
  74516. * @return {Object}
  74517. */
  74518. function dataTransform(seriesModel, item) {
  74519. var data = seriesModel.getData();
  74520. var coordSys = seriesModel.coordinateSystem;
  74521. // 1. If not specify the position with pixel directly
  74522. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74523. // `yAxis` to specify the coord on each dimension
  74524. // parseFloat first because item.x and item.y can be percent string like '20%'
  74525. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  74526. var dims = coordSys.dimensions;
  74527. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74528. // Clone the option
  74529. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74530. item = clone(item);
  74531. if (item.type
  74532. && markerTypeCalculator[item.type]
  74533. && axisInfo.baseAxis && axisInfo.valueAxis
  74534. ) {
  74535. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  74536. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  74537. item.coord = markerTypeCalculator[item.type](
  74538. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  74539. otherCoordIndex, targetCoordIndex
  74540. );
  74541. // Force to use the value of calculated value.
  74542. item.value = item.coord[targetCoordIndex];
  74543. }
  74544. else {
  74545. // FIXME Only has one of xAxis and yAxis.
  74546. var coord = [
  74547. item.xAxis != null ? item.xAxis : item.radiusAxis,
  74548. item.yAxis != null ? item.yAxis : item.angleAxis
  74549. ];
  74550. // Each coord support max, min, average
  74551. for (var i = 0; i < 2; i++) {
  74552. if (markerTypeCalculator[coord[i]]) {
  74553. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74554. }
  74555. }
  74556. item.coord = coord;
  74557. }
  74558. }
  74559. return item;
  74560. }
  74561. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74562. var ret = {};
  74563. if (item.valueIndex != null || item.valueDim != null) {
  74564. ret.valueDataDim = item.valueIndex != null
  74565. ? data.getDimension(item.valueIndex) : item.valueDim;
  74566. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74567. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74568. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74569. }
  74570. else {
  74571. ret.baseAxis = seriesModel.getBaseAxis();
  74572. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74573. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74574. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74575. }
  74576. return ret;
  74577. }
  74578. function dataDimToCoordDim(seriesModel, dataDim) {
  74579. var data = seriesModel.getData();
  74580. var dimensions = data.dimensions;
  74581. dataDim = data.getDimension(dataDim);
  74582. for (var i = 0; i < dimensions.length; i++) {
  74583. var dimItem = data.getDimensionInfo(dimensions[i]);
  74584. if (dimItem.name === dataDim) {
  74585. return dimItem.coordDim;
  74586. }
  74587. }
  74588. }
  74589. /**
  74590. * Filter data which is out of coordinateSystem range
  74591. * [dataFilter description]
  74592. * @param {module:echarts/coord/*} [coordSys]
  74593. * @param {Object} item
  74594. * @return {boolean}
  74595. */
  74596. function dataFilter$1(coordSys, item) {
  74597. // Alwalys return true if there is no coordSys
  74598. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  74599. ? coordSys.containData(item.coord) : true;
  74600. }
  74601. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  74602. // x, y, radius, angle
  74603. if (dimIndex < 2) {
  74604. return item.coord && item.coord[dimIndex];
  74605. }
  74606. return item.value;
  74607. }
  74608. function numCalculate(data, valueDataDim, type) {
  74609. if (type === 'average') {
  74610. var sum = 0;
  74611. var count = 0;
  74612. data.each(valueDataDim, function (val, idx) {
  74613. if (!isNaN(val)) {
  74614. sum += val;
  74615. count++;
  74616. }
  74617. });
  74618. return sum / count;
  74619. }
  74620. else if (type === 'median') {
  74621. return data.getMedian(valueDataDim);
  74622. }
  74623. else {
  74624. // max & min
  74625. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  74626. }
  74627. }
  74628. /*
  74629. * Licensed to the Apache Software Foundation (ASF) under one
  74630. * or more contributor license agreements. See the NOTICE file
  74631. * distributed with this work for additional information
  74632. * regarding copyright ownership. The ASF licenses this file
  74633. * to you under the Apache License, Version 2.0 (the
  74634. * "License"); you may not use this file except in compliance
  74635. * with the License. You may obtain a copy of the License at
  74636. *
  74637. * http://www.apache.org/licenses/LICENSE-2.0
  74638. *
  74639. * Unless required by applicable law or agreed to in writing,
  74640. * software distributed under the License is distributed on an
  74641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74642. * KIND, either express or implied. See the License for the
  74643. * specific language governing permissions and limitations
  74644. * under the License.
  74645. */
  74646. var MarkerView = extendComponentView({
  74647. type: 'marker',
  74648. init: function () {
  74649. /**
  74650. * Markline grouped by series
  74651. * @private
  74652. * @type {module:zrender/core/util.HashMap}
  74653. */
  74654. this.markerGroupMap = createHashMap();
  74655. },
  74656. render: function (markerModel, ecModel, api) {
  74657. var markerGroupMap = this.markerGroupMap;
  74658. markerGroupMap.each(function (item) {
  74659. item.__keep = false;
  74660. });
  74661. var markerModelKey = this.type + 'Model';
  74662. ecModel.eachSeries(function (seriesModel) {
  74663. var markerModel = seriesModel[markerModelKey];
  74664. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  74665. }, this);
  74666. markerGroupMap.each(function (item) {
  74667. !item.__keep && this.group.remove(item.group);
  74668. }, this);
  74669. },
  74670. renderSeries: function () {}
  74671. });
  74672. /*
  74673. * Licensed to the Apache Software Foundation (ASF) under one
  74674. * or more contributor license agreements. See the NOTICE file
  74675. * distributed with this work for additional information
  74676. * regarding copyright ownership. The ASF licenses this file
  74677. * to you under the Apache License, Version 2.0 (the
  74678. * "License"); you may not use this file except in compliance
  74679. * with the License. You may obtain a copy of the License at
  74680. *
  74681. * http://www.apache.org/licenses/LICENSE-2.0
  74682. *
  74683. * Unless required by applicable law or agreed to in writing,
  74684. * software distributed under the License is distributed on an
  74685. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74686. * KIND, either express or implied. See the License for the
  74687. * specific language governing permissions and limitations
  74688. * under the License.
  74689. */
  74690. function updateMarkerLayout(mpData, seriesModel, api) {
  74691. var coordSys = seriesModel.coordinateSystem;
  74692. mpData.each(function (idx) {
  74693. var itemModel = mpData.getItemModel(idx);
  74694. var point;
  74695. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74696. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74697. if (!isNaN(xPx) && !isNaN(yPx)) {
  74698. point = [xPx, yPx];
  74699. }
  74700. // Chart like bar may have there own marker positioning logic
  74701. else if (seriesModel.getMarkerPosition) {
  74702. // Use the getMarkerPoisition
  74703. point = seriesModel.getMarkerPosition(
  74704. mpData.getValues(mpData.dimensions, idx)
  74705. );
  74706. }
  74707. else if (coordSys) {
  74708. var x = mpData.get(coordSys.dimensions[0], idx);
  74709. var y = mpData.get(coordSys.dimensions[1], idx);
  74710. point = coordSys.dataToPoint([x, y]);
  74711. }
  74712. // Use x, y if has any
  74713. if (!isNaN(xPx)) {
  74714. point[0] = xPx;
  74715. }
  74716. if (!isNaN(yPx)) {
  74717. point[1] = yPx;
  74718. }
  74719. mpData.setItemLayout(idx, point);
  74720. });
  74721. }
  74722. MarkerView.extend({
  74723. type: 'markPoint',
  74724. // updateLayout: function (markPointModel, ecModel, api) {
  74725. // ecModel.eachSeries(function (seriesModel) {
  74726. // var mpModel = seriesModel.markPointModel;
  74727. // if (mpModel) {
  74728. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74729. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74730. // }
  74731. // }, this);
  74732. // },
  74733. updateTransform: function (markPointModel, ecModel, api) {
  74734. ecModel.eachSeries(function (seriesModel) {
  74735. var mpModel = seriesModel.markPointModel;
  74736. if (mpModel) {
  74737. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74738. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74739. }
  74740. }, this);
  74741. },
  74742. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  74743. var coordSys = seriesModel.coordinateSystem;
  74744. var seriesId = seriesModel.id;
  74745. var seriesData = seriesModel.getData();
  74746. var symbolDrawMap = this.markerGroupMap;
  74747. var symbolDraw = symbolDrawMap.get(seriesId)
  74748. || symbolDrawMap.set(seriesId, new SymbolDraw());
  74749. var mpData = createList$1(coordSys, seriesModel, mpModel);
  74750. // FIXME
  74751. mpModel.setData(mpData);
  74752. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74753. mpData.each(function (idx) {
  74754. var itemModel = mpData.getItemModel(idx);
  74755. var symbolSize = itemModel.getShallow('symbolSize');
  74756. if (typeof symbolSize === 'function') {
  74757. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74758. symbolSize = symbolSize(
  74759. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  74760. );
  74761. }
  74762. mpData.setItemVisual(idx, {
  74763. symbolSize: symbolSize,
  74764. color: itemModel.get('itemStyle.color')
  74765. || seriesData.getVisual('color'),
  74766. symbol: itemModel.getShallow('symbol')
  74767. });
  74768. });
  74769. // TODO Text are wrong
  74770. symbolDraw.updateData(mpData);
  74771. this.group.add(symbolDraw.group);
  74772. // Set host model for tooltip
  74773. // FIXME
  74774. mpData.eachItemGraphicEl(function (el) {
  74775. el.traverse(function (child) {
  74776. child.dataModel = mpModel;
  74777. });
  74778. });
  74779. symbolDraw.__keep = true;
  74780. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74781. }
  74782. });
  74783. /**
  74784. * @inner
  74785. * @param {module:echarts/coord/*} [coordSys]
  74786. * @param {module:echarts/model/Series} seriesModel
  74787. * @param {module:echarts/model/Model} mpModel
  74788. */
  74789. function createList$1(coordSys, seriesModel, mpModel) {
  74790. var coordDimsInfos;
  74791. if (coordSys) {
  74792. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74793. var info = seriesModel.getData().getDimensionInfo(
  74794. seriesModel.getData().mapDimension(coordDim)
  74795. ) || {};
  74796. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74797. return defaults({name: coordDim}, info);
  74798. });
  74799. }
  74800. else {
  74801. coordDimsInfos = [{
  74802. name: 'value',
  74803. type: 'float'
  74804. }];
  74805. }
  74806. var mpData = new List(coordDimsInfos, mpModel);
  74807. var dataOpt = map(mpModel.get('data'), curry(
  74808. dataTransform, seriesModel
  74809. ));
  74810. if (coordSys) {
  74811. dataOpt = filter(
  74812. dataOpt, curry(dataFilter$1, coordSys)
  74813. );
  74814. }
  74815. mpData.initData(dataOpt, null,
  74816. coordSys ? dimValueGetter : function (item) {
  74817. return item.value;
  74818. }
  74819. );
  74820. return mpData;
  74821. }
  74822. /*
  74823. * Licensed to the Apache Software Foundation (ASF) under one
  74824. * or more contributor license agreements. See the NOTICE file
  74825. * distributed with this work for additional information
  74826. * regarding copyright ownership. The ASF licenses this file
  74827. * to you under the Apache License, Version 2.0 (the
  74828. * "License"); you may not use this file except in compliance
  74829. * with the License. You may obtain a copy of the License at
  74830. *
  74831. * http://www.apache.org/licenses/LICENSE-2.0
  74832. *
  74833. * Unless required by applicable law or agreed to in writing,
  74834. * software distributed under the License is distributed on an
  74835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74836. * KIND, either express or implied. See the License for the
  74837. * specific language governing permissions and limitations
  74838. * under the License.
  74839. */
  74840. // HINT Markpoint can't be used too much
  74841. registerPreprocessor(function (opt) {
  74842. // Make sure markPoint component is enabled
  74843. opt.markPoint = opt.markPoint || {};
  74844. });
  74845. /*
  74846. * Licensed to the Apache Software Foundation (ASF) under one
  74847. * or more contributor license agreements. See the NOTICE file
  74848. * distributed with this work for additional information
  74849. * regarding copyright ownership. The ASF licenses this file
  74850. * to you under the Apache License, Version 2.0 (the
  74851. * "License"); you may not use this file except in compliance
  74852. * with the License. You may obtain a copy of the License at
  74853. *
  74854. * http://www.apache.org/licenses/LICENSE-2.0
  74855. *
  74856. * Unless required by applicable law or agreed to in writing,
  74857. * software distributed under the License is distributed on an
  74858. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74859. * KIND, either express or implied. See the License for the
  74860. * specific language governing permissions and limitations
  74861. * under the License.
  74862. */
  74863. MarkerModel.extend({
  74864. type: 'markLine',
  74865. defaultOption: {
  74866. zlevel: 0,
  74867. z: 5,
  74868. symbol: ['circle', 'arrow'],
  74869. symbolSize: [8, 16],
  74870. //symbolRotate: 0,
  74871. precision: 2,
  74872. tooltip: {
  74873. trigger: 'item'
  74874. },
  74875. label: {
  74876. show: true,
  74877. position: 'end'
  74878. },
  74879. lineStyle: {
  74880. type: 'dashed'
  74881. },
  74882. emphasis: {
  74883. label: {
  74884. show: true
  74885. },
  74886. lineStyle: {
  74887. width: 3
  74888. }
  74889. },
  74890. animationEasing: 'linear'
  74891. }
  74892. });
  74893. /*
  74894. * Licensed to the Apache Software Foundation (ASF) under one
  74895. * or more contributor license agreements. See the NOTICE file
  74896. * distributed with this work for additional information
  74897. * regarding copyright ownership. The ASF licenses this file
  74898. * to you under the Apache License, Version 2.0 (the
  74899. * "License"); you may not use this file except in compliance
  74900. * with the License. You may obtain a copy of the License at
  74901. *
  74902. * http://www.apache.org/licenses/LICENSE-2.0
  74903. *
  74904. * Unless required by applicable law or agreed to in writing,
  74905. * software distributed under the License is distributed on an
  74906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74907. * KIND, either express or implied. See the License for the
  74908. * specific language governing permissions and limitations
  74909. * under the License.
  74910. */
  74911. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  74912. var data = seriesModel.getData();
  74913. // Special type markLine like 'min', 'max', 'average', 'median'
  74914. var mlType = item.type;
  74915. if (!isArray(item)
  74916. && (
  74917. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  74918. // In case
  74919. // data: [{
  74920. // yAxis: 10
  74921. // }]
  74922. || (item.xAxis != null || item.yAxis != null)
  74923. )
  74924. ) {
  74925. var valueAxis;
  74926. var valueDataDim;
  74927. var value;
  74928. if (item.yAxis != null || item.xAxis != null) {
  74929. valueDataDim = item.yAxis != null ? 'y' : 'x';
  74930. valueAxis = coordSys.getAxis(valueDataDim);
  74931. value = retrieve(item.yAxis, item.xAxis);
  74932. }
  74933. else {
  74934. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74935. valueDataDim = axisInfo.valueDataDim;
  74936. valueAxis = axisInfo.valueAxis;
  74937. value = numCalculate(data, valueDataDim, mlType);
  74938. }
  74939. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  74940. var baseIndex = 1 - valueIndex;
  74941. var mlFrom = clone(item);
  74942. var mlTo = {};
  74943. mlFrom.type = null;
  74944. mlFrom.coord = [];
  74945. mlTo.coord = [];
  74946. mlFrom.coord[baseIndex] = -Infinity;
  74947. mlTo.coord[baseIndex] = Infinity;
  74948. var precision = mlModel.get('precision');
  74949. if (precision >= 0 && typeof value === 'number') {
  74950. value = +value.toFixed(Math.min(precision, 20));
  74951. }
  74952. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  74953. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  74954. type: mlType,
  74955. valueIndex: item.valueIndex,
  74956. // Force to use the value of calculated value.
  74957. value: value
  74958. }];
  74959. }
  74960. item = [
  74961. dataTransform(seriesModel, item[0]),
  74962. dataTransform(seriesModel, item[1]),
  74963. extend({}, item[2])
  74964. ];
  74965. // Avoid line data type is extended by from(to) data type
  74966. item[2].type = item[2].type || '';
  74967. // Merge from option and to option into line option
  74968. merge(item[2], item[0]);
  74969. merge(item[2], item[1]);
  74970. return item;
  74971. };
  74972. function isInifinity(val) {
  74973. return !isNaN(val) && !isFinite(val);
  74974. }
  74975. // If a markLine has one dim
  74976. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  74977. var otherDimIndex = 1 - dimIndex;
  74978. var dimName = coordSys.dimensions[dimIndex];
  74979. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  74980. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  74981. }
  74982. function markLineFilter(coordSys, item) {
  74983. if (coordSys.type === 'cartesian2d') {
  74984. var fromCoord = item[0].coord;
  74985. var toCoord = item[1].coord;
  74986. // In case
  74987. // {
  74988. // markLine: {
  74989. // data: [{ yAxis: 2 }]
  74990. // }
  74991. // }
  74992. if (
  74993. fromCoord && toCoord
  74994. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  74995. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  74996. ) {
  74997. return true;
  74998. }
  74999. }
  75000. return dataFilter$1(coordSys, item[0])
  75001. && dataFilter$1(coordSys, item[1]);
  75002. }
  75003. function updateSingleMarkerEndLayout(
  75004. data, idx, isFrom, seriesModel, api
  75005. ) {
  75006. var coordSys = seriesModel.coordinateSystem;
  75007. var itemModel = data.getItemModel(idx);
  75008. var point;
  75009. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75010. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75011. if (!isNaN(xPx) && !isNaN(yPx)) {
  75012. point = [xPx, yPx];
  75013. }
  75014. else {
  75015. // Chart like bar may have there own marker positioning logic
  75016. if (seriesModel.getMarkerPosition) {
  75017. // Use the getMarkerPoisition
  75018. point = seriesModel.getMarkerPosition(
  75019. data.getValues(data.dimensions, idx)
  75020. );
  75021. }
  75022. else {
  75023. var dims = coordSys.dimensions;
  75024. var x = data.get(dims[0], idx);
  75025. var y = data.get(dims[1], idx);
  75026. point = coordSys.dataToPoint([x, y]);
  75027. }
  75028. // Expand line to the edge of grid if value on one axis is Inifnity
  75029. // In case
  75030. // markLine: {
  75031. // data: [{
  75032. // yAxis: 2
  75033. // // or
  75034. // type: 'average'
  75035. // }]
  75036. // }
  75037. if (coordSys.type === 'cartesian2d') {
  75038. var xAxis = coordSys.getAxis('x');
  75039. var yAxis = coordSys.getAxis('y');
  75040. var dims = coordSys.dimensions;
  75041. if (isInifinity(data.get(dims[0], idx))) {
  75042. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75043. }
  75044. else if (isInifinity(data.get(dims[1], idx))) {
  75045. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75046. }
  75047. }
  75048. // Use x, y if has any
  75049. if (!isNaN(xPx)) {
  75050. point[0] = xPx;
  75051. }
  75052. if (!isNaN(yPx)) {
  75053. point[1] = yPx;
  75054. }
  75055. }
  75056. data.setItemLayout(idx, point);
  75057. }
  75058. MarkerView.extend({
  75059. type: 'markLine',
  75060. // updateLayout: function (markLineModel, ecModel, api) {
  75061. // ecModel.eachSeries(function (seriesModel) {
  75062. // var mlModel = seriesModel.markLineModel;
  75063. // if (mlModel) {
  75064. // var mlData = mlModel.getData();
  75065. // var fromData = mlModel.__from;
  75066. // var toData = mlModel.__to;
  75067. // // Update visual and layout of from symbol and to symbol
  75068. // fromData.each(function (idx) {
  75069. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75070. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75071. // });
  75072. // // Update layout of line
  75073. // mlData.each(function (idx) {
  75074. // mlData.setItemLayout(idx, [
  75075. // fromData.getItemLayout(idx),
  75076. // toData.getItemLayout(idx)
  75077. // ]);
  75078. // });
  75079. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  75080. // }
  75081. // }, this);
  75082. // },
  75083. updateTransform: function (markLineModel, ecModel, api) {
  75084. ecModel.eachSeries(function (seriesModel) {
  75085. var mlModel = seriesModel.markLineModel;
  75086. if (mlModel) {
  75087. var mlData = mlModel.getData();
  75088. var fromData = mlModel.__from;
  75089. var toData = mlModel.__to;
  75090. // Update visual and layout of from symbol and to symbol
  75091. fromData.each(function (idx) {
  75092. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75093. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75094. });
  75095. // Update layout of line
  75096. mlData.each(function (idx) {
  75097. mlData.setItemLayout(idx, [
  75098. fromData.getItemLayout(idx),
  75099. toData.getItemLayout(idx)
  75100. ]);
  75101. });
  75102. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75103. }
  75104. }, this);
  75105. },
  75106. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  75107. var coordSys = seriesModel.coordinateSystem;
  75108. var seriesId = seriesModel.id;
  75109. var seriesData = seriesModel.getData();
  75110. var lineDrawMap = this.markerGroupMap;
  75111. var lineDraw = lineDrawMap.get(seriesId)
  75112. || lineDrawMap.set(seriesId, new LineDraw());
  75113. this.group.add(lineDraw.group);
  75114. var mlData = createList$2(coordSys, seriesModel, mlModel);
  75115. var fromData = mlData.from;
  75116. var toData = mlData.to;
  75117. var lineData = mlData.line;
  75118. mlModel.__from = fromData;
  75119. mlModel.__to = toData;
  75120. // Line data for tooltip and formatter
  75121. mlModel.setData(lineData);
  75122. var symbolType = mlModel.get('symbol');
  75123. var symbolSize = mlModel.get('symbolSize');
  75124. if (!isArray(symbolType)) {
  75125. symbolType = [symbolType, symbolType];
  75126. }
  75127. if (typeof symbolSize === 'number') {
  75128. symbolSize = [symbolSize, symbolSize];
  75129. }
  75130. // Update visual and layout of from symbol and to symbol
  75131. mlData.from.each(function (idx) {
  75132. updateDataVisualAndLayout(fromData, idx, true);
  75133. updateDataVisualAndLayout(toData, idx, false);
  75134. });
  75135. // Update visual and layout of line
  75136. lineData.each(function (idx) {
  75137. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  75138. lineData.setItemVisual(idx, {
  75139. color: lineColor || fromData.getItemVisual(idx, 'color')
  75140. });
  75141. lineData.setItemLayout(idx, [
  75142. fromData.getItemLayout(idx),
  75143. toData.getItemLayout(idx)
  75144. ]);
  75145. lineData.setItemVisual(idx, {
  75146. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  75147. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  75148. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  75149. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  75150. });
  75151. });
  75152. lineDraw.updateData(lineData);
  75153. // Set host model for tooltip
  75154. // FIXME
  75155. mlData.line.eachItemGraphicEl(function (el, idx) {
  75156. el.traverse(function (child) {
  75157. child.dataModel = mlModel;
  75158. });
  75159. });
  75160. function updateDataVisualAndLayout(data, idx, isFrom) {
  75161. var itemModel = data.getItemModel(idx);
  75162. updateSingleMarkerEndLayout(
  75163. data, idx, isFrom, seriesModel, api
  75164. );
  75165. data.setItemVisual(idx, {
  75166. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  75167. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  75168. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  75169. });
  75170. }
  75171. lineDraw.__keep = true;
  75172. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75173. }
  75174. });
  75175. /**
  75176. * @inner
  75177. * @param {module:echarts/coord/*} coordSys
  75178. * @param {module:echarts/model/Series} seriesModel
  75179. * @param {module:echarts/model/Model} mpModel
  75180. */
  75181. function createList$2(coordSys, seriesModel, mlModel) {
  75182. var coordDimsInfos;
  75183. if (coordSys) {
  75184. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75185. var info = seriesModel.getData().getDimensionInfo(
  75186. seriesModel.getData().mapDimension(coordDim)
  75187. ) || {};
  75188. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75189. return defaults({name: coordDim}, info);
  75190. });
  75191. }
  75192. else {
  75193. coordDimsInfos = [{
  75194. name: 'value',
  75195. type: 'float'
  75196. }];
  75197. }
  75198. var fromData = new List(coordDimsInfos, mlModel);
  75199. var toData = new List(coordDimsInfos, mlModel);
  75200. // No dimensions
  75201. var lineData = new List([], mlModel);
  75202. var optData = map(mlModel.get('data'), curry(
  75203. markLineTransform, seriesModel, coordSys, mlModel
  75204. ));
  75205. if (coordSys) {
  75206. optData = filter(
  75207. optData, curry(markLineFilter, coordSys)
  75208. );
  75209. }
  75210. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  75211. return item.value;
  75212. };
  75213. fromData.initData(
  75214. map(optData, function (item) {
  75215. return item[0];
  75216. }),
  75217. null,
  75218. dimValueGetter$$1
  75219. );
  75220. toData.initData(
  75221. map(optData, function (item) {
  75222. return item[1];
  75223. }),
  75224. null,
  75225. dimValueGetter$$1
  75226. );
  75227. lineData.initData(
  75228. map(optData, function (item) {
  75229. return item[2];
  75230. })
  75231. );
  75232. lineData.hasItemOption = true;
  75233. return {
  75234. from: fromData,
  75235. to: toData,
  75236. line: lineData
  75237. };
  75238. }
  75239. /*
  75240. * Licensed to the Apache Software Foundation (ASF) under one
  75241. * or more contributor license agreements. See the NOTICE file
  75242. * distributed with this work for additional information
  75243. * regarding copyright ownership. The ASF licenses this file
  75244. * to you under the Apache License, Version 2.0 (the
  75245. * "License"); you may not use this file except in compliance
  75246. * with the License. You may obtain a copy of the License at
  75247. *
  75248. * http://www.apache.org/licenses/LICENSE-2.0
  75249. *
  75250. * Unless required by applicable law or agreed to in writing,
  75251. * software distributed under the License is distributed on an
  75252. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75253. * KIND, either express or implied. See the License for the
  75254. * specific language governing permissions and limitations
  75255. * under the License.
  75256. */
  75257. registerPreprocessor(function (opt) {
  75258. // Make sure markLine component is enabled
  75259. opt.markLine = opt.markLine || {};
  75260. });
  75261. /*
  75262. * Licensed to the Apache Software Foundation (ASF) under one
  75263. * or more contributor license agreements. See the NOTICE file
  75264. * distributed with this work for additional information
  75265. * regarding copyright ownership. The ASF licenses this file
  75266. * to you under the Apache License, Version 2.0 (the
  75267. * "License"); you may not use this file except in compliance
  75268. * with the License. You may obtain a copy of the License at
  75269. *
  75270. * http://www.apache.org/licenses/LICENSE-2.0
  75271. *
  75272. * Unless required by applicable law or agreed to in writing,
  75273. * software distributed under the License is distributed on an
  75274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75275. * KIND, either express or implied. See the License for the
  75276. * specific language governing permissions and limitations
  75277. * under the License.
  75278. */
  75279. MarkerModel.extend({
  75280. type: 'markArea',
  75281. defaultOption: {
  75282. zlevel: 0,
  75283. // PENDING
  75284. z: 1,
  75285. tooltip: {
  75286. trigger: 'item'
  75287. },
  75288. // markArea should fixed on the coordinate system
  75289. animation: false,
  75290. label: {
  75291. show: true,
  75292. position: 'top'
  75293. },
  75294. itemStyle: {
  75295. // color and borderColor default to use color from series
  75296. // color: 'auto'
  75297. // borderColor: 'auto'
  75298. borderWidth: 0
  75299. },
  75300. emphasis: {
  75301. label: {
  75302. show: true,
  75303. position: 'top'
  75304. }
  75305. }
  75306. }
  75307. });
  75308. /*
  75309. * Licensed to the Apache Software Foundation (ASF) under one
  75310. * or more contributor license agreements. See the NOTICE file
  75311. * distributed with this work for additional information
  75312. * regarding copyright ownership. The ASF licenses this file
  75313. * to you under the Apache License, Version 2.0 (the
  75314. * "License"); you may not use this file except in compliance
  75315. * with the License. You may obtain a copy of the License at
  75316. *
  75317. * http://www.apache.org/licenses/LICENSE-2.0
  75318. *
  75319. * Unless required by applicable law or agreed to in writing,
  75320. * software distributed under the License is distributed on an
  75321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75322. * KIND, either express or implied. See the License for the
  75323. * specific language governing permissions and limitations
  75324. * under the License.
  75325. */
  75326. // TODO Better on polar
  75327. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75328. var lt = dataTransform(seriesModel, item[0]);
  75329. var rb = dataTransform(seriesModel, item[1]);
  75330. var retrieve$$1 = retrieve;
  75331. // FIXME make sure lt is less than rb
  75332. var ltCoord = lt.coord;
  75333. var rbCoord = rb.coord;
  75334. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  75335. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  75336. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  75337. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  75338. // Merge option into one
  75339. var result = mergeAll([{}, lt, rb]);
  75340. result.coord = [
  75341. lt.coord, rb.coord
  75342. ];
  75343. result.x0 = lt.x;
  75344. result.y0 = lt.y;
  75345. result.x1 = rb.x;
  75346. result.y1 = rb.y;
  75347. return result;
  75348. };
  75349. function isInifinity$1(val) {
  75350. return !isNaN(val) && !isFinite(val);
  75351. }
  75352. // If a markArea has one dim
  75353. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  75354. var otherDimIndex = 1 - dimIndex;
  75355. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  75356. }
  75357. function markAreaFilter(coordSys, item) {
  75358. var fromCoord = item.coord[0];
  75359. var toCoord = item.coord[1];
  75360. if (coordSys.type === 'cartesian2d') {
  75361. // In case
  75362. // {
  75363. // markArea: {
  75364. // data: [{ yAxis: 2 }]
  75365. // }
  75366. // }
  75367. if (
  75368. fromCoord && toCoord
  75369. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  75370. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  75371. ) {
  75372. return true;
  75373. }
  75374. }
  75375. return dataFilter$1(coordSys, {
  75376. coord: fromCoord,
  75377. x: item.x0,
  75378. y: item.y0
  75379. })
  75380. || dataFilter$1(coordSys, {
  75381. coord: toCoord,
  75382. x: item.x1,
  75383. y: item.y1
  75384. });
  75385. }
  75386. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75387. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75388. var coordSys = seriesModel.coordinateSystem;
  75389. var itemModel = data.getItemModel(idx);
  75390. var point;
  75391. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75392. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75393. if (!isNaN(xPx) && !isNaN(yPx)) {
  75394. point = [xPx, yPx];
  75395. }
  75396. else {
  75397. // Chart like bar may have there own marker positioning logic
  75398. if (seriesModel.getMarkerPosition) {
  75399. // Use the getMarkerPoisition
  75400. point = seriesModel.getMarkerPosition(
  75401. data.getValues(dims, idx)
  75402. );
  75403. }
  75404. else {
  75405. var x = data.get(dims[0], idx);
  75406. var y = data.get(dims[1], idx);
  75407. var pt = [x, y];
  75408. coordSys.clampData && coordSys.clampData(pt, pt);
  75409. point = coordSys.dataToPoint(pt, true);
  75410. }
  75411. if (coordSys.type === 'cartesian2d') {
  75412. var xAxis = coordSys.getAxis('x');
  75413. var yAxis = coordSys.getAxis('y');
  75414. var x = data.get(dims[0], idx);
  75415. var y = data.get(dims[1], idx);
  75416. if (isInifinity$1(x)) {
  75417. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75418. }
  75419. else if (isInifinity$1(y)) {
  75420. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75421. }
  75422. }
  75423. // Use x, y if has any
  75424. if (!isNaN(xPx)) {
  75425. point[0] = xPx;
  75426. }
  75427. if (!isNaN(yPx)) {
  75428. point[1] = yPx;
  75429. }
  75430. }
  75431. return point;
  75432. }
  75433. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75434. MarkerView.extend({
  75435. type: 'markArea',
  75436. // updateLayout: function (markAreaModel, ecModel, api) {
  75437. // ecModel.eachSeries(function (seriesModel) {
  75438. // var maModel = seriesModel.markAreaModel;
  75439. // if (maModel) {
  75440. // var areaData = maModel.getData();
  75441. // areaData.each(function (idx) {
  75442. // var points = zrUtil.map(dimPermutations, function (dim) {
  75443. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75444. // });
  75445. // // Layout
  75446. // areaData.setItemLayout(idx, points);
  75447. // var el = areaData.getItemGraphicEl(idx);
  75448. // el.setShape('points', points);
  75449. // });
  75450. // }
  75451. // }, this);
  75452. // },
  75453. updateTransform: function (markAreaModel, ecModel, api) {
  75454. ecModel.eachSeries(function (seriesModel) {
  75455. var maModel = seriesModel.markAreaModel;
  75456. if (maModel) {
  75457. var areaData = maModel.getData();
  75458. areaData.each(function (idx) {
  75459. var points = map(dimPermutations, function (dim) {
  75460. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75461. });
  75462. // Layout
  75463. areaData.setItemLayout(idx, points);
  75464. var el = areaData.getItemGraphicEl(idx);
  75465. el.setShape('points', points);
  75466. });
  75467. }
  75468. }, this);
  75469. },
  75470. renderSeries: function (seriesModel, maModel, ecModel, api) {
  75471. var coordSys = seriesModel.coordinateSystem;
  75472. var seriesId = seriesModel.id;
  75473. var seriesData = seriesModel.getData();
  75474. var areaGroupMap = this.markerGroupMap;
  75475. var polygonGroup = areaGroupMap.get(seriesId)
  75476. || areaGroupMap.set(seriesId, {group: new Group()});
  75477. this.group.add(polygonGroup.group);
  75478. polygonGroup.__keep = true;
  75479. var areaData = createList$3(coordSys, seriesModel, maModel);
  75480. // Line data for tooltip and formatter
  75481. maModel.setData(areaData);
  75482. // Update visual and layout of line
  75483. areaData.each(function (idx) {
  75484. // Layout
  75485. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  75486. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75487. }));
  75488. // Visual
  75489. areaData.setItemVisual(idx, {
  75490. color: seriesData.getVisual('color')
  75491. });
  75492. });
  75493. areaData.diff(polygonGroup.__data)
  75494. .add(function (idx) {
  75495. var polygon = new Polygon({
  75496. shape: {
  75497. points: areaData.getItemLayout(idx)
  75498. }
  75499. });
  75500. areaData.setItemGraphicEl(idx, polygon);
  75501. polygonGroup.group.add(polygon);
  75502. })
  75503. .update(function (newIdx, oldIdx) {
  75504. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  75505. updateProps(polygon, {
  75506. shape: {
  75507. points: areaData.getItemLayout(newIdx)
  75508. }
  75509. }, maModel, newIdx);
  75510. polygonGroup.group.add(polygon);
  75511. areaData.setItemGraphicEl(newIdx, polygon);
  75512. })
  75513. .remove(function (idx) {
  75514. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  75515. polygonGroup.group.remove(polygon);
  75516. })
  75517. .execute();
  75518. areaData.eachItemGraphicEl(function (polygon, idx) {
  75519. var itemModel = areaData.getItemModel(idx);
  75520. var labelModel = itemModel.getModel('label');
  75521. var labelHoverModel = itemModel.getModel('emphasis.label');
  75522. var color = areaData.getItemVisual(idx, 'color');
  75523. polygon.useStyle(
  75524. defaults(
  75525. itemModel.getModel('itemStyle').getItemStyle(),
  75526. {
  75527. fill: modifyAlpha(color, 0.4),
  75528. stroke: color
  75529. }
  75530. )
  75531. );
  75532. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  75533. setLabelStyle(
  75534. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  75535. {
  75536. labelFetcher: maModel,
  75537. labelDataIndex: idx,
  75538. defaultText: areaData.getName(idx) || '',
  75539. isRectText: true,
  75540. autoColor: color
  75541. }
  75542. );
  75543. setHoverStyle(polygon, {});
  75544. polygon.dataModel = maModel;
  75545. });
  75546. polygonGroup.__data = areaData;
  75547. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75548. }
  75549. });
  75550. /**
  75551. * @inner
  75552. * @param {module:echarts/coord/*} coordSys
  75553. * @param {module:echarts/model/Series} seriesModel
  75554. * @param {module:echarts/model/Model} mpModel
  75555. */
  75556. function createList$3(coordSys, seriesModel, maModel) {
  75557. var coordDimsInfos;
  75558. var areaData;
  75559. var dims = ['x0', 'y0', 'x1', 'y1'];
  75560. if (coordSys) {
  75561. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75562. var data = seriesModel.getData();
  75563. var info = data.getDimensionInfo(
  75564. data.mapDimension(coordDim)
  75565. ) || {};
  75566. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75567. return defaults({name: coordDim}, info);
  75568. });
  75569. areaData = new List(map(dims, function (dim, idx) {
  75570. return {
  75571. name: dim,
  75572. type: coordDimsInfos[idx % 2].type
  75573. };
  75574. }), maModel);
  75575. }
  75576. else {
  75577. coordDimsInfos = [{
  75578. name: 'value',
  75579. type: 'float'
  75580. }];
  75581. areaData = new List(coordDimsInfos, maModel);
  75582. }
  75583. var optData = map(maModel.get('data'), curry(
  75584. markAreaTransform, seriesModel, coordSys, maModel
  75585. ));
  75586. if (coordSys) {
  75587. optData = filter(
  75588. optData, curry(markAreaFilter, coordSys)
  75589. );
  75590. }
  75591. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75592. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75593. } : function (item) {
  75594. return item.value;
  75595. };
  75596. areaData.initData(optData, null, dimValueGetter$$1);
  75597. areaData.hasItemOption = true;
  75598. return areaData;
  75599. }
  75600. /*
  75601. * Licensed to the Apache Software Foundation (ASF) under one
  75602. * or more contributor license agreements. See the NOTICE file
  75603. * distributed with this work for additional information
  75604. * regarding copyright ownership. The ASF licenses this file
  75605. * to you under the Apache License, Version 2.0 (the
  75606. * "License"); you may not use this file except in compliance
  75607. * with the License. You may obtain a copy of the License at
  75608. *
  75609. * http://www.apache.org/licenses/LICENSE-2.0
  75610. *
  75611. * Unless required by applicable law or agreed to in writing,
  75612. * software distributed under the License is distributed on an
  75613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75614. * KIND, either express or implied. See the License for the
  75615. * specific language governing permissions and limitations
  75616. * under the License.
  75617. */
  75618. registerPreprocessor(function (opt) {
  75619. // Make sure markArea component is enabled
  75620. opt.markArea = opt.markArea || {};
  75621. });
  75622. /*
  75623. * Licensed to the Apache Software Foundation (ASF) under one
  75624. * or more contributor license agreements. See the NOTICE file
  75625. * distributed with this work for additional information
  75626. * regarding copyright ownership. The ASF licenses this file
  75627. * to you under the Apache License, Version 2.0 (the
  75628. * "License"); you may not use this file except in compliance
  75629. * with the License. You may obtain a copy of the License at
  75630. *
  75631. * http://www.apache.org/licenses/LICENSE-2.0
  75632. *
  75633. * Unless required by applicable law or agreed to in writing,
  75634. * software distributed under the License is distributed on an
  75635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75636. * KIND, either express or implied. See the License for the
  75637. * specific language governing permissions and limitations
  75638. * under the License.
  75639. */
  75640. var preprocessor$3 = function (option) {
  75641. var timelineOpt = option && option.timeline;
  75642. if (!isArray(timelineOpt)) {
  75643. timelineOpt = timelineOpt ? [timelineOpt] : [];
  75644. }
  75645. each$1(timelineOpt, function (opt) {
  75646. if (!opt) {
  75647. return;
  75648. }
  75649. compatibleEC2(opt);
  75650. });
  75651. };
  75652. function compatibleEC2(opt) {
  75653. var type = opt.type;
  75654. var ec2Types = {'number': 'value', 'time': 'time'};
  75655. // Compatible with ec2
  75656. if (ec2Types[type]) {
  75657. opt.axisType = ec2Types[type];
  75658. delete opt.type;
  75659. }
  75660. transferItem(opt);
  75661. if (has$2(opt, 'controlPosition')) {
  75662. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  75663. if (!has$2(controlStyle, 'position')) {
  75664. controlStyle.position = opt.controlPosition;
  75665. }
  75666. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  75667. controlStyle.show = false;
  75668. delete controlStyle.position;
  75669. }
  75670. delete opt.controlPosition;
  75671. }
  75672. each$1(opt.data || [], function (dataItem) {
  75673. if (isObject$1(dataItem) && !isArray(dataItem)) {
  75674. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  75675. // In ec2, using name as value.
  75676. dataItem.value = dataItem.name;
  75677. }
  75678. transferItem(dataItem);
  75679. }
  75680. });
  75681. }
  75682. function transferItem(opt) {
  75683. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  75684. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  75685. // Transfer label out
  75686. var label = opt.label || (opt.label || {});
  75687. var labelNormal = label.normal || (label.normal = {});
  75688. var excludeLabelAttr = {normal: 1, emphasis: 1};
  75689. each$1(label, function (value, name) {
  75690. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  75691. labelNormal[name] = value;
  75692. }
  75693. });
  75694. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  75695. label.emphasis = itemStyleEmphasis.label;
  75696. delete itemStyleEmphasis.label;
  75697. }
  75698. }
  75699. function has$2(obj, attr) {
  75700. return obj.hasOwnProperty(attr);
  75701. }
  75702. /*
  75703. * Licensed to the Apache Software Foundation (ASF) under one
  75704. * or more contributor license agreements. See the NOTICE file
  75705. * distributed with this work for additional information
  75706. * regarding copyright ownership. The ASF licenses this file
  75707. * to you under the Apache License, Version 2.0 (the
  75708. * "License"); you may not use this file except in compliance
  75709. * with the License. You may obtain a copy of the License at
  75710. *
  75711. * http://www.apache.org/licenses/LICENSE-2.0
  75712. *
  75713. * Unless required by applicable law or agreed to in writing,
  75714. * software distributed under the License is distributed on an
  75715. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75716. * KIND, either express or implied. See the License for the
  75717. * specific language governing permissions and limitations
  75718. * under the License.
  75719. */
  75720. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  75721. // Only slider now.
  75722. return 'slider';
  75723. });
  75724. /*
  75725. * Licensed to the Apache Software Foundation (ASF) under one
  75726. * or more contributor license agreements. See the NOTICE file
  75727. * distributed with this work for additional information
  75728. * regarding copyright ownership. The ASF licenses this file
  75729. * to you under the Apache License, Version 2.0 (the
  75730. * "License"); you may not use this file except in compliance
  75731. * with the License. You may obtain a copy of the License at
  75732. *
  75733. * http://www.apache.org/licenses/LICENSE-2.0
  75734. *
  75735. * Unless required by applicable law or agreed to in writing,
  75736. * software distributed under the License is distributed on an
  75737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75738. * KIND, either express or implied. See the License for the
  75739. * specific language governing permissions and limitations
  75740. * under the License.
  75741. */
  75742. registerAction(
  75743. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  75744. function (payload, ecModel) {
  75745. var timelineModel = ecModel.getComponent('timeline');
  75746. if (timelineModel && payload.currentIndex != null) {
  75747. timelineModel.setCurrentIndex(payload.currentIndex);
  75748. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  75749. timelineModel.setPlayState(false);
  75750. }
  75751. }
  75752. // Set normalized currentIndex to payload.
  75753. ecModel.resetOption('timeline');
  75754. return defaults({
  75755. currentIndex: timelineModel.option.currentIndex
  75756. }, payload);
  75757. }
  75758. );
  75759. registerAction(
  75760. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  75761. function (payload, ecModel) {
  75762. var timelineModel = ecModel.getComponent('timeline');
  75763. if (timelineModel && payload.playState != null) {
  75764. timelineModel.setPlayState(payload.playState);
  75765. }
  75766. }
  75767. );
  75768. /*
  75769. * Licensed to the Apache Software Foundation (ASF) under one
  75770. * or more contributor license agreements. See the NOTICE file
  75771. * distributed with this work for additional information
  75772. * regarding copyright ownership. The ASF licenses this file
  75773. * to you under the Apache License, Version 2.0 (the
  75774. * "License"); you may not use this file except in compliance
  75775. * with the License. You may obtain a copy of the License at
  75776. *
  75777. * http://www.apache.org/licenses/LICENSE-2.0
  75778. *
  75779. * Unless required by applicable law or agreed to in writing,
  75780. * software distributed under the License is distributed on an
  75781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75782. * KIND, either express or implied. See the License for the
  75783. * specific language governing permissions and limitations
  75784. * under the License.
  75785. */
  75786. var TimelineModel = ComponentModel.extend({
  75787. type: 'timeline',
  75788. layoutMode: 'box',
  75789. /**
  75790. * @protected
  75791. */
  75792. defaultOption: {
  75793. zlevel: 0, // 一级层叠
  75794. z: 4, // 二级层叠
  75795. show: true,
  75796. axisType: 'time', // 模式是时间类型,支持 value, category
  75797. realtime: true,
  75798. left: '20%',
  75799. top: null,
  75800. right: '20%',
  75801. bottom: 0,
  75802. width: null,
  75803. height: 40,
  75804. padding: 5,
  75805. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  75806. autoPlay: false,
  75807. rewind: false, // 反向播放
  75808. loop: true,
  75809. playInterval: 2000, // 播放时间间隔,单位ms
  75810. currentIndex: 0,
  75811. itemStyle: {},
  75812. label: {
  75813. color: '#000'
  75814. },
  75815. data: []
  75816. },
  75817. /**
  75818. * @override
  75819. */
  75820. init: function (option, parentModel, ecModel) {
  75821. /**
  75822. * @private
  75823. * @type {module:echarts/data/List}
  75824. */
  75825. this._data;
  75826. /**
  75827. * @private
  75828. * @type {Array.<string>}
  75829. */
  75830. this._names;
  75831. this.mergeDefaultAndTheme(option, ecModel);
  75832. this._initData();
  75833. },
  75834. /**
  75835. * @override
  75836. */
  75837. mergeOption: function (option) {
  75838. TimelineModel.superApply(this, 'mergeOption', arguments);
  75839. this._initData();
  75840. },
  75841. /**
  75842. * @param {number} [currentIndex]
  75843. */
  75844. setCurrentIndex: function (currentIndex) {
  75845. if (currentIndex == null) {
  75846. currentIndex = this.option.currentIndex;
  75847. }
  75848. var count = this._data.count();
  75849. if (this.option.loop) {
  75850. currentIndex = (currentIndex % count + count) % count;
  75851. }
  75852. else {
  75853. currentIndex >= count && (currentIndex = count - 1);
  75854. currentIndex < 0 && (currentIndex = 0);
  75855. }
  75856. this.option.currentIndex = currentIndex;
  75857. },
  75858. /**
  75859. * @return {number} currentIndex
  75860. */
  75861. getCurrentIndex: function () {
  75862. return this.option.currentIndex;
  75863. },
  75864. /**
  75865. * @return {boolean}
  75866. */
  75867. isIndexMax: function () {
  75868. return this.getCurrentIndex() >= this._data.count() - 1;
  75869. },
  75870. /**
  75871. * @param {boolean} state true: play, false: stop
  75872. */
  75873. setPlayState: function (state) {
  75874. this.option.autoPlay = !!state;
  75875. },
  75876. /**
  75877. * @return {boolean} true: play, false: stop
  75878. */
  75879. getPlayState: function () {
  75880. return !!this.option.autoPlay;
  75881. },
  75882. /**
  75883. * @private
  75884. */
  75885. _initData: function () {
  75886. var thisOption = this.option;
  75887. var dataArr = thisOption.data || [];
  75888. var axisType = thisOption.axisType;
  75889. var names = this._names = [];
  75890. if (axisType === 'category') {
  75891. var idxArr = [];
  75892. each$1(dataArr, function (item, index) {
  75893. var value = getDataItemValue(item);
  75894. var newItem;
  75895. if (isObject$1(item)) {
  75896. newItem = clone(item);
  75897. newItem.value = index;
  75898. }
  75899. else {
  75900. newItem = index;
  75901. }
  75902. idxArr.push(newItem);
  75903. if (!isString(value) && (value == null || isNaN(value))) {
  75904. value = '';
  75905. }
  75906. names.push(value + '');
  75907. });
  75908. dataArr = idxArr;
  75909. }
  75910. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  75911. var data = this._data = new List([{name: 'value', type: dimType}], this);
  75912. data.initData(dataArr, names);
  75913. },
  75914. getData: function () {
  75915. return this._data;
  75916. },
  75917. /**
  75918. * @public
  75919. * @return {Array.<string>} categoreis
  75920. */
  75921. getCategories: function () {
  75922. if (this.get('axisType') === 'category') {
  75923. return this._names.slice();
  75924. }
  75925. }
  75926. });
  75927. /*
  75928. * Licensed to the Apache Software Foundation (ASF) under one
  75929. * or more contributor license agreements. See the NOTICE file
  75930. * distributed with this work for additional information
  75931. * regarding copyright ownership. The ASF licenses this file
  75932. * to you under the Apache License, Version 2.0 (the
  75933. * "License"); you may not use this file except in compliance
  75934. * with the License. You may obtain a copy of the License at
  75935. *
  75936. * http://www.apache.org/licenses/LICENSE-2.0
  75937. *
  75938. * Unless required by applicable law or agreed to in writing,
  75939. * software distributed under the License is distributed on an
  75940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75941. * KIND, either express or implied. See the License for the
  75942. * specific language governing permissions and limitations
  75943. * under the License.
  75944. */
  75945. var SliderTimelineModel = TimelineModel.extend({
  75946. type: 'timeline.slider',
  75947. /**
  75948. * @protected
  75949. */
  75950. defaultOption: {
  75951. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  75952. borderColor: '#ccc', // 时间轴边框颜色
  75953. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  75954. orient: 'horizontal', // 'vertical'
  75955. inverse: false,
  75956. tooltip: { // boolean or Object
  75957. trigger: 'item' // data item may also have tootip attr.
  75958. },
  75959. symbol: 'emptyCircle',
  75960. symbolSize: 10,
  75961. lineStyle: {
  75962. show: true,
  75963. width: 2,
  75964. color: '#304654'
  75965. },
  75966. label: { // 文本标签
  75967. position: 'auto', // auto left right top bottom
  75968. // When using number, label position is not
  75969. // restricted by viewRect.
  75970. // positive: right/bottom, negative: left/top
  75971. show: true,
  75972. interval: 'auto',
  75973. rotate: 0,
  75974. // formatter: null,
  75975. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  75976. color: '#304654'
  75977. },
  75978. itemStyle: {
  75979. color: '#304654',
  75980. borderWidth: 1
  75981. },
  75982. checkpointStyle: {
  75983. symbol: 'circle',
  75984. symbolSize: 13,
  75985. color: '#c23531',
  75986. borderWidth: 5,
  75987. borderColor: 'rgba(194,53,49, 0.5)',
  75988. animation: true,
  75989. animationDuration: 300,
  75990. animationEasing: 'quinticInOut'
  75991. },
  75992. controlStyle: {
  75993. show: true,
  75994. showPlayBtn: true,
  75995. showPrevBtn: true,
  75996. showNextBtn: true,
  75997. itemSize: 22,
  75998. itemGap: 12,
  75999. position: 'left', // 'left' 'right' 'top' 'bottom'
  76000. 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
  76001. 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
  76002. 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
  76003. 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
  76004. color: '#304654',
  76005. borderColor: '#304654',
  76006. borderWidth: 1
  76007. },
  76008. emphasis: {
  76009. label: {
  76010. show: true,
  76011. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  76012. color: '#c23531'
  76013. },
  76014. itemStyle: {
  76015. color: '#c23531'
  76016. },
  76017. controlStyle: {
  76018. color: '#c23531',
  76019. borderColor: '#c23531',
  76020. borderWidth: 2
  76021. }
  76022. },
  76023. data: []
  76024. }
  76025. });
  76026. mixin(SliderTimelineModel, dataFormatMixin);
  76027. /*
  76028. * Licensed to the Apache Software Foundation (ASF) under one
  76029. * or more contributor license agreements. See the NOTICE file
  76030. * distributed with this work for additional information
  76031. * regarding copyright ownership. The ASF licenses this file
  76032. * to you under the Apache License, Version 2.0 (the
  76033. * "License"); you may not use this file except in compliance
  76034. * with the License. You may obtain a copy of the License at
  76035. *
  76036. * http://www.apache.org/licenses/LICENSE-2.0
  76037. *
  76038. * Unless required by applicable law or agreed to in writing,
  76039. * software distributed under the License is distributed on an
  76040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76041. * KIND, either express or implied. See the License for the
  76042. * specific language governing permissions and limitations
  76043. * under the License.
  76044. */
  76045. var TimelineView = Component.extend({
  76046. type: 'timeline'
  76047. });
  76048. /*
  76049. * Licensed to the Apache Software Foundation (ASF) under one
  76050. * or more contributor license agreements. See the NOTICE file
  76051. * distributed with this work for additional information
  76052. * regarding copyright ownership. The ASF licenses this file
  76053. * to you under the Apache License, Version 2.0 (the
  76054. * "License"); you may not use this file except in compliance
  76055. * with the License. You may obtain a copy of the License at
  76056. *
  76057. * http://www.apache.org/licenses/LICENSE-2.0
  76058. *
  76059. * Unless required by applicable law or agreed to in writing,
  76060. * software distributed under the License is distributed on an
  76061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76062. * KIND, either express or implied. See the License for the
  76063. * specific language governing permissions and limitations
  76064. * under the License.
  76065. */
  76066. /**
  76067. * Extend axis 2d
  76068. * @constructor module:echarts/coord/cartesian/Axis2D
  76069. * @extends {module:echarts/coord/cartesian/Axis}
  76070. * @param {string} dim
  76071. * @param {*} scale
  76072. * @param {Array.<number>} coordExtent
  76073. * @param {string} axisType
  76074. * @param {string} position
  76075. */
  76076. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  76077. Axis.call(this, dim, scale, coordExtent);
  76078. /**
  76079. * Axis type
  76080. * - 'category'
  76081. * - 'value'
  76082. * - 'time'
  76083. * - 'log'
  76084. * @type {string}
  76085. */
  76086. this.type = axisType || 'value';
  76087. /**
  76088. * Axis model
  76089. * @param {module:echarts/component/TimelineModel}
  76090. */
  76091. this.model = null;
  76092. };
  76093. TimelineAxis.prototype = {
  76094. constructor: TimelineAxis,
  76095. /**
  76096. * @override
  76097. */
  76098. getLabelModel: function () {
  76099. return this.model.getModel('label');
  76100. },
  76101. /**
  76102. * @override
  76103. */
  76104. isHorizontal: function () {
  76105. return this.model.get('orient') === 'horizontal';
  76106. }
  76107. };
  76108. inherits(TimelineAxis, Axis);
  76109. /*
  76110. * Licensed to the Apache Software Foundation (ASF) under one
  76111. * or more contributor license agreements. See the NOTICE file
  76112. * distributed with this work for additional information
  76113. * regarding copyright ownership. The ASF licenses this file
  76114. * to you under the Apache License, Version 2.0 (the
  76115. * "License"); you may not use this file except in compliance
  76116. * with the License. You may obtain a copy of the License at
  76117. *
  76118. * http://www.apache.org/licenses/LICENSE-2.0
  76119. *
  76120. * Unless required by applicable law or agreed to in writing,
  76121. * software distributed under the License is distributed on an
  76122. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76123. * KIND, either express or implied. See the License for the
  76124. * specific language governing permissions and limitations
  76125. * under the License.
  76126. */
  76127. var bind$6 = bind;
  76128. var each$27 = each$1;
  76129. var PI$4 = Math.PI;
  76130. TimelineView.extend({
  76131. type: 'timeline.slider',
  76132. init: function (ecModel, api) {
  76133. this.api = api;
  76134. /**
  76135. * @private
  76136. * @type {module:echarts/component/timeline/TimelineAxis}
  76137. */
  76138. this._axis;
  76139. /**
  76140. * @private
  76141. * @type {module:zrender/core/BoundingRect}
  76142. */
  76143. this._viewRect;
  76144. /**
  76145. * @type {number}
  76146. */
  76147. this._timer;
  76148. /**
  76149. * @type {module:zrender/Element}
  76150. */
  76151. this._currentPointer;
  76152. /**
  76153. * @type {module:zrender/container/Group}
  76154. */
  76155. this._mainGroup;
  76156. /**
  76157. * @type {module:zrender/container/Group}
  76158. */
  76159. this._labelGroup;
  76160. },
  76161. /**
  76162. * @override
  76163. */
  76164. render: function (timelineModel, ecModel, api, payload) {
  76165. this.model = timelineModel;
  76166. this.api = api;
  76167. this.ecModel = ecModel;
  76168. this.group.removeAll();
  76169. if (timelineModel.get('show', true)) {
  76170. var layoutInfo = this._layout(timelineModel, api);
  76171. var mainGroup = this._createGroup('mainGroup');
  76172. var labelGroup = this._createGroup('labelGroup');
  76173. /**
  76174. * @private
  76175. * @type {module:echarts/component/timeline/TimelineAxis}
  76176. */
  76177. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  76178. timelineModel.formatTooltip = function (dataIndex) {
  76179. return encodeHTML(axis.scale.getLabel(dataIndex));
  76180. };
  76181. each$27(
  76182. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  76183. function (name) {
  76184. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  76185. },
  76186. this
  76187. );
  76188. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  76189. this._position(layoutInfo, timelineModel);
  76190. }
  76191. this._doPlayStop();
  76192. },
  76193. /**
  76194. * @override
  76195. */
  76196. remove: function () {
  76197. this._clearTimer();
  76198. this.group.removeAll();
  76199. },
  76200. /**
  76201. * @override
  76202. */
  76203. dispose: function () {
  76204. this._clearTimer();
  76205. },
  76206. _layout: function (timelineModel, api) {
  76207. var labelPosOpt = timelineModel.get('label.position');
  76208. var orient = timelineModel.get('orient');
  76209. var viewRect = getViewRect$4(timelineModel, api);
  76210. // Auto label offset.
  76211. if (labelPosOpt == null || labelPosOpt === 'auto') {
  76212. labelPosOpt = orient === 'horizontal'
  76213. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  76214. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  76215. }
  76216. else if (isNaN(labelPosOpt)) {
  76217. labelPosOpt = ({
  76218. horizontal: {top: '-', bottom: '+'},
  76219. vertical: {left: '-', right: '+'}
  76220. })[orient][labelPosOpt];
  76221. }
  76222. var labelAlignMap = {
  76223. horizontal: 'center',
  76224. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  76225. };
  76226. var labelBaselineMap = {
  76227. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  76228. vertical: 'middle'
  76229. };
  76230. var rotationMap = {
  76231. horizontal: 0,
  76232. vertical: PI$4 / 2
  76233. };
  76234. // Position
  76235. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  76236. var controlModel = timelineModel.getModel('controlStyle');
  76237. var showControl = controlModel.get('show', true);
  76238. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  76239. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  76240. var sizePlusGap = controlSize + controlGap;
  76241. // Special label rotate.
  76242. var labelRotation = timelineModel.get('label.rotate') || 0;
  76243. labelRotation = labelRotation * PI$4 / 180; // To radian.
  76244. var playPosition;
  76245. var prevBtnPosition;
  76246. var nextBtnPosition;
  76247. var axisExtent;
  76248. var controlPosition = controlModel.get('position', true);
  76249. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  76250. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  76251. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  76252. var xLeft = 0;
  76253. var xRight = mainLength;
  76254. // position[0] means left, position[1] means middle.
  76255. if (controlPosition === 'left' || controlPosition === 'bottom') {
  76256. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  76257. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  76258. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76259. }
  76260. else { // 'top' 'right'
  76261. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76262. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  76263. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76264. }
  76265. axisExtent = [xLeft, xRight];
  76266. if (timelineModel.get('inverse')) {
  76267. axisExtent.reverse();
  76268. }
  76269. return {
  76270. viewRect: viewRect,
  76271. mainLength: mainLength,
  76272. orient: orient,
  76273. rotation: rotationMap[orient],
  76274. labelRotation: labelRotation,
  76275. labelPosOpt: labelPosOpt,
  76276. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  76277. labelBaseline: timelineModel.get('label.verticalAlign')
  76278. || timelineModel.get('label.baseline')
  76279. || labelBaselineMap[orient],
  76280. // Based on mainGroup.
  76281. playPosition: playPosition,
  76282. prevBtnPosition: prevBtnPosition,
  76283. nextBtnPosition: nextBtnPosition,
  76284. axisExtent: axisExtent,
  76285. controlSize: controlSize,
  76286. controlGap: controlGap
  76287. };
  76288. },
  76289. _position: function (layoutInfo, timelineModel) {
  76290. // Position is be called finally, because bounding rect is needed for
  76291. // adapt content to fill viewRect (auto adapt offset).
  76292. // Timeline may be not all in the viewRect when 'offset' is specified
  76293. // as a number, because it is more appropriate that label aligns at
  76294. // 'offset' but not the other edge defined by viewRect.
  76295. var mainGroup = this._mainGroup;
  76296. var labelGroup = this._labelGroup;
  76297. var viewRect = layoutInfo.viewRect;
  76298. if (layoutInfo.orient === 'vertical') {
  76299. // transform to horizontal, inverse rotate by left-top point.
  76300. var m = create$1();
  76301. var rotateOriginX = viewRect.x;
  76302. var rotateOriginY = viewRect.y + viewRect.height;
  76303. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  76304. rotate(m, m, -PI$4 / 2);
  76305. translate(m, m, [rotateOriginX, rotateOriginY]);
  76306. viewRect = viewRect.clone();
  76307. viewRect.applyTransform(m);
  76308. }
  76309. var viewBound = getBound(viewRect);
  76310. var mainBound = getBound(mainGroup.getBoundingRect());
  76311. var labelBound = getBound(labelGroup.getBoundingRect());
  76312. var mainPosition = mainGroup.position;
  76313. var labelsPosition = labelGroup.position;
  76314. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  76315. var labelPosOpt = layoutInfo.labelPosOpt;
  76316. if (isNaN(labelPosOpt)) { // '+' or '-'
  76317. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  76318. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  76319. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  76320. }
  76321. else {
  76322. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  76323. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  76324. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  76325. }
  76326. mainGroup.attr('position', mainPosition);
  76327. labelGroup.attr('position', labelsPosition);
  76328. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  76329. setOrigin(mainGroup);
  76330. setOrigin(labelGroup);
  76331. function setOrigin(targetGroup) {
  76332. var pos = targetGroup.position;
  76333. targetGroup.origin = [
  76334. viewBound[0][0] - pos[0],
  76335. viewBound[1][0] - pos[1]
  76336. ];
  76337. }
  76338. function getBound(rect) {
  76339. // [[xmin, xmax], [ymin, ymax]]
  76340. return [
  76341. [rect.x, rect.x + rect.width],
  76342. [rect.y, rect.y + rect.height]
  76343. ];
  76344. }
  76345. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  76346. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  76347. }
  76348. },
  76349. _createAxis: function (layoutInfo, timelineModel) {
  76350. var data = timelineModel.getData();
  76351. var axisType = timelineModel.get('axisType');
  76352. var scale = createScaleByModel(timelineModel, axisType);
  76353. // Customize scale. The `tickValue` is `dataIndex`.
  76354. scale.getTicks = function () {
  76355. return data.mapArray(['value'], function (value) {
  76356. return value;
  76357. });
  76358. };
  76359. var dataExtent = data.getDataExtent('value');
  76360. scale.setExtent(dataExtent[0], dataExtent[1]);
  76361. scale.niceTicks();
  76362. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  76363. axis.model = timelineModel;
  76364. return axis;
  76365. },
  76366. _createGroup: function (name) {
  76367. var newGroup = this['_' + name] = new Group();
  76368. this.group.add(newGroup);
  76369. return newGroup;
  76370. },
  76371. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  76372. var axisExtent = axis.getExtent();
  76373. if (!timelineModel.get('lineStyle.show')) {
  76374. return;
  76375. }
  76376. group.add(new Line({
  76377. shape: {
  76378. x1: axisExtent[0], y1: 0,
  76379. x2: axisExtent[1], y2: 0
  76380. },
  76381. style: extend(
  76382. {lineCap: 'round'},
  76383. timelineModel.getModel('lineStyle').getLineStyle()
  76384. ),
  76385. silent: true,
  76386. z2: 1
  76387. }));
  76388. },
  76389. /**
  76390. * @private
  76391. */
  76392. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  76393. var data = timelineModel.getData();
  76394. // Show all ticks, despite ignoring strategy.
  76395. var ticks = axis.scale.getTicks();
  76396. // The value is dataIndex, see the costomized scale.
  76397. each$27(ticks, function (value) {
  76398. var tickCoord = axis.dataToCoord(value);
  76399. var itemModel = data.getItemModel(value);
  76400. var itemStyleModel = itemModel.getModel('itemStyle');
  76401. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  76402. var symbolOpt = {
  76403. position: [tickCoord, 0],
  76404. onclick: bind$6(this._changeTimeline, this, value)
  76405. };
  76406. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  76407. setHoverStyle(el, hoverStyleModel.getItemStyle());
  76408. if (itemModel.get('tooltip')) {
  76409. el.dataIndex = value;
  76410. el.dataModel = timelineModel;
  76411. }
  76412. else {
  76413. el.dataIndex = el.dataModel = null;
  76414. }
  76415. }, this);
  76416. },
  76417. /**
  76418. * @private
  76419. */
  76420. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  76421. var labelModel = axis.getLabelModel();
  76422. if (!labelModel.get('show')) {
  76423. return;
  76424. }
  76425. var data = timelineModel.getData();
  76426. var labels = axis.getViewLabels();
  76427. each$27(labels, function (labelItem) {
  76428. // The tickValue is dataIndex, see the costomized scale.
  76429. var dataIndex = labelItem.tickValue;
  76430. var itemModel = data.getItemModel(dataIndex);
  76431. var normalLabelModel = itemModel.getModel('label');
  76432. var hoverLabelModel = itemModel.getModel('emphasis.label');
  76433. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  76434. var textEl = new Text({
  76435. position: [tickCoord, 0],
  76436. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  76437. onclick: bind$6(this._changeTimeline, this, dataIndex),
  76438. silent: false
  76439. });
  76440. setTextStyle(textEl.style, normalLabelModel, {
  76441. text: labelItem.formattedLabel,
  76442. textAlign: layoutInfo.labelAlign,
  76443. textVerticalAlign: layoutInfo.labelBaseline
  76444. });
  76445. group.add(textEl);
  76446. setHoverStyle(
  76447. textEl, setTextStyle({}, hoverLabelModel)
  76448. );
  76449. }, this);
  76450. },
  76451. /**
  76452. * @private
  76453. */
  76454. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  76455. var controlSize = layoutInfo.controlSize;
  76456. var rotation = layoutInfo.rotation;
  76457. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  76458. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  76459. var rect = [0, -controlSize / 2, controlSize, controlSize];
  76460. var playState = timelineModel.getPlayState();
  76461. var inverse = timelineModel.get('inverse', true);
  76462. makeBtn(
  76463. layoutInfo.nextBtnPosition,
  76464. 'controlStyle.nextIcon',
  76465. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  76466. );
  76467. makeBtn(
  76468. layoutInfo.prevBtnPosition,
  76469. 'controlStyle.prevIcon',
  76470. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  76471. );
  76472. makeBtn(
  76473. layoutInfo.playPosition,
  76474. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  76475. bind$6(this._handlePlayClick, this, !playState),
  76476. true
  76477. );
  76478. function makeBtn(position, iconPath, onclick, willRotate) {
  76479. if (!position) {
  76480. return;
  76481. }
  76482. var opt = {
  76483. position: position,
  76484. origin: [controlSize / 2, 0],
  76485. rotation: willRotate ? -rotation : 0,
  76486. rectHover: true,
  76487. style: itemStyle,
  76488. onclick: onclick
  76489. };
  76490. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  76491. group.add(btn);
  76492. setHoverStyle(btn, hoverStyle);
  76493. }
  76494. },
  76495. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  76496. var data = timelineModel.getData();
  76497. var currentIndex = timelineModel.getCurrentIndex();
  76498. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  76499. var me = this;
  76500. var callback = {
  76501. onCreate: function (pointer) {
  76502. pointer.draggable = true;
  76503. pointer.drift = bind$6(me._handlePointerDrag, me);
  76504. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  76505. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  76506. },
  76507. onUpdate: function (pointer) {
  76508. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  76509. }
  76510. };
  76511. // Reuse when exists, for animation and drag.
  76512. this._currentPointer = giveSymbol(
  76513. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  76514. );
  76515. },
  76516. _handlePlayClick: function (nextState) {
  76517. this._clearTimer();
  76518. this.api.dispatchAction({
  76519. type: 'timelinePlayChange',
  76520. playState: nextState,
  76521. from: this.uid
  76522. });
  76523. },
  76524. _handlePointerDrag: function (dx, dy, e) {
  76525. this._clearTimer();
  76526. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  76527. },
  76528. _handlePointerDragend: function (e) {
  76529. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  76530. },
  76531. _pointerChangeTimeline: function (mousePos, trigger) {
  76532. var toCoord = this._toAxisCoord(mousePos)[0];
  76533. var axis = this._axis;
  76534. var axisExtent = asc(axis.getExtent().slice());
  76535. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  76536. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  76537. this._currentPointer.position[0] = toCoord;
  76538. this._currentPointer.dirty();
  76539. var targetDataIndex = this._findNearestTick(toCoord);
  76540. var timelineModel = this.model;
  76541. if (trigger || (
  76542. targetDataIndex !== timelineModel.getCurrentIndex()
  76543. && timelineModel.get('realtime')
  76544. )) {
  76545. this._changeTimeline(targetDataIndex);
  76546. }
  76547. },
  76548. _doPlayStop: function () {
  76549. this._clearTimer();
  76550. if (this.model.getPlayState()) {
  76551. this._timer = setTimeout(
  76552. bind$6(handleFrame, this),
  76553. this.model.get('playInterval')
  76554. );
  76555. }
  76556. function handleFrame() {
  76557. // Do not cache
  76558. var timelineModel = this.model;
  76559. this._changeTimeline(
  76560. timelineModel.getCurrentIndex()
  76561. + (timelineModel.get('rewind', true) ? -1 : 1)
  76562. );
  76563. }
  76564. },
  76565. _toAxisCoord: function (vertex) {
  76566. var trans = this._mainGroup.getLocalTransform();
  76567. return applyTransform$1(vertex, trans, true);
  76568. },
  76569. _findNearestTick: function (axisCoord) {
  76570. var data = this.model.getData();
  76571. var dist = Infinity;
  76572. var targetDataIndex;
  76573. var axis = this._axis;
  76574. data.each(['value'], function (value, dataIndex) {
  76575. var coord = axis.dataToCoord(value);
  76576. var d = Math.abs(coord - axisCoord);
  76577. if (d < dist) {
  76578. dist = d;
  76579. targetDataIndex = dataIndex;
  76580. }
  76581. });
  76582. return targetDataIndex;
  76583. },
  76584. _clearTimer: function () {
  76585. if (this._timer) {
  76586. clearTimeout(this._timer);
  76587. this._timer = null;
  76588. }
  76589. },
  76590. _changeTimeline: function (nextIndex) {
  76591. var currentIndex = this.model.getCurrentIndex();
  76592. if (nextIndex === '+') {
  76593. nextIndex = currentIndex + 1;
  76594. }
  76595. else if (nextIndex === '-') {
  76596. nextIndex = currentIndex - 1;
  76597. }
  76598. this.api.dispatchAction({
  76599. type: 'timelineChange',
  76600. currentIndex: nextIndex,
  76601. from: this.uid
  76602. });
  76603. }
  76604. });
  76605. function getViewRect$4(model, api) {
  76606. return getLayoutRect(
  76607. model.getBoxLayoutParams(),
  76608. {
  76609. width: api.getWidth(),
  76610. height: api.getHeight()
  76611. },
  76612. model.get('padding')
  76613. );
  76614. }
  76615. function makeIcon(timelineModel, objPath, rect, opts) {
  76616. var icon = makePath(
  76617. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  76618. clone(opts || {}),
  76619. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  76620. 'center'
  76621. );
  76622. return icon;
  76623. }
  76624. /**
  76625. * Create symbol or update symbol
  76626. * opt: basic position and event handlers
  76627. */
  76628. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  76629. var color = itemStyleModel.get('color');
  76630. if (!symbol) {
  76631. var symbolType = hostModel.get('symbol');
  76632. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  76633. symbol.setStyle('strokeNoScale', true);
  76634. group.add(symbol);
  76635. callback && callback.onCreate(symbol);
  76636. }
  76637. else {
  76638. symbol.setColor(color);
  76639. group.add(symbol); // Group may be new, also need to add.
  76640. callback && callback.onUpdate(symbol);
  76641. }
  76642. // Style
  76643. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  76644. symbol.setStyle(itemStyle);
  76645. // Transform and events.
  76646. opt = merge({
  76647. rectHover: true,
  76648. z2: 100
  76649. }, opt, true);
  76650. var symbolSize = hostModel.get('symbolSize');
  76651. symbolSize = symbolSize instanceof Array
  76652. ? symbolSize.slice()
  76653. : [+symbolSize, +symbolSize];
  76654. symbolSize[0] /= 2;
  76655. symbolSize[1] /= 2;
  76656. opt.scale = symbolSize;
  76657. var symbolOffset = hostModel.get('symbolOffset');
  76658. if (symbolOffset) {
  76659. var pos = opt.position = opt.position || [0, 0];
  76660. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  76661. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  76662. }
  76663. var symbolRotate = hostModel.get('symbolRotate');
  76664. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  76665. symbol.attr(opt);
  76666. // FIXME
  76667. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  76668. // getBoundingRect will return wrong result.
  76669. // (This is supposed to be resolved in zrender, but it is a little difficult to
  76670. // leverage performance and auto updateTransform)
  76671. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  76672. symbol.updateTransform();
  76673. return symbol;
  76674. }
  76675. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  76676. if (pointer.dragging) {
  76677. return;
  76678. }
  76679. var pointerModel = timelineModel.getModel('checkpointStyle');
  76680. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  76681. if (noAnimation || !pointerModel.get('animation', true)) {
  76682. pointer.attr({position: [toCoord, 0]});
  76683. }
  76684. else {
  76685. pointer.stopAnimation(true);
  76686. pointer.animateTo(
  76687. {position: [toCoord, 0]},
  76688. pointerModel.get('animationDuration', true),
  76689. pointerModel.get('animationEasing', true)
  76690. );
  76691. }
  76692. }
  76693. /*
  76694. * Licensed to the Apache Software Foundation (ASF) under one
  76695. * or more contributor license agreements. See the NOTICE file
  76696. * distributed with this work for additional information
  76697. * regarding copyright ownership. The ASF licenses this file
  76698. * to you under the Apache License, Version 2.0 (the
  76699. * "License"); you may not use this file except in compliance
  76700. * with the License. You may obtain a copy of the License at
  76701. *
  76702. * http://www.apache.org/licenses/LICENSE-2.0
  76703. *
  76704. * Unless required by applicable law or agreed to in writing,
  76705. * software distributed under the License is distributed on an
  76706. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76707. * KIND, either express or implied. See the License for the
  76708. * specific language governing permissions and limitations
  76709. * under the License.
  76710. */
  76711. /**
  76712. * DataZoom component entry
  76713. */
  76714. registerPreprocessor(preprocessor$3);
  76715. /*
  76716. * Licensed to the Apache Software Foundation (ASF) under one
  76717. * or more contributor license agreements. See the NOTICE file
  76718. * distributed with this work for additional information
  76719. * regarding copyright ownership. The ASF licenses this file
  76720. * to you under the Apache License, Version 2.0 (the
  76721. * "License"); you may not use this file except in compliance
  76722. * with the License. You may obtain a copy of the License at
  76723. *
  76724. * http://www.apache.org/licenses/LICENSE-2.0
  76725. *
  76726. * Unless required by applicable law or agreed to in writing,
  76727. * software distributed under the License is distributed on an
  76728. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76729. * KIND, either express or implied. See the License for the
  76730. * specific language governing permissions and limitations
  76731. * under the License.
  76732. */
  76733. var ToolboxModel = extendComponentModel({
  76734. type: 'toolbox',
  76735. layoutMode: {
  76736. type: 'box',
  76737. ignoreSize: true
  76738. },
  76739. optionUpdated: function () {
  76740. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  76741. each$1(this.option.feature, function (featureOpt, featureName) {
  76742. var Feature = get$1(featureName);
  76743. Feature && merge(featureOpt, Feature.defaultOption);
  76744. });
  76745. },
  76746. defaultOption: {
  76747. show: true,
  76748. z: 6,
  76749. zlevel: 0,
  76750. orient: 'horizontal',
  76751. left: 'right',
  76752. top: 'top',
  76753. // right
  76754. // bottom
  76755. backgroundColor: 'transparent',
  76756. borderColor: '#ccc',
  76757. borderRadius: 0,
  76758. borderWidth: 0,
  76759. padding: 5,
  76760. itemSize: 15,
  76761. itemGap: 8,
  76762. showTitle: true,
  76763. iconStyle: {
  76764. borderColor: '#666',
  76765. color: 'none'
  76766. },
  76767. emphasis: {
  76768. iconStyle: {
  76769. borderColor: '#3E98C5'
  76770. }
  76771. }
  76772. // textStyle: {},
  76773. // feature
  76774. }
  76775. });
  76776. /*
  76777. * Licensed to the Apache Software Foundation (ASF) under one
  76778. * or more contributor license agreements. See the NOTICE file
  76779. * distributed with this work for additional information
  76780. * regarding copyright ownership. The ASF licenses this file
  76781. * to you under the Apache License, Version 2.0 (the
  76782. * "License"); you may not use this file except in compliance
  76783. * with the License. You may obtain a copy of the License at
  76784. *
  76785. * http://www.apache.org/licenses/LICENSE-2.0
  76786. *
  76787. * Unless required by applicable law or agreed to in writing,
  76788. * software distributed under the License is distributed on an
  76789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76790. * KIND, either express or implied. See the License for the
  76791. * specific language governing permissions and limitations
  76792. * under the License.
  76793. */
  76794. extendComponentView({
  76795. type: 'toolbox',
  76796. render: function (toolboxModel, ecModel, api, payload) {
  76797. var group = this.group;
  76798. group.removeAll();
  76799. if (!toolboxModel.get('show')) {
  76800. return;
  76801. }
  76802. var itemSize = +toolboxModel.get('itemSize');
  76803. var featureOpts = toolboxModel.get('feature') || {};
  76804. var features = this._features || (this._features = {});
  76805. var featureNames = [];
  76806. each$1(featureOpts, function (opt, name) {
  76807. featureNames.push(name);
  76808. });
  76809. (new DataDiffer(this._featureNames || [], featureNames))
  76810. .add(processFeature)
  76811. .update(processFeature)
  76812. .remove(curry(processFeature, null))
  76813. .execute();
  76814. // Keep for diff.
  76815. this._featureNames = featureNames;
  76816. function processFeature(newIndex, oldIndex) {
  76817. var featureName = featureNames[newIndex];
  76818. var oldName = featureNames[oldIndex];
  76819. var featureOpt = featureOpts[featureName];
  76820. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  76821. var feature;
  76822. if (featureName && !oldName) { // Create
  76823. if (isUserFeatureName(featureName)) {
  76824. feature = {
  76825. model: featureModel,
  76826. onclick: featureModel.option.onclick,
  76827. featureName: featureName
  76828. };
  76829. }
  76830. else {
  76831. var Feature = get$1(featureName);
  76832. if (!Feature) {
  76833. return;
  76834. }
  76835. feature = new Feature(featureModel, ecModel, api);
  76836. }
  76837. features[featureName] = feature;
  76838. }
  76839. else {
  76840. feature = features[oldName];
  76841. // If feature does not exsit.
  76842. if (!feature) {
  76843. return;
  76844. }
  76845. feature.model = featureModel;
  76846. feature.ecModel = ecModel;
  76847. feature.api = api;
  76848. }
  76849. if (!featureName && oldName) {
  76850. feature.dispose && feature.dispose(ecModel, api);
  76851. return;
  76852. }
  76853. if (!featureModel.get('show') || feature.unusable) {
  76854. feature.remove && feature.remove(ecModel, api);
  76855. return;
  76856. }
  76857. createIconPaths(featureModel, feature, featureName);
  76858. featureModel.setIconStatus = function (iconName, status) {
  76859. var option = this.option;
  76860. var iconPaths = this.iconPaths;
  76861. option.iconStatus = option.iconStatus || {};
  76862. option.iconStatus[iconName] = status;
  76863. // FIXME
  76864. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  76865. };
  76866. if (feature.render) {
  76867. feature.render(featureModel, ecModel, api, payload);
  76868. }
  76869. }
  76870. function createIconPaths(featureModel, feature, featureName) {
  76871. var iconStyleModel = featureModel.getModel('iconStyle');
  76872. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  76873. // If one feature has mutiple icon. they are orginaized as
  76874. // {
  76875. // icon: {
  76876. // foo: '',
  76877. // bar: ''
  76878. // },
  76879. // title: {
  76880. // foo: '',
  76881. // bar: ''
  76882. // }
  76883. // }
  76884. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  76885. var titles = featureModel.get('title') || {};
  76886. if (typeof icons === 'string') {
  76887. var icon = icons;
  76888. var title = titles;
  76889. icons = {};
  76890. titles = {};
  76891. icons[featureName] = icon;
  76892. titles[featureName] = title;
  76893. }
  76894. var iconPaths = featureModel.iconPaths = {};
  76895. each$1(icons, function (iconStr, iconName) {
  76896. var path = createIcon(
  76897. iconStr,
  76898. {},
  76899. {
  76900. x: -itemSize / 2,
  76901. y: -itemSize / 2,
  76902. width: itemSize,
  76903. height: itemSize
  76904. }
  76905. );
  76906. path.setStyle(iconStyleModel.getItemStyle());
  76907. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76908. setHoverStyle(path);
  76909. if (toolboxModel.get('showTitle')) {
  76910. path.__title = titles[iconName];
  76911. path.on('mouseover', function () {
  76912. // Should not reuse above hoverStyle, which might be modified.
  76913. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76914. path.setStyle({
  76915. text: titles[iconName],
  76916. textPosition: hoverStyle.textPosition || 'bottom',
  76917. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  76918. textAlign: hoverStyle.textAlign || 'center'
  76919. });
  76920. })
  76921. .on('mouseout', function () {
  76922. path.setStyle({
  76923. textFill: null
  76924. });
  76925. });
  76926. }
  76927. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  76928. group.add(path);
  76929. path.on('click', bind(
  76930. feature.onclick, feature, ecModel, api, iconName
  76931. ));
  76932. iconPaths[iconName] = path;
  76933. });
  76934. }
  76935. layout$3(group, toolboxModel, api);
  76936. // Render background after group is layout
  76937. // FIXME
  76938. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  76939. // Adjust icon title positions to avoid them out of screen
  76940. group.eachChild(function (icon) {
  76941. var titleText = icon.__title;
  76942. var hoverStyle = icon.hoverStyle;
  76943. // May be background element
  76944. if (hoverStyle && titleText) {
  76945. var rect = getBoundingRect(
  76946. titleText, makeFont(hoverStyle)
  76947. );
  76948. var offsetX = icon.position[0] + group.position[0];
  76949. var offsetY = icon.position[1] + group.position[1] + itemSize;
  76950. var needPutOnTop = false;
  76951. if (offsetY + rect.height > api.getHeight()) {
  76952. hoverStyle.textPosition = 'top';
  76953. needPutOnTop = true;
  76954. }
  76955. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  76956. if (offsetX + rect.width / 2 > api.getWidth()) {
  76957. hoverStyle.textPosition = ['100%', topOffset];
  76958. hoverStyle.textAlign = 'right';
  76959. }
  76960. else if (offsetX - rect.width / 2 < 0) {
  76961. hoverStyle.textPosition = [0, topOffset];
  76962. hoverStyle.textAlign = 'left';
  76963. }
  76964. }
  76965. });
  76966. },
  76967. updateView: function (toolboxModel, ecModel, api, payload) {
  76968. each$1(this._features, function (feature) {
  76969. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  76970. });
  76971. },
  76972. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  76973. // zrUtil.each(this._features, function (feature) {
  76974. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  76975. // });
  76976. // },
  76977. remove: function (ecModel, api) {
  76978. each$1(this._features, function (feature) {
  76979. feature.remove && feature.remove(ecModel, api);
  76980. });
  76981. this.group.removeAll();
  76982. },
  76983. dispose: function (ecModel, api) {
  76984. each$1(this._features, function (feature) {
  76985. feature.dispose && feature.dispose(ecModel, api);
  76986. });
  76987. }
  76988. });
  76989. function isUserFeatureName(featureName) {
  76990. return featureName.indexOf('my') === 0;
  76991. }
  76992. /*
  76993. * Licensed to the Apache Software Foundation (ASF) under one
  76994. * or more contributor license agreements. See the NOTICE file
  76995. * distributed with this work for additional information
  76996. * regarding copyright ownership. The ASF licenses this file
  76997. * to you under the Apache License, Version 2.0 (the
  76998. * "License"); you may not use this file except in compliance
  76999. * with the License. You may obtain a copy of the License at
  77000. *
  77001. * http://www.apache.org/licenses/LICENSE-2.0
  77002. *
  77003. * Unless required by applicable law or agreed to in writing,
  77004. * software distributed under the License is distributed on an
  77005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77006. * KIND, either express or implied. See the License for the
  77007. * specific language governing permissions and limitations
  77008. * under the License.
  77009. */
  77010. /* global Uint8Array */
  77011. var saveAsImageLang = lang.toolbox.saveAsImage;
  77012. function SaveAsImage(model) {
  77013. this.model = model;
  77014. }
  77015. SaveAsImage.defaultOption = {
  77016. show: true,
  77017. 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',
  77018. title: saveAsImageLang.title,
  77019. type: 'png',
  77020. // Default use option.backgroundColor
  77021. // backgroundColor: '#fff',
  77022. name: '',
  77023. excludeComponents: ['toolbox'],
  77024. pixelRatio: 1,
  77025. lang: saveAsImageLang.lang.slice()
  77026. };
  77027. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  77028. var proto$4 = SaveAsImage.prototype;
  77029. proto$4.onclick = function (ecModel, api) {
  77030. var model = this.model;
  77031. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  77032. var $a = document.createElement('a');
  77033. var type = model.get('type', true) || 'png';
  77034. $a.download = title + '.' + type;
  77035. $a.target = '_blank';
  77036. var url = api.getConnectedDataURL({
  77037. type: type,
  77038. backgroundColor: model.get('backgroundColor', true)
  77039. || ecModel.get('backgroundColor') || '#fff',
  77040. excludeComponents: model.get('excludeComponents'),
  77041. pixelRatio: model.get('pixelRatio')
  77042. });
  77043. $a.href = url;
  77044. // Chrome and Firefox
  77045. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  77046. var evt = new MouseEvent('click', {
  77047. view: window,
  77048. bubbles: true,
  77049. cancelable: false
  77050. });
  77051. $a.dispatchEvent(evt);
  77052. }
  77053. // IE
  77054. else {
  77055. if (window.navigator.msSaveOrOpenBlob) {
  77056. var bstr = atob(url.split(',')[1]);
  77057. var n = bstr.length;
  77058. var u8arr = new Uint8Array(n);
  77059. while (n--) {
  77060. u8arr[n] = bstr.charCodeAt(n);
  77061. }
  77062. var blob = new Blob([u8arr]);
  77063. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  77064. }
  77065. else {
  77066. var lang$$1 = model.get('lang');
  77067. var html = ''
  77068. + '<body style="margin:0;">'
  77069. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  77070. + '</body>';
  77071. var tab = window.open();
  77072. tab.document.write(html);
  77073. }
  77074. }
  77075. };
  77076. register$1(
  77077. 'saveAsImage', SaveAsImage
  77078. );
  77079. /*
  77080. * Licensed to the Apache Software Foundation (ASF) under one
  77081. * or more contributor license agreements. See the NOTICE file
  77082. * distributed with this work for additional information
  77083. * regarding copyright ownership. The ASF licenses this file
  77084. * to you under the Apache License, Version 2.0 (the
  77085. * "License"); you may not use this file except in compliance
  77086. * with the License. You may obtain a copy of the License at
  77087. *
  77088. * http://www.apache.org/licenses/LICENSE-2.0
  77089. *
  77090. * Unless required by applicable law or agreed to in writing,
  77091. * software distributed under the License is distributed on an
  77092. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77093. * KIND, either express or implied. See the License for the
  77094. * specific language governing permissions and limitations
  77095. * under the License.
  77096. */
  77097. var magicTypeLang = lang.toolbox.magicType;
  77098. function MagicType(model) {
  77099. this.model = model;
  77100. }
  77101. MagicType.defaultOption = {
  77102. show: true,
  77103. type: [],
  77104. // Icon group
  77105. icon: {
  77106. /* eslint-disable */
  77107. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  77108. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  77109. 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
  77110. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  77111. /* eslint-enable */
  77112. },
  77113. // `line`, `bar`, `stack`, `tiled`
  77114. title: clone(magicTypeLang.title),
  77115. option: {},
  77116. seriesIndex: {}
  77117. };
  77118. var proto$5 = MagicType.prototype;
  77119. proto$5.getIcons = function () {
  77120. var model = this.model;
  77121. var availableIcons = model.get('icon');
  77122. var icons = {};
  77123. each$1(model.get('type'), function (type) {
  77124. if (availableIcons[type]) {
  77125. icons[type] = availableIcons[type];
  77126. }
  77127. });
  77128. return icons;
  77129. };
  77130. var seriesOptGenreator = {
  77131. 'line': function (seriesType, seriesId, seriesModel, model) {
  77132. if (seriesType === 'bar') {
  77133. return merge({
  77134. id: seriesId,
  77135. type: 'line',
  77136. // Preserve data related option
  77137. data: seriesModel.get('data'),
  77138. stack: seriesModel.get('stack'),
  77139. markPoint: seriesModel.get('markPoint'),
  77140. markLine: seriesModel.get('markLine')
  77141. }, model.get('option.line') || {}, true);
  77142. }
  77143. },
  77144. 'bar': function (seriesType, seriesId, seriesModel, model) {
  77145. if (seriesType === 'line') {
  77146. return merge({
  77147. id: seriesId,
  77148. type: 'bar',
  77149. // Preserve data related option
  77150. data: seriesModel.get('data'),
  77151. stack: seriesModel.get('stack'),
  77152. markPoint: seriesModel.get('markPoint'),
  77153. markLine: seriesModel.get('markLine')
  77154. }, model.get('option.bar') || {}, true);
  77155. }
  77156. },
  77157. 'stack': function (seriesType, seriesId, seriesModel, model) {
  77158. if (seriesType === 'line' || seriesType === 'bar') {
  77159. return merge({
  77160. id: seriesId,
  77161. stack: '__ec_magicType_stack__'
  77162. }, model.get('option.stack') || {}, true);
  77163. }
  77164. },
  77165. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  77166. if (seriesType === 'line' || seriesType === 'bar') {
  77167. return merge({
  77168. id: seriesId,
  77169. stack: ''
  77170. }, model.get('option.tiled') || {}, true);
  77171. }
  77172. }
  77173. };
  77174. var radioTypes = [
  77175. ['line', 'bar'],
  77176. ['stack', 'tiled']
  77177. ];
  77178. proto$5.onclick = function (ecModel, api, type) {
  77179. var model = this.model;
  77180. var seriesIndex = model.get('seriesIndex.' + type);
  77181. // Not supported magicType
  77182. if (!seriesOptGenreator[type]) {
  77183. return;
  77184. }
  77185. var newOption = {
  77186. series: []
  77187. };
  77188. var generateNewSeriesTypes = function (seriesModel) {
  77189. var seriesType = seriesModel.subType;
  77190. var seriesId = seriesModel.id;
  77191. var newSeriesOpt = seriesOptGenreator[type](
  77192. seriesType, seriesId, seriesModel, model
  77193. );
  77194. if (newSeriesOpt) {
  77195. // PENDING If merge original option?
  77196. defaults(newSeriesOpt, seriesModel.option);
  77197. newOption.series.push(newSeriesOpt);
  77198. }
  77199. // Modify boundaryGap
  77200. var coordSys = seriesModel.coordinateSystem;
  77201. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  77202. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  77203. if (categoryAxis) {
  77204. var axisDim = categoryAxis.dim;
  77205. var axisType = axisDim + 'Axis';
  77206. var axisModel = ecModel.queryComponents({
  77207. mainType: axisType,
  77208. index: seriesModel.get(name + 'Index'),
  77209. id: seriesModel.get(name + 'Id')
  77210. })[0];
  77211. var axisIndex = axisModel.componentIndex;
  77212. newOption[axisType] = newOption[axisType] || [];
  77213. for (var i = 0; i <= axisIndex; i++) {
  77214. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  77215. }
  77216. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  77217. }
  77218. }
  77219. };
  77220. each$1(radioTypes, function (radio) {
  77221. if (indexOf(radio, type) >= 0) {
  77222. each$1(radio, function (item) {
  77223. model.setIconStatus(item, 'normal');
  77224. });
  77225. }
  77226. });
  77227. model.setIconStatus(type, 'emphasis');
  77228. ecModel.eachComponent(
  77229. {
  77230. mainType: 'series',
  77231. query: seriesIndex == null ? null : {
  77232. seriesIndex: seriesIndex
  77233. }
  77234. }, generateNewSeriesTypes
  77235. );
  77236. api.dispatchAction({
  77237. type: 'changeMagicType',
  77238. currentType: type,
  77239. newOption: newOption
  77240. });
  77241. };
  77242. registerAction({
  77243. type: 'changeMagicType',
  77244. event: 'magicTypeChanged',
  77245. update: 'prepareAndUpdate'
  77246. }, function (payload, ecModel) {
  77247. ecModel.mergeOption(payload.newOption);
  77248. });
  77249. register$1('magicType', MagicType);
  77250. /*
  77251. * Licensed to the Apache Software Foundation (ASF) under one
  77252. * or more contributor license agreements. See the NOTICE file
  77253. * distributed with this work for additional information
  77254. * regarding copyright ownership. The ASF licenses this file
  77255. * to you under the Apache License, Version 2.0 (the
  77256. * "License"); you may not use this file except in compliance
  77257. * with the License. You may obtain a copy of the License at
  77258. *
  77259. * http://www.apache.org/licenses/LICENSE-2.0
  77260. *
  77261. * Unless required by applicable law or agreed to in writing,
  77262. * software distributed under the License is distributed on an
  77263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77264. * KIND, either express or implied. See the License for the
  77265. * specific language governing permissions and limitations
  77266. * under the License.
  77267. */
  77268. var dataViewLang = lang.toolbox.dataView;
  77269. var BLOCK_SPLITER = new Array(60).join('-');
  77270. var ITEM_SPLITER = '\t';
  77271. /**
  77272. * Group series into two types
  77273. * 1. on category axis, like line, bar
  77274. * 2. others, like scatter, pie
  77275. * @param {module:echarts/model/Global} ecModel
  77276. * @return {Object}
  77277. * @inner
  77278. */
  77279. function groupSeries(ecModel) {
  77280. var seriesGroupByCategoryAxis = {};
  77281. var otherSeries = [];
  77282. var meta = [];
  77283. ecModel.eachRawSeries(function (seriesModel) {
  77284. var coordSys = seriesModel.coordinateSystem;
  77285. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  77286. var baseAxis = coordSys.getBaseAxis();
  77287. if (baseAxis.type === 'category') {
  77288. var key = baseAxis.dim + '_' + baseAxis.index;
  77289. if (!seriesGroupByCategoryAxis[key]) {
  77290. seriesGroupByCategoryAxis[key] = {
  77291. categoryAxis: baseAxis,
  77292. valueAxis: coordSys.getOtherAxis(baseAxis),
  77293. series: []
  77294. };
  77295. meta.push({
  77296. axisDim: baseAxis.dim,
  77297. axisIndex: baseAxis.index
  77298. });
  77299. }
  77300. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  77301. }
  77302. else {
  77303. otherSeries.push(seriesModel);
  77304. }
  77305. }
  77306. else {
  77307. otherSeries.push(seriesModel);
  77308. }
  77309. });
  77310. return {
  77311. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  77312. other: otherSeries,
  77313. meta: meta
  77314. };
  77315. }
  77316. /**
  77317. * Assemble content of series on cateogory axis
  77318. * @param {Array.<module:echarts/model/Series>} series
  77319. * @return {string}
  77320. * @inner
  77321. */
  77322. function assembleSeriesWithCategoryAxis(series) {
  77323. var tables = [];
  77324. each$1(series, function (group, key) {
  77325. var categoryAxis = group.categoryAxis;
  77326. var valueAxis = group.valueAxis;
  77327. var valueAxisDim = valueAxis.dim;
  77328. var headers = [' '].concat(map(group.series, function (series) {
  77329. return series.name;
  77330. }));
  77331. var columns = [categoryAxis.model.getCategories()];
  77332. each$1(group.series, function (series) {
  77333. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  77334. return val;
  77335. }));
  77336. });
  77337. // Assemble table content
  77338. var lines = [headers.join(ITEM_SPLITER)];
  77339. for (var i = 0; i < columns[0].length; i++) {
  77340. var items = [];
  77341. for (var j = 0; j < columns.length; j++) {
  77342. items.push(columns[j][i]);
  77343. }
  77344. lines.push(items.join(ITEM_SPLITER));
  77345. }
  77346. tables.push(lines.join('\n'));
  77347. });
  77348. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  77349. }
  77350. /**
  77351. * Assemble content of other series
  77352. * @param {Array.<module:echarts/model/Series>} series
  77353. * @return {string}
  77354. * @inner
  77355. */
  77356. function assembleOtherSeries(series) {
  77357. return map(series, function (series) {
  77358. var data = series.getRawData();
  77359. var lines = [series.name];
  77360. var vals = [];
  77361. data.each(data.dimensions, function () {
  77362. var argLen = arguments.length;
  77363. var dataIndex = arguments[argLen - 1];
  77364. var name = data.getName(dataIndex);
  77365. for (var i = 0; i < argLen - 1; i++) {
  77366. vals[i] = arguments[i];
  77367. }
  77368. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  77369. });
  77370. return lines.join('\n');
  77371. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  77372. }
  77373. /**
  77374. * @param {module:echarts/model/Global}
  77375. * @return {Object}
  77376. * @inner
  77377. */
  77378. function getContentFromModel(ecModel) {
  77379. var result = groupSeries(ecModel);
  77380. return {
  77381. value: filter([
  77382. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  77383. assembleOtherSeries(result.other)
  77384. ], function (str) {
  77385. return str.replace(/[\n\t\s]/g, '');
  77386. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  77387. meta: result.meta
  77388. };
  77389. }
  77390. function trim$1(str) {
  77391. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  77392. }
  77393. /**
  77394. * If a block is tsv format
  77395. */
  77396. function isTSVFormat(block) {
  77397. // Simple method to find out if a block is tsv format
  77398. var firstLine = block.slice(0, block.indexOf('\n'));
  77399. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  77400. return true;
  77401. }
  77402. }
  77403. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  77404. /**
  77405. * @param {string} tsv
  77406. * @return {Object}
  77407. */
  77408. function parseTSVContents(tsv) {
  77409. var tsvLines = tsv.split(/\n+/g);
  77410. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  77411. var categories = [];
  77412. var series = map(headers, function (header) {
  77413. return {
  77414. name: header,
  77415. data: []
  77416. };
  77417. });
  77418. for (var i = 0; i < tsvLines.length; i++) {
  77419. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  77420. categories.push(items.shift());
  77421. for (var j = 0; j < items.length; j++) {
  77422. series[j] && (series[j].data[i] = items[j]);
  77423. }
  77424. }
  77425. return {
  77426. series: series,
  77427. categories: categories
  77428. };
  77429. }
  77430. /**
  77431. * @param {string} str
  77432. * @return {Array.<Object>}
  77433. * @inner
  77434. */
  77435. function parseListContents(str) {
  77436. var lines = str.split(/\n+/g);
  77437. var seriesName = trim$1(lines.shift());
  77438. var data = [];
  77439. for (var i = 0; i < lines.length; i++) {
  77440. var items = trim$1(lines[i]).split(itemSplitRegex);
  77441. var name = '';
  77442. var value;
  77443. var hasName = false;
  77444. if (isNaN(items[0])) { // First item is name
  77445. hasName = true;
  77446. name = items[0];
  77447. items = items.slice(1);
  77448. data[i] = {
  77449. name: name,
  77450. value: []
  77451. };
  77452. value = data[i].value;
  77453. }
  77454. else {
  77455. value = data[i] = [];
  77456. }
  77457. for (var j = 0; j < items.length; j++) {
  77458. value.push(+items[j]);
  77459. }
  77460. if (value.length === 1) {
  77461. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  77462. }
  77463. }
  77464. return {
  77465. name: seriesName,
  77466. data: data
  77467. };
  77468. }
  77469. /**
  77470. * @param {string} str
  77471. * @param {Array.<Object>} blockMetaList
  77472. * @return {Object}
  77473. * @inner
  77474. */
  77475. function parseContents(str, blockMetaList) {
  77476. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  77477. var newOption = {
  77478. series: []
  77479. };
  77480. each$1(blocks, function (block, idx) {
  77481. if (isTSVFormat(block)) {
  77482. var result = parseTSVContents(block);
  77483. var blockMeta = blockMetaList[idx];
  77484. var axisKey = blockMeta.axisDim + 'Axis';
  77485. if (blockMeta) {
  77486. newOption[axisKey] = newOption[axisKey] || [];
  77487. newOption[axisKey][blockMeta.axisIndex] = {
  77488. data: result.categories
  77489. };
  77490. newOption.series = newOption.series.concat(result.series);
  77491. }
  77492. }
  77493. else {
  77494. var result = parseListContents(block);
  77495. newOption.series.push(result);
  77496. }
  77497. });
  77498. return newOption;
  77499. }
  77500. /**
  77501. * @alias {module:echarts/component/toolbox/feature/DataView}
  77502. * @constructor
  77503. * @param {module:echarts/model/Model} model
  77504. */
  77505. function DataView(model) {
  77506. this._dom = null;
  77507. this.model = model;
  77508. }
  77509. DataView.defaultOption = {
  77510. show: true,
  77511. readOnly: false,
  77512. optionToContent: null,
  77513. contentToOption: null,
  77514. 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',
  77515. title: clone(dataViewLang.title),
  77516. lang: clone(dataViewLang.lang),
  77517. backgroundColor: '#fff',
  77518. textColor: '#000',
  77519. textareaColor: '#fff',
  77520. textareaBorderColor: '#333',
  77521. buttonColor: '#c23531',
  77522. buttonTextColor: '#fff'
  77523. };
  77524. DataView.prototype.onclick = function (ecModel, api) {
  77525. var container = api.getDom();
  77526. var model = this.model;
  77527. if (this._dom) {
  77528. container.removeChild(this._dom);
  77529. }
  77530. var root = document.createElement('div');
  77531. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  77532. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  77533. // Create elements
  77534. var header = document.createElement('h4');
  77535. var lang$$1 = model.get('lang') || [];
  77536. header.innerHTML = lang$$1[0] || model.get('title');
  77537. header.style.cssText = 'margin: 10px 20px;';
  77538. header.style.color = model.get('textColor');
  77539. var viewMain = document.createElement('div');
  77540. var textarea = document.createElement('textarea');
  77541. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  77542. var optionToContent = model.get('optionToContent');
  77543. var contentToOption = model.get('contentToOption');
  77544. var result = getContentFromModel(ecModel);
  77545. if (typeof optionToContent === 'function') {
  77546. var htmlOrDom = optionToContent(api.getOption());
  77547. if (typeof htmlOrDom === 'string') {
  77548. viewMain.innerHTML = htmlOrDom;
  77549. }
  77550. else if (isDom(htmlOrDom)) {
  77551. viewMain.appendChild(htmlOrDom);
  77552. }
  77553. }
  77554. else {
  77555. // Use default textarea
  77556. viewMain.appendChild(textarea);
  77557. textarea.readOnly = model.get('readOnly');
  77558. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  77559. textarea.style.color = model.get('textColor');
  77560. textarea.style.borderColor = model.get('textareaBorderColor');
  77561. textarea.style.backgroundColor = model.get('textareaColor');
  77562. textarea.value = result.value;
  77563. }
  77564. var blockMetaList = result.meta;
  77565. var buttonContainer = document.createElement('div');
  77566. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  77567. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  77568. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  77569. var closeButton = document.createElement('div');
  77570. var refreshButton = document.createElement('div');
  77571. buttonStyle += ';background-color:' + model.get('buttonColor');
  77572. buttonStyle += ';color:' + model.get('buttonTextColor');
  77573. var self = this;
  77574. function close() {
  77575. container.removeChild(root);
  77576. self._dom = null;
  77577. }
  77578. addEventListener(closeButton, 'click', close);
  77579. addEventListener(refreshButton, 'click', function () {
  77580. var newOption;
  77581. try {
  77582. if (typeof contentToOption === 'function') {
  77583. newOption = contentToOption(viewMain, api.getOption());
  77584. }
  77585. else {
  77586. newOption = parseContents(textarea.value, blockMetaList);
  77587. }
  77588. }
  77589. catch (e) {
  77590. close();
  77591. throw new Error('Data view format error ' + e);
  77592. }
  77593. if (newOption) {
  77594. api.dispatchAction({
  77595. type: 'changeDataView',
  77596. newOption: newOption
  77597. });
  77598. }
  77599. close();
  77600. });
  77601. closeButton.innerHTML = lang$$1[1];
  77602. refreshButton.innerHTML = lang$$1[2];
  77603. refreshButton.style.cssText = buttonStyle;
  77604. closeButton.style.cssText = buttonStyle;
  77605. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  77606. buttonContainer.appendChild(closeButton);
  77607. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  77608. addEventListener(textarea, 'keydown', function (e) {
  77609. if ((e.keyCode || e.which) === 9) {
  77610. // get caret position/selection
  77611. var val = this.value;
  77612. var start = this.selectionStart;
  77613. var end = this.selectionEnd;
  77614. // set textarea value to: text before caret + tab + text after caret
  77615. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  77616. // put caret at right position again
  77617. this.selectionStart = this.selectionEnd = start + 1;
  77618. // prevent the focus lose
  77619. stop(e);
  77620. }
  77621. });
  77622. root.appendChild(header);
  77623. root.appendChild(viewMain);
  77624. root.appendChild(buttonContainer);
  77625. viewMain.style.height = (container.clientHeight - 80) + 'px';
  77626. container.appendChild(root);
  77627. this._dom = root;
  77628. };
  77629. DataView.prototype.remove = function (ecModel, api) {
  77630. this._dom && api.getDom().removeChild(this._dom);
  77631. };
  77632. DataView.prototype.dispose = function (ecModel, api) {
  77633. this.remove(ecModel, api);
  77634. };
  77635. /**
  77636. * @inner
  77637. */
  77638. function tryMergeDataOption(newData, originalData) {
  77639. return map(newData, function (newVal, idx) {
  77640. var original = originalData && originalData[idx];
  77641. if (isObject$1(original) && !isArray(original)) {
  77642. if (isObject$1(newVal) && !isArray(newVal)) {
  77643. newVal = newVal.value;
  77644. }
  77645. // Original data has option
  77646. return defaults({
  77647. value: newVal
  77648. }, original);
  77649. }
  77650. else {
  77651. return newVal;
  77652. }
  77653. });
  77654. }
  77655. register$1('dataView', DataView);
  77656. registerAction({
  77657. type: 'changeDataView',
  77658. event: 'dataViewChanged',
  77659. update: 'prepareAndUpdate'
  77660. }, function (payload, ecModel) {
  77661. var newSeriesOptList = [];
  77662. each$1(payload.newOption.series, function (seriesOpt) {
  77663. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  77664. if (!seriesModel) {
  77665. // New created series
  77666. // Geuss the series type
  77667. newSeriesOptList.push(extend({
  77668. // Default is scatter
  77669. type: 'scatter'
  77670. }, seriesOpt));
  77671. }
  77672. else {
  77673. var originalData = seriesModel.get('data');
  77674. newSeriesOptList.push({
  77675. name: seriesOpt.name,
  77676. data: tryMergeDataOption(seriesOpt.data, originalData)
  77677. });
  77678. }
  77679. });
  77680. ecModel.mergeOption(defaults({
  77681. series: newSeriesOptList
  77682. }, payload.newOption));
  77683. });
  77684. /*
  77685. * Licensed to the Apache Software Foundation (ASF) under one
  77686. * or more contributor license agreements. See the NOTICE file
  77687. * distributed with this work for additional information
  77688. * regarding copyright ownership. The ASF licenses this file
  77689. * to you under the Apache License, Version 2.0 (the
  77690. * "License"); you may not use this file except in compliance
  77691. * with the License. You may obtain a copy of the License at
  77692. *
  77693. * http://www.apache.org/licenses/LICENSE-2.0
  77694. *
  77695. * Unless required by applicable law or agreed to in writing,
  77696. * software distributed under the License is distributed on an
  77697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77698. * KIND, either express or implied. See the License for the
  77699. * specific language governing permissions and limitations
  77700. * under the License.
  77701. */
  77702. var each$29 = each$1;
  77703. var ATTR$2 = '\0_ec_hist_store';
  77704. /**
  77705. * @param {module:echarts/model/Global} ecModel
  77706. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  77707. */
  77708. function push(ecModel, newSnapshot) {
  77709. var store = giveStore$1(ecModel);
  77710. // If previous dataZoom can not be found,
  77711. // complete an range with current range.
  77712. each$29(newSnapshot, function (batchItem, dataZoomId) {
  77713. var i = store.length - 1;
  77714. for (; i >= 0; i--) {
  77715. var snapshot = store[i];
  77716. if (snapshot[dataZoomId]) {
  77717. break;
  77718. }
  77719. }
  77720. if (i < 0) {
  77721. // No origin range set, create one by current range.
  77722. var dataZoomModel = ecModel.queryComponents(
  77723. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  77724. )[0];
  77725. if (dataZoomModel) {
  77726. var percentRange = dataZoomModel.getPercentRange();
  77727. store[0][dataZoomId] = {
  77728. dataZoomId: dataZoomId,
  77729. start: percentRange[0],
  77730. end: percentRange[1]
  77731. };
  77732. }
  77733. }
  77734. });
  77735. store.push(newSnapshot);
  77736. }
  77737. /**
  77738. * @param {module:echarts/model/Global} ecModel
  77739. * @return {Object} snapshot
  77740. */
  77741. function pop(ecModel) {
  77742. var store = giveStore$1(ecModel);
  77743. var head = store[store.length - 1];
  77744. store.length > 1 && store.pop();
  77745. // Find top for all dataZoom.
  77746. var snapshot = {};
  77747. each$29(head, function (batchItem, dataZoomId) {
  77748. for (var i = store.length - 1; i >= 0; i--) {
  77749. var batchItem = store[i][dataZoomId];
  77750. if (batchItem) {
  77751. snapshot[dataZoomId] = batchItem;
  77752. break;
  77753. }
  77754. }
  77755. });
  77756. return snapshot;
  77757. }
  77758. /**
  77759. * @param {module:echarts/model/Global} ecModel
  77760. */
  77761. function clear$1(ecModel) {
  77762. ecModel[ATTR$2] = null;
  77763. }
  77764. /**
  77765. * @param {module:echarts/model/Global} ecModel
  77766. * @return {number} records. always >= 1.
  77767. */
  77768. function count(ecModel) {
  77769. return giveStore$1(ecModel).length;
  77770. }
  77771. /**
  77772. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  77773. * History length of each dataZoom may be different.
  77774. * this._history[0] is used to store origin range.
  77775. * @type {Array.<Object>}
  77776. */
  77777. function giveStore$1(ecModel) {
  77778. var store = ecModel[ATTR$2];
  77779. if (!store) {
  77780. store = ecModel[ATTR$2] = [{}];
  77781. }
  77782. return store;
  77783. }
  77784. /*
  77785. * Licensed to the Apache Software Foundation (ASF) under one
  77786. * or more contributor license agreements. See the NOTICE file
  77787. * distributed with this work for additional information
  77788. * regarding copyright ownership. The ASF licenses this file
  77789. * to you under the Apache License, Version 2.0 (the
  77790. * "License"); you may not use this file except in compliance
  77791. * with the License. You may obtain a copy of the License at
  77792. *
  77793. * http://www.apache.org/licenses/LICENSE-2.0
  77794. *
  77795. * Unless required by applicable law or agreed to in writing,
  77796. * software distributed under the License is distributed on an
  77797. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77798. * KIND, either express or implied. See the License for the
  77799. * specific language governing permissions and limitations
  77800. * under the License.
  77801. */
  77802. DataZoomModel.extend({
  77803. type: 'dataZoom.select'
  77804. });
  77805. /*
  77806. * Licensed to the Apache Software Foundation (ASF) under one
  77807. * or more contributor license agreements. See the NOTICE file
  77808. * distributed with this work for additional information
  77809. * regarding copyright ownership. The ASF licenses this file
  77810. * to you under the Apache License, Version 2.0 (the
  77811. * "License"); you may not use this file except in compliance
  77812. * with the License. You may obtain a copy of the License at
  77813. *
  77814. * http://www.apache.org/licenses/LICENSE-2.0
  77815. *
  77816. * Unless required by applicable law or agreed to in writing,
  77817. * software distributed under the License is distributed on an
  77818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77819. * KIND, either express or implied. See the License for the
  77820. * specific language governing permissions and limitations
  77821. * under the License.
  77822. */
  77823. DataZoomView.extend({
  77824. type: 'dataZoom.select'
  77825. });
  77826. /*
  77827. * Licensed to the Apache Software Foundation (ASF) under one
  77828. * or more contributor license agreements. See the NOTICE file
  77829. * distributed with this work for additional information
  77830. * regarding copyright ownership. The ASF licenses this file
  77831. * to you under the Apache License, Version 2.0 (the
  77832. * "License"); you may not use this file except in compliance
  77833. * with the License. You may obtain a copy of the License at
  77834. *
  77835. * http://www.apache.org/licenses/LICENSE-2.0
  77836. *
  77837. * Unless required by applicable law or agreed to in writing,
  77838. * software distributed under the License is distributed on an
  77839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77840. * KIND, either express or implied. See the License for the
  77841. * specific language governing permissions and limitations
  77842. * under the License.
  77843. */
  77844. /**
  77845. * DataZoom component entry
  77846. */
  77847. /*
  77848. * Licensed to the Apache Software Foundation (ASF) under one
  77849. * or more contributor license agreements. See the NOTICE file
  77850. * distributed with this work for additional information
  77851. * regarding copyright ownership. The ASF licenses this file
  77852. * to you under the Apache License, Version 2.0 (the
  77853. * "License"); you may not use this file except in compliance
  77854. * with the License. You may obtain a copy of the License at
  77855. *
  77856. * http://www.apache.org/licenses/LICENSE-2.0
  77857. *
  77858. * Unless required by applicable law or agreed to in writing,
  77859. * software distributed under the License is distributed on an
  77860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77861. * KIND, either express or implied. See the License for the
  77862. * specific language governing permissions and limitations
  77863. * under the License.
  77864. */
  77865. // Use dataZoomSelect
  77866. var dataZoomLang = lang.toolbox.dataZoom;
  77867. var each$28 = each$1;
  77868. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  77869. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  77870. function DataZoom(model, ecModel, api) {
  77871. /**
  77872. * @private
  77873. * @type {module:echarts/component/helper/BrushController}
  77874. */
  77875. (this._brushController = new BrushController(api.getZr()))
  77876. .on('brush', bind(this._onBrush, this))
  77877. .mount();
  77878. /**
  77879. * @private
  77880. * @type {boolean}
  77881. */
  77882. this._isZoomActive;
  77883. }
  77884. DataZoom.defaultOption = {
  77885. show: true,
  77886. // Icon group
  77887. icon: {
  77888. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  77889. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  77890. },
  77891. // `zoom`, `back`
  77892. title: clone(dataZoomLang.title)
  77893. };
  77894. var proto$6 = DataZoom.prototype;
  77895. proto$6.render = function (featureModel, ecModel, api, payload) {
  77896. this.model = featureModel;
  77897. this.ecModel = ecModel;
  77898. this.api = api;
  77899. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  77900. updateBackBtnStatus(featureModel, ecModel);
  77901. };
  77902. proto$6.onclick = function (ecModel, api, type) {
  77903. handlers$1[type].call(this);
  77904. };
  77905. proto$6.remove = function (ecModel, api) {
  77906. this._brushController.unmount();
  77907. };
  77908. proto$6.dispose = function (ecModel, api) {
  77909. this._brushController.dispose();
  77910. };
  77911. /**
  77912. * @private
  77913. */
  77914. var handlers$1 = {
  77915. zoom: function () {
  77916. var nextActive = !this._isZoomActive;
  77917. this.api.dispatchAction({
  77918. type: 'takeGlobalCursor',
  77919. key: 'dataZoomSelect',
  77920. dataZoomSelectActive: nextActive
  77921. });
  77922. },
  77923. back: function () {
  77924. this._dispatchZoomAction(pop(this.ecModel));
  77925. }
  77926. };
  77927. /**
  77928. * @private
  77929. */
  77930. proto$6._onBrush = function (areas, opt) {
  77931. if (!opt.isEnd || !areas.length) {
  77932. return;
  77933. }
  77934. var snapshot = {};
  77935. var ecModel = this.ecModel;
  77936. this._brushController.updateCovers([]); // remove cover
  77937. var brushTargetManager = new BrushTargetManager(
  77938. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  77939. );
  77940. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  77941. if (coordSys.type !== 'cartesian2d') {
  77942. return;
  77943. }
  77944. var brushType = area.brushType;
  77945. if (brushType === 'rect') {
  77946. setBatch('x', coordSys, coordRange[0]);
  77947. setBatch('y', coordSys, coordRange[1]);
  77948. }
  77949. else {
  77950. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  77951. }
  77952. });
  77953. push(ecModel, snapshot);
  77954. this._dispatchZoomAction(snapshot);
  77955. function setBatch(dimName, coordSys, minMax) {
  77956. var axis = coordSys.getAxis(dimName);
  77957. var axisModel = axis.model;
  77958. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  77959. // Restrict range.
  77960. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  77961. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  77962. minMax = sliderMove(
  77963. 0, minMax.slice(), axis.scale.getExtent(), 0,
  77964. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  77965. );
  77966. }
  77967. dataZoomModel && (snapshot[dataZoomModel.id] = {
  77968. dataZoomId: dataZoomModel.id,
  77969. startValue: minMax[0],
  77970. endValue: minMax[1]
  77971. });
  77972. }
  77973. function findDataZoom(dimName, axisModel, ecModel) {
  77974. var found;
  77975. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  77976. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  77977. has && (found = dzModel);
  77978. });
  77979. return found;
  77980. }
  77981. };
  77982. /**
  77983. * @private
  77984. */
  77985. proto$6._dispatchZoomAction = function (snapshot) {
  77986. var batch = [];
  77987. // Convert from hash map to array.
  77988. each$28(snapshot, function (batchItem, dataZoomId) {
  77989. batch.push(clone(batchItem));
  77990. });
  77991. batch.length && this.api.dispatchAction({
  77992. type: 'dataZoom',
  77993. from: this.uid,
  77994. batch: batch
  77995. });
  77996. };
  77997. function retrieveAxisSetting(option) {
  77998. var setting = {};
  77999. // Compatible with previous setting: null => all axis, false => no axis.
  78000. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  78001. setting[name] = option[name];
  78002. setting[name] == null && (setting[name] = 'all');
  78003. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  78004. });
  78005. return setting;
  78006. }
  78007. function updateBackBtnStatus(featureModel, ecModel) {
  78008. featureModel.setIconStatus(
  78009. 'back',
  78010. count(ecModel) > 1 ? 'emphasis' : 'normal'
  78011. );
  78012. }
  78013. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  78014. var zoomActive = view._isZoomActive;
  78015. if (payload && payload.type === 'takeGlobalCursor') {
  78016. zoomActive = payload.key === 'dataZoomSelect'
  78017. ? payload.dataZoomSelectActive : false;
  78018. }
  78019. view._isZoomActive = zoomActive;
  78020. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  78021. var brushTargetManager = new BrushTargetManager(
  78022. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  78023. );
  78024. view._brushController
  78025. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  78026. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  78027. ? 'lineX'
  78028. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  78029. ? 'lineY'
  78030. : 'rect';
  78031. }))
  78032. .enableBrush(
  78033. zoomActive
  78034. ? {
  78035. brushType: 'auto',
  78036. brushStyle: {
  78037. // FIXME user customized?
  78038. lineWidth: 0,
  78039. fill: 'rgba(0,0,0,0.2)'
  78040. }
  78041. }
  78042. : false
  78043. );
  78044. }
  78045. register$1('dataZoom', DataZoom);
  78046. // Create special dataZoom option for select
  78047. // FIXME consider the case of merge option, where axes options are not exists.
  78048. registerPreprocessor(function (option) {
  78049. if (!option) {
  78050. return;
  78051. }
  78052. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  78053. if (!isArray(dataZoomOpts)) {
  78054. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  78055. }
  78056. var toolboxOpt = option.toolbox;
  78057. if (toolboxOpt) {
  78058. // Assume there is only one toolbox
  78059. if (isArray(toolboxOpt)) {
  78060. toolboxOpt = toolboxOpt[0];
  78061. }
  78062. if (toolboxOpt && toolboxOpt.feature) {
  78063. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  78064. // FIXME: If add dataZoom when setOption in merge mode,
  78065. // no axis info to be added. See `test/dataZoom-extreme.html`
  78066. addForAxis('xAxis', dataZoomOpt);
  78067. addForAxis('yAxis', dataZoomOpt);
  78068. }
  78069. }
  78070. function addForAxis(axisName, dataZoomOpt) {
  78071. if (!dataZoomOpt) {
  78072. return;
  78073. }
  78074. // Try not to modify model, because it is not merged yet.
  78075. var axisIndicesName = axisName + 'Index';
  78076. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  78077. if (givenAxisIndices != null
  78078. && givenAxisIndices !== 'all'
  78079. && !isArray(givenAxisIndices)
  78080. ) {
  78081. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  78082. }
  78083. forEachComponent(axisName, function (axisOpt, axisIndex) {
  78084. if (givenAxisIndices != null
  78085. && givenAxisIndices !== 'all'
  78086. && indexOf(givenAxisIndices, axisIndex) === -1
  78087. ) {
  78088. return;
  78089. }
  78090. var newOpt = {
  78091. type: 'select',
  78092. $fromToolbox: true,
  78093. // Id for merge mapping.
  78094. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  78095. };
  78096. // FIXME
  78097. // Only support one axis now.
  78098. newOpt[axisIndicesName] = axisIndex;
  78099. dataZoomOpts.push(newOpt);
  78100. });
  78101. }
  78102. function forEachComponent(mainType, cb) {
  78103. var opts = option[mainType];
  78104. if (!isArray(opts)) {
  78105. opts = opts ? [opts] : [];
  78106. }
  78107. each$28(opts, cb);
  78108. }
  78109. });
  78110. /*
  78111. * Licensed to the Apache Software Foundation (ASF) under one
  78112. * or more contributor license agreements. See the NOTICE file
  78113. * distributed with this work for additional information
  78114. * regarding copyright ownership. The ASF licenses this file
  78115. * to you under the Apache License, Version 2.0 (the
  78116. * "License"); you may not use this file except in compliance
  78117. * with the License. You may obtain a copy of the License at
  78118. *
  78119. * http://www.apache.org/licenses/LICENSE-2.0
  78120. *
  78121. * Unless required by applicable law or agreed to in writing,
  78122. * software distributed under the License is distributed on an
  78123. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78124. * KIND, either express or implied. See the License for the
  78125. * specific language governing permissions and limitations
  78126. * under the License.
  78127. */
  78128. var restoreLang = lang.toolbox.restore;
  78129. function Restore(model) {
  78130. this.model = model;
  78131. }
  78132. Restore.defaultOption = {
  78133. show: true,
  78134. /* eslint-disable */
  78135. 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',
  78136. /* eslint-enable */
  78137. title: restoreLang.title
  78138. };
  78139. var proto$7 = Restore.prototype;
  78140. proto$7.onclick = function (ecModel, api, type) {
  78141. clear$1(ecModel);
  78142. api.dispatchAction({
  78143. type: 'restore',
  78144. from: this.uid
  78145. });
  78146. };
  78147. register$1('restore', Restore);
  78148. registerAction(
  78149. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  78150. function (payload, ecModel) {
  78151. ecModel.resetOption('recreate');
  78152. }
  78153. );
  78154. /*
  78155. * Licensed to the Apache Software Foundation (ASF) under one
  78156. * or more contributor license agreements. See the NOTICE file
  78157. * distributed with this work for additional information
  78158. * regarding copyright ownership. The ASF licenses this file
  78159. * to you under the Apache License, Version 2.0 (the
  78160. * "License"); you may not use this file except in compliance
  78161. * with the License. You may obtain a copy of the License at
  78162. *
  78163. * http://www.apache.org/licenses/LICENSE-2.0
  78164. *
  78165. * Unless required by applicable law or agreed to in writing,
  78166. * software distributed under the License is distributed on an
  78167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78168. * KIND, either express or implied. See the License for the
  78169. * specific language governing permissions and limitations
  78170. * under the License.
  78171. */
  78172. var urn = 'urn:schemas-microsoft-com:vml';
  78173. var win = typeof window === 'undefined' ? null : window;
  78174. var vmlInited = false;
  78175. var doc = win && win.document;
  78176. function createNode(tagName) {
  78177. return doCreateNode(tagName);
  78178. }
  78179. // Avoid assign to an exported variable, for transforming to cjs.
  78180. var doCreateNode;
  78181. if (doc && !env$1.canvasSupported) {
  78182. try {
  78183. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  78184. doCreateNode = function (tagName) {
  78185. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  78186. };
  78187. }
  78188. catch (e) {
  78189. doCreateNode = function (tagName) {
  78190. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  78191. };
  78192. }
  78193. }
  78194. // From raphael
  78195. function initVML() {
  78196. if (vmlInited || !doc) {
  78197. return;
  78198. }
  78199. vmlInited = true;
  78200. var styleSheets = doc.styleSheets;
  78201. if (styleSheets.length < 31) {
  78202. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  78203. }
  78204. else {
  78205. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  78206. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  78207. }
  78208. }
  78209. // http://www.w3.org/TR/NOTE-VML
  78210. // TODO Use proxy like svg instead of overwrite brush methods
  78211. var CMD$3 = PathProxy.CMD;
  78212. var round$4 = Math.round;
  78213. var sqrt = Math.sqrt;
  78214. var abs$1 = Math.abs;
  78215. var cos = Math.cos;
  78216. var sin = Math.sin;
  78217. var mathMax$8 = Math.max;
  78218. if (!env$1.canvasSupported) {
  78219. var comma = ',';
  78220. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  78221. var Z = 21600;
  78222. var Z2 = Z / 2;
  78223. var ZLEVEL_BASE = 100000;
  78224. var Z_BASE$1 = 1000;
  78225. var initRootElStyle = function (el) {
  78226. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  78227. el.coordsize = Z + ',' + Z;
  78228. el.coordorigin = '0,0';
  78229. };
  78230. var encodeHtmlAttribute = function (s) {
  78231. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  78232. };
  78233. var rgb2Str = function (r, g, b) {
  78234. return 'rgb(' + [r, g, b].join(',') + ')';
  78235. };
  78236. var append = function (parent, child) {
  78237. if (child && parent && child.parentNode !== parent) {
  78238. parent.appendChild(child);
  78239. }
  78240. };
  78241. var remove = function (parent, child) {
  78242. if (child && parent && child.parentNode === parent) {
  78243. parent.removeChild(child);
  78244. }
  78245. };
  78246. var getZIndex = function (zlevel, z, z2) {
  78247. // z 的取值范围为 [0, 1000]
  78248. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  78249. };
  78250. var parsePercent$3 = function (value, maxValue) {
  78251. if (typeof value === 'string') {
  78252. if (value.lastIndexOf('%') >= 0) {
  78253. return parseFloat(value) / 100 * maxValue;
  78254. }
  78255. return parseFloat(value);
  78256. }
  78257. return value;
  78258. };
  78259. /***************************************************
  78260. * PATH
  78261. **************************************************/
  78262. var setColorAndOpacity = function (el, color, opacity) {
  78263. var colorArr = parse(color);
  78264. opacity = +opacity;
  78265. if (isNaN(opacity)) {
  78266. opacity = 1;
  78267. }
  78268. if (colorArr) {
  78269. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  78270. el.opacity = opacity * colorArr[3];
  78271. }
  78272. };
  78273. var getColorAndAlpha = function (color) {
  78274. var colorArr = parse(color);
  78275. return [
  78276. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  78277. colorArr[3]
  78278. ];
  78279. };
  78280. var updateFillNode = function (el, style, zrEl) {
  78281. // TODO pattern
  78282. var fill = style.fill;
  78283. if (fill != null) {
  78284. // Modified from excanvas
  78285. if (fill instanceof Gradient) {
  78286. var gradientType;
  78287. var angle = 0;
  78288. var focus = [0, 0];
  78289. // additional offset
  78290. var shift = 0;
  78291. // scale factor for offset
  78292. var expansion = 1;
  78293. var rect = zrEl.getBoundingRect();
  78294. var rectWidth = rect.width;
  78295. var rectHeight = rect.height;
  78296. if (fill.type === 'linear') {
  78297. gradientType = 'gradient';
  78298. var transform = zrEl.transform;
  78299. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  78300. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  78301. if (transform) {
  78302. applyTransform(p0, p0, transform);
  78303. applyTransform(p1, p1, transform);
  78304. }
  78305. var dx = p1[0] - p0[0];
  78306. var dy = p1[1] - p0[1];
  78307. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  78308. // The angle should be a non-negative number.
  78309. if (angle < 0) {
  78310. angle += 360;
  78311. }
  78312. // Very small angles produce an unexpected result because they are
  78313. // converted to a scientific notation string.
  78314. if (angle < 1e-6) {
  78315. angle = 0;
  78316. }
  78317. }
  78318. else {
  78319. gradientType = 'gradientradial';
  78320. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  78321. var transform = zrEl.transform;
  78322. var scale$$1 = zrEl.scale;
  78323. var width = rectWidth;
  78324. var height = rectHeight;
  78325. focus = [
  78326. // Percent in bounding rect
  78327. (p0[0] - rect.x) / width,
  78328. (p0[1] - rect.y) / height
  78329. ];
  78330. if (transform) {
  78331. applyTransform(p0, p0, transform);
  78332. }
  78333. width /= scale$$1[0] * Z;
  78334. height /= scale$$1[1] * Z;
  78335. var dimension = mathMax$8(width, height);
  78336. shift = 2 * 0 / dimension;
  78337. expansion = 2 * fill.r / dimension - shift;
  78338. }
  78339. // We need to sort the color stops in ascending order by offset,
  78340. // otherwise IE won't interpret it correctly.
  78341. var stops = fill.colorStops.slice();
  78342. stops.sort(function (cs1, cs2) {
  78343. return cs1.offset - cs2.offset;
  78344. });
  78345. var length$$1 = stops.length;
  78346. // Color and alpha list of first and last stop
  78347. var colorAndAlphaList = [];
  78348. var colors = [];
  78349. for (var i = 0; i < length$$1; i++) {
  78350. var stop = stops[i];
  78351. var colorAndAlpha = getColorAndAlpha(stop.color);
  78352. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  78353. if (i === 0 || i === length$$1 - 1) {
  78354. colorAndAlphaList.push(colorAndAlpha);
  78355. }
  78356. }
  78357. if (length$$1 >= 2) {
  78358. var color1 = colorAndAlphaList[0][0];
  78359. var color2 = colorAndAlphaList[1][0];
  78360. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  78361. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  78362. el.type = gradientType;
  78363. el.method = 'none';
  78364. el.focus = '100%';
  78365. el.angle = angle;
  78366. el.color = color1;
  78367. el.color2 = color2;
  78368. el.colors = colors.join(',');
  78369. // When colors attribute is used, the meanings of opacity and o:opacity2
  78370. // are reversed.
  78371. el.opacity = opacity2;
  78372. // FIXME g_o_:opacity ?
  78373. el.opacity2 = opacity1;
  78374. }
  78375. if (gradientType === 'radial') {
  78376. el.focusposition = focus.join(',');
  78377. }
  78378. }
  78379. else {
  78380. // FIXME Change from Gradient fill to color fill
  78381. setColorAndOpacity(el, fill, style.opacity);
  78382. }
  78383. }
  78384. };
  78385. var updateStrokeNode = function (el, style) {
  78386. // if (style.lineJoin != null) {
  78387. // el.joinstyle = style.lineJoin;
  78388. // }
  78389. // if (style.miterLimit != null) {
  78390. // el.miterlimit = style.miterLimit * Z;
  78391. // }
  78392. // if (style.lineCap != null) {
  78393. // el.endcap = style.lineCap;
  78394. // }
  78395. if (style.lineDash != null) {
  78396. el.dashstyle = style.lineDash.join(' ');
  78397. }
  78398. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  78399. setColorAndOpacity(el, style.stroke, style.opacity);
  78400. }
  78401. };
  78402. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  78403. var isFill = type === 'fill';
  78404. var el = vmlEl.getElementsByTagName(type)[0];
  78405. // Stroke must have lineWidth
  78406. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  78407. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  78408. // FIXME Remove before updating, or set `colors` will throw error
  78409. if (style[type] instanceof Gradient) {
  78410. remove(vmlEl, el);
  78411. }
  78412. if (!el) {
  78413. el = createNode(type);
  78414. }
  78415. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  78416. append(vmlEl, el);
  78417. }
  78418. else {
  78419. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  78420. remove(vmlEl, el);
  78421. }
  78422. };
  78423. var points$3 = [[], [], []];
  78424. var pathDataToString = function (path, m) {
  78425. var M = CMD$3.M;
  78426. var C = CMD$3.C;
  78427. var L = CMD$3.L;
  78428. var A = CMD$3.A;
  78429. var Q = CMD$3.Q;
  78430. var str = [];
  78431. var nPoint;
  78432. var cmdStr;
  78433. var cmd;
  78434. var i;
  78435. var xi;
  78436. var yi;
  78437. var data = path.data;
  78438. var dataLength = path.len();
  78439. for (i = 0; i < dataLength;) {
  78440. cmd = data[i++];
  78441. cmdStr = '';
  78442. nPoint = 0;
  78443. switch (cmd) {
  78444. case M:
  78445. cmdStr = ' m ';
  78446. nPoint = 1;
  78447. xi = data[i++];
  78448. yi = data[i++];
  78449. points$3[0][0] = xi;
  78450. points$3[0][1] = yi;
  78451. break;
  78452. case L:
  78453. cmdStr = ' l ';
  78454. nPoint = 1;
  78455. xi = data[i++];
  78456. yi = data[i++];
  78457. points$3[0][0] = xi;
  78458. points$3[0][1] = yi;
  78459. break;
  78460. case Q:
  78461. case C:
  78462. cmdStr = ' c ';
  78463. nPoint = 3;
  78464. var x1 = data[i++];
  78465. var y1 = data[i++];
  78466. var x2 = data[i++];
  78467. var y2 = data[i++];
  78468. var x3;
  78469. var y3;
  78470. if (cmd === Q) {
  78471. // Convert quadratic to cubic using degree elevation
  78472. x3 = x2;
  78473. y3 = y2;
  78474. x2 = (x2 + 2 * x1) / 3;
  78475. y2 = (y2 + 2 * y1) / 3;
  78476. x1 = (xi + 2 * x1) / 3;
  78477. y1 = (yi + 2 * y1) / 3;
  78478. }
  78479. else {
  78480. x3 = data[i++];
  78481. y3 = data[i++];
  78482. }
  78483. points$3[0][0] = x1;
  78484. points$3[0][1] = y1;
  78485. points$3[1][0] = x2;
  78486. points$3[1][1] = y2;
  78487. points$3[2][0] = x3;
  78488. points$3[2][1] = y3;
  78489. xi = x3;
  78490. yi = y3;
  78491. break;
  78492. case A:
  78493. var x = 0;
  78494. var y = 0;
  78495. var sx = 1;
  78496. var sy = 1;
  78497. var angle = 0;
  78498. if (m) {
  78499. // Extract SRT from matrix
  78500. x = m[4];
  78501. y = m[5];
  78502. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  78503. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  78504. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  78505. }
  78506. var cx = data[i++];
  78507. var cy = data[i++];
  78508. var rx = data[i++];
  78509. var ry = data[i++];
  78510. var startAngle = data[i++] + angle;
  78511. var endAngle = data[i++] + startAngle + angle;
  78512. // FIXME
  78513. // var psi = data[i++];
  78514. i++;
  78515. var clockwise = data[i++];
  78516. var x0 = cx + cos(startAngle) * rx;
  78517. var y0 = cy + sin(startAngle) * ry;
  78518. var x1 = cx + cos(endAngle) * rx;
  78519. var y1 = cy + sin(endAngle) * ry;
  78520. var type = clockwise ? ' wa ' : ' at ';
  78521. if (Math.abs(x0 - x1) < 1e-4) {
  78522. // IE won't render arches drawn counter clockwise if x0 == x1.
  78523. if (Math.abs(endAngle - startAngle) > 1e-2) {
  78524. // Offset x0 by 1/80 of a pixel. Use something
  78525. // that can be represented in binary
  78526. if (clockwise) {
  78527. x0 += 270 / Z;
  78528. }
  78529. }
  78530. else {
  78531. // Avoid case draw full circle
  78532. if (Math.abs(y0 - cy) < 1e-4) {
  78533. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  78534. y1 -= 270 / Z;
  78535. }
  78536. else {
  78537. y1 += 270 / Z;
  78538. }
  78539. }
  78540. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  78541. x1 += 270 / Z;
  78542. }
  78543. else {
  78544. x1 -= 270 / Z;
  78545. }
  78546. }
  78547. }
  78548. str.push(
  78549. type,
  78550. round$4(((cx - rx) * sx + x) * Z - Z2), comma,
  78551. round$4(((cy - ry) * sy + y) * Z - Z2), comma,
  78552. round$4(((cx + rx) * sx + x) * Z - Z2), comma,
  78553. round$4(((cy + ry) * sy + y) * Z - Z2), comma,
  78554. round$4((x0 * sx + x) * Z - Z2), comma,
  78555. round$4((y0 * sy + y) * Z - Z2), comma,
  78556. round$4((x1 * sx + x) * Z - Z2), comma,
  78557. round$4((y1 * sy + y) * Z - Z2)
  78558. );
  78559. xi = x1;
  78560. yi = y1;
  78561. break;
  78562. case CMD$3.R:
  78563. var p0 = points$3[0];
  78564. var p1 = points$3[1];
  78565. // x0, y0
  78566. p0[0] = data[i++];
  78567. p0[1] = data[i++];
  78568. // x1, y1
  78569. p1[0] = p0[0] + data[i++];
  78570. p1[1] = p0[1] + data[i++];
  78571. if (m) {
  78572. applyTransform(p0, p0, m);
  78573. applyTransform(p1, p1, m);
  78574. }
  78575. p0[0] = round$4(p0[0] * Z - Z2);
  78576. p1[0] = round$4(p1[0] * Z - Z2);
  78577. p0[1] = round$4(p0[1] * Z - Z2);
  78578. p1[1] = round$4(p1[1] * Z - Z2);
  78579. str.push(
  78580. // x0, y0
  78581. ' m ', p0[0], comma, p0[1],
  78582. // x1, y0
  78583. ' l ', p1[0], comma, p0[1],
  78584. // x1, y1
  78585. ' l ', p1[0], comma, p1[1],
  78586. // x0, y1
  78587. ' l ', p0[0], comma, p1[1]
  78588. );
  78589. break;
  78590. case CMD$3.Z:
  78591. // FIXME Update xi, yi
  78592. str.push(' x ');
  78593. }
  78594. if (nPoint > 0) {
  78595. str.push(cmdStr);
  78596. for (var k = 0; k < nPoint; k++) {
  78597. var p = points$3[k];
  78598. m && applyTransform(p, p, m);
  78599. // 不 round 会非常慢
  78600. str.push(
  78601. round$4(p[0] * Z - Z2), comma, round$4(p[1] * Z - Z2),
  78602. k < nPoint - 1 ? comma : ''
  78603. );
  78604. }
  78605. }
  78606. }
  78607. return str.join('');
  78608. };
  78609. // Rewrite the original path method
  78610. Path.prototype.brushVML = function (vmlRoot) {
  78611. var style = this.style;
  78612. var vmlEl = this._vmlEl;
  78613. if (!vmlEl) {
  78614. vmlEl = createNode('shape');
  78615. initRootElStyle(vmlEl);
  78616. this._vmlEl = vmlEl;
  78617. }
  78618. updateFillAndStroke(vmlEl, 'fill', style, this);
  78619. updateFillAndStroke(vmlEl, 'stroke', style, this);
  78620. var m = this.transform;
  78621. var needTransform = m != null;
  78622. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  78623. if (strokeEl) {
  78624. var lineWidth = style.lineWidth;
  78625. // Get the line scale.
  78626. // Determinant of this.m_ means how much the area is enlarged by the
  78627. // transformation. So its square root can be used as a scale factor
  78628. // for width.
  78629. if (needTransform && !style.strokeNoScale) {
  78630. var det = m[0] * m[3] - m[1] * m[2];
  78631. lineWidth *= sqrt(abs$1(det));
  78632. }
  78633. strokeEl.weight = lineWidth + 'px';
  78634. }
  78635. var path = this.path || (this.path = new PathProxy());
  78636. if (this.__dirtyPath) {
  78637. path.beginPath();
  78638. path.subPixelOptimize = false;
  78639. this.buildPath(path, this.shape);
  78640. path.toStatic();
  78641. this.__dirtyPath = false;
  78642. }
  78643. vmlEl.path = pathDataToString(path, this.transform);
  78644. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78645. // Append to root
  78646. append(vmlRoot, vmlEl);
  78647. // Text
  78648. if (style.text != null) {
  78649. this.drawRectText(vmlRoot, this.getBoundingRect());
  78650. }
  78651. else {
  78652. this.removeRectText(vmlRoot);
  78653. }
  78654. };
  78655. Path.prototype.onRemove = function (vmlRoot) {
  78656. remove(vmlRoot, this._vmlEl);
  78657. this.removeRectText(vmlRoot);
  78658. };
  78659. Path.prototype.onAdd = function (vmlRoot) {
  78660. append(vmlRoot, this._vmlEl);
  78661. this.appendRectText(vmlRoot);
  78662. };
  78663. /***************************************************
  78664. * IMAGE
  78665. **************************************************/
  78666. var isImage = function (img) {
  78667. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  78668. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  78669. // return img instanceof Image;
  78670. };
  78671. // Rewrite the original path method
  78672. ZImage.prototype.brushVML = function (vmlRoot) {
  78673. var style = this.style;
  78674. var image = style.image;
  78675. // Image original width, height
  78676. var ow;
  78677. var oh;
  78678. if (isImage(image)) {
  78679. var src = image.src;
  78680. if (src === this._imageSrc) {
  78681. ow = this._imageWidth;
  78682. oh = this._imageHeight;
  78683. }
  78684. else {
  78685. var imageRuntimeStyle = image.runtimeStyle;
  78686. var oldRuntimeWidth = imageRuntimeStyle.width;
  78687. var oldRuntimeHeight = imageRuntimeStyle.height;
  78688. imageRuntimeStyle.width = 'auto';
  78689. imageRuntimeStyle.height = 'auto';
  78690. // get the original size
  78691. ow = image.width;
  78692. oh = image.height;
  78693. // and remove overides
  78694. imageRuntimeStyle.width = oldRuntimeWidth;
  78695. imageRuntimeStyle.height = oldRuntimeHeight;
  78696. // Caching image original width, height and src
  78697. this._imageSrc = src;
  78698. this._imageWidth = ow;
  78699. this._imageHeight = oh;
  78700. }
  78701. image = src;
  78702. }
  78703. else {
  78704. if (image === this._imageSrc) {
  78705. ow = this._imageWidth;
  78706. oh = this._imageHeight;
  78707. }
  78708. }
  78709. if (!image) {
  78710. return;
  78711. }
  78712. var x = style.x || 0;
  78713. var y = style.y || 0;
  78714. var dw = style.width;
  78715. var dh = style.height;
  78716. var sw = style.sWidth;
  78717. var sh = style.sHeight;
  78718. var sx = style.sx || 0;
  78719. var sy = style.sy || 0;
  78720. var hasCrop = sw && sh;
  78721. var vmlEl = this._vmlEl;
  78722. if (!vmlEl) {
  78723. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  78724. // vmlEl = vmlCore.createNode('group');
  78725. vmlEl = doc.createElement('div');
  78726. initRootElStyle(vmlEl);
  78727. this._vmlEl = vmlEl;
  78728. }
  78729. var vmlElStyle = vmlEl.style;
  78730. var hasRotation = false;
  78731. var m;
  78732. var scaleX = 1;
  78733. var scaleY = 1;
  78734. if (this.transform) {
  78735. m = this.transform;
  78736. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  78737. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  78738. hasRotation = m[1] || m[2];
  78739. }
  78740. if (hasRotation) {
  78741. // If filters are necessary (rotation exists), create them
  78742. // filters are bog-slow, so only create them if abbsolutely necessary
  78743. // The following check doesn't account for skews (which don't exist
  78744. // in the canvas spec (yet) anyway.
  78745. // From excanvas
  78746. var p0 = [x, y];
  78747. var p1 = [x + dw, y];
  78748. var p2 = [x, y + dh];
  78749. var p3 = [x + dw, y + dh];
  78750. applyTransform(p0, p0, m);
  78751. applyTransform(p1, p1, m);
  78752. applyTransform(p2, p2, m);
  78753. applyTransform(p3, p3, m);
  78754. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  78755. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  78756. var transformFilter = [];
  78757. transformFilter.push('M11=', m[0] / scaleX, comma,
  78758. 'M12=', m[2] / scaleY, comma,
  78759. 'M21=', m[1] / scaleX, comma,
  78760. 'M22=', m[3] / scaleY, comma,
  78761. 'Dx=', round$4(x * scaleX + m[4]), comma,
  78762. 'Dy=', round$4(y * scaleY + m[5]));
  78763. vmlElStyle.padding = '0 ' + round$4(maxX) + 'px ' + round$4(maxY) + 'px 0';
  78764. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  78765. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  78766. + transformFilter.join('') + ', SizingMethod=clip)';
  78767. }
  78768. else {
  78769. if (m) {
  78770. x = x * scaleX + m[4];
  78771. y = y * scaleY + m[5];
  78772. }
  78773. vmlElStyle.filter = '';
  78774. vmlElStyle.left = round$4(x) + 'px';
  78775. vmlElStyle.top = round$4(y) + 'px';
  78776. }
  78777. var imageEl = this._imageEl;
  78778. var cropEl = this._cropEl;
  78779. if (!imageEl) {
  78780. imageEl = doc.createElement('div');
  78781. this._imageEl = imageEl;
  78782. }
  78783. var imageELStyle = imageEl.style;
  78784. if (hasCrop) {
  78785. // Needs know image original width and height
  78786. if (!(ow && oh)) {
  78787. var tmpImage = new Image();
  78788. var self = this;
  78789. tmpImage.onload = function () {
  78790. tmpImage.onload = null;
  78791. ow = tmpImage.width;
  78792. oh = tmpImage.height;
  78793. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  78794. imageELStyle.width = round$4(scaleX * ow * dw / sw) + 'px';
  78795. imageELStyle.height = round$4(scaleY * oh * dh / sh) + 'px';
  78796. // Caching image original width, height and src
  78797. self._imageWidth = ow;
  78798. self._imageHeight = oh;
  78799. self._imageSrc = image;
  78800. };
  78801. tmpImage.src = image;
  78802. }
  78803. else {
  78804. imageELStyle.width = round$4(scaleX * ow * dw / sw) + 'px';
  78805. imageELStyle.height = round$4(scaleY * oh * dh / sh) + 'px';
  78806. }
  78807. if (!cropEl) {
  78808. cropEl = doc.createElement('div');
  78809. cropEl.style.overflow = 'hidden';
  78810. this._cropEl = cropEl;
  78811. }
  78812. var cropElStyle = cropEl.style;
  78813. cropElStyle.width = round$4((dw + sx * dw / sw) * scaleX);
  78814. cropElStyle.height = round$4((dh + sy * dh / sh) * scaleY);
  78815. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  78816. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  78817. if (!cropEl.parentNode) {
  78818. vmlEl.appendChild(cropEl);
  78819. }
  78820. if (imageEl.parentNode !== cropEl) {
  78821. cropEl.appendChild(imageEl);
  78822. }
  78823. }
  78824. else {
  78825. imageELStyle.width = round$4(scaleX * dw) + 'px';
  78826. imageELStyle.height = round$4(scaleY * dh) + 'px';
  78827. vmlEl.appendChild(imageEl);
  78828. if (cropEl && cropEl.parentNode) {
  78829. vmlEl.removeChild(cropEl);
  78830. this._cropEl = null;
  78831. }
  78832. }
  78833. var filterStr = '';
  78834. var alpha = style.opacity;
  78835. if (alpha < 1) {
  78836. filterStr += '.Alpha(opacity=' + round$4(alpha * 100) + ') ';
  78837. }
  78838. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  78839. imageELStyle.filter = filterStr;
  78840. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78841. // Append to root
  78842. append(vmlRoot, vmlEl);
  78843. // Text
  78844. if (style.text != null) {
  78845. this.drawRectText(vmlRoot, this.getBoundingRect());
  78846. }
  78847. };
  78848. ZImage.prototype.onRemove = function (vmlRoot) {
  78849. remove(vmlRoot, this._vmlEl);
  78850. this._vmlEl = null;
  78851. this._cropEl = null;
  78852. this._imageEl = null;
  78853. this.removeRectText(vmlRoot);
  78854. };
  78855. ZImage.prototype.onAdd = function (vmlRoot) {
  78856. append(vmlRoot, this._vmlEl);
  78857. this.appendRectText(vmlRoot);
  78858. };
  78859. /***************************************************
  78860. * TEXT
  78861. **************************************************/
  78862. var DEFAULT_STYLE_NORMAL = 'normal';
  78863. var fontStyleCache = {};
  78864. var fontStyleCacheCount = 0;
  78865. var MAX_FONT_CACHE_SIZE = 100;
  78866. var fontEl = document.createElement('div');
  78867. var getFontStyle = function (fontString) {
  78868. var fontStyle = fontStyleCache[fontString];
  78869. if (!fontStyle) {
  78870. // Clear cache
  78871. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  78872. fontStyleCacheCount = 0;
  78873. fontStyleCache = {};
  78874. }
  78875. var style = fontEl.style;
  78876. var fontFamily;
  78877. try {
  78878. style.font = fontString;
  78879. fontFamily = style.fontFamily.split(',')[0];
  78880. }
  78881. catch (e) {
  78882. }
  78883. fontStyle = {
  78884. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  78885. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  78886. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  78887. size: parseFloat(style.fontSize || 12) | 0,
  78888. family: fontFamily || 'Microsoft YaHei'
  78889. };
  78890. fontStyleCache[fontString] = fontStyle;
  78891. fontStyleCacheCount++;
  78892. }
  78893. return fontStyle;
  78894. };
  78895. var textMeasureEl;
  78896. // Overwrite measure text method
  78897. $override$1('measureText', function (text, textFont) {
  78898. var doc$$1 = doc;
  78899. if (!textMeasureEl) {
  78900. textMeasureEl = doc$$1.createElement('div');
  78901. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  78902. + 'padding:0;margin:0;border:none;white-space:pre;';
  78903. doc.body.appendChild(textMeasureEl);
  78904. }
  78905. try {
  78906. textMeasureEl.style.font = textFont;
  78907. }
  78908. catch (ex) {
  78909. // Ignore failures to set to invalid font.
  78910. }
  78911. textMeasureEl.innerHTML = '';
  78912. // Don't use innerHTML or innerText because they allow markup/whitespace.
  78913. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  78914. return {
  78915. width: textMeasureEl.offsetWidth
  78916. };
  78917. });
  78918. var tmpRect$2 = new BoundingRect();
  78919. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  78920. var style = this.style;
  78921. // Optimize, avoid normalize every time.
  78922. this.__dirty && normalizeTextStyle(style, true);
  78923. var text = style.text;
  78924. // Convert to string
  78925. text != null && (text += '');
  78926. if (!text) {
  78927. return;
  78928. }
  78929. // Convert rich text to plain text. Rich text is not supported in
  78930. // IE8-, but tags in rich text template will be removed.
  78931. if (style.rich) {
  78932. var contentBlock = parseRichText(text, style);
  78933. text = [];
  78934. for (var i = 0; i < contentBlock.lines.length; i++) {
  78935. var tokens = contentBlock.lines[i].tokens;
  78936. var textLine = [];
  78937. for (var j = 0; j < tokens.length; j++) {
  78938. textLine.push(tokens[j].text);
  78939. }
  78940. text.push(textLine.join(''));
  78941. }
  78942. text = text.join('\n');
  78943. }
  78944. var x;
  78945. var y;
  78946. var align = style.textAlign;
  78947. var verticalAlign = style.textVerticalAlign;
  78948. var fontStyle = getFontStyle(style.font);
  78949. // FIXME encodeHtmlAttribute ?
  78950. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  78951. + fontStyle.size + 'px "' + fontStyle.family + '"';
  78952. textRect = textRect || getBoundingRect(text, font, align, verticalAlign, style.textPadding, style.textLineHeight);
  78953. // Transform rect to view space
  78954. var m = this.transform;
  78955. // Ignore transform for text in other element
  78956. if (m && !fromTextEl) {
  78957. tmpRect$2.copy(rect);
  78958. tmpRect$2.applyTransform(m);
  78959. rect = tmpRect$2;
  78960. }
  78961. if (!fromTextEl) {
  78962. var textPosition = style.textPosition;
  78963. var distance$$1 = style.textDistance;
  78964. // Text position represented by coord
  78965. if (textPosition instanceof Array) {
  78966. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  78967. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  78968. align = align || 'left';
  78969. }
  78970. else {
  78971. var res = adjustTextPositionOnRect(
  78972. textPosition, rect, distance$$1
  78973. );
  78974. x = res.x;
  78975. y = res.y;
  78976. // Default align and baseline when has textPosition
  78977. align = align || res.textAlign;
  78978. verticalAlign = verticalAlign || res.textVerticalAlign;
  78979. }
  78980. }
  78981. else {
  78982. x = rect.x;
  78983. y = rect.y;
  78984. }
  78985. x = adjustTextX(x, textRect.width, align);
  78986. y = adjustTextY(y, textRect.height, verticalAlign);
  78987. // Force baseline 'middle'
  78988. y += textRect.height / 2;
  78989. // var fontSize = fontStyle.size;
  78990. // 1.75 is an arbitrary number, as there is no info about the text baseline
  78991. // switch (baseline) {
  78992. // case 'hanging':
  78993. // case 'top':
  78994. // y += fontSize / 1.75;
  78995. // break;
  78996. // case 'middle':
  78997. // break;
  78998. // default:
  78999. // // case null:
  79000. // // case 'alphabetic':
  79001. // // case 'ideographic':
  79002. // // case 'bottom':
  79003. // y -= fontSize / 2.25;
  79004. // break;
  79005. // }
  79006. // switch (align) {
  79007. // case 'left':
  79008. // break;
  79009. // case 'center':
  79010. // x -= textRect.width / 2;
  79011. // break;
  79012. // case 'right':
  79013. // x -= textRect.width;
  79014. // break;
  79015. // case 'end':
  79016. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  79017. // break;
  79018. // case 'start':
  79019. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  79020. // break;
  79021. // default:
  79022. // align = 'left';
  79023. // }
  79024. var createNode$$1 = createNode;
  79025. var textVmlEl = this._textVmlEl;
  79026. var pathEl;
  79027. var textPathEl;
  79028. var skewEl;
  79029. if (!textVmlEl) {
  79030. textVmlEl = createNode$$1('line');
  79031. pathEl = createNode$$1('path');
  79032. textPathEl = createNode$$1('textpath');
  79033. skewEl = createNode$$1('skew');
  79034. // FIXME Why here is not cammel case
  79035. // Align 'center' seems wrong
  79036. textPathEl.style['v-text-align'] = 'left';
  79037. initRootElStyle(textVmlEl);
  79038. pathEl.textpathok = true;
  79039. textPathEl.on = true;
  79040. textVmlEl.from = '0 0';
  79041. textVmlEl.to = '1000 0.05';
  79042. append(textVmlEl, skewEl);
  79043. append(textVmlEl, pathEl);
  79044. append(textVmlEl, textPathEl);
  79045. this._textVmlEl = textVmlEl;
  79046. }
  79047. else {
  79048. // 这里是在前面 appendChild 保证顺序的前提下
  79049. skewEl = textVmlEl.firstChild;
  79050. pathEl = skewEl.nextSibling;
  79051. textPathEl = pathEl.nextSibling;
  79052. }
  79053. var coords = [x, y];
  79054. var textVmlElStyle = textVmlEl.style;
  79055. // Ignore transform for text in other element
  79056. if (m && fromTextEl) {
  79057. applyTransform(coords, coords, m);
  79058. skewEl.on = true;
  79059. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  79060. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  79061. // Text position
  79062. skewEl.offset = (round$4(coords[0]) || 0) + ',' + (round$4(coords[1]) || 0);
  79063. // Left top point as origin
  79064. skewEl.origin = '0 0';
  79065. textVmlElStyle.left = '0px';
  79066. textVmlElStyle.top = '0px';
  79067. }
  79068. else {
  79069. skewEl.on = false;
  79070. textVmlElStyle.left = round$4(x) + 'px';
  79071. textVmlElStyle.top = round$4(y) + 'px';
  79072. }
  79073. textPathEl.string = encodeHtmlAttribute(text);
  79074. // TODO
  79075. try {
  79076. textPathEl.style.font = font;
  79077. }
  79078. // Error font format
  79079. catch (e) {}
  79080. updateFillAndStroke(textVmlEl, 'fill', {
  79081. fill: style.textFill,
  79082. opacity: style.opacity
  79083. }, this);
  79084. updateFillAndStroke(textVmlEl, 'stroke', {
  79085. stroke: style.textStroke,
  79086. opacity: style.opacity,
  79087. lineDash: style.lineDash
  79088. }, this);
  79089. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  79090. // Attached to root
  79091. append(vmlRoot, textVmlEl);
  79092. };
  79093. var removeRectText = function (vmlRoot) {
  79094. remove(vmlRoot, this._textVmlEl);
  79095. this._textVmlEl = null;
  79096. };
  79097. var appendRectText = function (vmlRoot) {
  79098. append(vmlRoot, this._textVmlEl);
  79099. };
  79100. var list = [RectText, Displayable, ZImage, Path, Text];
  79101. // In case Displayable has been mixed in RectText
  79102. for (var i$3 = 0; i$3 < list.length; i$3++) {
  79103. var proto$8 = list[i$3].prototype;
  79104. proto$8.drawRectText = drawRectText;
  79105. proto$8.removeRectText = removeRectText;
  79106. proto$8.appendRectText = appendRectText;
  79107. }
  79108. Text.prototype.brushVML = function (vmlRoot) {
  79109. var style = this.style;
  79110. if (style.text != null) {
  79111. this.drawRectText(vmlRoot, {
  79112. x: style.x || 0, y: style.y || 0,
  79113. width: 0, height: 0
  79114. }, this.getBoundingRect(), true);
  79115. }
  79116. else {
  79117. this.removeRectText(vmlRoot);
  79118. }
  79119. };
  79120. Text.prototype.onRemove = function (vmlRoot) {
  79121. this.removeRectText(vmlRoot);
  79122. };
  79123. Text.prototype.onAdd = function (vmlRoot) {
  79124. this.appendRectText(vmlRoot);
  79125. };
  79126. }
  79127. /**
  79128. * VML Painter.
  79129. *
  79130. * @module zrender/vml/Painter
  79131. */
  79132. function parseInt10$1(val) {
  79133. return parseInt(val, 10);
  79134. }
  79135. /**
  79136. * @alias module:zrender/vml/Painter
  79137. */
  79138. function VMLPainter(root, storage) {
  79139. initVML();
  79140. this.root = root;
  79141. this.storage = storage;
  79142. var vmlViewport = document.createElement('div');
  79143. var vmlRoot = document.createElement('div');
  79144. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  79145. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  79146. root.appendChild(vmlViewport);
  79147. this._vmlRoot = vmlRoot;
  79148. this._vmlViewport = vmlViewport;
  79149. this.resize();
  79150. // Modify storage
  79151. var oldDelFromStorage = storage.delFromStorage;
  79152. var oldAddToStorage = storage.addToStorage;
  79153. storage.delFromStorage = function (el) {
  79154. oldDelFromStorage.call(storage, el);
  79155. if (el) {
  79156. el.onRemove && el.onRemove(vmlRoot);
  79157. }
  79158. };
  79159. storage.addToStorage = function (el) {
  79160. // Displayable already has a vml node
  79161. el.onAdd && el.onAdd(vmlRoot);
  79162. oldAddToStorage.call(storage, el);
  79163. };
  79164. this._firstPaint = true;
  79165. }
  79166. VMLPainter.prototype = {
  79167. constructor: VMLPainter,
  79168. getType: function () {
  79169. return 'vml';
  79170. },
  79171. /**
  79172. * @return {HTMLDivElement}
  79173. */
  79174. getViewportRoot: function () {
  79175. return this._vmlViewport;
  79176. },
  79177. getViewportRootOffset: function () {
  79178. var viewportRoot = this.getViewportRoot();
  79179. if (viewportRoot) {
  79180. return {
  79181. offsetLeft: viewportRoot.offsetLeft || 0,
  79182. offsetTop: viewportRoot.offsetTop || 0
  79183. };
  79184. }
  79185. },
  79186. /**
  79187. * 刷新
  79188. */
  79189. refresh: function () {
  79190. var list = this.storage.getDisplayList(true, true);
  79191. this._paintList(list);
  79192. },
  79193. _paintList: function (list) {
  79194. var vmlRoot = this._vmlRoot;
  79195. for (var i = 0; i < list.length; i++) {
  79196. var el = list[i];
  79197. if (el.invisible || el.ignore) {
  79198. if (!el.__alreadyNotVisible) {
  79199. el.onRemove(vmlRoot);
  79200. }
  79201. // Set as already invisible
  79202. el.__alreadyNotVisible = true;
  79203. }
  79204. else {
  79205. if (el.__alreadyNotVisible) {
  79206. el.onAdd(vmlRoot);
  79207. }
  79208. el.__alreadyNotVisible = false;
  79209. if (el.__dirty) {
  79210. el.beforeBrush && el.beforeBrush();
  79211. (el.brushVML || el.brush).call(el, vmlRoot);
  79212. el.afterBrush && el.afterBrush();
  79213. }
  79214. }
  79215. el.__dirty = false;
  79216. }
  79217. if (this._firstPaint) {
  79218. // Detached from document at first time
  79219. // to avoid page refreshing too many times
  79220. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  79221. this._vmlViewport.appendChild(vmlRoot);
  79222. this._firstPaint = false;
  79223. }
  79224. },
  79225. resize: function (width, height) {
  79226. var width = width == null ? this._getWidth() : width;
  79227. var height = height == null ? this._getHeight() : height;
  79228. if (this._width !== width || this._height !== height) {
  79229. this._width = width;
  79230. this._height = height;
  79231. var vmlViewportStyle = this._vmlViewport.style;
  79232. vmlViewportStyle.width = width + 'px';
  79233. vmlViewportStyle.height = height + 'px';
  79234. }
  79235. },
  79236. dispose: function () {
  79237. this.root.innerHTML = '';
  79238. this._vmlRoot =
  79239. this._vmlViewport =
  79240. this.storage = null;
  79241. },
  79242. getWidth: function () {
  79243. return this._width;
  79244. },
  79245. getHeight: function () {
  79246. return this._height;
  79247. },
  79248. clear: function () {
  79249. if (this._vmlViewport) {
  79250. this.root.removeChild(this._vmlViewport);
  79251. }
  79252. },
  79253. _getWidth: function () {
  79254. var root = this.root;
  79255. var stl = root.currentStyle;
  79256. return ((root.clientWidth || parseInt10$1(stl.width))
  79257. - parseInt10$1(stl.paddingLeft)
  79258. - parseInt10$1(stl.paddingRight)) | 0;
  79259. },
  79260. _getHeight: function () {
  79261. var root = this.root;
  79262. var stl = root.currentStyle;
  79263. return ((root.clientHeight || parseInt10$1(stl.height))
  79264. - parseInt10$1(stl.paddingTop)
  79265. - parseInt10$1(stl.paddingBottom)) | 0;
  79266. }
  79267. };
  79268. // Not supported methods
  79269. function createMethodNotSupport(method) {
  79270. return function () {
  79271. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  79272. };
  79273. }
  79274. // Unsupported methods
  79275. each$1([
  79276. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  79277. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  79278. ], function (name) {
  79279. VMLPainter.prototype[name] = createMethodNotSupport(name);
  79280. });
  79281. registerPainter('vml', VMLPainter);
  79282. var svgURI = 'http://www.w3.org/2000/svg';
  79283. function createElement(name) {
  79284. return document.createElementNS(svgURI, name);
  79285. }
  79286. // TODO
  79287. // 1. shadow
  79288. // 2. Image: sx, sy, sw, sh
  79289. var CMD$4 = PathProxy.CMD;
  79290. var arrayJoin = Array.prototype.join;
  79291. var NONE = 'none';
  79292. var mathRound = Math.round;
  79293. var mathSin$3 = Math.sin;
  79294. var mathCos$3 = Math.cos;
  79295. var PI$5 = Math.PI;
  79296. var PI2$7 = Math.PI * 2;
  79297. var degree = 180 / PI$5;
  79298. var EPSILON$4 = 1e-4;
  79299. function round4(val) {
  79300. return mathRound(val * 1e4) / 1e4;
  79301. }
  79302. function isAroundZero$1(val) {
  79303. return val < EPSILON$4 && val > -EPSILON$4;
  79304. }
  79305. function pathHasFill(style, isText) {
  79306. var fill = isText ? style.textFill : style.fill;
  79307. return fill != null && fill !== NONE;
  79308. }
  79309. function pathHasStroke(style, isText) {
  79310. var stroke = isText ? style.textStroke : style.stroke;
  79311. return stroke != null && stroke !== NONE;
  79312. }
  79313. function setTransform(svgEl, m) {
  79314. if (m) {
  79315. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  79316. }
  79317. }
  79318. function attr(el, key, val) {
  79319. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  79320. // Don't set attribute for gradient, since it need new dom nodes
  79321. el.setAttribute(key, val);
  79322. }
  79323. }
  79324. function attrXLink(el, key, val) {
  79325. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  79326. }
  79327. function bindStyle(svgEl, style, isText, el) {
  79328. if (pathHasFill(style, isText)) {
  79329. var fill = isText ? style.textFill : style.fill;
  79330. fill = fill === 'transparent' ? NONE : fill;
  79331. /**
  79332. * FIXME:
  79333. * This is a temporary fix for Chrome's clipping bug
  79334. * that happens when a clip-path is referring another one.
  79335. * This fix should be used before Chrome's bug is fixed.
  79336. * For an element that has clip-path, and fill is none,
  79337. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  79338. * Otherwise, it will show black fill color.
  79339. * 0.002 is used because this won't work for alpha values smaller
  79340. * than 0.002.
  79341. *
  79342. * See
  79343. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  79344. * for more information.
  79345. */
  79346. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  79347. fill = 'rgba(0, 0, 0, 0.002)';
  79348. }
  79349. attr(svgEl, 'fill', fill);
  79350. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  79351. }
  79352. else {
  79353. attr(svgEl, 'fill', NONE);
  79354. }
  79355. if (pathHasStroke(style, isText)) {
  79356. var stroke = isText ? style.textStroke : style.stroke;
  79357. stroke = stroke === 'transparent' ? NONE : stroke;
  79358. attr(svgEl, 'stroke', stroke);
  79359. var strokeWidth = isText
  79360. ? style.textStrokeWidth
  79361. : style.lineWidth;
  79362. var strokeScale = !isText && style.strokeNoScale
  79363. ? el.getLineScale()
  79364. : 1;
  79365. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  79366. // stroke then fill for text; fill then stroke for others
  79367. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  79368. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  79369. var lineDash = style.lineDash;
  79370. if (lineDash) {
  79371. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  79372. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  79373. }
  79374. else {
  79375. attr(svgEl, 'stroke-dasharray', '');
  79376. }
  79377. // PENDING
  79378. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  79379. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  79380. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  79381. }
  79382. else {
  79383. attr(svgEl, 'stroke', NONE);
  79384. }
  79385. }
  79386. /***************************************************
  79387. * PATH
  79388. **************************************************/
  79389. function pathDataToString$1(path) {
  79390. var str = [];
  79391. var data = path.data;
  79392. var dataLength = path.len();
  79393. for (var i = 0; i < dataLength;) {
  79394. var cmd = data[i++];
  79395. var cmdStr = '';
  79396. var nData = 0;
  79397. switch (cmd) {
  79398. case CMD$4.M:
  79399. cmdStr = 'M';
  79400. nData = 2;
  79401. break;
  79402. case CMD$4.L:
  79403. cmdStr = 'L';
  79404. nData = 2;
  79405. break;
  79406. case CMD$4.Q:
  79407. cmdStr = 'Q';
  79408. nData = 4;
  79409. break;
  79410. case CMD$4.C:
  79411. cmdStr = 'C';
  79412. nData = 6;
  79413. break;
  79414. case CMD$4.A:
  79415. var cx = data[i++];
  79416. var cy = data[i++];
  79417. var rx = data[i++];
  79418. var ry = data[i++];
  79419. var theta = data[i++];
  79420. var dTheta = data[i++];
  79421. var psi = data[i++];
  79422. var clockwise = data[i++];
  79423. var dThetaPositive = Math.abs(dTheta);
  79424. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  79425. && !isAroundZero$1(dThetaPositive);
  79426. var large = false;
  79427. if (dThetaPositive >= PI2$7) {
  79428. large = true;
  79429. }
  79430. else if (isAroundZero$1(dThetaPositive)) {
  79431. large = false;
  79432. }
  79433. else {
  79434. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  79435. === !!clockwise;
  79436. }
  79437. var x0 = round4(cx + rx * mathCos$3(theta));
  79438. var y0 = round4(cy + ry * mathSin$3(theta));
  79439. // It will not draw if start point and end point are exactly the same
  79440. // We need to shift the end point with a small value
  79441. // FIXME A better way to draw circle ?
  79442. if (isCircle) {
  79443. if (clockwise) {
  79444. dTheta = PI2$7 - 1e-4;
  79445. }
  79446. else {
  79447. dTheta = -PI2$7 + 1e-4;
  79448. }
  79449. large = true;
  79450. if (i === 9) {
  79451. // Move to (x0, y0) only when CMD.A comes at the
  79452. // first position of a shape.
  79453. // For instance, when drawing a ring, CMD.A comes
  79454. // after CMD.M, so it's unnecessary to move to
  79455. // (x0, y0).
  79456. str.push('M', x0, y0);
  79457. }
  79458. }
  79459. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  79460. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  79461. // FIXME Ellipse
  79462. str.push('A', round4(rx), round4(ry),
  79463. mathRound(psi * degree), +large, +clockwise, x, y);
  79464. break;
  79465. case CMD$4.Z:
  79466. cmdStr = 'Z';
  79467. break;
  79468. case CMD$4.R:
  79469. var x = round4(data[i++]);
  79470. var y = round4(data[i++]);
  79471. var w = round4(data[i++]);
  79472. var h = round4(data[i++]);
  79473. str.push(
  79474. 'M', x, y,
  79475. 'L', x + w, y,
  79476. 'L', x + w, y + h,
  79477. 'L', x, y + h,
  79478. 'L', x, y
  79479. );
  79480. break;
  79481. }
  79482. cmdStr && str.push(cmdStr);
  79483. for (var j = 0; j < nData; j++) {
  79484. // PENDING With scale
  79485. str.push(round4(data[i++]));
  79486. }
  79487. }
  79488. return str.join(' ');
  79489. }
  79490. var svgPath = {};
  79491. svgPath.brush = function (el) {
  79492. var style = el.style;
  79493. var svgEl = el.__svgEl;
  79494. if (!svgEl) {
  79495. svgEl = createElement('path');
  79496. el.__svgEl = svgEl;
  79497. }
  79498. if (!el.path) {
  79499. el.createPathProxy();
  79500. }
  79501. var path = el.path;
  79502. if (el.__dirtyPath) {
  79503. path.beginPath();
  79504. path.subPixelOptimize = false;
  79505. el.buildPath(path, el.shape);
  79506. el.__dirtyPath = false;
  79507. var pathStr = pathDataToString$1(path);
  79508. if (pathStr.indexOf('NaN') < 0) {
  79509. // Ignore illegal path, which may happen such in out-of-range
  79510. // data in Calendar series.
  79511. attr(svgEl, 'd', pathStr);
  79512. }
  79513. }
  79514. bindStyle(svgEl, style, false, el);
  79515. setTransform(svgEl, el.transform);
  79516. if (style.text != null) {
  79517. svgTextDrawRectText(el, el.getBoundingRect());
  79518. }
  79519. };
  79520. /***************************************************
  79521. * IMAGE
  79522. **************************************************/
  79523. var svgImage = {};
  79524. svgImage.brush = function (el) {
  79525. var style = el.style;
  79526. var image = style.image;
  79527. if (image instanceof HTMLImageElement) {
  79528. var src = image.src;
  79529. image = src;
  79530. }
  79531. if (!image) {
  79532. return;
  79533. }
  79534. var x = style.x || 0;
  79535. var y = style.y || 0;
  79536. var dw = style.width;
  79537. var dh = style.height;
  79538. var svgEl = el.__svgEl;
  79539. if (!svgEl) {
  79540. svgEl = createElement('image');
  79541. el.__svgEl = svgEl;
  79542. }
  79543. if (image !== el.__imageSrc) {
  79544. attrXLink(svgEl, 'href', image);
  79545. // Caching image src
  79546. el.__imageSrc = image;
  79547. }
  79548. attr(svgEl, 'width', dw);
  79549. attr(svgEl, 'height', dh);
  79550. attr(svgEl, 'x', x);
  79551. attr(svgEl, 'y', y);
  79552. setTransform(svgEl, el.transform);
  79553. if (style.text != null) {
  79554. svgTextDrawRectText(el, el.getBoundingRect());
  79555. }
  79556. };
  79557. /***************************************************
  79558. * TEXT
  79559. **************************************************/
  79560. var svgText = {};
  79561. var tmpRect$3 = new BoundingRect();
  79562. var svgTextDrawRectText = function (el, rect, textRect) {
  79563. var style = el.style;
  79564. el.__dirty && normalizeTextStyle(style, true);
  79565. var text = style.text;
  79566. // Convert to string
  79567. if (text == null) {
  79568. // Draw no text only when text is set to null, but not ''
  79569. return;
  79570. }
  79571. else {
  79572. text += '';
  79573. }
  79574. var textSvgEl = el.__textSvgEl;
  79575. if (!textSvgEl) {
  79576. textSvgEl = createElement('text');
  79577. el.__textSvgEl = textSvgEl;
  79578. }
  79579. var x;
  79580. var y;
  79581. var textPosition = style.textPosition;
  79582. var distance = style.textDistance;
  79583. var align = style.textAlign || 'left';
  79584. if (typeof style.fontSize === 'number') {
  79585. style.fontSize += 'px';
  79586. }
  79587. var font = style.font
  79588. || [
  79589. style.fontStyle || '',
  79590. style.fontWeight || '',
  79591. style.fontSize || '',
  79592. style.fontFamily || ''
  79593. ].join(' ')
  79594. || DEFAULT_FONT$1;
  79595. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  79596. textRect = getBoundingRect(text, font, align,
  79597. verticalAlign, style.textPadding, style.textLineHeight);
  79598. var lineHeight = textRect.lineHeight;
  79599. // Text position represented by coord
  79600. if (textPosition instanceof Array) {
  79601. x = rect.x + textPosition[0];
  79602. y = rect.y + textPosition[1];
  79603. }
  79604. else {
  79605. var newPos = adjustTextPositionOnRect(
  79606. textPosition, rect, distance
  79607. );
  79608. x = newPos.x;
  79609. y = newPos.y;
  79610. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  79611. align = newPos.textAlign;
  79612. }
  79613. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  79614. if (font) {
  79615. textSvgEl.style.font = font;
  79616. }
  79617. var textPadding = style.textPadding;
  79618. // Make baseline top
  79619. attr(textSvgEl, 'x', x);
  79620. attr(textSvgEl, 'y', y);
  79621. bindStyle(textSvgEl, style, true, el);
  79622. if (el instanceof Text || el.style.transformText) {
  79623. // Transform text with element
  79624. setTransform(textSvgEl, el.transform);
  79625. }
  79626. else {
  79627. if (el.transform) {
  79628. tmpRect$3.copy(rect);
  79629. tmpRect$3.applyTransform(el.transform);
  79630. rect = tmpRect$3;
  79631. }
  79632. else {
  79633. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  79634. rect.x = pos[0];
  79635. rect.y = pos[1];
  79636. el.transform = identity(create$1());
  79637. }
  79638. // Text rotation, but no element transform
  79639. var origin = style.textOrigin;
  79640. if (origin === 'center') {
  79641. x = textRect.width / 2 + x;
  79642. y = textRect.height / 2 + y;
  79643. }
  79644. else if (origin) {
  79645. x = origin[0] + x;
  79646. y = origin[1] + y;
  79647. }
  79648. var rotate$$1 = -style.textRotation || 0;
  79649. var transform = create$1();
  79650. // Apply textRotate to element matrix
  79651. rotate(transform, transform, rotate$$1);
  79652. var pos = [el.transform[4], el.transform[5]];
  79653. translate(transform, transform, pos);
  79654. setTransform(textSvgEl, transform);
  79655. }
  79656. var textLines = text.split('\n');
  79657. var nTextLines = textLines.length;
  79658. var textAnchor = align;
  79659. // PENDING
  79660. if (textAnchor === 'left') {
  79661. textAnchor = 'start';
  79662. textPadding && (x += textPadding[3]);
  79663. }
  79664. else if (textAnchor === 'right') {
  79665. textAnchor = 'end';
  79666. textPadding && (x -= textPadding[1]);
  79667. }
  79668. else if (textAnchor === 'center') {
  79669. textAnchor = 'middle';
  79670. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  79671. }
  79672. var dy = 0;
  79673. if (verticalAlign === 'after-edge') {
  79674. dy = -textRect.height + lineHeight;
  79675. textPadding && (dy -= textPadding[2]);
  79676. }
  79677. else if (verticalAlign === 'middle') {
  79678. dy = (-textRect.height + lineHeight) / 2;
  79679. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  79680. }
  79681. else {
  79682. textPadding && (dy += textPadding[0]);
  79683. }
  79684. // Font may affect position of each tspan elements
  79685. if (el.__text !== text || el.__textFont !== font) {
  79686. var tspanList = el.__tspanList || [];
  79687. el.__tspanList = tspanList;
  79688. for (var i = 0; i < nTextLines; i++) {
  79689. // Using cached tspan elements
  79690. var tspan = tspanList[i];
  79691. if (!tspan) {
  79692. tspan = tspanList[i] = createElement('tspan');
  79693. textSvgEl.appendChild(tspan);
  79694. attr(tspan, 'alignment-baseline', verticalAlign);
  79695. attr(tspan, 'text-anchor', textAnchor);
  79696. }
  79697. else {
  79698. tspan.innerHTML = '';
  79699. }
  79700. attr(tspan, 'x', x);
  79701. attr(tspan, 'y', y + i * lineHeight + dy);
  79702. tspan.appendChild(document.createTextNode(textLines[i]));
  79703. }
  79704. // Remove unsed tspan elements
  79705. for (; i < tspanList.length; i++) {
  79706. textSvgEl.removeChild(tspanList[i]);
  79707. }
  79708. tspanList.length = nTextLines;
  79709. el.__text = text;
  79710. el.__textFont = font;
  79711. }
  79712. else if (el.__tspanList.length) {
  79713. // Update span x and y
  79714. var len = el.__tspanList.length;
  79715. for (var i = 0; i < len; ++i) {
  79716. var tspan = el.__tspanList[i];
  79717. if (tspan) {
  79718. attr(tspan, 'x', x);
  79719. attr(tspan, 'y', y + i * lineHeight + dy);
  79720. }
  79721. }
  79722. }
  79723. };
  79724. function getVerticalAlignForSvg(verticalAlign) {
  79725. if (verticalAlign === 'middle') {
  79726. return 'middle';
  79727. }
  79728. else if (verticalAlign === 'bottom') {
  79729. return 'after-edge';
  79730. }
  79731. else {
  79732. return 'hanging';
  79733. }
  79734. }
  79735. svgText.drawRectText = svgTextDrawRectText;
  79736. svgText.brush = function (el) {
  79737. var style = el.style;
  79738. if (style.text != null) {
  79739. // 强制设置 textPosition
  79740. style.textPosition = [0, 0];
  79741. svgTextDrawRectText(el, {
  79742. x: style.x || 0, y: style.y || 0,
  79743. width: 0, height: 0
  79744. }, el.getBoundingRect());
  79745. }
  79746. };
  79747. // Myers' Diff Algorithm
  79748. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  79749. function Diff() {}
  79750. Diff.prototype = {
  79751. diff: function (oldArr, newArr, equals) {
  79752. if (!equals) {
  79753. equals = function (a, b) {
  79754. return a === b;
  79755. };
  79756. }
  79757. this.equals = equals;
  79758. var self = this;
  79759. oldArr = oldArr.slice();
  79760. newArr = newArr.slice();
  79761. // Allow subclasses to massage the input prior to running
  79762. var newLen = newArr.length;
  79763. var oldLen = oldArr.length;
  79764. var editLength = 1;
  79765. var maxEditLength = newLen + oldLen;
  79766. var bestPath = [{ newPos: -1, components: [] }];
  79767. // Seed editLength = 0, i.e. the content starts with the same values
  79768. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  79769. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79770. var indices = [];
  79771. for (var i = 0; i < newArr.length; i++) {
  79772. indices.push(i);
  79773. }
  79774. // Identity per the equality and tokenizer
  79775. return [{
  79776. indices: indices, count: newArr.length
  79777. }];
  79778. }
  79779. // Main worker method. checks all permutations of a given edit length for acceptance.
  79780. function execEditLength() {
  79781. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  79782. var basePath;
  79783. var addPath = bestPath[diagonalPath - 1];
  79784. var removePath = bestPath[diagonalPath + 1];
  79785. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  79786. if (addPath) {
  79787. // No one else is going to attempt to use this value, clear it
  79788. bestPath[diagonalPath - 1] = undefined;
  79789. }
  79790. var canAdd = addPath && addPath.newPos + 1 < newLen;
  79791. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  79792. if (!canAdd && !canRemove) {
  79793. // If this path is a terminal then prune
  79794. bestPath[diagonalPath] = undefined;
  79795. continue;
  79796. }
  79797. // Select the diagonal that we want to branch from. We select the prior
  79798. // path whose position in the new string is the farthest from the origin
  79799. // and does not pass the bounds of the diff graph
  79800. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  79801. basePath = clonePath(removePath);
  79802. self.pushComponent(basePath.components, undefined, true);
  79803. }
  79804. else {
  79805. basePath = addPath; // No need to clone, we've pulled it from the list
  79806. basePath.newPos++;
  79807. self.pushComponent(basePath.components, true, undefined);
  79808. }
  79809. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  79810. // If we have hit the end of both strings, then we are done
  79811. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79812. return buildValues(self, basePath.components, newArr, oldArr);
  79813. }
  79814. else {
  79815. // Otherwise track this path as a potential candidate and continue.
  79816. bestPath[diagonalPath] = basePath;
  79817. }
  79818. }
  79819. editLength++;
  79820. }
  79821. while (editLength <= maxEditLength) {
  79822. var ret = execEditLength();
  79823. if (ret) {
  79824. return ret;
  79825. }
  79826. }
  79827. },
  79828. pushComponent: function (components, added, removed) {
  79829. var last = components[components.length - 1];
  79830. if (last && last.added === added && last.removed === removed) {
  79831. // We need to clone here as the component clone operation is just
  79832. // as shallow array clone
  79833. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  79834. }
  79835. else {
  79836. components.push({count: 1, added: added, removed: removed });
  79837. }
  79838. },
  79839. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  79840. var newLen = newArr.length;
  79841. var oldLen = oldArr.length;
  79842. var newPos = basePath.newPos;
  79843. var oldPos = newPos - diagonalPath;
  79844. var commonCount = 0;
  79845. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  79846. newPos++;
  79847. oldPos++;
  79848. commonCount++;
  79849. }
  79850. if (commonCount) {
  79851. basePath.components.push({count: commonCount});
  79852. }
  79853. basePath.newPos = newPos;
  79854. return oldPos;
  79855. },
  79856. tokenize: function (value) {
  79857. return value.slice();
  79858. },
  79859. join: function (value) {
  79860. return value.slice();
  79861. }
  79862. };
  79863. function buildValues(diff, components, newArr, oldArr) {
  79864. var componentPos = 0;
  79865. var componentLen = components.length;
  79866. var newPos = 0;
  79867. var oldPos = 0;
  79868. for (; componentPos < componentLen; componentPos++) {
  79869. var component = components[componentPos];
  79870. if (!component.removed) {
  79871. var indices = [];
  79872. for (var i = newPos; i < newPos + component.count; i++) {
  79873. indices.push(i);
  79874. }
  79875. component.indices = indices;
  79876. newPos += component.count;
  79877. // Common case
  79878. if (!component.added) {
  79879. oldPos += component.count;
  79880. }
  79881. }
  79882. else {
  79883. var indices = [];
  79884. for (var i = oldPos; i < oldPos + component.count; i++) {
  79885. indices.push(i);
  79886. }
  79887. component.indices = indices;
  79888. oldPos += component.count;
  79889. }
  79890. }
  79891. return components;
  79892. }
  79893. function clonePath(path) {
  79894. return { newPos: path.newPos, components: path.components.slice(0) };
  79895. }
  79896. var arrayDiff = new Diff();
  79897. var arrayDiff$1 = function (oldArr, newArr, callback) {
  79898. return arrayDiff.diff(oldArr, newArr, callback);
  79899. };
  79900. /**
  79901. * @file Manages elements that can be defined in <defs> in SVG,
  79902. * e.g., gradients, clip path, etc.
  79903. * @author Zhang Wenli
  79904. */
  79905. var MARK_UNUSED = '0';
  79906. var MARK_USED = '1';
  79907. /**
  79908. * Manages elements that can be defined in <defs> in SVG,
  79909. * e.g., gradients, clip path, etc.
  79910. *
  79911. * @class
  79912. * @param {number} zrId zrender instance id
  79913. * @param {SVGElement} svgRoot root of SVG document
  79914. * @param {string|string[]} tagNames possible tag names
  79915. * @param {string} markLabel label name to make if the element
  79916. * is used
  79917. */
  79918. function Definable(
  79919. zrId,
  79920. svgRoot,
  79921. tagNames,
  79922. markLabel,
  79923. domName
  79924. ) {
  79925. this._zrId = zrId;
  79926. this._svgRoot = svgRoot;
  79927. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  79928. this._markLabel = markLabel;
  79929. this._domName = domName || '_dom';
  79930. this.nextId = 0;
  79931. }
  79932. Definable.prototype.createElement = createElement;
  79933. /**
  79934. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  79935. *
  79936. * @param {boolean} isForceCreating if need to create when not exists
  79937. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  79938. * exist and isForceCreating is false
  79939. */
  79940. Definable.prototype.getDefs = function (isForceCreating) {
  79941. var svgRoot = this._svgRoot;
  79942. var defs = this._svgRoot.getElementsByTagName('defs');
  79943. if (defs.length === 0) {
  79944. // Not exist
  79945. if (isForceCreating) {
  79946. defs = svgRoot.insertBefore(
  79947. this.createElement('defs'), // Create new tag
  79948. svgRoot.firstChild // Insert in the front of svg
  79949. );
  79950. if (!defs.contains) {
  79951. // IE doesn't support contains method
  79952. defs.contains = function (el) {
  79953. var children = defs.children;
  79954. if (!children) {
  79955. return false;
  79956. }
  79957. for (var i = children.length - 1; i >= 0; --i) {
  79958. if (children[i] === el) {
  79959. return true;
  79960. }
  79961. }
  79962. return false;
  79963. };
  79964. }
  79965. return defs;
  79966. }
  79967. else {
  79968. return null;
  79969. }
  79970. }
  79971. else {
  79972. return defs[0];
  79973. }
  79974. };
  79975. /**
  79976. * Update DOM element if necessary.
  79977. *
  79978. * @param {Object|string} element style element. e.g., for gradient,
  79979. * it may be '#ccc' or {type: 'linear', ...}
  79980. * @param {Function|undefined} onUpdate update callback
  79981. */
  79982. Definable.prototype.update = function (element, onUpdate) {
  79983. if (!element) {
  79984. return;
  79985. }
  79986. var defs = this.getDefs(false);
  79987. if (element[this._domName] && defs.contains(element[this._domName])) {
  79988. // Update DOM
  79989. if (typeof onUpdate === 'function') {
  79990. onUpdate(element);
  79991. }
  79992. }
  79993. else {
  79994. // No previous dom, create new
  79995. var dom = this.add(element);
  79996. if (dom) {
  79997. element[this._domName] = dom;
  79998. }
  79999. }
  80000. };
  80001. /**
  80002. * Add gradient dom to defs
  80003. *
  80004. * @param {SVGElement} dom DOM to be added to <defs>
  80005. */
  80006. Definable.prototype.addDom = function (dom) {
  80007. var defs = this.getDefs(true);
  80008. defs.appendChild(dom);
  80009. };
  80010. /**
  80011. * Remove DOM of a given element.
  80012. *
  80013. * @param {SVGElement} element element to remove dom
  80014. */
  80015. Definable.prototype.removeDom = function (element) {
  80016. var defs = this.getDefs(false);
  80017. if (defs && element[this._domName]) {
  80018. defs.removeChild(element[this._domName]);
  80019. element[this._domName] = null;
  80020. }
  80021. };
  80022. /**
  80023. * Get DOMs of this element.
  80024. *
  80025. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  80026. */
  80027. Definable.prototype.getDoms = function () {
  80028. var defs = this.getDefs(false);
  80029. if (!defs) {
  80030. // No dom when defs is not defined
  80031. return [];
  80032. }
  80033. var doms = [];
  80034. each$1(this._tagNames, function (tagName) {
  80035. var tags = defs.getElementsByTagName(tagName);
  80036. // Note that tags is HTMLCollection, which is array-like
  80037. // rather than real array.
  80038. // So `doms.concat(tags)` add tags as one object.
  80039. doms = doms.concat([].slice.call(tags));
  80040. });
  80041. return doms;
  80042. };
  80043. /**
  80044. * Mark DOMs to be unused before painting, and clear unused ones at the end
  80045. * of the painting.
  80046. */
  80047. Definable.prototype.markAllUnused = function () {
  80048. var doms = this.getDoms();
  80049. var that = this;
  80050. each$1(doms, function (dom) {
  80051. dom[that._markLabel] = MARK_UNUSED;
  80052. });
  80053. };
  80054. /**
  80055. * Mark a single DOM to be used.
  80056. *
  80057. * @param {SVGElement} dom DOM to mark
  80058. */
  80059. Definable.prototype.markUsed = function (dom) {
  80060. if (dom) {
  80061. dom[this._markLabel] = MARK_USED;
  80062. }
  80063. };
  80064. /**
  80065. * Remove unused DOMs defined in <defs>
  80066. */
  80067. Definable.prototype.removeUnused = function () {
  80068. var defs = this.getDefs(false);
  80069. if (!defs) {
  80070. // Nothing to remove
  80071. return;
  80072. }
  80073. var doms = this.getDoms();
  80074. var that = this;
  80075. each$1(doms, function (dom) {
  80076. if (dom[that._markLabel] !== MARK_USED) {
  80077. // Remove gradient
  80078. defs.removeChild(dom);
  80079. }
  80080. });
  80081. };
  80082. /**
  80083. * Get SVG proxy.
  80084. *
  80085. * @param {Displayable} displayable displayable element
  80086. * @return {Path|Image|Text} svg proxy of given element
  80087. */
  80088. Definable.prototype.getSvgProxy = function (displayable) {
  80089. if (displayable instanceof Path) {
  80090. return svgPath;
  80091. }
  80092. else if (displayable instanceof ZImage) {
  80093. return svgImage;
  80094. }
  80095. else if (displayable instanceof Text) {
  80096. return svgText;
  80097. }
  80098. else {
  80099. return svgPath;
  80100. }
  80101. };
  80102. /**
  80103. * Get text SVG element.
  80104. *
  80105. * @param {Displayable} displayable displayable element
  80106. * @return {SVGElement} SVG element of text
  80107. */
  80108. Definable.prototype.getTextSvgElement = function (displayable) {
  80109. return displayable.__textSvgEl;
  80110. };
  80111. /**
  80112. * Get SVG element.
  80113. *
  80114. * @param {Displayable} displayable displayable element
  80115. * @return {SVGElement} SVG element
  80116. */
  80117. Definable.prototype.getSvgElement = function (displayable) {
  80118. return displayable.__svgEl;
  80119. };
  80120. /**
  80121. * @file Manages SVG gradient elements.
  80122. * @author Zhang Wenli
  80123. */
  80124. /**
  80125. * Manages SVG gradient elements.
  80126. *
  80127. * @class
  80128. * @extends Definable
  80129. * @param {number} zrId zrender instance id
  80130. * @param {SVGElement} svgRoot root of SVG document
  80131. */
  80132. function GradientManager(zrId, svgRoot) {
  80133. Definable.call(
  80134. this,
  80135. zrId,
  80136. svgRoot,
  80137. ['linearGradient', 'radialGradient'],
  80138. '__gradient_in_use__'
  80139. );
  80140. }
  80141. inherits(GradientManager, Definable);
  80142. /**
  80143. * Create new gradient DOM for fill or stroke if not exist,
  80144. * but will not update gradient if exists.
  80145. *
  80146. * @param {SvgElement} svgElement SVG element to paint
  80147. * @param {Displayable} displayable zrender displayable element
  80148. */
  80149. GradientManager.prototype.addWithoutUpdate = function (
  80150. svgElement,
  80151. displayable
  80152. ) {
  80153. if (displayable && displayable.style) {
  80154. var that = this;
  80155. each$1(['fill', 'stroke'], function (fillOrStroke) {
  80156. if (displayable.style[fillOrStroke]
  80157. && (displayable.style[fillOrStroke].type === 'linear'
  80158. || displayable.style[fillOrStroke].type === 'radial')
  80159. ) {
  80160. var gradient = displayable.style[fillOrStroke];
  80161. var defs = that.getDefs(true);
  80162. // Create dom in <defs> if not exists
  80163. var dom;
  80164. if (gradient._dom) {
  80165. // Gradient exists
  80166. dom = gradient._dom;
  80167. if (!defs.contains(gradient._dom)) {
  80168. // _dom is no longer in defs, recreate
  80169. that.addDom(dom);
  80170. }
  80171. }
  80172. else {
  80173. // New dom
  80174. dom = that.add(gradient);
  80175. }
  80176. that.markUsed(displayable);
  80177. var id = dom.getAttribute('id');
  80178. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  80179. }
  80180. });
  80181. }
  80182. };
  80183. /**
  80184. * Add a new gradient tag in <defs>
  80185. *
  80186. * @param {Gradient} gradient zr gradient instance
  80187. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  80188. * created DOM
  80189. */
  80190. GradientManager.prototype.add = function (gradient) {
  80191. var dom;
  80192. if (gradient.type === 'linear') {
  80193. dom = this.createElement('linearGradient');
  80194. }
  80195. else if (gradient.type === 'radial') {
  80196. dom = this.createElement('radialGradient');
  80197. }
  80198. else {
  80199. zrLog('Illegal gradient type.');
  80200. return null;
  80201. }
  80202. // Set dom id with gradient id, since each gradient instance
  80203. // will have no more than one dom element.
  80204. // id may exists before for those dirty elements, in which case
  80205. // id should remain the same, and other attributes should be
  80206. // updated.
  80207. gradient.id = gradient.id || this.nextId++;
  80208. dom.setAttribute('id', 'zr' + this._zrId
  80209. + '-gradient-' + gradient.id);
  80210. this.updateDom(gradient, dom);
  80211. this.addDom(dom);
  80212. return dom;
  80213. };
  80214. /**
  80215. * Update gradient.
  80216. *
  80217. * @param {Gradient} gradient zr gradient instance
  80218. */
  80219. GradientManager.prototype.update = function (gradient) {
  80220. var that = this;
  80221. Definable.prototype.update.call(this, gradient, function () {
  80222. var type = gradient.type;
  80223. var tagName = gradient._dom.tagName;
  80224. if (type === 'linear' && tagName === 'linearGradient'
  80225. || type === 'radial' && tagName === 'radialGradient'
  80226. ) {
  80227. // Gradient type is not changed, update gradient
  80228. that.updateDom(gradient, gradient._dom);
  80229. }
  80230. else {
  80231. // Remove and re-create if type is changed
  80232. that.removeDom(gradient);
  80233. that.add(gradient);
  80234. }
  80235. });
  80236. };
  80237. /**
  80238. * Update gradient dom
  80239. *
  80240. * @param {Gradient} gradient zr gradient instance
  80241. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  80242. * DOM to update
  80243. */
  80244. GradientManager.prototype.updateDom = function (gradient, dom) {
  80245. if (gradient.type === 'linear') {
  80246. dom.setAttribute('x1', gradient.x);
  80247. dom.setAttribute('y1', gradient.y);
  80248. dom.setAttribute('x2', gradient.x2);
  80249. dom.setAttribute('y2', gradient.y2);
  80250. }
  80251. else if (gradient.type === 'radial') {
  80252. dom.setAttribute('cx', gradient.x);
  80253. dom.setAttribute('cy', gradient.y);
  80254. dom.setAttribute('r', gradient.r);
  80255. }
  80256. else {
  80257. zrLog('Illegal gradient type.');
  80258. return;
  80259. }
  80260. if (gradient.global) {
  80261. // x1, x2, y1, y2 in range of 0 to canvas width or height
  80262. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  80263. }
  80264. else {
  80265. // x1, x2, y1, y2 in range of 0 to 1
  80266. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  80267. }
  80268. // Remove color stops if exists
  80269. dom.innerHTML = '';
  80270. // Add color stops
  80271. var colors = gradient.colorStops;
  80272. for (var i = 0, len = colors.length; i < len; ++i) {
  80273. var stop = this.createElement('stop');
  80274. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  80275. var color = colors[i].color;
  80276. if (color.indexOf('rgba' > -1)) {
  80277. // Fix Safari bug that stop-color not recognizing alpha #9014
  80278. var opacity = parse(color)[3];
  80279. var hex = toHex(color);
  80280. // stop-color cannot be color, since:
  80281. // The opacity value used for the gradient calculation is the
  80282. // *product* of the value of stop-opacity and the opacity of the
  80283. // value of stop-color.
  80284. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  80285. stop.setAttribute('stop-color', '#' + hex);
  80286. stop.setAttribute('stop-opacity', opacity);
  80287. }
  80288. else {
  80289. stop.setAttribute('stop-color', colors[i].color);
  80290. }
  80291. dom.appendChild(stop);
  80292. }
  80293. // Store dom element in gradient, to avoid creating multiple
  80294. // dom instances for the same gradient element
  80295. gradient._dom = dom;
  80296. };
  80297. /**
  80298. * Mark a single gradient to be used
  80299. *
  80300. * @param {Displayable} displayable displayable element
  80301. */
  80302. GradientManager.prototype.markUsed = function (displayable) {
  80303. if (displayable.style) {
  80304. var gradient = displayable.style.fill;
  80305. if (gradient && gradient._dom) {
  80306. Definable.prototype.markUsed.call(this, gradient._dom);
  80307. }
  80308. gradient = displayable.style.stroke;
  80309. if (gradient && gradient._dom) {
  80310. Definable.prototype.markUsed.call(this, gradient._dom);
  80311. }
  80312. }
  80313. };
  80314. /**
  80315. * @file Manages SVG clipPath elements.
  80316. * @author Zhang Wenli
  80317. */
  80318. /**
  80319. * Manages SVG clipPath elements.
  80320. *
  80321. * @class
  80322. * @extends Definable
  80323. * @param {number} zrId zrender instance id
  80324. * @param {SVGElement} svgRoot root of SVG document
  80325. */
  80326. function ClippathManager(zrId, svgRoot) {
  80327. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  80328. }
  80329. inherits(ClippathManager, Definable);
  80330. /**
  80331. * Update clipPath.
  80332. *
  80333. * @param {Displayable} displayable displayable element
  80334. */
  80335. ClippathManager.prototype.update = function (displayable) {
  80336. var svgEl = this.getSvgElement(displayable);
  80337. if (svgEl) {
  80338. this.updateDom(svgEl, displayable.__clipPaths, false);
  80339. }
  80340. var textEl = this.getTextSvgElement(displayable);
  80341. if (textEl) {
  80342. // Make another clipPath for text, since it's transform
  80343. // matrix is not the same with svgElement
  80344. this.updateDom(textEl, displayable.__clipPaths, true);
  80345. }
  80346. this.markUsed(displayable);
  80347. };
  80348. /**
  80349. * Create an SVGElement of displayable and create a <clipPath> of its
  80350. * clipPath
  80351. *
  80352. * @param {Displayable} parentEl parent element
  80353. * @param {ClipPath[]} clipPaths clipPaths of parent element
  80354. * @param {boolean} isText if parent element is Text
  80355. */
  80356. ClippathManager.prototype.updateDom = function (
  80357. parentEl,
  80358. clipPaths,
  80359. isText
  80360. ) {
  80361. if (clipPaths && clipPaths.length > 0) {
  80362. // Has clipPath, create <clipPath> with the first clipPath
  80363. var defs = this.getDefs(true);
  80364. var clipPath = clipPaths[0];
  80365. var clipPathEl;
  80366. var id;
  80367. var dom = isText ? '_textDom' : '_dom';
  80368. if (clipPath[dom]) {
  80369. // Use a dom that is already in <defs>
  80370. id = clipPath[dom].getAttribute('id');
  80371. clipPathEl = clipPath[dom];
  80372. // Use a dom that is already in <defs>
  80373. if (!defs.contains(clipPathEl)) {
  80374. // This happens when set old clipPath that has
  80375. // been previously removed
  80376. defs.appendChild(clipPathEl);
  80377. }
  80378. }
  80379. else {
  80380. // New <clipPath>
  80381. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  80382. ++this.nextId;
  80383. clipPathEl = this.createElement('clipPath');
  80384. clipPathEl.setAttribute('id', id);
  80385. defs.appendChild(clipPathEl);
  80386. clipPath[dom] = clipPathEl;
  80387. }
  80388. // Build path and add to <clipPath>
  80389. var svgProxy = this.getSvgProxy(clipPath);
  80390. if (clipPath.transform
  80391. && clipPath.parent.invTransform
  80392. && !isText
  80393. ) {
  80394. /**
  80395. * If a clipPath has a parent with transform, the transform
  80396. * of parent should not be considered when setting transform
  80397. * of clipPath. So we need to transform back from parent's
  80398. * transform, which is done by multiplying parent's inverse
  80399. * transform.
  80400. */
  80401. // Store old transform
  80402. var transform = Array.prototype.slice.call(
  80403. clipPath.transform
  80404. );
  80405. // Transform back from parent, and brush path
  80406. mul$1(
  80407. clipPath.transform,
  80408. clipPath.parent.invTransform,
  80409. clipPath.transform
  80410. );
  80411. svgProxy.brush(clipPath);
  80412. // Set back transform of clipPath
  80413. clipPath.transform = transform;
  80414. }
  80415. else {
  80416. svgProxy.brush(clipPath);
  80417. }
  80418. var pathEl = this.getSvgElement(clipPath);
  80419. clipPathEl.innerHTML = '';
  80420. /**
  80421. * Use `cloneNode()` here to appendChild to multiple parents,
  80422. * which may happend when Text and other shapes are using the same
  80423. * clipPath. Since Text will create an extra clipPath DOM due to
  80424. * different transform rules.
  80425. */
  80426. clipPathEl.appendChild(pathEl.cloneNode());
  80427. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  80428. if (clipPaths.length > 1) {
  80429. // Make the other clipPaths recursively
  80430. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  80431. }
  80432. }
  80433. else {
  80434. // No clipPath
  80435. if (parentEl) {
  80436. parentEl.setAttribute('clip-path', 'none');
  80437. }
  80438. }
  80439. };
  80440. /**
  80441. * Mark a single clipPath to be used
  80442. *
  80443. * @param {Displayable} displayable displayable element
  80444. */
  80445. ClippathManager.prototype.markUsed = function (displayable) {
  80446. var that = this;
  80447. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  80448. each$1(displayable.__clipPaths, function (clipPath) {
  80449. if (clipPath._dom) {
  80450. Definable.prototype.markUsed.call(that, clipPath._dom);
  80451. }
  80452. if (clipPath._textDom) {
  80453. Definable.prototype.markUsed.call(that, clipPath._textDom);
  80454. }
  80455. });
  80456. }
  80457. };
  80458. /**
  80459. * @file Manages SVG shadow elements.
  80460. * @author Zhang Wenli
  80461. */
  80462. /**
  80463. * Manages SVG shadow elements.
  80464. *
  80465. * @class
  80466. * @extends Definable
  80467. * @param {number} zrId zrender instance id
  80468. * @param {SVGElement} svgRoot root of SVG document
  80469. */
  80470. function ShadowManager(zrId, svgRoot) {
  80471. Definable.call(
  80472. this,
  80473. zrId,
  80474. svgRoot,
  80475. ['filter'],
  80476. '__filter_in_use__',
  80477. '_shadowDom'
  80478. );
  80479. }
  80480. inherits(ShadowManager, Definable);
  80481. /**
  80482. * Create new shadow DOM for fill or stroke if not exist,
  80483. * but will not update shadow if exists.
  80484. *
  80485. * @param {SvgElement} svgElement SVG element to paint
  80486. * @param {Displayable} displayable zrender displayable element
  80487. */
  80488. ShadowManager.prototype.addWithoutUpdate = function (
  80489. svgElement,
  80490. displayable
  80491. ) {
  80492. if (displayable && hasShadow(displayable.style)) {
  80493. var style = displayable.style;
  80494. // Create dom in <defs> if not exists
  80495. var dom;
  80496. if (style._shadowDom) {
  80497. // Gradient exists
  80498. dom = style._shadowDom;
  80499. var defs = this.getDefs(true);
  80500. if (!defs.contains(style._shadowDom)) {
  80501. // _shadowDom is no longer in defs, recreate
  80502. this.addDom(dom);
  80503. }
  80504. }
  80505. else {
  80506. // New dom
  80507. dom = this.add(displayable);
  80508. }
  80509. this.markUsed(displayable);
  80510. var id = dom.getAttribute('id');
  80511. svgElement.style.filter = 'url(#' + id + ')';
  80512. }
  80513. };
  80514. /**
  80515. * Add a new shadow tag in <defs>
  80516. *
  80517. * @param {Displayable} displayable zrender displayable element
  80518. * @return {SVGFilterElement} created DOM
  80519. */
  80520. ShadowManager.prototype.add = function (displayable) {
  80521. var dom = this.createElement('filter');
  80522. var style = displayable.style;
  80523. // Set dom id with shadow id, since each shadow instance
  80524. // will have no more than one dom element.
  80525. // id may exists before for those dirty elements, in which case
  80526. // id should remain the same, and other attributes should be
  80527. // updated.
  80528. style._shadowDomId = style._shadowDomId || this.nextId++;
  80529. dom.setAttribute('id', 'zr' + this._zrId
  80530. + '-shadow-' + style._shadowDomId);
  80531. this.updateDom(displayable, dom);
  80532. this.addDom(dom);
  80533. return dom;
  80534. };
  80535. /**
  80536. * Update shadow.
  80537. *
  80538. * @param {Displayable} displayable zrender displayable element
  80539. */
  80540. ShadowManager.prototype.update = function (svgElement, displayable) {
  80541. var style = displayable.style;
  80542. if (hasShadow(style)) {
  80543. var that = this;
  80544. Definable.prototype.update.call(this, displayable, function (style) {
  80545. that.updateDom(displayable, style._shadowDom);
  80546. });
  80547. }
  80548. else {
  80549. // Remove shadow
  80550. this.remove(svgElement, style);
  80551. }
  80552. };
  80553. /**
  80554. * Remove DOM and clear parent filter
  80555. */
  80556. ShadowManager.prototype.remove = function (svgElement, style) {
  80557. if (style._shadowDomId != null) {
  80558. this.removeDom(style);
  80559. svgElement.style.filter = '';
  80560. }
  80561. };
  80562. /**
  80563. * Update shadow dom
  80564. *
  80565. * @param {Displayable} displayable zrender displayable element
  80566. * @param {SVGFilterElement} dom DOM to update
  80567. */
  80568. ShadowManager.prototype.updateDom = function (displayable, dom) {
  80569. var domChild = dom.getElementsByTagName('feDropShadow');
  80570. if (domChild.length === 0) {
  80571. domChild = this.createElement('feDropShadow');
  80572. }
  80573. else {
  80574. domChild = domChild[0];
  80575. }
  80576. var style = displayable.style;
  80577. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  80578. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  80579. // TODO: textBoxShadowBlur is not supported yet
  80580. var offsetX, offsetY, blur, color;
  80581. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  80582. offsetX = style.shadowOffsetX || 0;
  80583. offsetY = style.shadowOffsetY || 0;
  80584. blur = style.shadowBlur;
  80585. color = style.shadowColor;
  80586. }
  80587. else if (style.textShadowBlur) {
  80588. offsetX = style.textShadowOffsetX || 0;
  80589. offsetY = style.textShadowOffsetY || 0;
  80590. blur = style.textShadowBlur;
  80591. color = style.textShadowColor;
  80592. }
  80593. else {
  80594. // Remove shadow
  80595. this.removeDom(dom, style);
  80596. return;
  80597. }
  80598. domChild.setAttribute('dx', offsetX / scaleX);
  80599. domChild.setAttribute('dy', offsetY / scaleY);
  80600. domChild.setAttribute('flood-color', color);
  80601. // Divide by two here so that it looks the same as in canvas
  80602. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  80603. var stdDx = blur / 2 / scaleX;
  80604. var stdDy = blur / 2 / scaleY;
  80605. var stdDeviation = stdDx + ' ' + stdDy;
  80606. domChild.setAttribute('stdDeviation', stdDeviation);
  80607. // Fix filter clipping problem
  80608. dom.setAttribute('x', '-100%');
  80609. dom.setAttribute('y', '-100%');
  80610. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  80611. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  80612. dom.appendChild(domChild);
  80613. // Store dom element in shadow, to avoid creating multiple
  80614. // dom instances for the same shadow element
  80615. style._shadowDom = dom;
  80616. };
  80617. /**
  80618. * Mark a single shadow to be used
  80619. *
  80620. * @param {Displayable} displayable displayable element
  80621. */
  80622. ShadowManager.prototype.markUsed = function (displayable) {
  80623. var style = displayable.style;
  80624. if (style && style._shadowDom) {
  80625. Definable.prototype.markUsed.call(this, style._shadowDom);
  80626. }
  80627. };
  80628. function hasShadow(style) {
  80629. // TODO: textBoxShadowBlur is not supported yet
  80630. return style
  80631. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  80632. || style.textShadowBlur || style.textShadowOffsetX
  80633. || style.textShadowOffsetY);
  80634. }
  80635. /**
  80636. * SVG Painter
  80637. * @module zrender/svg/Painter
  80638. */
  80639. function parseInt10$2(val) {
  80640. return parseInt(val, 10);
  80641. }
  80642. function getSvgProxy(el) {
  80643. if (el instanceof Path) {
  80644. return svgPath;
  80645. }
  80646. else if (el instanceof ZImage) {
  80647. return svgImage;
  80648. }
  80649. else if (el instanceof Text) {
  80650. return svgText;
  80651. }
  80652. else {
  80653. return svgPath;
  80654. }
  80655. }
  80656. function checkParentAvailable(parent, child) {
  80657. return child && parent && child.parentNode !== parent;
  80658. }
  80659. function insertAfter(parent, child, prevSibling) {
  80660. if (checkParentAvailable(parent, child) && prevSibling) {
  80661. var nextSibling = prevSibling.nextSibling;
  80662. nextSibling ? parent.insertBefore(child, nextSibling)
  80663. : parent.appendChild(child);
  80664. }
  80665. }
  80666. function prepend(parent, child) {
  80667. if (checkParentAvailable(parent, child)) {
  80668. var firstChild = parent.firstChild;
  80669. firstChild ? parent.insertBefore(child, firstChild)
  80670. : parent.appendChild(child);
  80671. }
  80672. }
  80673. function remove$1(parent, child) {
  80674. if (child && parent && child.parentNode === parent) {
  80675. parent.removeChild(child);
  80676. }
  80677. }
  80678. function getTextSvgElement(displayable) {
  80679. return displayable.__textSvgEl;
  80680. }
  80681. function getSvgElement(displayable) {
  80682. return displayable.__svgEl;
  80683. }
  80684. /**
  80685. * @alias module:zrender/svg/Painter
  80686. * @constructor
  80687. * @param {HTMLElement} root 绘图容器
  80688. * @param {module:zrender/Storage} storage
  80689. * @param {Object} opts
  80690. */
  80691. var SVGPainter = function (root, storage, opts, zrId) {
  80692. this.root = root;
  80693. this.storage = storage;
  80694. this._opts = opts = extend({}, opts || {});
  80695. var svgRoot = createElement('svg');
  80696. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  80697. svgRoot.setAttribute('version', '1.1');
  80698. svgRoot.setAttribute('baseProfile', 'full');
  80699. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  80700. this.gradientManager = new GradientManager(zrId, svgRoot);
  80701. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  80702. this.shadowManager = new ShadowManager(zrId, svgRoot);
  80703. var viewport = document.createElement('div');
  80704. viewport.style.cssText = 'overflow:hidden;position:relative';
  80705. this._svgRoot = svgRoot;
  80706. this._viewport = viewport;
  80707. root.appendChild(viewport);
  80708. viewport.appendChild(svgRoot);
  80709. this.resize(opts.width, opts.height);
  80710. this._visibleList = [];
  80711. };
  80712. SVGPainter.prototype = {
  80713. constructor: SVGPainter,
  80714. getType: function () {
  80715. return 'svg';
  80716. },
  80717. getViewportRoot: function () {
  80718. return this._viewport;
  80719. },
  80720. getViewportRootOffset: function () {
  80721. var viewportRoot = this.getViewportRoot();
  80722. if (viewportRoot) {
  80723. return {
  80724. offsetLeft: viewportRoot.offsetLeft || 0,
  80725. offsetTop: viewportRoot.offsetTop || 0
  80726. };
  80727. }
  80728. },
  80729. refresh: function () {
  80730. var list = this.storage.getDisplayList(true);
  80731. this._paintList(list);
  80732. },
  80733. setBackgroundColor: function (backgroundColor) {
  80734. // TODO gradient
  80735. this._viewport.style.background = backgroundColor;
  80736. },
  80737. _paintList: function (list) {
  80738. this.gradientManager.markAllUnused();
  80739. this.clipPathManager.markAllUnused();
  80740. this.shadowManager.markAllUnused();
  80741. var svgRoot = this._svgRoot;
  80742. var visibleList = this._visibleList;
  80743. var listLen = list.length;
  80744. var newVisibleList = [];
  80745. var i;
  80746. for (i = 0; i < listLen; i++) {
  80747. var displayable = list[i];
  80748. var svgProxy = getSvgProxy(displayable);
  80749. var svgElement = getSvgElement(displayable)
  80750. || getTextSvgElement(displayable);
  80751. if (!displayable.invisible) {
  80752. if (displayable.__dirty) {
  80753. svgProxy && svgProxy.brush(displayable);
  80754. // Update clipPath
  80755. this.clipPathManager.update(displayable);
  80756. // Update gradient and shadow
  80757. if (displayable.style) {
  80758. this.gradientManager
  80759. .update(displayable.style.fill);
  80760. this.gradientManager
  80761. .update(displayable.style.stroke);
  80762. this.shadowManager
  80763. .update(svgElement, displayable);
  80764. }
  80765. displayable.__dirty = false;
  80766. }
  80767. newVisibleList.push(displayable);
  80768. }
  80769. }
  80770. var diff = arrayDiff$1(visibleList, newVisibleList);
  80771. var prevSvgElement;
  80772. // First do remove, in case element moved to the head and do remove
  80773. // after add
  80774. for (i = 0; i < diff.length; i++) {
  80775. var item = diff[i];
  80776. if (item.removed) {
  80777. for (var k = 0; k < item.count; k++) {
  80778. var displayable = visibleList[item.indices[k]];
  80779. var svgElement = getSvgElement(displayable);
  80780. var textSvgElement = getTextSvgElement(displayable);
  80781. remove$1(svgRoot, svgElement);
  80782. remove$1(svgRoot, textSvgElement);
  80783. }
  80784. }
  80785. }
  80786. for (i = 0; i < diff.length; i++) {
  80787. var item = diff[i];
  80788. if (item.added) {
  80789. for (var k = 0; k < item.count; k++) {
  80790. var displayable = newVisibleList[item.indices[k]];
  80791. var svgElement = getSvgElement(displayable);
  80792. var textSvgElement = getTextSvgElement(displayable);
  80793. prevSvgElement
  80794. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  80795. : prepend(svgRoot, svgElement);
  80796. if (svgElement) {
  80797. insertAfter(svgRoot, textSvgElement, svgElement);
  80798. }
  80799. else if (prevSvgElement) {
  80800. insertAfter(
  80801. svgRoot, textSvgElement, prevSvgElement
  80802. );
  80803. }
  80804. else {
  80805. prepend(svgRoot, textSvgElement);
  80806. }
  80807. // Insert text
  80808. insertAfter(svgRoot, textSvgElement, svgElement);
  80809. prevSvgElement = textSvgElement || svgElement
  80810. || prevSvgElement;
  80811. this.gradientManager
  80812. .addWithoutUpdate(svgElement, displayable);
  80813. this.shadowManager
  80814. .addWithoutUpdate(prevSvgElement, displayable);
  80815. this.clipPathManager.markUsed(displayable);
  80816. }
  80817. }
  80818. else if (!item.removed) {
  80819. for (var k = 0; k < item.count; k++) {
  80820. var displayable = newVisibleList[item.indices[k]];
  80821. prevSvgElement =
  80822. svgElement =
  80823. getTextSvgElement(displayable)
  80824. || getSvgElement(displayable)
  80825. || prevSvgElement;
  80826. this.gradientManager.markUsed(displayable);
  80827. this.gradientManager
  80828. .addWithoutUpdate(svgElement, displayable);
  80829. this.shadowManager.markUsed(displayable);
  80830. this.shadowManager
  80831. .addWithoutUpdate(svgElement, displayable);
  80832. this.clipPathManager.markUsed(displayable);
  80833. }
  80834. }
  80835. }
  80836. this.gradientManager.removeUnused();
  80837. this.clipPathManager.removeUnused();
  80838. this.shadowManager.removeUnused();
  80839. this._visibleList = newVisibleList;
  80840. },
  80841. _getDefs: function (isForceCreating) {
  80842. var svgRoot = this._svgRoot;
  80843. var defs = this._svgRoot.getElementsByTagName('defs');
  80844. if (defs.length === 0) {
  80845. // Not exist
  80846. if (isForceCreating) {
  80847. var defs = svgRoot.insertBefore(
  80848. createElement('defs'), // Create new tag
  80849. svgRoot.firstChild // Insert in the front of svg
  80850. );
  80851. if (!defs.contains) {
  80852. // IE doesn't support contains method
  80853. defs.contains = function (el) {
  80854. var children = defs.children;
  80855. if (!children) {
  80856. return false;
  80857. }
  80858. for (var i = children.length - 1; i >= 0; --i) {
  80859. if (children[i] === el) {
  80860. return true;
  80861. }
  80862. }
  80863. return false;
  80864. };
  80865. }
  80866. return defs;
  80867. }
  80868. else {
  80869. return null;
  80870. }
  80871. }
  80872. else {
  80873. return defs[0];
  80874. }
  80875. },
  80876. resize: function (width, height) {
  80877. var viewport = this._viewport;
  80878. // FIXME Why ?
  80879. viewport.style.display = 'none';
  80880. // Save input w/h
  80881. var opts = this._opts;
  80882. width != null && (opts.width = width);
  80883. height != null && (opts.height = height);
  80884. width = this._getSize(0);
  80885. height = this._getSize(1);
  80886. viewport.style.display = '';
  80887. if (this._width !== width || this._height !== height) {
  80888. this._width = width;
  80889. this._height = height;
  80890. var viewportStyle = viewport.style;
  80891. viewportStyle.width = width + 'px';
  80892. viewportStyle.height = height + 'px';
  80893. var svgRoot = this._svgRoot;
  80894. // Set width by 'svgRoot.width = width' is invalid
  80895. svgRoot.setAttribute('width', width);
  80896. svgRoot.setAttribute('height', height);
  80897. }
  80898. },
  80899. /**
  80900. * 获取绘图区域宽度
  80901. */
  80902. getWidth: function () {
  80903. return this._width;
  80904. },
  80905. /**
  80906. * 获取绘图区域高度
  80907. */
  80908. getHeight: function () {
  80909. return this._height;
  80910. },
  80911. _getSize: function (whIdx) {
  80912. var opts = this._opts;
  80913. var wh = ['width', 'height'][whIdx];
  80914. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  80915. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  80916. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  80917. if (opts[wh] != null && opts[wh] !== 'auto') {
  80918. return parseFloat(opts[wh]);
  80919. }
  80920. var root = this.root;
  80921. // IE8 does not support getComputedStyle, but it use VML.
  80922. var stl = document.defaultView.getComputedStyle(root);
  80923. return (
  80924. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  80925. - (parseInt10$2(stl[plt]) || 0)
  80926. - (parseInt10$2(stl[prb]) || 0)
  80927. ) | 0;
  80928. },
  80929. dispose: function () {
  80930. this.root.innerHTML = '';
  80931. this._svgRoot =
  80932. this._viewport =
  80933. this.storage =
  80934. null;
  80935. },
  80936. clear: function () {
  80937. if (this._viewport) {
  80938. this.root.removeChild(this._viewport);
  80939. }
  80940. },
  80941. pathToDataUrl: function () {
  80942. this.refresh();
  80943. var html = this._svgRoot.outerHTML;
  80944. return 'data:image/svg+xml;charset=UTF-8,' + html;
  80945. }
  80946. };
  80947. // Not supported methods
  80948. function createMethodNotSupport$1(method) {
  80949. return function () {
  80950. zrLog('In SVG mode painter not support method "' + method + '"');
  80951. };
  80952. }
  80953. // Unsuppoted methods
  80954. each$1([
  80955. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  80956. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  80957. 'toDataURL', 'pathToImage'
  80958. ], function (name) {
  80959. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  80960. });
  80961. registerPainter('svg', SVGPainter);
  80962. /*
  80963. * Licensed to the Apache Software Foundation (ASF) under one
  80964. * or more contributor license agreements. See the NOTICE file
  80965. * distributed with this work for additional information
  80966. * regarding copyright ownership. The ASF licenses this file
  80967. * to you under the Apache License, Version 2.0 (the
  80968. * "License"); you may not use this file except in compliance
  80969. * with the License. You may obtain a copy of the License at
  80970. *
  80971. * http://www.apache.org/licenses/LICENSE-2.0
  80972. *
  80973. * Unless required by applicable law or agreed to in writing,
  80974. * software distributed under the License is distributed on an
  80975. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80976. * KIND, either express or implied. See the License for the
  80977. * specific language governing permissions and limitations
  80978. * under the License.
  80979. */
  80980. // Import all charts and components
  80981. exports.version = version;
  80982. exports.dependencies = dependencies;
  80983. exports.PRIORITY = PRIORITY;
  80984. exports.init = init;
  80985. exports.connect = connect;
  80986. exports.disConnect = disConnect;
  80987. exports.disconnect = disconnect;
  80988. exports.dispose = dispose;
  80989. exports.getInstanceByDom = getInstanceByDom;
  80990. exports.getInstanceById = getInstanceById;
  80991. exports.registerTheme = registerTheme;
  80992. exports.registerPreprocessor = registerPreprocessor;
  80993. exports.registerProcessor = registerProcessor;
  80994. exports.registerPostUpdate = registerPostUpdate;
  80995. exports.registerAction = registerAction;
  80996. exports.registerCoordinateSystem = registerCoordinateSystem;
  80997. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  80998. exports.registerLayout = registerLayout;
  80999. exports.registerVisual = registerVisual;
  81000. exports.registerLoading = registerLoading;
  81001. exports.extendComponentModel = extendComponentModel;
  81002. exports.extendComponentView = extendComponentView;
  81003. exports.extendSeriesModel = extendSeriesModel;
  81004. exports.extendChartView = extendChartView;
  81005. exports.setCanvasCreator = setCanvasCreator;
  81006. exports.registerMap = registerMap;
  81007. exports.getMap = getMap;
  81008. exports.dataTool = dataTool;
  81009. exports.zrender = zrender;
  81010. exports.number = number;
  81011. exports.format = format;
  81012. exports.throttle = throttle;
  81013. exports.helper = helper;
  81014. exports.matrix = matrix;
  81015. exports.vector = vector;
  81016. exports.color = color;
  81017. exports.parseGeoJSON = parseGeoJson$1;
  81018. exports.parseGeoJson = parseGeoJson;
  81019. exports.util = ecUtil;
  81020. exports.graphic = graphic$1;
  81021. exports.List = List;
  81022. exports.Model = Model;
  81023. exports.Axis = Axis;
  81024. exports.env = env$1;
  81025. })));
  81026. //# sourceMappingURL=echarts.js.map